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/jgum/category/type/TypeCategoryTutorialTest.java b/src/test/java/org/jgum/category/type/TypeCategoryTutorialTest.java index 48edefc..48f399d 100644 --- a/src/test/java/org/jgum/category/type/TypeCategoryTutorialTest.java +++ b/src/test/java/org/jgum/category/type/TypeCategoryTutorialTest.java @@ -1,36 +1,36 @@ package org.jgum.category.type; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import org.apache.log4j.or.ObjectRenderer; import org.jgum.JGum; import org.junit.Test; public class TypeCategoryTutorialTest { public class Fruit {} public class Orange extends Fruit{} public class FruitRenderer implements ObjectRenderer { @Override public String doRender(Object fruit) { // TODO Auto-generated method stub return null; } } @Test public void testTypeCategoryInheritance() { JGum jgum = new JGum(); TypeCategory<?> parent = jgum.forClass(Fruit.class); //type category for Fruit.class TypeCategory<?> child = jgum.forClass(Orange.class); //type category for Orange.class FruitRenderer fruitRenderer = new FruitRenderer(); - parent.setProperty(ObjectRenderer.class, fruitRenderer); //"renderer" property set to fruitRenderer for Fruit.class - assertEquals(fruitRenderer, parent.getProperty(ObjectRenderer.class).get()); //"renderer" property is fruitRenderer for Fruit.class - assertEquals(fruitRenderer, child.getProperty(ObjectRenderer.class).get()); //"renderer" property is also fruitRenderer for Orange.class - assertFalse(jgum.forClass(Object.class).getProperty(ObjectRenderer.class).isPresent()); //"renderer" property has not been set for Object.class + parent.setProperty(ObjectRenderer.class, fruitRenderer); //ObjectRenderer.class property set to fruitRenderer for Fruit.class + assertEquals(fruitRenderer, parent.getProperty(ObjectRenderer.class).get()); //ObjectRenderer.class property is fruitRenderer for Fruit.class + assertEquals(fruitRenderer, child.getProperty(ObjectRenderer.class).get()); //ObjectRenderer.class property is also fruitRenderer for Orange.class + assertFalse(jgum.forClass(Object.class).getProperty(ObjectRenderer.class).isPresent()); //ObjectRenderer.class property has not been set for Object.class } }
true
true
public void testTypeCategoryInheritance() { JGum jgum = new JGum(); TypeCategory<?> parent = jgum.forClass(Fruit.class); //type category for Fruit.class TypeCategory<?> child = jgum.forClass(Orange.class); //type category for Orange.class FruitRenderer fruitRenderer = new FruitRenderer(); parent.setProperty(ObjectRenderer.class, fruitRenderer); //"renderer" property set to fruitRenderer for Fruit.class assertEquals(fruitRenderer, parent.getProperty(ObjectRenderer.class).get()); //"renderer" property is fruitRenderer for Fruit.class assertEquals(fruitRenderer, child.getProperty(ObjectRenderer.class).get()); //"renderer" property is also fruitRenderer for Orange.class assertFalse(jgum.forClass(Object.class).getProperty(ObjectRenderer.class).isPresent()); //"renderer" property has not been set for Object.class }
public void testTypeCategoryInheritance() { JGum jgum = new JGum(); TypeCategory<?> parent = jgum.forClass(Fruit.class); //type category for Fruit.class TypeCategory<?> child = jgum.forClass(Orange.class); //type category for Orange.class FruitRenderer fruitRenderer = new FruitRenderer(); parent.setProperty(ObjectRenderer.class, fruitRenderer); //ObjectRenderer.class property set to fruitRenderer for Fruit.class assertEquals(fruitRenderer, parent.getProperty(ObjectRenderer.class).get()); //ObjectRenderer.class property is fruitRenderer for Fruit.class assertEquals(fruitRenderer, child.getProperty(ObjectRenderer.class).get()); //ObjectRenderer.class property is also fruitRenderer for Orange.class assertFalse(jgum.forClass(Object.class).getProperty(ObjectRenderer.class).isPresent()); //ObjectRenderer.class property has not been set for Object.class }
diff --git a/src/net/loadingchunks/plugins/GuardWolf/GWSQL.java b/src/net/loadingchunks/plugins/GuardWolf/GWSQL.java index ef7e4af..a2d6581 100644 --- a/src/net/loadingchunks/plugins/GuardWolf/GWSQL.java +++ b/src/net/loadingchunks/plugins/GuardWolf/GWSQL.java @@ -1,122 +1,124 @@ package net.loadingchunks.plugins.GuardWolf; import java.sql.*; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; /** * Handler for the /gw sample command. * @author Cue */ public class GWSQL { public Connection con; public Statement stmt; public final GuardWolf plugin; public GWSQL(GuardWolf plugin) { this.plugin = plugin; } public void Connect() { try { Class.forName("com.mysql.jdbc.Driver"); this.con = DriverManager.getConnection(this.plugin.gwConfig.get("db_address"), this.plugin.gwConfig.get("db_user"), this.plugin.gwConfig.get("db_pass")); } catch ( SQLException e ) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public void Ban(String name, String banner, long time, String reason, int permanent) { Integer strike = 1; try { PreparedStatement stat = con.prepareStatement("INSERT INTO `" + this.plugin.gwConfig.get("db_table") + "`" + "(`user`,`country`,`banned_at`,`expires_at`,`reason`,`banned_by`,`strike`,`strike_expires`,`unbanned`,`permanent`)" + " VALUES ('" + name + "','?',NOW(),FROM_UNIXTIME(" + time + "),'" + reason + "','" + banner + "'," + strike + ",NOW(),0," + permanent + ")" ); stat.execute(); } catch ( SQLException e ) { e.printStackTrace(); } } public void UnBan(String name, String unbanner) { try { PreparedStatement stat = con.prepareStatement("UPDATE `" + this.plugin.gwConfig.get("db_table") + "` SET `unbanned` = 0 WHERE `user` = '" + name + "' LIMIT 1"); stat.execute(); } catch ( SQLException e ) { e.printStackTrace(); } } public void Stats() { try { Statement stat = con.createStatement(); ResultSet result = stat.executeQuery("SELECT COUNT(*) as counter FROM `" + this.plugin.gwConfig.get("db_table") + "`"); result.next(); System.out.println("Ban Records: " + result.getInt("counter")); } catch ( SQLException e ) { e.printStackTrace(); } } public String CheckBan(String user) { System.out.println("[GW] Checking ban status..."); try { PreparedStatement stat = con.prepareStatement("SELECT * FROM `mcusers_ban` WHERE (expires_at > NOW() OR `permanent` = 1) AND `user` = '" + user + "' AND `unbanned` = 0 ORDER BY id DESC"); ResultSet result = stat.executeQuery(); if(result.last()) { if(result.getInt("permanent") == 1) return result.getString("reason") + " (Permanent Ban)"; else return result.getString("reason") + " (Expires " + result.getString("expires_at") + ")"; } else return null; } catch ( SQLException e ) { e.printStackTrace(); } return null; } public void ListBan(int page, String user, CommandSender sender) { String tempString = ""; if(user.isEmpty()) { try { PreparedStatement stat = con.prepareStatement("SELECT *,COUNT(*) as c FROM `mcusers_ban` GROUP BY `user` ORDER BY `permanent`,`expires_at` DESC LIMIT " + ((page - 1)*(Integer.parseInt(this.plugin.gwConfig.get("per_page")))) + "," + (Integer.parseInt(this.plugin.gwConfig.get("per_page")))); ResultSet result = stat.executeQuery(); if(!result.last()) sender.sendMessage(ChatColor.RED + "No bans found."); else { result.first(); do { sender.sendMessage("- " + ChatColor.WHITE + result.getString("user") + " (" + result.getInt("c") + " bans found)"); } while(result.next()); } + return; } catch ( SQLException e ) { e.printStackTrace(); } } else { try { PreparedStatement stat = con.prepareStatement("SELECT * FROM `mcusers_ban` WHERE `user` = '" + user + "' ORDER BY `permanent`,`expires_at` DESC LIMIT " + ((page - 1)*(Integer.parseInt(this.plugin.gwConfig.get("per_page")))) + "," + (Integer.parseInt(this.plugin.gwConfig.get("per_page")))); ResultSet result = stat.executeQuery(); if(!result.last()) sender.sendMessage(ChatColor.RED + "No bans found for this user."); else { result.first(); do { tempString = "- " + ChatColor.WHITE + result.getString("reason"); if(result.getInt("permanent") == 1) tempString = tempString + " (Permanent)"; else tempString = tempString + " (Expires: " + result.getString("expires_at") + ")"; sender.sendMessage(tempString); } while (result.next()); } + return; } catch ( SQLException e ) { e.printStackTrace(); } } sender.sendMessage(ChatColor.RED + "Error getting Ban List!"); } }
false
true
public void ListBan(int page, String user, CommandSender sender) { String tempString = ""; if(user.isEmpty()) { try { PreparedStatement stat = con.prepareStatement("SELECT *,COUNT(*) as c FROM `mcusers_ban` GROUP BY `user` ORDER BY `permanent`,`expires_at` DESC LIMIT " + ((page - 1)*(Integer.parseInt(this.plugin.gwConfig.get("per_page")))) + "," + (Integer.parseInt(this.plugin.gwConfig.get("per_page")))); ResultSet result = stat.executeQuery(); if(!result.last()) sender.sendMessage(ChatColor.RED + "No bans found."); else { result.first(); do { sender.sendMessage("- " + ChatColor.WHITE + result.getString("user") + " (" + result.getInt("c") + " bans found)"); } while(result.next()); } } catch ( SQLException e ) { e.printStackTrace(); } } else { try { PreparedStatement stat = con.prepareStatement("SELECT * FROM `mcusers_ban` WHERE `user` = '" + user + "' ORDER BY `permanent`,`expires_at` DESC LIMIT " + ((page - 1)*(Integer.parseInt(this.plugin.gwConfig.get("per_page")))) + "," + (Integer.parseInt(this.plugin.gwConfig.get("per_page")))); ResultSet result = stat.executeQuery(); if(!result.last()) sender.sendMessage(ChatColor.RED + "No bans found for this user."); else { result.first(); do { tempString = "- " + ChatColor.WHITE + result.getString("reason"); if(result.getInt("permanent") == 1) tempString = tempString + " (Permanent)"; else tempString = tempString + " (Expires: " + result.getString("expires_at") + ")"; sender.sendMessage(tempString); } while (result.next()); } } catch ( SQLException e ) { e.printStackTrace(); } } sender.sendMessage(ChatColor.RED + "Error getting Ban List!"); }
public void ListBan(int page, String user, CommandSender sender) { String tempString = ""; if(user.isEmpty()) { try { PreparedStatement stat = con.prepareStatement("SELECT *,COUNT(*) as c FROM `mcusers_ban` GROUP BY `user` ORDER BY `permanent`,`expires_at` DESC LIMIT " + ((page - 1)*(Integer.parseInt(this.plugin.gwConfig.get("per_page")))) + "," + (Integer.parseInt(this.plugin.gwConfig.get("per_page")))); ResultSet result = stat.executeQuery(); if(!result.last()) sender.sendMessage(ChatColor.RED + "No bans found."); else { result.first(); do { sender.sendMessage("- " + ChatColor.WHITE + result.getString("user") + " (" + result.getInt("c") + " bans found)"); } while(result.next()); } return; } catch ( SQLException e ) { e.printStackTrace(); } } else { try { PreparedStatement stat = con.prepareStatement("SELECT * FROM `mcusers_ban` WHERE `user` = '" + user + "' ORDER BY `permanent`,`expires_at` DESC LIMIT " + ((page - 1)*(Integer.parseInt(this.plugin.gwConfig.get("per_page")))) + "," + (Integer.parseInt(this.plugin.gwConfig.get("per_page")))); ResultSet result = stat.executeQuery(); if(!result.last()) sender.sendMessage(ChatColor.RED + "No bans found for this user."); else { result.first(); do { tempString = "- " + ChatColor.WHITE + result.getString("reason"); if(result.getInt("permanent") == 1) tempString = tempString + " (Permanent)"; else tempString = tempString + " (Expires: " + result.getString("expires_at") + ")"; sender.sendMessage(tempString); } while (result.next()); } return; } catch ( SQLException e ) { e.printStackTrace(); } } sender.sendMessage(ChatColor.RED + "Error getting Ban List!"); }
diff --git a/src/main/java/org/deegree/igeo/dataadapter/database/postgis/PostgisDataLoader.java b/src/main/java/org/deegree/igeo/dataadapter/database/postgis/PostgisDataLoader.java index fe16964..28654cc 100644 --- a/src/main/java/org/deegree/igeo/dataadapter/database/postgis/PostgisDataLoader.java +++ b/src/main/java/org/deegree/igeo/dataadapter/database/postgis/PostgisDataLoader.java @@ -1,198 +1,198 @@ //$HeadURL$ /*---------------- FILE HEADER ------------------------------------------ This file is part of deegree. Copyright (C) 2001-2008 by: Department of Geography, University of Bonn http://www.giub.uni-bonn.de/deegree/ lat/lon GmbH http://www.lat-lon.de 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 Contact: Andreas Poth lat/lon GmbH Aennchenstr. 19 53177 Bonn Germany E-Mail: [email protected] Prof. Dr. Klaus Greve Department of Geography University of Bonn Meckenheimer Allee 166 53115 Bonn Germany E-Mail: [email protected] ---------------------------------------------------------------------------*/ package org.deegree.igeo.dataadapter.database.postgis; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import org.deegree.framework.log.ILogger; import org.deegree.framework.log.LoggerFactory; import org.deegree.framework.util.StringTools; import org.deegree.igeo.config.JDBCConnection; import org.deegree.igeo.dataadapter.database.AbstractDatabaseLoader; import org.deegree.igeo.mapmodel.DatabaseDatasource; import org.deegree.io.DBPoolException; import org.deegree.io.datastore.sql.postgis.PGgeometryAdapter; import org.deegree.model.crs.CoordinateSystem; import org.deegree.model.spatialschema.Envelope; import org.deegree.model.spatialschema.GeometryException; import org.deegree.model.spatialschema.GeometryFactory; import org.deegree.model.spatialschema.Surface; import org.postgis.PGboxbase; import org.postgis.PGgeometry; import org.postgresql.PGConnection; /** * class for loading data as feature collection from a postgis database * * @author <a href="mailto:[email protected]">Andreas Poth</a> * @author last edited by: $Author$ * * @version. $Revision$, $Date$ */ public class PostgisDataLoader extends AbstractDatabaseLoader { private static final ILogger LOG = LoggerFactory.getLogger( PostgisDataLoader.class ); private static final String GEOMETRY_DATATYPE_NAME = "geometry"; private static final String BOX3D_DATATYPE_NAME = "box3d"; private static final String PG_GEOMETRY_CLASS_NAME = "org.postgis.PGgeometry"; private static final String PG_BOX3D_CLASS_NAME = "org.postgis.PGbox3d"; private static Class<?> pgGeometryClass; private static Class<?> pgBox3dClass; static { try { pgGeometryClass = Class.forName( PG_GEOMETRY_CLASS_NAME ); } catch ( ClassNotFoundException e ) { LOG.logError( "Cannot find class '" + PG_GEOMETRY_CLASS_NAME + "'.", e ); } try { pgBox3dClass = Class.forName( PG_BOX3D_CLASS_NAME ); } catch ( ClassNotFoundException e ) { LOG.logError( "Cannot find class '" + PG_BOX3D_CLASS_NAME + "'.", e ); } } /** * * @param datasource */ public PostgisDataLoader( DatabaseDatasource datasource ) { super( datasource ); } @Override protected Object handleGeometryValue( Object value, CoordinateSystem crs ) throws GeometryException { value = PGgeometryAdapter.wrap( (PGgeometry) value, crs ); return value; } @Override protected PreparedStatement createPreparedStatement( DatabaseDatasource datasource, Envelope envelope, Connection conn ) throws GeometryException, SQLException { // special case if all features need to be requested, eg. for the classification if ( envelope == null ) { return conn.prepareStatement( datasource.getSqlTemplate() ); } PreparedStatement stmt; String envCRS = envelope.getCoordinateSystem().getLocalName(); String nativeCRS = getSRSCode( datasource.getSRID() ); PGboxbase box = PGgeometryAdapter.export( envelope ); Surface surface = GeometryFactory.createSurface( envelope, envelope.getCoordinateSystem() ); PGgeometry pggeom = PGgeometryAdapter.export( surface, Integer.parseInt( envCRS ) ); StringBuffer query = new StringBuffer( 1000 ); if ( nativeCRS.equals( "-1" ) ) { query.append( " (" ); query.append( datasource.getGeometryFieldName() ); - query.append( " && SetSRID( ?, -1) " ); - query.append( " AND intersects(" ); + query.append( " && ST_SetSRID( ?, -1) " ); + query.append( " AND ST_Intersects(" ); query.append( datasource.getGeometryFieldName() ); - query.append( ",SetSRID( ?,-1 ) ) ) " ); + query.append( ",ST_SetSRID( ?,-1 ) ) ) " ); } else { // use the bbox operator (&&) to filter using the spatial index query.append( " (" ); query.append( datasource.getGeometryFieldName() ); - query.append( " && transform(SetSRID( ?, " ); + query.append( " && ST_Transform(ST_SetSRID( ?, " ); query.append( envCRS ); query.append( "), " ); query.append( nativeCRS ); - query.append( ")) AND intersects(" ); + query.append( ")) AND ST_Intersects(" ); query.append( datasource.getGeometryFieldName() ); - query.append( ",transform(?, " ); + query.append( ",ST_Transform(?, " ); query.append( nativeCRS ); query.append( "))" ); } String sql = datasource.getSqlTemplate(); System.out.println( sql ); if ( sql.trim().toUpperCase().endsWith( " WHERE" ) ) { LOG.logDebug( "performed SQL: ", sql + query ); stmt = conn.prepareStatement( sql + query ); } else if ( sql.trim().toUpperCase().indexOf( " WHERE " ) < 0 ) { LOG.logDebug( "performed SQL: ", sql + " WHERE " + query ); stmt = conn.prepareStatement( sql + " WHERE " + query ); } else { LOG.logDebug( "performed SQL: ", sql + " AND " + query ); stmt = conn.prepareStatement( sql + " AND " + query ); } // TODO // if connection is not available ask user updated connection parameters stmt.setObject( 1, box, java.sql.Types.OTHER ); stmt.setObject( 2, pggeom, java.sql.Types.OTHER ); stmt.setMaxRows( maxFeatures ); // seems that not every postgres version supports this // stmt.setQueryTimeout( timeout ); System.out.println( stmt ); return stmt; } /** * @param srid * @return */ private static String getSRSCode( String srid ) { if ( srid.indexOf( ":" ) > -1 ) { String[] t = StringTools.toArray( srid, ":", false ); return t[t.length - 1]; } return srid; } @Override protected Connection acquireConnection( JDBCConnection jdbc ) throws DBPoolException, SQLException { Connection conn = super.acquireConnection( jdbc ); PGConnection pgConn = (PGConnection) conn; pgConn.addDataType( GEOMETRY_DATATYPE_NAME, pgGeometryClass ); pgConn.addDataType( BOX3D_DATATYPE_NAME, pgBox3dClass ); return conn; } }
false
true
protected PreparedStatement createPreparedStatement( DatabaseDatasource datasource, Envelope envelope, Connection conn ) throws GeometryException, SQLException { // special case if all features need to be requested, eg. for the classification if ( envelope == null ) { return conn.prepareStatement( datasource.getSqlTemplate() ); } PreparedStatement stmt; String envCRS = envelope.getCoordinateSystem().getLocalName(); String nativeCRS = getSRSCode( datasource.getSRID() ); PGboxbase box = PGgeometryAdapter.export( envelope ); Surface surface = GeometryFactory.createSurface( envelope, envelope.getCoordinateSystem() ); PGgeometry pggeom = PGgeometryAdapter.export( surface, Integer.parseInt( envCRS ) ); StringBuffer query = new StringBuffer( 1000 ); if ( nativeCRS.equals( "-1" ) ) { query.append( " (" ); query.append( datasource.getGeometryFieldName() ); query.append( " && SetSRID( ?, -1) " ); query.append( " AND intersects(" ); query.append( datasource.getGeometryFieldName() ); query.append( ",SetSRID( ?,-1 ) ) ) " ); } else { // use the bbox operator (&&) to filter using the spatial index query.append( " (" ); query.append( datasource.getGeometryFieldName() ); query.append( " && transform(SetSRID( ?, " ); query.append( envCRS ); query.append( "), " ); query.append( nativeCRS ); query.append( ")) AND intersects(" ); query.append( datasource.getGeometryFieldName() ); query.append( ",transform(?, " ); query.append( nativeCRS ); query.append( "))" ); } String sql = datasource.getSqlTemplate(); System.out.println( sql ); if ( sql.trim().toUpperCase().endsWith( " WHERE" ) ) { LOG.logDebug( "performed SQL: ", sql + query ); stmt = conn.prepareStatement( sql + query ); } else if ( sql.trim().toUpperCase().indexOf( " WHERE " ) < 0 ) { LOG.logDebug( "performed SQL: ", sql + " WHERE " + query ); stmt = conn.prepareStatement( sql + " WHERE " + query ); } else { LOG.logDebug( "performed SQL: ", sql + " AND " + query ); stmt = conn.prepareStatement( sql + " AND " + query ); } // TODO // if connection is not available ask user updated connection parameters stmt.setObject( 1, box, java.sql.Types.OTHER ); stmt.setObject( 2, pggeom, java.sql.Types.OTHER ); stmt.setMaxRows( maxFeatures ); // seems that not every postgres version supports this // stmt.setQueryTimeout( timeout ); System.out.println( stmt ); return stmt; }
protected PreparedStatement createPreparedStatement( DatabaseDatasource datasource, Envelope envelope, Connection conn ) throws GeometryException, SQLException { // special case if all features need to be requested, eg. for the classification if ( envelope == null ) { return conn.prepareStatement( datasource.getSqlTemplate() ); } PreparedStatement stmt; String envCRS = envelope.getCoordinateSystem().getLocalName(); String nativeCRS = getSRSCode( datasource.getSRID() ); PGboxbase box = PGgeometryAdapter.export( envelope ); Surface surface = GeometryFactory.createSurface( envelope, envelope.getCoordinateSystem() ); PGgeometry pggeom = PGgeometryAdapter.export( surface, Integer.parseInt( envCRS ) ); StringBuffer query = new StringBuffer( 1000 ); if ( nativeCRS.equals( "-1" ) ) { query.append( " (" ); query.append( datasource.getGeometryFieldName() ); query.append( " && ST_SetSRID( ?, -1) " ); query.append( " AND ST_Intersects(" ); query.append( datasource.getGeometryFieldName() ); query.append( ",ST_SetSRID( ?,-1 ) ) ) " ); } else { // use the bbox operator (&&) to filter using the spatial index query.append( " (" ); query.append( datasource.getGeometryFieldName() ); query.append( " && ST_Transform(ST_SetSRID( ?, " ); query.append( envCRS ); query.append( "), " ); query.append( nativeCRS ); query.append( ")) AND ST_Intersects(" ); query.append( datasource.getGeometryFieldName() ); query.append( ",ST_Transform(?, " ); query.append( nativeCRS ); query.append( "))" ); } String sql = datasource.getSqlTemplate(); System.out.println( sql ); if ( sql.trim().toUpperCase().endsWith( " WHERE" ) ) { LOG.logDebug( "performed SQL: ", sql + query ); stmt = conn.prepareStatement( sql + query ); } else if ( sql.trim().toUpperCase().indexOf( " WHERE " ) < 0 ) { LOG.logDebug( "performed SQL: ", sql + " WHERE " + query ); stmt = conn.prepareStatement( sql + " WHERE " + query ); } else { LOG.logDebug( "performed SQL: ", sql + " AND " + query ); stmt = conn.prepareStatement( sql + " AND " + query ); } // TODO // if connection is not available ask user updated connection parameters stmt.setObject( 1, box, java.sql.Types.OTHER ); stmt.setObject( 2, pggeom, java.sql.Types.OTHER ); stmt.setMaxRows( maxFeatures ); // seems that not every postgres version supports this // stmt.setQueryTimeout( timeout ); System.out.println( stmt ); return stmt; }
diff --git a/CubicTestPlugin/src/main/java/org/cubictest/common/utils/EnvironmentInfo.java b/CubicTestPlugin/src/main/java/org/cubictest/common/utils/EnvironmentInfo.java index 02fe4ffc..4cd7ac06 100644 --- a/CubicTestPlugin/src/main/java/org/cubictest/common/utils/EnvironmentInfo.java +++ b/CubicTestPlugin/src/main/java/org/cubictest/common/utils/EnvironmentInfo.java @@ -1,39 +1,39 @@ /* * This software is licensed under the terms of the GNU GENERAL PUBLIC LICENSE * Version 2, which can be found at http://www.gnu.org/copyleft/gpl.html */ package org.cubictest.common.utils; /** * Class containing plugin environment info. * * @author Christian Schwarz */ public class EnvironmentInfo { private static Boolean runningInEclipse; /** * Get whether CubicTest is running in Eclipse or not. * @return */ public static boolean isRunningInEclipse() { if (runningInEclipse == null) { try { - Class plugin = Class.forName("org.cubictest.CubicTestPlugin"); + Class<?> plugin = Class.forName("org.cubictest.CubicTestPlugin"); if (plugin == null) { runningInEclipse = false; } else { runningInEclipse = true; } } catch (Throwable e) { runningInEclipse = false; } } return runningInEclipse; } }
true
true
public static boolean isRunningInEclipse() { if (runningInEclipse == null) { try { Class plugin = Class.forName("org.cubictest.CubicTestPlugin"); if (plugin == null) { runningInEclipse = false; } else { runningInEclipse = true; } } catch (Throwable e) { runningInEclipse = false; } } return runningInEclipse; }
public static boolean isRunningInEclipse() { if (runningInEclipse == null) { try { Class<?> plugin = Class.forName("org.cubictest.CubicTestPlugin"); if (plugin == null) { runningInEclipse = false; } else { runningInEclipse = true; } } catch (Throwable e) { runningInEclipse = false; } } return runningInEclipse; }
diff --git a/epcis-queryclient/src/main/java/org/fosstrak/epcis/queryclient/QueryClientSoapImpl.java b/epcis-queryclient/src/main/java/org/fosstrak/epcis/queryclient/QueryClientSoapImpl.java index e9225d6..0e1f7f3 100644 --- a/epcis-queryclient/src/main/java/org/fosstrak/epcis/queryclient/QueryClientSoapImpl.java +++ b/epcis-queryclient/src/main/java/org/fosstrak/epcis/queryclient/QueryClientSoapImpl.java @@ -1,373 +1,373 @@ package org.accada.epcis.queryclient; import java.io.InputStream; import java.rmi.RemoteException; import java.text.ParseException; import java.util.Calendar; import java.util.Vector; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.rpc.ServiceException; import org.accada.epcis.soapapi.ArrayOfString; import org.accada.epcis.soapapi.DuplicateSubscriptionException; import org.accada.epcis.soapapi.EPCISServiceBindingStub; import org.accada.epcis.soapapi.ImplementationException; import org.accada.epcis.soapapi.InvalidURIException; import org.accada.epcis.soapapi.NoSuchNameException; import org.accada.epcis.soapapi.Poll; import org.accada.epcis.soapapi.QueryParam; import org.accada.epcis.soapapi.QueryParameterException; import org.accada.epcis.soapapi.QueryResults; import org.accada.epcis.soapapi.QuerySchedule; import org.accada.epcis.soapapi.QueryScheduleExtensionType; import org.accada.epcis.soapapi.QueryTooComplexException; import org.accada.epcis.soapapi.QueryTooLargeException; import org.accada.epcis.soapapi.SecurityException; import org.accada.epcis.soapapi.Subscribe; import org.accada.epcis.soapapi.SubscribeNotPermittedException; import org.accada.epcis.soapapi.SubscriptionControls; import org.accada.epcis.soapapi.SubscriptionControlsException; import org.accada.epcis.soapapi.SubscriptionControlsExtensionType; import org.accada.epcis.soapapi.ValidationException; import org.accada.epcis.utils.TimeParser; import org.apache.axis.message.MessageElement; import org.apache.axis.types.URI; import org.apache.axis.types.URI.MalformedURIException; import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * An adapter (according to the Class Adapter Pattern) for the QuerySoapClient * making it possible to send a query in xml representation. * * @author Andrea Gr�ssbauer * @author Marco Steybe */ public class QueryClientSoapImpl extends QueryClientBase { private static final Logger LOG = Logger.getLogger(QueryClientSoapImpl.class); /** * Holds the query parameters. */ private Vector<QueryParam> queryParamsVector = new Vector<QueryParam>(); /** * Constructs a new QueryClientSoapImpl. */ public QueryClientSoapImpl() { super(); } /** * Constructs a new QueryClientSoapImpl. * * @param address * The address at which the query service listens. */ public QueryClientSoapImpl(final String address) { super(address); } private QueryParam[] handleParams(Element params) { NodeList paramList = params.getElementsByTagName("param"); int nofParams = paramList.getLength(); QueryParam[] queryParams = new QueryParam[nofParams]; for (int i = 0; i < nofParams; i++) { Element param = (Element) paramList.item(i); Element name = (Element) param.getElementsByTagName("name").item(0); Element value = (Element) param.getElementsByTagName("value").item( 0); String paramName = name.getTextContent(); Object paramValue = parseParamValue(value); QueryParam queryParam = new QueryParam(paramName, paramValue); queryParams[i] = queryParam; } return queryParams; } private Object parseParamValue(Element valueElement) { Object paramValue = null; // check if we have an array of strings NodeList stringNodes = valueElement.getElementsByTagName("string"); int size = stringNodes.getLength(); if (size > 0) { String[] strings = new String[size]; boolean[] noHackAroundBugs = new boolean[size]; for (int i = 0; i < size; i++) { - String string = stringNodes.item(0).getTextContent(); + String string = stringNodes.item(i).getTextContent(); strings[i] = string; noHackAroundBugs[i] = true; if (LOG.isDebugEnabled()) { LOG.debug("found parameter value <string>" + string + "</string>"); } } paramValue = new ArrayOfString(strings, noHackAroundBugs); } else { // check if we have an Integer try { paramValue = Integer.parseInt(valueElement.getTextContent()); if (LOG.isDebugEnabled()) { LOG.debug("found parameter value (Integer) " + paramValue); } } catch (Exception e) { // check if we have a time value try { paramValue = handleTime(valueElement); if (LOG.isDebugEnabled()) { LOG.debug("found parameter value (Calendar) " + paramValue); } } catch (Exception e1) { // check if we have an URI try { paramValue = handleUri(valueElement); if (LOG.isDebugEnabled()) { LOG.debug("found parameter value (URI) " + paramValue); } } catch (Exception e2) { // ok lets take it as String paramValue = valueElement.getTextContent(); if (LOG.isDebugEnabled()) { LOG.debug("found parameter value (String) " + paramValue); } } } } } return paramValue; } /** * @see org.accada.epcis.queryclient.QueryClientInterface#runQuery(java.io.InputStream) */ public QueryResults runQuery(InputStream request) throws ServiceException, QueryTooComplexException, ImplementationException, QueryTooLargeException, QueryParameterException, ValidationException, SecurityException, NoSuchNameException, RemoteException { clearParameters(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document epcisq; try { DocumentBuilder builder = factory.newDocumentBuilder(); epcisq = builder.parse(request); } catch (Exception e) { throw new RuntimeException("Unable to parse the XML query.", e); } String queryName = epcisq.getElementsByTagName("queryName").item(0).getTextContent(); Element params = (Element) epcisq.getElementsByTagName("params").item(0); QueryParam[] queryParams = handleParams(params); Poll poll = new Poll(queryName, queryParams); if (LOG.isDebugEnabled()) { LOG.debug("submitting " + queryParams.length + " query parameters to the query service:"); for (int i = 0; i < queryParams.length; i++) { LOG.debug("param" + i + ": [" + queryParams[i].getName() + ", " + queryParams[i].getValue() + "]"); } } EPCISServiceBindingStub stub = (EPCISServiceBindingStub) service.getEPCglobalEPCISServicePort(); QueryResults response = stub.poll(poll); return response; } /** * @see org.accada.epcis.queryclient.QueryClientInterface#subscribeQuery(java.io.InputStream) */ public void subscribeQuery(InputStream request) throws ServiceException, QueryTooComplexException, ImplementationException, InvalidURIException, SubscribeNotPermittedException, SubscriptionControlsException, QueryParameterException, ValidationException, SecurityException, DuplicateSubscriptionException, NoSuchNameException, RemoteException { clearParameters(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document epcisq; try { DocumentBuilder builder = factory.newDocumentBuilder(); epcisq = builder.parse(request); } catch (Exception e) { throw new RuntimeException("Unable to parse the XML query.", e); } String queryName = epcisq.getElementsByTagName("queryName").item(0).getTextContent(); Element params = (Element) epcisq.getElementsByTagName("params").item(0); QueryParam[] queryParams = handleParams(params); URI dest = handleUri(epcisq.getElementsByTagName("dest").item(0)); Element controlsNode = (Element) epcisq.getElementsByTagName("controls").item( 0); SubscriptionControls controls = handleControls(controlsNode); String subscrId = null; Node subscribeIdNode = epcisq.getElementsByTagName("subscriptionID").item( 0); if (subscribeIdNode != null) { subscrId = subscribeIdNode.getTextContent(); } Subscribe subscribe = new Subscribe(queryName, queryParams, dest, controls, subscrId); if (LOG.isDebugEnabled()) { LOG.debug("submitting " + queryParams.length + " query parameters to the query service:"); for (int i = 0; i < queryParams.length; i++) { LOG.debug("param" + i + ": [" + queryParams[i].getName() + ", " + queryParams[i].getValue() + "]"); } } EPCISServiceBindingStub stub = (EPCISServiceBindingStub) service.getEPCglobalEPCISServicePort(); stub.subscribe(subscribe); } private SubscriptionControls handleControls(Element controlsNode) { Element scheduleNode = (Element) controlsNode.getElementsByTagName( "schedule").item(0); QuerySchedule schedule = handleSchedule(scheduleNode); URI trigger = null; Node triggerNode = controlsNode.getElementsByTagName("trigger").item(0); if (triggerNode != null) { trigger = handleUri(triggerNode); } Node timeNode = controlsNode.getElementsByTagName("initialRecordTime").item( 0); Calendar initialRecordTime = null; try { initialRecordTime = handleTime(timeNode); } catch (ParseException e) { String msg = "Unable to parse time value for 'initialRecordTime': " + e.getMessage(); LOG.error(msg, e); throw new RuntimeException(msg, e); } String boolStr = controlsNode.getElementsByTagName("reportIfEmpty").item( 0).getTextContent(); boolean reportIfEmpty = Boolean.parseBoolean(boolStr); // TODO handle extension SubscriptionControlsExtensionType ext = null; // TODO handle message MessageElement[] msg = null; SubscriptionControls controls = new SubscriptionControls(schedule, trigger, initialRecordTime, reportIfEmpty, ext, msg); return controls; } private QuerySchedule handleSchedule(Element scheduleNode) { QuerySchedule schedule = null; if (scheduleNode != null) { String sec = null; Node secNode = scheduleNode.getElementsByTagName("second").item(0); if (secNode != null) { sec = secNode.getTextContent(); } String min = null; Node minNode = scheduleNode.getElementsByTagName("minute").item(0); if (minNode != null) { min = minNode.getTextContent(); } String hr = null; Node hrNode = scheduleNode.getElementsByTagName("hour").item(0); if (hrNode != null) { hr = hrNode.getTextContent(); } String dom = null; Node domNode = scheduleNode.getElementsByTagName("dayOfMonth").item( 0); if (domNode != null) { dom = domNode.getTextContent(); } String m = null; Node mNode = scheduleNode.getElementsByTagName("month").item(0); if (mNode != null) { m = mNode.getTextContent(); } String dow = null; Node dowNode = scheduleNode.getElementsByTagName("dayOfWeek").item( 0); if (dowNode != null) { dow = dowNode.getTextContent(); } // TODO handle extension QueryScheduleExtensionType extension = null; // TODO handle message MessageElement[] msg = null; schedule = new QuerySchedule(sec, min, hr, dom, m, dow, extension, msg); } return schedule; } private URI handleUri(Node node) { URI uri = null; if (node != null) { try { uri = new URI(node.getTextContent()); } catch (MalformedURIException e) { throw new RuntimeException("URI '" + node.getTextContent() + "' is not valid.", e); } } return uri; } /** * Parses an event field containing a time value. * * @param eventTimeNode * The Node with the time value. * @return A Calendar representing the time value. */ private Calendar handleTime(final Node eventTimeNode) throws ParseException { Calendar cal = null; if (eventTimeNode != null) { String eventTimeStr = eventTimeNode.getTextContent(); cal = TimeParser.parseAsCalendar(eventTimeStr); } return cal; } /** * Reset the query arguments. */ public void clearParameters() { queryParamsVector.clear(); } /** * Add a new query parameter. * * @param param * The query parameter to add. */ public void addParameter(QueryParam param) { queryParamsVector.add(param); } }
true
true
private Object parseParamValue(Element valueElement) { Object paramValue = null; // check if we have an array of strings NodeList stringNodes = valueElement.getElementsByTagName("string"); int size = stringNodes.getLength(); if (size > 0) { String[] strings = new String[size]; boolean[] noHackAroundBugs = new boolean[size]; for (int i = 0; i < size; i++) { String string = stringNodes.item(0).getTextContent(); strings[i] = string; noHackAroundBugs[i] = true; if (LOG.isDebugEnabled()) { LOG.debug("found parameter value <string>" + string + "</string>"); } } paramValue = new ArrayOfString(strings, noHackAroundBugs); } else { // check if we have an Integer try { paramValue = Integer.parseInt(valueElement.getTextContent()); if (LOG.isDebugEnabled()) { LOG.debug("found parameter value (Integer) " + paramValue); } } catch (Exception e) { // check if we have a time value try { paramValue = handleTime(valueElement); if (LOG.isDebugEnabled()) { LOG.debug("found parameter value (Calendar) " + paramValue); } } catch (Exception e1) { // check if we have an URI try { paramValue = handleUri(valueElement); if (LOG.isDebugEnabled()) { LOG.debug("found parameter value (URI) " + paramValue); } } catch (Exception e2) { // ok lets take it as String paramValue = valueElement.getTextContent(); if (LOG.isDebugEnabled()) { LOG.debug("found parameter value (String) " + paramValue); } } } } } return paramValue; }
private Object parseParamValue(Element valueElement) { Object paramValue = null; // check if we have an array of strings NodeList stringNodes = valueElement.getElementsByTagName("string"); int size = stringNodes.getLength(); if (size > 0) { String[] strings = new String[size]; boolean[] noHackAroundBugs = new boolean[size]; for (int i = 0; i < size; i++) { String string = stringNodes.item(i).getTextContent(); strings[i] = string; noHackAroundBugs[i] = true; if (LOG.isDebugEnabled()) { LOG.debug("found parameter value <string>" + string + "</string>"); } } paramValue = new ArrayOfString(strings, noHackAroundBugs); } else { // check if we have an Integer try { paramValue = Integer.parseInt(valueElement.getTextContent()); if (LOG.isDebugEnabled()) { LOG.debug("found parameter value (Integer) " + paramValue); } } catch (Exception e) { // check if we have a time value try { paramValue = handleTime(valueElement); if (LOG.isDebugEnabled()) { LOG.debug("found parameter value (Calendar) " + paramValue); } } catch (Exception e1) { // check if we have an URI try { paramValue = handleUri(valueElement); if (LOG.isDebugEnabled()) { LOG.debug("found parameter value (URI) " + paramValue); } } catch (Exception e2) { // ok lets take it as String paramValue = valueElement.getTextContent(); if (LOG.isDebugEnabled()) { LOG.debug("found parameter value (String) " + paramValue); } } } } } return paramValue; }
diff --git a/src/org/fbreader/formats/fb2/FB2Reader.java b/src/org/fbreader/formats/fb2/FB2Reader.java index 700b917d..5c014f49 100644 --- a/src/org/fbreader/formats/fb2/FB2Reader.java +++ b/src/org/fbreader/formats/fb2/FB2Reader.java @@ -1,359 +1,359 @@ package org.fbreader.formats.fb2; import java.util.Map; import java.util.Set; import org.fbreader.bookmodel.BookModel; import org.fbreader.bookmodel.BookReader; import org.fbreader.bookmodel.FBTextKind; import org.zlibrary.core.xml.ZLXMLReader; import org.zlibrary.text.model.ZLTextParagraph; public class FB2Reader extends ZLXMLReader { private BookReader myModelReader = new BookReader(new BookModel()); // private String myFileName; private boolean myInsidePoem = false; private boolean myInsideTitle = false; private int myBodyCounter = 0; private boolean myReadMainText = false; private int mySectionDepth = 0; private boolean mySectionStarted = false; private byte myHyperlinkType; private Base64EncodedImage myCurrentImage; private boolean myInsideCoverpage = false; private boolean myProcessingImage = false; private final StringBuffer myImageBuffer = new StringBuffer(); private String myCoverImageReference; private int myParagraphsBeforeBodyNumber = Integer.MAX_VALUE; private FB2Tag getTag(String s) { if (s.contains("-")) { s = s.replace('-', '_'); } return FB2Tag.valueOf(s.toUpperCase()); } private String reference(Map<String, String> attributes) { Set<String> keys = attributes.keySet(); for (String s : keys) { if (s.endsWith(":href")) { return attributes.get(s); } } return ""; } // private BookModel myBookModel = new BookModel(); @Override public void characterDataHandler(char[] ch, int start, int length) { if (length > 0 && myProcessingImage) { myImageBuffer.append(String.valueOf(ch, start, length)); } else { myModelReader.addData(String.valueOf(ch, start, length)); } } @Override public void endElementHandler(String tagName) { FB2Tag tag; try { tag = getTag(tagName); } catch (IllegalArgumentException e) { return; } switch (tag) { case P: myModelReader.endParagraph(); break; case SUB: myModelReader.addControl(FBTextKind.SUB, false); break; case SUP: myModelReader.addControl(FBTextKind.SUP, false); break; case CODE: myModelReader.addControl(FBTextKind.CODE, false); break; case EMPHASIS: myModelReader.addControl(FBTextKind.EMPHASIS, false); break; case STRONG: myModelReader.addControl(FBTextKind.STRONG, false); break; case STRIKETHROUGH: myModelReader.addControl(FBTextKind.STRIKETHROUGH, false); break; case V: case SUBTITLE: case TEXT_AUTHOR: case DATE: myModelReader.popKind(); myModelReader.endParagraph(); break; case CITE: case EPIGRAPH: myModelReader.popKind(); break; case POEM: myInsidePoem = false; break; case STANZA: myModelReader.beginParagraph(ZLTextParagraph.Kind.AFTER_SKIP_PARAGRAPH); myModelReader.endParagraph(); myModelReader.popKind(); break; case SECTION: if (myReadMainText) { myModelReader.endContentsParagraph(); --mySectionDepth; mySectionStarted = false; } else { myModelReader.unsetCurrentTextModel(); } break; case ANNOTATION: myModelReader.popKind(); if (myBodyCounter == 0) { myModelReader.insertEndOfSectionParagraph(); myModelReader.unsetCurrentTextModel(); } break; case TITLE: myModelReader.popKind(); myModelReader.exitTitle(); myInsideTitle = false; break; case BODY: myModelReader.popKind(); myReadMainText = false; myModelReader.unsetCurrentTextModel(); break; case A: myModelReader.addControl(myHyperlinkType, false); break; case COVERPAGE: if (myBodyCounter == 0) { myInsideCoverpage = false; myModelReader.insertEndOfSectionParagraph(); myModelReader.unsetCurrentTextModel(); } break; case BINARY: if ((myImageBuffer.length() != 0) && (myCurrentImage != null)) { myCurrentImage.addData(myImageBuffer); myImageBuffer.delete(0, myImageBuffer.length()); myCurrentImage = null; } myProcessingImage = false; break; default: break; } } @Override public void startElementHandler(String tagName, Map<String, String> attributes) { String id = attributes.get("id"); if (id != null) { if (!myReadMainText) { myModelReader.setFootnoteTextModel(id); } myModelReader.addHyperlinkLabel(id); } FB2Tag tag; try { tag = getTag(tagName); } catch (IllegalArgumentException e) { return; } switch (tag) { case P: if (mySectionStarted) { mySectionStarted = false; } else if (myInsideTitle) { myModelReader.addContentsData(" "); } myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case SUB: myModelReader.addControl(FBTextKind.SUB, true); break; case SUP: myModelReader.addControl(FBTextKind.SUP, true); break; case CODE: myModelReader.addControl(FBTextKind.CODE, true); break; case EMPHASIS: myModelReader.addControl(FBTextKind.EMPHASIS, true); break; case STRONG: myModelReader.addControl(FBTextKind.STRONG, true); break; case STRIKETHROUGH: myModelReader.addControl(FBTextKind.STRIKETHROUGH, true); break; case V: myModelReader.pushKind(FBTextKind.VERSE); myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case TEXT_AUTHOR: myModelReader.pushKind(FBTextKind.AUTHOR); myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case SUBTITLE: myModelReader.pushKind(FBTextKind.SUBTITLE); myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case DATE: myModelReader.pushKind(FBTextKind.DATE); myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case EMPTY_LINE: myModelReader.beginParagraph(ZLTextParagraph.Kind.EMPTY_LINE_PARAGRAPH); myModelReader.endParagraph(); break; case CITE: myModelReader.pushKind(FBTextKind.CITE); break; case EPIGRAPH: myModelReader.pushKind(FBTextKind.EPIGRAPH); break; case POEM: myInsidePoem = true; break; case STANZA: myModelReader.pushKind(FBTextKind.STANZA); myModelReader.beginParagraph(ZLTextParagraph.Kind.BEFORE_SKIP_PARAGRAPH); myModelReader.endParagraph(); break; case SECTION: if (myReadMainText) { myModelReader.insertEndOfSectionParagraph(); ++mySectionDepth; myModelReader.beginContentsParagraph(); mySectionStarted = true; } break; case ANNOTATION: if (myBodyCounter == 0) { myModelReader.setMainTextModel(); } myModelReader.pushKind(FBTextKind.ANNOTATION); break; case TITLE: if (myInsidePoem) { myModelReader.pushKind(FBTextKind.POEM_TITLE); } else if (mySectionDepth == 0) { myModelReader.insertEndOfSectionParagraph(); myModelReader.pushKind(FBTextKind.TITLE); } else { myModelReader.pushKind(FBTextKind.SECTION_TITLE); myInsideTitle = true; myModelReader.enterTitle(); } break; case BODY: ++myBodyCounter; myParagraphsBeforeBodyNumber = myModelReader.getModel().getBookModel().getParagraphsNumber(); if ((myBodyCounter == 1) || (attributes.get("name") == null)) { myModelReader.setMainTextModel(); myReadMainText = true; } myModelReader.pushKind(FBTextKind.REGULAR); break; case A: String ref = reference(attributes); - if (!ref.equals("")) { + if ((ref != null) && !ref.isEmpty()) { if (ref.charAt(0) == '#') { myHyperlinkType = FBTextKind.FOOTNOTE; ref = ref.substring(1); } else { myHyperlinkType = FBTextKind.EXTERNAL_HYPERLINK; } myModelReader.addHyperlinkControl(myHyperlinkType, ref); } else { myHyperlinkType = FBTextKind.FOOTNOTE; myModelReader.addControl(myHyperlinkType, true); } break; case COVERPAGE: if (myBodyCounter == 0) { myInsideCoverpage = true; myModelReader.setMainTextModel(); } break; case IMAGE: String imgRef = reference(attributes); String vOffset = attributes.get("voffset"); short offset = 0; try { offset = Short.valueOf(vOffset); } catch (NumberFormatException e) { } - if ((imgRef != null) && (imgRef.charAt(0) == '#')) { + if ((imgRef != null) && !imgRef.isEmpty() && (imgRef.charAt(0) == '#')) { imgRef = imgRef.substring(1); if (!imgRef.equals(myCoverImageReference) || myParagraphsBeforeBodyNumber != myModelReader.getModel().getBookModel().getParagraphsNumber()) { myModelReader.addImageReference(imgRef, offset); } if (myInsideCoverpage) { myCoverImageReference = imgRef; } } break; case BINARY: String contentType = attributes.get("content-type"); String imgId = attributes.get("id"); if ((contentType != null) && (id != null)) { myCurrentImage = new Base64EncodedImage(contentType); myModelReader.addImage(imgId, myCurrentImage); myProcessingImage = true; } break; default: break; } } public BookModel readBook(String fileName) { long start = System.currentTimeMillis(); boolean success = read(fileName); System.err.println("loading book time = " + (System.currentTimeMillis() - start)); return success ? myModelReader.getModel() : null; } }
false
true
public void startElementHandler(String tagName, Map<String, String> attributes) { String id = attributes.get("id"); if (id != null) { if (!myReadMainText) { myModelReader.setFootnoteTextModel(id); } myModelReader.addHyperlinkLabel(id); } FB2Tag tag; try { tag = getTag(tagName); } catch (IllegalArgumentException e) { return; } switch (tag) { case P: if (mySectionStarted) { mySectionStarted = false; } else if (myInsideTitle) { myModelReader.addContentsData(" "); } myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case SUB: myModelReader.addControl(FBTextKind.SUB, true); break; case SUP: myModelReader.addControl(FBTextKind.SUP, true); break; case CODE: myModelReader.addControl(FBTextKind.CODE, true); break; case EMPHASIS: myModelReader.addControl(FBTextKind.EMPHASIS, true); break; case STRONG: myModelReader.addControl(FBTextKind.STRONG, true); break; case STRIKETHROUGH: myModelReader.addControl(FBTextKind.STRIKETHROUGH, true); break; case V: myModelReader.pushKind(FBTextKind.VERSE); myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case TEXT_AUTHOR: myModelReader.pushKind(FBTextKind.AUTHOR); myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case SUBTITLE: myModelReader.pushKind(FBTextKind.SUBTITLE); myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case DATE: myModelReader.pushKind(FBTextKind.DATE); myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case EMPTY_LINE: myModelReader.beginParagraph(ZLTextParagraph.Kind.EMPTY_LINE_PARAGRAPH); myModelReader.endParagraph(); break; case CITE: myModelReader.pushKind(FBTextKind.CITE); break; case EPIGRAPH: myModelReader.pushKind(FBTextKind.EPIGRAPH); break; case POEM: myInsidePoem = true; break; case STANZA: myModelReader.pushKind(FBTextKind.STANZA); myModelReader.beginParagraph(ZLTextParagraph.Kind.BEFORE_SKIP_PARAGRAPH); myModelReader.endParagraph(); break; case SECTION: if (myReadMainText) { myModelReader.insertEndOfSectionParagraph(); ++mySectionDepth; myModelReader.beginContentsParagraph(); mySectionStarted = true; } break; case ANNOTATION: if (myBodyCounter == 0) { myModelReader.setMainTextModel(); } myModelReader.pushKind(FBTextKind.ANNOTATION); break; case TITLE: if (myInsidePoem) { myModelReader.pushKind(FBTextKind.POEM_TITLE); } else if (mySectionDepth == 0) { myModelReader.insertEndOfSectionParagraph(); myModelReader.pushKind(FBTextKind.TITLE); } else { myModelReader.pushKind(FBTextKind.SECTION_TITLE); myInsideTitle = true; myModelReader.enterTitle(); } break; case BODY: ++myBodyCounter; myParagraphsBeforeBodyNumber = myModelReader.getModel().getBookModel().getParagraphsNumber(); if ((myBodyCounter == 1) || (attributes.get("name") == null)) { myModelReader.setMainTextModel(); myReadMainText = true; } myModelReader.pushKind(FBTextKind.REGULAR); break; case A: String ref = reference(attributes); if (!ref.equals("")) { if (ref.charAt(0) == '#') { myHyperlinkType = FBTextKind.FOOTNOTE; ref = ref.substring(1); } else { myHyperlinkType = FBTextKind.EXTERNAL_HYPERLINK; } myModelReader.addHyperlinkControl(myHyperlinkType, ref); } else { myHyperlinkType = FBTextKind.FOOTNOTE; myModelReader.addControl(myHyperlinkType, true); } break; case COVERPAGE: if (myBodyCounter == 0) { myInsideCoverpage = true; myModelReader.setMainTextModel(); } break; case IMAGE: String imgRef = reference(attributes); String vOffset = attributes.get("voffset"); short offset = 0; try { offset = Short.valueOf(vOffset); } catch (NumberFormatException e) { } if ((imgRef != null) && (imgRef.charAt(0) == '#')) { imgRef = imgRef.substring(1); if (!imgRef.equals(myCoverImageReference) || myParagraphsBeforeBodyNumber != myModelReader.getModel().getBookModel().getParagraphsNumber()) { myModelReader.addImageReference(imgRef, offset); } if (myInsideCoverpage) { myCoverImageReference = imgRef; } } break; case BINARY: String contentType = attributes.get("content-type"); String imgId = attributes.get("id"); if ((contentType != null) && (id != null)) { myCurrentImage = new Base64EncodedImage(contentType); myModelReader.addImage(imgId, myCurrentImage); myProcessingImage = true; } break; default: break; } }
public void startElementHandler(String tagName, Map<String, String> attributes) { String id = attributes.get("id"); if (id != null) { if (!myReadMainText) { myModelReader.setFootnoteTextModel(id); } myModelReader.addHyperlinkLabel(id); } FB2Tag tag; try { tag = getTag(tagName); } catch (IllegalArgumentException e) { return; } switch (tag) { case P: if (mySectionStarted) { mySectionStarted = false; } else if (myInsideTitle) { myModelReader.addContentsData(" "); } myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case SUB: myModelReader.addControl(FBTextKind.SUB, true); break; case SUP: myModelReader.addControl(FBTextKind.SUP, true); break; case CODE: myModelReader.addControl(FBTextKind.CODE, true); break; case EMPHASIS: myModelReader.addControl(FBTextKind.EMPHASIS, true); break; case STRONG: myModelReader.addControl(FBTextKind.STRONG, true); break; case STRIKETHROUGH: myModelReader.addControl(FBTextKind.STRIKETHROUGH, true); break; case V: myModelReader.pushKind(FBTextKind.VERSE); myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case TEXT_AUTHOR: myModelReader.pushKind(FBTextKind.AUTHOR); myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case SUBTITLE: myModelReader.pushKind(FBTextKind.SUBTITLE); myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case DATE: myModelReader.pushKind(FBTextKind.DATE); myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case EMPTY_LINE: myModelReader.beginParagraph(ZLTextParagraph.Kind.EMPTY_LINE_PARAGRAPH); myModelReader.endParagraph(); break; case CITE: myModelReader.pushKind(FBTextKind.CITE); break; case EPIGRAPH: myModelReader.pushKind(FBTextKind.EPIGRAPH); break; case POEM: myInsidePoem = true; break; case STANZA: myModelReader.pushKind(FBTextKind.STANZA); myModelReader.beginParagraph(ZLTextParagraph.Kind.BEFORE_SKIP_PARAGRAPH); myModelReader.endParagraph(); break; case SECTION: if (myReadMainText) { myModelReader.insertEndOfSectionParagraph(); ++mySectionDepth; myModelReader.beginContentsParagraph(); mySectionStarted = true; } break; case ANNOTATION: if (myBodyCounter == 0) { myModelReader.setMainTextModel(); } myModelReader.pushKind(FBTextKind.ANNOTATION); break; case TITLE: if (myInsidePoem) { myModelReader.pushKind(FBTextKind.POEM_TITLE); } else if (mySectionDepth == 0) { myModelReader.insertEndOfSectionParagraph(); myModelReader.pushKind(FBTextKind.TITLE); } else { myModelReader.pushKind(FBTextKind.SECTION_TITLE); myInsideTitle = true; myModelReader.enterTitle(); } break; case BODY: ++myBodyCounter; myParagraphsBeforeBodyNumber = myModelReader.getModel().getBookModel().getParagraphsNumber(); if ((myBodyCounter == 1) || (attributes.get("name") == null)) { myModelReader.setMainTextModel(); myReadMainText = true; } myModelReader.pushKind(FBTextKind.REGULAR); break; case A: String ref = reference(attributes); if ((ref != null) && !ref.isEmpty()) { if (ref.charAt(0) == '#') { myHyperlinkType = FBTextKind.FOOTNOTE; ref = ref.substring(1); } else { myHyperlinkType = FBTextKind.EXTERNAL_HYPERLINK; } myModelReader.addHyperlinkControl(myHyperlinkType, ref); } else { myHyperlinkType = FBTextKind.FOOTNOTE; myModelReader.addControl(myHyperlinkType, true); } break; case COVERPAGE: if (myBodyCounter == 0) { myInsideCoverpage = true; myModelReader.setMainTextModel(); } break; case IMAGE: String imgRef = reference(attributes); String vOffset = attributes.get("voffset"); short offset = 0; try { offset = Short.valueOf(vOffset); } catch (NumberFormatException e) { } if ((imgRef != null) && !imgRef.isEmpty() && (imgRef.charAt(0) == '#')) { imgRef = imgRef.substring(1); if (!imgRef.equals(myCoverImageReference) || myParagraphsBeforeBodyNumber != myModelReader.getModel().getBookModel().getParagraphsNumber()) { myModelReader.addImageReference(imgRef, offset); } if (myInsideCoverpage) { myCoverImageReference = imgRef; } } break; case BINARY: String contentType = attributes.get("content-type"); String imgId = attributes.get("id"); if ((contentType != null) && (id != null)) { myCurrentImage = new Base64EncodedImage(contentType); myModelReader.addImage(imgId, myCurrentImage); myProcessingImage = true; } break; default: break; } }
diff --git a/io/rampant/bukkit/orchard/Tree.java b/io/rampant/bukkit/orchard/Tree.java index 29d2c96..f0980cd 100644 --- a/io/rampant/bukkit/orchard/Tree.java +++ b/io/rampant/bukkit/orchard/Tree.java @@ -1,59 +1,59 @@ package io.rampant.bukkit.orchard; import java.util.Map; import java.util.Random; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.util.config.ConfigurationNode; /** * * @author jonathan */ public class Tree { public static void pruneLeaf(Block leafBlock, Boolean decay, Player player) { int leafType = (leafBlock.getData() & 3); if( !Orchard.LEAF_MAP.containsKey(leafType) ) { return; } boolean wieldingShears = (null != player) && (player.getItemInHand().getType() == Material.SHEARS); Random generator = new Random(); double chance = generator.nextDouble() * 100.0; double cumulativeChance = 0.0; String path = Orchard.LEAF_MAP.get(leafType) + (decay ? ".decay" : ".break"); Map<String, ConfigurationNode> blocks = Orchard.config.getNodes(path); if( null == blocks || blocks.isEmpty() ) { return; } for( Map.Entry<String, ConfigurationNode> block : blocks.entrySet() ) { ConfigurationNode node = block.getValue(); double thisChance = node.getDouble("chance", 0.0); if( chance > (cumulativeChance + thisChance) ) { cumulativeChance += thisChance; continue; } - if( decay || node.getBoolean("shears", false) || wieldingShears ) { + if( decay || !node.getBoolean("shears", false) || wieldingShears ) { Material itemType; try { itemType = Material.valueOf(block.getKey()); dropItemFromLeaf(leafBlock, itemType, node.getInt("data", -1), node.getInt("amount", 1)); } catch( IllegalArgumentException e ) { } } return; } } protected static void dropItemFromLeaf(Block block, Material itemType, int metaData, int amount) { block.getWorld().dropItemNaturally(block.getLocation(), new ItemStack(itemType, amount, (short) 0, (byte) metaData)); } }
true
true
public static void pruneLeaf(Block leafBlock, Boolean decay, Player player) { int leafType = (leafBlock.getData() & 3); if( !Orchard.LEAF_MAP.containsKey(leafType) ) { return; } boolean wieldingShears = (null != player) && (player.getItemInHand().getType() == Material.SHEARS); Random generator = new Random(); double chance = generator.nextDouble() * 100.0; double cumulativeChance = 0.0; String path = Orchard.LEAF_MAP.get(leafType) + (decay ? ".decay" : ".break"); Map<String, ConfigurationNode> blocks = Orchard.config.getNodes(path); if( null == blocks || blocks.isEmpty() ) { return; } for( Map.Entry<String, ConfigurationNode> block : blocks.entrySet() ) { ConfigurationNode node = block.getValue(); double thisChance = node.getDouble("chance", 0.0); if( chance > (cumulativeChance + thisChance) ) { cumulativeChance += thisChance; continue; } if( decay || node.getBoolean("shears", false) || wieldingShears ) { Material itemType; try { itemType = Material.valueOf(block.getKey()); dropItemFromLeaf(leafBlock, itemType, node.getInt("data", -1), node.getInt("amount", 1)); } catch( IllegalArgumentException e ) { } } return; } }
public static void pruneLeaf(Block leafBlock, Boolean decay, Player player) { int leafType = (leafBlock.getData() & 3); if( !Orchard.LEAF_MAP.containsKey(leafType) ) { return; } boolean wieldingShears = (null != player) && (player.getItemInHand().getType() == Material.SHEARS); Random generator = new Random(); double chance = generator.nextDouble() * 100.0; double cumulativeChance = 0.0; String path = Orchard.LEAF_MAP.get(leafType) + (decay ? ".decay" : ".break"); Map<String, ConfigurationNode> blocks = Orchard.config.getNodes(path); if( null == blocks || blocks.isEmpty() ) { return; } for( Map.Entry<String, ConfigurationNode> block : blocks.entrySet() ) { ConfigurationNode node = block.getValue(); double thisChance = node.getDouble("chance", 0.0); if( chance > (cumulativeChance + thisChance) ) { cumulativeChance += thisChance; continue; } if( decay || !node.getBoolean("shears", false) || wieldingShears ) { Material itemType; try { itemType = Material.valueOf(block.getKey()); dropItemFromLeaf(leafBlock, itemType, node.getInt("data", -1), node.getInt("amount", 1)); } catch( IllegalArgumentException e ) { } } return; } }
diff --git a/src/com/reil/bukkit/rTriggers/rPropertiesFile.java b/src/com/reil/bukkit/rTriggers/rPropertiesFile.java index 7e3137e..b73a76e 100644 --- a/src/com/reil/bukkit/rTriggers/rPropertiesFile.java +++ b/src/com/reil/bukkit/rTriggers/rPropertiesFile.java @@ -1,186 +1,186 @@ package com.reil.bukkit.rTriggers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Set; import java.util.logging.Logger; import com.reil.bukkit.rParser.rParser; public class rPropertiesFile { HashMap<String,ArrayList<String>> Properties = new HashMap<String,ArrayList<String>>(); String fileName; Logger log = Logger.getLogger("Minecraft"); File file; /** * Creates or opens a properties file using specified filename * * @param fileName */ public rPropertiesFile(String fileName) { this.fileName = fileName; file = new File(fileName); if (file.exists()) { try { load(); } catch (IOException ex) { log.severe("[PropertiesFile] Unable to load " + fileName + "!"); } } else { try { file.createNewFile(); Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "UTF8")); Date timestamp = new Date(); writer.write("# Properties file generated on " + timestamp.toString()); writer.close(); } catch (IOException ex) { log.severe("[rPropertiesFile] Unable to create file " + fileName + "!"); } } } String[] load() throws IOException { /* Go through, line by line. * If the line starts with # or !, then save the line in list * If the line has an assignment, put the name here. */ Properties.clear(); ArrayList<String> messages = new ArrayList<String>(); BufferedReader reader; reader = new BufferedReader(new FileReader(fileName)); String tempLine; //Cycle through complete contents of the file. while ((tempLine = reader.readLine()) != null) { /***************** * Credit for original line-continuation implementation goes to ioScream!*/ // Check for multiple lines with <<;>> and recreate them as one line. StringBuilder concatMe = new StringBuilder(tempLine); while (concatMe.toString().endsWith("$")){ //Skip next element because it's been merged concatMe.deleteCharAt(concatMe.length() - 1); if ((tempLine = reader.readLine()) != null) concatMe.append(tempLine); } String line = concatMe.toString(); // Line is now built, read it in as usual. if (line.startsWith("#")|| line.isEmpty() || line.startsWith("\n") || line.startsWith("\r")) { } else { /* TODO: Error checking */ String [] split = line.split("="); if (split.length >= 2){ String PropertySide = split[0]; String Value = rParser.combineSplit(1, split, "="); for (String Property : PropertySide.split(",")) { - if (Property.startsWith("<<")) Property = Property.toLowerCase(); + if (Property.startsWith("<<") && !Property.startsWith("<<list")) Property = Property.toLowerCase(); if (Properties.containsKey(Property)){ Properties.get(Property).add(Value); } else { ArrayList<String> newList = new ArrayList<String>(); newList.add(Value); Properties.put(Property, newList); } } messages.add(Value); } } } reader.close(); return messages.toArray(new String[messages.size()]); } void save(){ } boolean getBoolean(java.lang.String key) { return true; } boolean getBoolean(java.lang.String key, boolean value) { return true; } int getInt(java.lang.String key){ return 0; } int getInt(java.lang.String key, int value){ return 0; } long getLong(java.lang.String key) { return 0; } long getLong(java.lang.String key, long value){ return 0; } String getString(java.lang.String key) { ArrayList<String> arrayList = Properties.get(key); return arrayList.get(0); } String getString(java.lang.String key, java.lang.String value) { if (Properties.containsKey(key)){ ArrayList<String> arrayList = Properties.get(key); return arrayList.get(0); } else { setString(key, value); } return value; } String [] getStrings(String key) { if (Properties.containsKey(key)) { ArrayList <String> rt = Properties.get(key); return rt.toArray(new String[rt.size()]); } else return null; } String [] getStrings(String [] keys){ ArrayList <String> returnMe = new ArrayList<String>(); for (String key : keys) { if (Properties.containsKey(key)) { ArrayList <String> rt = Properties.get(key); returnMe.addAll(rt); } } String[] returnArray = new String[returnMe.size()]; return returnMe.toArray(returnArray); } String [] getKeys() { Set<String> keys = Properties.keySet(); String [] keyArray = new String[keys.size()]; return keys.toArray(keyArray); } boolean keyExists(java.lang.String key) { return Properties.containsKey(key); } void setBoolean(java.lang.String key, boolean value) { } void setInt(java.lang.String key, int value) { } void setLong(java.lang.String key, long value) { } void setString(java.lang.String key, java.lang.String value) { } }
true
true
String[] load() throws IOException { /* Go through, line by line. * If the line starts with # or !, then save the line in list * If the line has an assignment, put the name here. */ Properties.clear(); ArrayList<String> messages = new ArrayList<String>(); BufferedReader reader; reader = new BufferedReader(new FileReader(fileName)); String tempLine; //Cycle through complete contents of the file. while ((tempLine = reader.readLine()) != null) { /***************** * Credit for original line-continuation implementation goes to ioScream!*/ // Check for multiple lines with <<;>> and recreate them as one line. StringBuilder concatMe = new StringBuilder(tempLine); while (concatMe.toString().endsWith("$")){ //Skip next element because it's been merged concatMe.deleteCharAt(concatMe.length() - 1); if ((tempLine = reader.readLine()) != null) concatMe.append(tempLine); } String line = concatMe.toString(); // Line is now built, read it in as usual. if (line.startsWith("#")|| line.isEmpty() || line.startsWith("\n") || line.startsWith("\r")) { } else { /* TODO: Error checking */ String [] split = line.split("="); if (split.length >= 2){ String PropertySide = split[0]; String Value = rParser.combineSplit(1, split, "="); for (String Property : PropertySide.split(",")) { if (Property.startsWith("<<")) Property = Property.toLowerCase(); if (Properties.containsKey(Property)){ Properties.get(Property).add(Value); } else { ArrayList<String> newList = new ArrayList<String>(); newList.add(Value); Properties.put(Property, newList); } } messages.add(Value); } } } reader.close(); return messages.toArray(new String[messages.size()]); }
String[] load() throws IOException { /* Go through, line by line. * If the line starts with # or !, then save the line in list * If the line has an assignment, put the name here. */ Properties.clear(); ArrayList<String> messages = new ArrayList<String>(); BufferedReader reader; reader = new BufferedReader(new FileReader(fileName)); String tempLine; //Cycle through complete contents of the file. while ((tempLine = reader.readLine()) != null) { /***************** * Credit for original line-continuation implementation goes to ioScream!*/ // Check for multiple lines with <<;>> and recreate them as one line. StringBuilder concatMe = new StringBuilder(tempLine); while (concatMe.toString().endsWith("$")){ //Skip next element because it's been merged concatMe.deleteCharAt(concatMe.length() - 1); if ((tempLine = reader.readLine()) != null) concatMe.append(tempLine); } String line = concatMe.toString(); // Line is now built, read it in as usual. if (line.startsWith("#")|| line.isEmpty() || line.startsWith("\n") || line.startsWith("\r")) { } else { /* TODO: Error checking */ String [] split = line.split("="); if (split.length >= 2){ String PropertySide = split[0]; String Value = rParser.combineSplit(1, split, "="); for (String Property : PropertySide.split(",")) { if (Property.startsWith("<<") && !Property.startsWith("<<list")) Property = Property.toLowerCase(); if (Properties.containsKey(Property)){ Properties.get(Property).add(Value); } else { ArrayList<String> newList = new ArrayList<String>(); newList.add(Value); Properties.put(Property, newList); } } messages.add(Value); } } } reader.close(); return messages.toArray(new String[messages.size()]); }
diff --git a/websockets/src/test/java/io/undertow/websockets/utils/WebSocketTestClient.java b/websockets/src/test/java/io/undertow/websockets/utils/WebSocketTestClient.java index 986eff8d1..14320b119 100644 --- a/websockets/src/test/java/io/undertow/websockets/utils/WebSocketTestClient.java +++ b/websockets/src/test/java/io/undertow/websockets/utils/WebSocketTestClient.java @@ -1,184 +1,184 @@ /* * JBoss, Home of Professional Open Source. * Copyright 2012 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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 io.undertow.websockets.utils; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.handler.codec.http.HttpRequestEncoder; import org.jboss.netty.handler.codec.http.HttpResponse; import org.jboss.netty.handler.codec.http.HttpResponseDecoder; import org.jboss.netty.handler.codec.http.websocketx.WebSocketClientHandshaker; import org.jboss.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory; import org.jboss.netty.handler.codec.http.websocketx.WebSocketFrame; import org.jboss.netty.handler.codec.http.websocketx.WebSocketVersion; import org.jboss.netty.util.CharsetUtil; import java.net.InetSocketAddress; import java.net.URI; import java.util.Collections; import java.util.concurrent.CountDownLatch; /** * * Client which can be used to Test a websocket server * * @author <a href="mailto:[email protected]">Norman Maurer</a> */ public final class WebSocketTestClient { private final ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory()); private Channel ch; private final URI uri; private final WebSocketVersion version; public WebSocketTestClient(WebSocketVersion version, URI uri) { this.uri = uri; this.version = version; } /** * Connect the WebSocket client * * @throws Exception */ - public WebSocketTestClient connect() throws Exception { + public WebSocketTestClient connect() throws Exception { String protocol = uri.getScheme(); if (!"ws".equals(protocol)) { throw new IllegalArgumentException("Unsupported protocol: " + protocol); } final WebSocketClientHandshaker handshaker = new WebSocketClientHandshakerFactory().newHandshaker( uri, version, null, false, Collections.<String, String>emptyMap()); final CountDownLatch handshakeLatch = new CountDownLatch(1); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("decoder", new HttpResponseDecoder()); pipeline.addLast("encoder", new HttpRequestEncoder()); pipeline.addLast("ws-handler", new WSClientHandler(handshaker, handshakeLatch)); return pipeline; } }); // Connect System.out.println("WebSocket Client connecting"); ChannelFuture future = bootstrap.connect( new InetSocketAddress(uri.getHost(), uri.getPort())); future.syncUninterruptibly(); ch = future.getChannel(); - handshaker.handshake(ch); + handshaker.handshake(ch).syncUninterruptibly(); handshakeLatch.await(); return this; } /** * Send the WebSocketFrame and call the FrameListener once a frame was received as resposne or * when an Exception was caught. */ public WebSocketTestClient send(WebSocketFrame frame, final FrameListener listener) { ch.getPipeline().addLast("responseHandler", new SimpleChannelUpstreamHandler() { @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { listener.onFrame((WebSocketFrame) e.getMessage()); ctx.getPipeline().remove(this); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { listener.onError(e.getCause()); ctx.getPipeline().remove(this); } }); ChannelFuture cf = ch.write(frame).syncUninterruptibly(); if (!cf.isSuccess()) { listener.onError(cf.getCause()); } return this; } /** * Destroy the client and also close open connections if any exist */ public void destroy() { if (ch != null) { ch.close().syncUninterruptibly(); } bootstrap.releaseExternalResources(); } public interface FrameListener { /** * Is called if an WebSocketFrame was received */ void onFrame(WebSocketFrame frame); /** * Is called if an error accured */ void onError(Throwable t); } private final static class WSClientHandler extends SimpleChannelUpstreamHandler { private final WebSocketClientHandshaker handshaker; private final CountDownLatch handshakeLatch; public WSClientHandler(WebSocketClientHandshaker handshaker, CountDownLatch handshakeLatch) { this.handshaker = handshaker; this.handshakeLatch = handshakeLatch; } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Channel ch = ctx.getChannel(); if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch, (HttpResponse) e.getMessage()); // the handshake response was processed upgrade is complete handshakeLatch.countDown(); return; } if (e.getMessage() instanceof HttpResponse) { HttpResponse response = (HttpResponse) e.getMessage(); throw new Exception("Unexpected HttpResponse (status=" + response.getStatus() + ", content=" + response.getContent().toString(CharsetUtil.UTF_8) + ')'); } // foward to the next handler super.messageReceived(ctx, e); } } }
false
true
public WebSocketTestClient connect() throws Exception { String protocol = uri.getScheme(); if (!"ws".equals(protocol)) { throw new IllegalArgumentException("Unsupported protocol: " + protocol); } final WebSocketClientHandshaker handshaker = new WebSocketClientHandshakerFactory().newHandshaker( uri, version, null, false, Collections.<String, String>emptyMap()); final CountDownLatch handshakeLatch = new CountDownLatch(1); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("decoder", new HttpResponseDecoder()); pipeline.addLast("encoder", new HttpRequestEncoder()); pipeline.addLast("ws-handler", new WSClientHandler(handshaker, handshakeLatch)); return pipeline; } }); // Connect System.out.println("WebSocket Client connecting"); ChannelFuture future = bootstrap.connect( new InetSocketAddress(uri.getHost(), uri.getPort())); future.syncUninterruptibly(); ch = future.getChannel(); handshaker.handshake(ch); handshakeLatch.await(); return this; }
public WebSocketTestClient connect() throws Exception { String protocol = uri.getScheme(); if (!"ws".equals(protocol)) { throw new IllegalArgumentException("Unsupported protocol: " + protocol); } final WebSocketClientHandshaker handshaker = new WebSocketClientHandshakerFactory().newHandshaker( uri, version, null, false, Collections.<String, String>emptyMap()); final CountDownLatch handshakeLatch = new CountDownLatch(1); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("decoder", new HttpResponseDecoder()); pipeline.addLast("encoder", new HttpRequestEncoder()); pipeline.addLast("ws-handler", new WSClientHandler(handshaker, handshakeLatch)); return pipeline; } }); // Connect System.out.println("WebSocket Client connecting"); ChannelFuture future = bootstrap.connect( new InetSocketAddress(uri.getHost(), uri.getPort())); future.syncUninterruptibly(); ch = future.getChannel(); handshaker.handshake(ch).syncUninterruptibly(); handshakeLatch.await(); return this; }
diff --git a/src/main/java/com/me/tft_02/assassin/listeners/TagListener.java b/src/main/java/com/me/tft_02/assassin/listeners/TagListener.java index 8dd7fd9..f318a9d 100644 --- a/src/main/java/com/me/tft_02/assassin/listeners/TagListener.java +++ b/src/main/java/com/me/tft_02/assassin/listeners/TagListener.java @@ -1,48 +1,44 @@ package com.me.tft_02.assassin.listeners; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import com.me.tft_02.assassin.Assassin; import com.me.tft_02.assassin.util.PlayerData; import org.kitteh.tag.PlayerReceiveNameTagEvent; public class TagListener implements Listener { private PlayerData data = new PlayerData(Assassin.p); @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onNameTag(PlayerReceiveNameTagEvent event) { Player namedPlayer = event.getNamedPlayer(); if (data.isAssassin(namedPlayer)) { event.setTag(ChatColor.DARK_RED + "[ASSASSIN] " + data.getKillCount(namedPlayer)); - if (Assassin.p.debug_mode) { - System.out.println("Changed player tag to [ASSASSIN] for " + namedPlayer.getName()); - } + Assassin.p.debug("Changed player tag to [ASSASSIN] for " + namedPlayer.getName()); } else { event.setTag(ChatColor.RESET + namedPlayer.getDisplayName()); - if (Assassin.p.debug_mode) { - System.out.println("Reset player tag for " + namedPlayer.getName()); - } + Assassin.p.debug("Reset player tag for " + namedPlayer.getName()); } // if (!data.isAssassin(player)) { // event.setTag(ChatColor.DARK_GRAY + "PLAYER"); // System.out.println("Changed player tag to Player for " + player.getName()); // } else { // event.setTag(ChatColor.RESET + player.getDisplayName()); // System.out.println("Reset player tag for " + player.getName()); // } // for(Player p : getServer().getOnlinePlayers()){ // if (event.getPlayer().getName().equals(player)) { // event.setTag(ChatColor.DARK_GRAY + "PLAYER"); // } } }
false
true
public void onNameTag(PlayerReceiveNameTagEvent event) { Player namedPlayer = event.getNamedPlayer(); if (data.isAssassin(namedPlayer)) { event.setTag(ChatColor.DARK_RED + "[ASSASSIN] " + data.getKillCount(namedPlayer)); if (Assassin.p.debug_mode) { System.out.println("Changed player tag to [ASSASSIN] for " + namedPlayer.getName()); } } else { event.setTag(ChatColor.RESET + namedPlayer.getDisplayName()); if (Assassin.p.debug_mode) { System.out.println("Reset player tag for " + namedPlayer.getName()); } } // if (!data.isAssassin(player)) { // event.setTag(ChatColor.DARK_GRAY + "PLAYER"); // System.out.println("Changed player tag to Player for " + player.getName()); // } else { // event.setTag(ChatColor.RESET + player.getDisplayName()); // System.out.println("Reset player tag for " + player.getName()); // } // for(Player p : getServer().getOnlinePlayers()){ // if (event.getPlayer().getName().equals(player)) { // event.setTag(ChatColor.DARK_GRAY + "PLAYER"); // } }
public void onNameTag(PlayerReceiveNameTagEvent event) { Player namedPlayer = event.getNamedPlayer(); if (data.isAssassin(namedPlayer)) { event.setTag(ChatColor.DARK_RED + "[ASSASSIN] " + data.getKillCount(namedPlayer)); Assassin.p.debug("Changed player tag to [ASSASSIN] for " + namedPlayer.getName()); } else { event.setTag(ChatColor.RESET + namedPlayer.getDisplayName()); Assassin.p.debug("Reset player tag for " + namedPlayer.getName()); } // if (!data.isAssassin(player)) { // event.setTag(ChatColor.DARK_GRAY + "PLAYER"); // System.out.println("Changed player tag to Player for " + player.getName()); // } else { // event.setTag(ChatColor.RESET + player.getDisplayName()); // System.out.println("Reset player tag for " + player.getName()); // } // for(Player p : getServer().getOnlinePlayers()){ // if (event.getPlayer().getName().equals(player)) { // event.setTag(ChatColor.DARK_GRAY + "PLAYER"); // } }
diff --git a/GAE/src/org/waterforpeople/mapping/app/gwt/server/surveyinstance/SurveyInstanceServiceImpl.java b/GAE/src/org/waterforpeople/mapping/app/gwt/server/surveyinstance/SurveyInstanceServiceImpl.java index 7e80b3b43..1fa686876 100644 --- a/GAE/src/org/waterforpeople/mapping/app/gwt/server/surveyinstance/SurveyInstanceServiceImpl.java +++ b/GAE/src/org/waterforpeople/mapping/app/gwt/server/surveyinstance/SurveyInstanceServiceImpl.java @@ -1,399 +1,402 @@ /* * Copyright (C) 2010-2012 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo FLOW. * * Akvo FLOW is free software: you can redistribute it and modify it under the terms of * the GNU Affero General Public License (AGPL) as published by the Free Software Foundation, * either version 3 of the License or any later version. * * Akvo FLOW 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 included below for more details. * * The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>. */ package org.waterforpeople.mapping.app.gwt.server.surveyinstance; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.waterforpeople.mapping.app.gwt.client.surveyinstance.QuestionAnswerStoreDto; import org.waterforpeople.mapping.app.gwt.client.surveyinstance.SurveyInstanceDto; import org.waterforpeople.mapping.app.gwt.client.surveyinstance.SurveyInstanceService; import org.waterforpeople.mapping.app.util.DtoMarshaller; import org.waterforpeople.mapping.dao.SurveyAttributeMappingDao; import org.waterforpeople.mapping.dao.SurveyInstanceDAO; import org.waterforpeople.mapping.domain.QuestionAnswerStore; import org.waterforpeople.mapping.domain.SurveyAttributeMapping; import org.waterforpeople.mapping.domain.SurveyInstance; import org.waterforpeople.mapping.helper.SurveyEventHelper; import com.gallatinsystems.framework.analytics.summarization.DataSummarizationRequest; import com.gallatinsystems.framework.domain.DataChangeRecord; import com.gallatinsystems.framework.gwt.dto.client.ResponseDto; import com.gallatinsystems.survey.dao.QuestionDao; import com.gallatinsystems.survey.dao.SurveyDAO; import com.gallatinsystems.survey.domain.Question; import com.gallatinsystems.survey.domain.Survey; import com.gallatinsystems.surveyal.app.web.SurveyalRestRequest; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.gwt.user.server.rpc.RemoteServiceServlet; public class SurveyInstanceServiceImpl extends RemoteServiceServlet implements SurveyInstanceService { private static final long serialVersionUID = -9175237700587455358L; private static final Logger log = Logger .getLogger(SurveyInstanceServiceImpl.class); @Override public ResponseDto<ArrayList<SurveyInstanceDto>> listSurveyInstance( Date beginDate, Date toDate, boolean unapprovedOnlyFlag, Long surveyId, String source, String cursorString) { SurveyInstanceDAO dao = new SurveyInstanceDAO(); SurveyDAO surveyDao = new SurveyDAO(); List<Survey> surveyList = surveyDao.list("all"); HashMap<Long, String> surveyMap = new HashMap<Long, String>(); for (Survey s : surveyList) { surveyMap.put(s.getKey().getId(), s.getPath() + "/" + s.getCode()); } List<SurveyInstance> siList = null; if (beginDate == null && toDate == null) { Calendar c = Calendar.getInstance(); c.add(Calendar.YEAR, -90); beginDate = c.getTime(); } siList = dao.listByDateRange(beginDate, toDate, unapprovedOnlyFlag, surveyId, source, cursorString); String newCursor = SurveyInstanceDAO.getCursor(siList); ArrayList<SurveyInstanceDto> siDtoList = new ArrayList<SurveyInstanceDto>(); for (SurveyInstance siItem : siList) { String code = surveyMap.get(siItem.getSurveyId()); SurveyInstanceDto siDto = marshalToDto(siItem); if (code != null) siDto.setSurveyCode(code); siDtoList.add(siDto); } ResponseDto<ArrayList<SurveyInstanceDto>> response = new ResponseDto<ArrayList<SurveyInstanceDto>>(); response.setCursorString(newCursor); response.setPayload(siDtoList); return response; } public List<QuestionAnswerStoreDto> listQuestionsByInstance(Long instanceId) { List<QuestionAnswerStoreDto> questionDtos = new ArrayList<QuestionAnswerStoreDto>(); SurveyInstanceDAO dao = new SurveyInstanceDAO(); List<QuestionAnswerStore> questions = dao.listQuestionAnswerStore( instanceId, null); QuestionDao qDao = new QuestionDao(); if (questions != null && questions.size() > 0) { List<Question> qList = qDao.listQuestionInOrder(questions.get(0) .getSurveyId()); Map<Integer, QuestionAnswerStoreDto> orderedResults = new TreeMap<Integer, QuestionAnswerStoreDto>(); int notFoundCount = 0; if (qList != null) { for (QuestionAnswerStore qas : questions) { QuestionAnswerStoreDto qasDto = new QuestionAnswerStoreDto(); DtoMarshaller.copyToDto(qas, qasDto); int idx = -1 - notFoundCount; for (int i = 0; i < qList.size(); i++) { if (Long.parseLong(qas.getQuestionID()) == qList.get(i) .getKey().getId()) { qasDto.setQuestionText(qList.get(i).getText()); idx = i; break; } } if (idx < 0) { // do this to prevent collisions on the -1 key if there // is more than one questionAnswerStore item that isn't // in the question list notFoundCount++; } orderedResults.put(idx, qasDto); } } questionDtos = new ArrayList<QuestionAnswerStoreDto>( orderedResults.values()); } return questionDtos; } private SurveyInstanceDto marshalToDto(SurveyInstance si) { SurveyInstanceDto siDto = new SurveyInstanceDto(); DtoMarshaller.copyToDto(si, siDto); siDto.setQuestionAnswersStore(null); if (si.getQuestionAnswersStore() != null) { for (QuestionAnswerStore qas : si.getQuestionAnswersStore()) { siDto.addQuestionAnswerStore(marshalToDto(qas)); } } return siDto; } private QuestionAnswerStoreDto marshalToDto(QuestionAnswerStore qas) { QuestionAnswerStoreDto qasDto = new QuestionAnswerStoreDto(); DtoMarshaller.copyToDto(qas, qasDto); return qasDto; } /** * updates the list of QAS dto objects passed in and fires summarization * messages to the async queues */ @Override public List<QuestionAnswerStoreDto> updateQuestions( List<QuestionAnswerStoreDto> dtoList, boolean isApproved) { return updateQuestions(dtoList, isApproved, true); } public List<QuestionAnswerStoreDto> updateQuestions( List<QuestionAnswerStoreDto> dtoList, boolean isApproved, boolean processSummaries) { List<QuestionAnswerStore> domainList = new ArrayList<QuestionAnswerStore>(); for (QuestionAnswerStoreDto dto : dtoList) { + if ("".equals(dto.getValue()) && dto.getOldValue() == null) { + continue; // empty string as value, skipping it + } QuestionAnswerStore answer = new QuestionAnswerStore(); DtoMarshaller.copyToCanonical(answer, dto); if (answer.getValue() != null) { answer.setValue(answer.getValue().replaceAll("\t", "")); } domainList.add(answer); } SurveyInstanceDAO dao = new SurveyInstanceDAO(); dao.save(domainList); // this is not active - questionAnswerSummary objects are updated in bulk // after the import in RawDataSpreadsheetImporter if (isApproved && processSummaries) { SurveyAttributeMappingDao mappingDao = new SurveyAttributeMappingDao(); // now send a change message for each item Queue queue = QueueFactory.getQueue("dataUpdate"); for (QuestionAnswerStoreDto item : dtoList) { DataChangeRecord value = new DataChangeRecord( QuestionAnswerStore.class.getName(), item.getQuestionID(), item.getOldValue(), item.getValue()); queue.add(TaskOptions.Builder .withUrl("/app_worker/dataupdate") .param(DataSummarizationRequest.OBJECT_KEY, item.getQuestionID()) .param(DataSummarizationRequest.OBJECT_TYPE, "QuestionDataChange") .param(DataSummarizationRequest.VALUE_KEY, value.packString())); // see if the question is mapped. And if it is, send an Access // Point // change message SurveyAttributeMapping mapping = mappingDao .findMappingForQuestion(item.getQuestionID()); if (mapping != null) { DataChangeRecord apValue = new DataChangeRecord( "AcessPointUpdate", mapping.getSurveyId() + "|" + mapping.getSurveyQuestionId() + "|" + item.getSurveyInstanceId() + "|" + mapping.getKey().getId(), item.getOldValue(), item.getValue()); queue.add(TaskOptions.Builder .withUrl("/app_worker/dataupdate") .param(DataSummarizationRequest.OBJECT_KEY, item.getQuestionID()) .param(DataSummarizationRequest.OBJECT_TYPE, "AccessPointChange") .param(DataSummarizationRequest.VALUE_KEY, apValue.packString())); } } } return dtoList; } /** * lists all responses for a single question */ @Override public ResponseDto<ArrayList<QuestionAnswerStoreDto>> listResponsesByQuestion( Long questionId, String cursorString) { SurveyInstanceDAO dao = new SurveyInstanceDAO(); List<QuestionAnswerStore> qasList = dao .listQuestionAnswerStoreForQuestion(questionId.toString(), cursorString); String newCursor = SurveyInstanceDAO.getCursor(qasList); ArrayList<QuestionAnswerStoreDto> qasDtoList = new ArrayList<QuestionAnswerStoreDto>(); for (QuestionAnswerStore item : qasList) { qasDtoList.add(marshalToDto(item)); } ResponseDto<ArrayList<QuestionAnswerStoreDto>> response = new ResponseDto<ArrayList<QuestionAnswerStoreDto>>(); response.setCursorString(newCursor); response.setPayload(qasDtoList); return response; } /** * deletes a survey instance. This will only back out Question summaries. To * back out the access point, the AP needs to be deleted manually since it * may have come from multiple instances. */ @Override public void deleteSurveyInstance(Long instanceId) { if (instanceId != null) { SurveyInstanceDAO dao = new SurveyInstanceDAO(); List<QuestionAnswerStore> answers = dao.listQuestionAnswerStore( instanceId, null); if (answers != null) { // back out summaries Queue queue = QueueFactory.getQueue("dataUpdate"); for (QuestionAnswerStore ans : answers) { DataChangeRecord value = new DataChangeRecord( QuestionAnswerStore.class.getName(), ans.getQuestionID(), ans.getValue(), ""); queue.add(TaskOptions.Builder .withUrl("/app_worker/dataupdate") .param(DataSummarizationRequest.OBJECT_KEY, ans.getQuestionID()) .param(DataSummarizationRequest.OBJECT_TYPE, "QuestionDataChange") .param(DataSummarizationRequest.VALUE_KEY, value.packString())); } dao.delete(answers); } SurveyInstance instance = dao.getByKey(instanceId); if (instance != null) { dao.delete(instance); log.log(Level.INFO, "Deleted: " + instanceId); } } } /** * saves a new survey instance and triggers processing * * @param instance * @return */ public SurveyInstanceDto submitSurveyInstance(SurveyInstanceDto instance) { SurveyInstanceDAO dao = new SurveyInstanceDAO(); SurveyInstance domain = new SurveyInstance(); DtoMarshaller.copyToCanonical(domain, instance); if (domain.getCollectionDate() == null) { domain.setCollectionDate(new Date()); } domain = dao.save(domain); instance.setKeyId(domain.getKey().getId()); if (instance.getQuestionAnswersStore() != null) { List<QuestionAnswerStore> answerList = new ArrayList<QuestionAnswerStore>(); for (QuestionAnswerStoreDto ans : instance .getQuestionAnswersStore()) { QuestionAnswerStore store = new QuestionAnswerStore(); if (ans.getCollectionDate() == null) { ans.setCollectionDate(domain.getCollectionDate()); } if (ans.getValue() != null) { ans.setValue(ans.getValue().replaceAll("\t", "")); if (ans.getValue().length() > 500) { ans.setValue(ans.getValue().substring(0, 499)); } } DtoMarshaller.copyToCanonical(store, ans); store.setSurveyInstanceId(domain.getKey().getId()); answerList.add(store); } dao.save(answerList); if (instance.getApprovedFlag() == null || !"False".equalsIgnoreCase(instance.getApprovedFlag())) { sendProcessingMessages(domain); } } SurveyEventHelper.fireEvent(SurveyEventHelper.SUBMISSION_EVENT, instance.getSurveyId(), instance.getKeyId()); return instance; } /** * marks the survey instance as approved, updating any changed answers as it * does so and then sends a processing message to the task queue so the * instance can be summarized. */ public void approveSurveyInstance(Long surveyInstanceId, List<QuestionAnswerStoreDto> changedAnswers) { SurveyInstanceDAO dao = new SurveyInstanceDAO(); SurveyInstance instance = dao.getByKey(surveyInstanceId); if (changedAnswers != null && changedAnswers.size() > 0) { updateQuestions(changedAnswers, false); } if (instance != null) { if (instance.getApprovedFlag() == null || !"True".equalsIgnoreCase(instance.getApprovedFlag())) { instance.setApprovedFlag("True"); sendProcessingMessages(instance); // fire a survey event SurveyEventHelper.fireEvent(SurveyEventHelper.APPROVAL_EVENT, instance.getSurveyId(), instance.getKey().getId()); } } } /** * lists all surveyInstances associated with the surveyedLocaleId passed in. * * @param localeId * @return */ public ResponseDto<ArrayList<SurveyInstanceDto>> listInstancesByLocale( Long localeId, Date dateFrom, Date dateTo, String cursor) { SurveyInstanceDAO dao = new SurveyInstanceDAO(); ResponseDto<ArrayList<SurveyInstanceDto>> response = new ResponseDto<ArrayList<SurveyInstanceDto>>(); ArrayList<SurveyInstanceDto> dtoList = new ArrayList<SurveyInstanceDto>(); List<SurveyInstance> instances = dao.listInstancesByLocale(localeId, dateFrom, dateTo, cursor); if (instances != null) { for (SurveyInstance inst : instances) { SurveyInstanceDto dto = new SurveyInstanceDto(); DtoMarshaller.copyToDto(inst, dto); dtoList.add(dto); } response.setPayload(dtoList); if (dtoList.size() == SurveyInstanceDAO.DEFAULT_RESULT_COUNT) { response.setCursorString(SurveyInstanceDAO.getCursor(instances)); } } return response; } public void sendProcessingMessages(SurveyInstance domain) { // send async request to populate the AccessPoint using the mapping QueueFactory.getDefaultQueue().add( TaskOptions.Builder.withUrl("/app_worker/task") .param("action", "addAccessPoint") .param("surveyId", domain.getKey().getId() + "")); // send asyn crequest to summarize the instance QueueFactory.getQueue("dataSummarization").add( TaskOptions.Builder.withUrl("/app_worker/datasummarization") .param("objectKey", domain.getKey().getId() + "") .param("type", "SurveyInstance")); QueueFactory.getDefaultQueue().add( TaskOptions.Builder .withUrl("/app_worker/surveyalservlet") .param(SurveyalRestRequest.ACTION_PARAM, SurveyalRestRequest.INGEST_INSTANCE_ACTION) .param(SurveyalRestRequest.SURVEY_INSTANCE_PARAM, domain.getKey().getId() + "")); } }
true
true
public List<QuestionAnswerStoreDto> updateQuestions( List<QuestionAnswerStoreDto> dtoList, boolean isApproved, boolean processSummaries) { List<QuestionAnswerStore> domainList = new ArrayList<QuestionAnswerStore>(); for (QuestionAnswerStoreDto dto : dtoList) { QuestionAnswerStore answer = new QuestionAnswerStore(); DtoMarshaller.copyToCanonical(answer, dto); if (answer.getValue() != null) { answer.setValue(answer.getValue().replaceAll("\t", "")); } domainList.add(answer); } SurveyInstanceDAO dao = new SurveyInstanceDAO(); dao.save(domainList); // this is not active - questionAnswerSummary objects are updated in bulk // after the import in RawDataSpreadsheetImporter if (isApproved && processSummaries) { SurveyAttributeMappingDao mappingDao = new SurveyAttributeMappingDao(); // now send a change message for each item Queue queue = QueueFactory.getQueue("dataUpdate"); for (QuestionAnswerStoreDto item : dtoList) { DataChangeRecord value = new DataChangeRecord( QuestionAnswerStore.class.getName(), item.getQuestionID(), item.getOldValue(), item.getValue()); queue.add(TaskOptions.Builder .withUrl("/app_worker/dataupdate") .param(DataSummarizationRequest.OBJECT_KEY, item.getQuestionID()) .param(DataSummarizationRequest.OBJECT_TYPE, "QuestionDataChange") .param(DataSummarizationRequest.VALUE_KEY, value.packString())); // see if the question is mapped. And if it is, send an Access // Point // change message SurveyAttributeMapping mapping = mappingDao .findMappingForQuestion(item.getQuestionID()); if (mapping != null) { DataChangeRecord apValue = new DataChangeRecord( "AcessPointUpdate", mapping.getSurveyId() + "|" + mapping.getSurveyQuestionId() + "|" + item.getSurveyInstanceId() + "|" + mapping.getKey().getId(), item.getOldValue(), item.getValue()); queue.add(TaskOptions.Builder .withUrl("/app_worker/dataupdate") .param(DataSummarizationRequest.OBJECT_KEY, item.getQuestionID()) .param(DataSummarizationRequest.OBJECT_TYPE, "AccessPointChange") .param(DataSummarizationRequest.VALUE_KEY, apValue.packString())); } } } return dtoList; }
public List<QuestionAnswerStoreDto> updateQuestions( List<QuestionAnswerStoreDto> dtoList, boolean isApproved, boolean processSummaries) { List<QuestionAnswerStore> domainList = new ArrayList<QuestionAnswerStore>(); for (QuestionAnswerStoreDto dto : dtoList) { if ("".equals(dto.getValue()) && dto.getOldValue() == null) { continue; // empty string as value, skipping it } QuestionAnswerStore answer = new QuestionAnswerStore(); DtoMarshaller.copyToCanonical(answer, dto); if (answer.getValue() != null) { answer.setValue(answer.getValue().replaceAll("\t", "")); } domainList.add(answer); } SurveyInstanceDAO dao = new SurveyInstanceDAO(); dao.save(domainList); // this is not active - questionAnswerSummary objects are updated in bulk // after the import in RawDataSpreadsheetImporter if (isApproved && processSummaries) { SurveyAttributeMappingDao mappingDao = new SurveyAttributeMappingDao(); // now send a change message for each item Queue queue = QueueFactory.getQueue("dataUpdate"); for (QuestionAnswerStoreDto item : dtoList) { DataChangeRecord value = new DataChangeRecord( QuestionAnswerStore.class.getName(), item.getQuestionID(), item.getOldValue(), item.getValue()); queue.add(TaskOptions.Builder .withUrl("/app_worker/dataupdate") .param(DataSummarizationRequest.OBJECT_KEY, item.getQuestionID()) .param(DataSummarizationRequest.OBJECT_TYPE, "QuestionDataChange") .param(DataSummarizationRequest.VALUE_KEY, value.packString())); // see if the question is mapped. And if it is, send an Access // Point // change message SurveyAttributeMapping mapping = mappingDao .findMappingForQuestion(item.getQuestionID()); if (mapping != null) { DataChangeRecord apValue = new DataChangeRecord( "AcessPointUpdate", mapping.getSurveyId() + "|" + mapping.getSurveyQuestionId() + "|" + item.getSurveyInstanceId() + "|" + mapping.getKey().getId(), item.getOldValue(), item.getValue()); queue.add(TaskOptions.Builder .withUrl("/app_worker/dataupdate") .param(DataSummarizationRequest.OBJECT_KEY, item.getQuestionID()) .param(DataSummarizationRequest.OBJECT_TYPE, "AccessPointChange") .param(DataSummarizationRequest.VALUE_KEY, apValue.packString())); } } } return dtoList; }
diff --git a/core/src/visad/trunk/ShadowTupleType.java b/core/src/visad/trunk/ShadowTupleType.java index 1714ad51b..ac94b66a3 100644 --- a/core/src/visad/trunk/ShadowTupleType.java +++ b/core/src/visad/trunk/ShadowTupleType.java @@ -1,507 +1,507 @@ // // ShadowTupleType.java // /* VisAD system for interactive analysis and visualization of numerical data. Copyright (C) 1996 - 2000 Bill Hibbard, Curtis Rueden, Tom Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and Tommy Jasmin. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ package visad; import java.text.*; import java.util.*; import java.rmi.*; /** The ShadowTupleType class shadows the TupleType class, within a DataDisplayLink.<P> */ public class ShadowTupleType extends ShadowType { ShadowType[] tupleComponents; private ShadowRealType[] RealComponents; /** value_indices from parent */ private int[] inherited_values; /** true if no component with mapped Scalar components is a ShadowSetType, ShadowFunctionType or ShadowTupleType; not the same as TupleType.Flat */ private boolean Flat; public ShadowTupleType(MathType t, DataDisplayLink link, ShadowType parent, ShadowType[] tcs) throws VisADException, RemoteException { super(t, link, parent); tupleComponents = tcs; int n = tupleComponents.length; Flat = true; ShadowType[] components = new ShadowType[n]; MultipleSpatialDisplayScalar = false; MultipleDisplayScalar = false; // compute Flat, DisplayIndices and ValueIndices for (int i=0; i<n; i++) { ShadowType shadow = tupleComponents[i]; MultipleSpatialDisplayScalar |= tupleComponents[i].getMultipleSpatialDisplayScalar(); MultipleDisplayScalar |= tupleComponents[i].getMultipleDisplayScalar(); boolean mappedComponent = tupleComponents[i].getMappedDisplayScalar(); MappedDisplayScalar |= mappedComponent; if (shadow instanceof ShadowFunctionType || shadow instanceof ShadowSetType || (shadow instanceof ShadowTupleType && !(shadow instanceof ShadowRealTupleType)) ) { if (mappedComponent) Flat = false; } else if (shadow instanceof ShadowScalarType || shadow instanceof ShadowRealTupleType) { // treat ShadowRealTupleType component as // a set of ShadowRealType components DisplayIndices = addIndices(DisplayIndices, shadow.getDisplayIndices()); ValueIndices = addIndices(ValueIndices, shadow.getValueIndices()); } } RealComponents = getComponents(this, true); } public ShadowRealType[] getRealComponents() { return RealComponents; } // copy and increment indices for each ShadowScalarType component and // each ShadowRealType component of a ShadowRealTupleType component int[] sumIndices(int[] indices) { int[] local_indices = copyIndices(indices); int n = tupleComponents.length; for (int j=0; j<n; j++) { ShadowType shadow = (ShadowType) tupleComponents[j]; if (shadow instanceof ShadowScalarType) { ((ShadowScalarType) shadow).incrementIndices(local_indices); } else if (shadow instanceof ShadowRealTupleType) { // treat ShadowRealTupleType component as // a set of ShadowRealType components local_indices = ((ShadowRealTupleType) shadow).sumIndices(local_indices); } } return local_indices; } /** add DisplayIndices (from each ShadowScalarType and ShadowRealTupleType component) */ int[] sumDisplayIndices(int[] display_indices) throws VisADException { return addIndices(display_indices, DisplayIndices); } /** add ValueIndices (from each ShadowScalarType and ShadowRealTupleType component) */ int[] sumValueIndices(int[] value_indices) throws VisADException { return addIndices(value_indices, ValueIndices); } /* if (Flat) { terminal, so check condition 5 } else { check condition 2 on Flat components pass levelOfDifficulty down to checkIndices on non-Flat components } */ public int checkIndices(int[] indices, int[] display_indices, int[] value_indices, boolean[] isTransform, int levelOfDifficulty) throws VisADException, RemoteException { // add indices & display_indices from RealType and // RealTupleType components int[] local_indices = sumIndices(indices); int[] local_display_indices = sumDisplayIndices(display_indices); int[] local_value_indices = sumValueIndices(value_indices); anyContour = checkContour(local_display_indices); anyFlow = checkFlow(local_display_indices); anyShape = checkShape(local_display_indices); anyText = checkText(local_display_indices); markTransform(isTransform); // get value_indices arrays used by doTransform inherited_values = copyIndices(value_indices); // check for any mapped if (levelOfDifficulty == NOTHING_MAPPED) { if (checkAny(DisplayIndices)) { levelOfDifficulty = NESTED; } } if (Flat) { // test legality of Animation and SelectValue if (checkAnimationOrValue(DisplayIndices) > 0) { throw new BadMappingException("Animation and SelectValue may not " + "occur in range: " + "ShadowTupleType.checkIndices"); } LevelOfDifficulty = testIndices(local_indices, local_display_indices, levelOfDifficulty); if (LevelOfDifficulty == NESTED) { if (checkR2D2(DisplayIndices)) { LevelOfDifficulty = SIMPLE_TUPLE; } else { LevelOfDifficulty = LEGAL; } } } else { // !Flat if (levelOfDifficulty == NESTED) { if (!checkNested(DisplayIndices)) { levelOfDifficulty = LEGAL; } } int minLevelOfDifficulty = ShadowType.NOTHING_MAPPED; for (int j=0; j<tupleComponents.length; j++) { ShadowType shadow = (ShadowType) tupleComponents[j]; // treat ShadowRealTupleType component as a set of // ShadowRealType components (i.e., not terminal) if (shadow instanceof ShadowFunctionType || shadow instanceof ShadowSetType || (shadow instanceof ShadowTupleType && !(shadow instanceof ShadowRealTupleType)) ) { int level = shadow.checkIndices(local_indices, local_display_indices, local_value_indices, isTransform, levelOfDifficulty); if (level < minLevelOfDifficulty) { minLevelOfDifficulty = level; } } } LevelOfDifficulty = minLevelOfDifficulty; } return LevelOfDifficulty; } public int[] getInheritedValues() { return inherited_values; } /** get number of components */ public int getDimension() { return tupleComponents.length; } public ShadowType getComponent(int i) { return tupleComponents[i]; } /** mark Control-s as needing re-Transform */ void markTransform(boolean[] isTransform) { for (int i=0; i<tupleComponents.length; i++) { tupleComponents[i].markTransform(isTransform); } } /** transform data into a (Java3D or Java2D) scene graph; add generated scene graph components as children of group; group is Group (Java3D) or VisADGroup (Java2D); value_array are inherited valueArray values; default_values are defaults for each display.DisplayRealTypeVector; return true if need post-process */ public boolean doTransform(Object group, Data data, float[] value_array, float[] default_values, DataRenderer renderer, ShadowType shadow_api) throws VisADException, RemoteException { if (data.isMissing()) return false; if (LevelOfDifficulty == NOTHING_MAPPED) return false; if (!(data instanceof TupleIface)) { throw new DisplayException("data must be Tuple: " + "ShadowTupleType.doTransform"); } // get some precomputed values useful for transform // length of ValueArray int valueArrayLength = display.getValueArrayLength(); // mapping from ValueArray to DisplayScalar int[] valueToScalar = display.getValueToScalar(); // mapping from ValueArray to MapVector int[] valueToMap = display.getValueToMap(); Vector MapVector = display.getMapVector(); // array to hold values for various mappings float[][] display_values = new float[valueArrayLength][]; // get values inherited from parent; // assume these do not include SelectRange, SelectValue // or Animation values - see temporary hack in // DataRenderer.isTransformControl int[] inherited_values = getInheritedValues(); for (int i=0; i<valueArrayLength; i++) { if (inherited_values[i] > 0) { display_values[i] = new float[1]; display_values[i][0] = value_array[i]; } } TupleIface tuple = (TupleIface) data; RealType[] realComponents = ((TupleType) data.getType()).getRealComponents(); int length = realComponents.length; if (length > 0) { double[][] value = new double[length][1]; Unit[] value_units = new Unit[length]; int j = 0; for (int i=0; i<tuple.getDimension(); i++) { Data component = tuple.getComponent(i); if (component instanceof Real) { value_units[j] = realComponents[j].getDefaultUnit(); value[j][0] = ((Real) component).getValue(value_units[j]); j++; } else if (component instanceof RealTuple) { for (int k=0; k<((RealTuple) component).getDimension(); k++) { value_units[j] = realComponents[j].getDefaultUnit(); value[j][0] = ((Real) ((RealTuple) component).getComponent(k)). getValue(value_units[j]); j++; } } } ShadowRealType[] RealComponents = getRealComponents(); mapValues(display_values, value, RealComponents); int[] refToComponent = getRefToComponent(); ShadowRealTupleType[] componentWithRef = getComponentWithRef(); int[] componentIndex = getComponentIndex(); if (refToComponent != null) { // TO_DO for (int i=0; i<refToComponent.length; i++) { int n = componentWithRef[i].getDimension(); int start = refToComponent[i]; double[][] values = new double[n][]; for (j=0; j<n; j++) values[j] = value[j + start]; ShadowRealTupleType component_reference = componentWithRef[i].getReference(); RealTupleType ref = (RealTupleType) component_reference.getType(); Unit[] range_units; CoordinateSystem range_coord_sys; if (i == 0 && componentWithRef[i].equals(this)) { range_units = value_units; range_coord_sys = ((RealTuple) data).getCoordinateSystem(); } else { range_units = new Unit[n]; for (j=0; j<n; j++) range_units[j] = value_units[j + start]; range_coord_sys = ((RealTuple) ((TupleIface) data). getComponent(componentIndex[i])).getCoordinateSystem(); } // MEM double[][] reference_values = CoordinateSystem.transformCoordinates( ref, null, ref.getDefaultUnits(), null, (RealTupleType) componentWithRef[i].getType(), range_coord_sys, range_units, null, values); // WLH 13 March 2000 // if (getAnyFlow()) { renderer.setEarthSpatialData(componentWithRef[i], component_reference, ref, ref.getDefaultUnits(), (RealTupleType) componentWithRef[i].getType(), new CoordinateSystem[] {range_coord_sys}, range_units); // WLH 13 March 2000 // } // map reference_values to appropriate DisplayRealType-s // MEM mapValues(display_values, reference_values, getComponents(component_reference, false)); // FREE reference_values = null; // FREE (redundant reference to range_values) values = null; } // end for (int i=0; i<refToComponent.length; i++) } // end if (refToComponent != null) // setEarthSpatialData calls when no CoordinateSystem // WLH 13 March 2000 // if (this instanceof ShadowTupleType && getAnyFlow()) { if (this instanceof ShadowTupleType) { if (this instanceof ShadowRealTupleType) { Unit[] range_units = value_units; CoordinateSystem range_coord_sys = ((RealTuple) data).getCoordinateSystem(); /* WLH 23 May 99 renderer.setEarthSpatialData((ShadowRealTupleType) this, null, null, null, (RealTupleType) this.getType(), new CoordinateSystem[] {range_coord_sys}, range_units); */ ShadowRealTupleType component_reference = ((ShadowRealTupleType) this).getReference(); RealTupleType ref = (component_reference == null) ? null : (RealTupleType) component_reference.getType(); Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits(); renderer.setEarthSpatialData((ShadowRealTupleType) this, component_reference, ref, ref_units, (RealTupleType) this.getType(), new CoordinateSystem[] {range_coord_sys}, range_units); } else { // if (!(this instanceof ShadowRealTupleType)) int start = 0; int n = ((ShadowTupleType) this).getDimension(); for (int i=0; i<n ;i++) { ShadowType component = ((ShadowTupleType) this).getComponent(i); if (component instanceof ShadowRealTupleType) { int m = ((ShadowRealTupleType) component).getDimension(); Unit[] range_units = new Unit[m]; for (j=0; j<m; j++) range_units[j] = value_units[j + start]; CoordinateSystem range_coord_sys = ((RealTuple) ((TupleIface) data).getComponent(i)).getCoordinateSystem(); /* WLH 23 May 99 renderer.setEarthSpatialData((ShadowRealTupleType) component, null, null, null, (RealTupleType) component.getType(), new CoordinateSystem[] {range_coord_sys}, range_units); */ ShadowRealTupleType component_reference = ((ShadowRealTupleType) component).getReference(); RealTupleType ref = (component_reference == null) ? null : (RealTupleType) component_reference.getType(); Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits(); renderer.setEarthSpatialData((ShadowRealTupleType) component, component_reference, ref, ref_units, (RealTupleType) component.getType(), new CoordinateSystem[] {range_coord_sys}, range_units); start += ((ShadowRealTupleType) component).getDimension(); } else if (component instanceof ShadowRealType) { start++; } } } // end if (!(this instanceof ShadowRealTupleType)) } // end if (this instanceof ShadowTupleType) } // end if (length > 0) // get any text String and TextControl inherited from parent String text_value = getParentText(); TextControl text_control = getParentTextControl(); boolean anyText = getAnyText(); if (anyText && text_value == null) { for (int i=0; i<valueArrayLength; i++) { if (display_values[i] != null) { int displayScalarIndex = valueToScalar[i]; - ScalarType real = display.getScalar(displayScalarIndex); + ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]); + ScalarType real = map.getScalar(); DisplayRealType dreal = display.getDisplayScalar(displayScalarIndex); if (dreal.equals(Display.Text) && real instanceof RealType) { - ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]); text_control = (TextControl) map.getControl(); NumberFormat format = text_control.getNumberFormat(); if (format == null) { text_value = PlotText.shortString(display_values[i][0]); } else { text_value = format.format(display_values[i][0]); } break; } } } if (text_value == null) { for (int i=0; i<tuple.getDimension(); i++) { Data component = tuple.getComponent(i); if (component instanceof Text) { ShadowTextType type = (ShadowTextType) tupleComponents[i]; Vector maps = type.getSelectedMapVector(); if (!maps.isEmpty()) { text_value = ((Text) component).getValue(); ScalarMap map = (ScalarMap) maps.firstElement(); text_control = (TextControl) map.getControl(); } } } } } // end if (anyText && text_value == null) boolean[][] range_select = shadow_api.assembleSelect(display_values, 1, valueArrayLength, valueToScalar, display, shadow_api); if (range_select[0] != null && !range_select[0][0]) { // data not selected return false; } if (getIsTerminal()) { return terminalTupleOrScalar(group, display_values, text_value, text_control, valueArrayLength, valueToScalar, default_values, inherited_values, renderer, shadow_api); } else { // if (!isTerminal) boolean post = false; // add values to value_array according to SelectedMapVector-s // of RealType-s in components (including Reference), and // recursively call doTransform on other components for (int i=0; i<valueArrayLength; i++) { if (display_values[i] != null) { value_array[i] = display_values[i][0]; } } if (text_value != null && text_control != null) { setText(text_value, text_control); } else { setText(null, null); } for (int i=0; i<tuple.getDimension(); i++) { Data component = tuple.getComponent(i); if (!(component instanceof Real) && !(component instanceof RealTuple)) { // push lat_index and lon_index for flow navigation int[] lat_lon_indices = renderer.getLatLonIndices(); post |= shadow_api.recurseComponent(i, group, component, value_array, default_values, renderer); // pop lat_index and lon_index for flow navigation renderer.setLatLonIndices(lat_lon_indices); } } return post; } } public boolean isFlat() { return Flat; } }
false
true
public boolean doTransform(Object group, Data data, float[] value_array, float[] default_values, DataRenderer renderer, ShadowType shadow_api) throws VisADException, RemoteException { if (data.isMissing()) return false; if (LevelOfDifficulty == NOTHING_MAPPED) return false; if (!(data instanceof TupleIface)) { throw new DisplayException("data must be Tuple: " + "ShadowTupleType.doTransform"); } // get some precomputed values useful for transform // length of ValueArray int valueArrayLength = display.getValueArrayLength(); // mapping from ValueArray to DisplayScalar int[] valueToScalar = display.getValueToScalar(); // mapping from ValueArray to MapVector int[] valueToMap = display.getValueToMap(); Vector MapVector = display.getMapVector(); // array to hold values for various mappings float[][] display_values = new float[valueArrayLength][]; // get values inherited from parent; // assume these do not include SelectRange, SelectValue // or Animation values - see temporary hack in // DataRenderer.isTransformControl int[] inherited_values = getInheritedValues(); for (int i=0; i<valueArrayLength; i++) { if (inherited_values[i] > 0) { display_values[i] = new float[1]; display_values[i][0] = value_array[i]; } } TupleIface tuple = (TupleIface) data; RealType[] realComponents = ((TupleType) data.getType()).getRealComponents(); int length = realComponents.length; if (length > 0) { double[][] value = new double[length][1]; Unit[] value_units = new Unit[length]; int j = 0; for (int i=0; i<tuple.getDimension(); i++) { Data component = tuple.getComponent(i); if (component instanceof Real) { value_units[j] = realComponents[j].getDefaultUnit(); value[j][0] = ((Real) component).getValue(value_units[j]); j++; } else if (component instanceof RealTuple) { for (int k=0; k<((RealTuple) component).getDimension(); k++) { value_units[j] = realComponents[j].getDefaultUnit(); value[j][0] = ((Real) ((RealTuple) component).getComponent(k)). getValue(value_units[j]); j++; } } } ShadowRealType[] RealComponents = getRealComponents(); mapValues(display_values, value, RealComponents); int[] refToComponent = getRefToComponent(); ShadowRealTupleType[] componentWithRef = getComponentWithRef(); int[] componentIndex = getComponentIndex(); if (refToComponent != null) { // TO_DO for (int i=0; i<refToComponent.length; i++) { int n = componentWithRef[i].getDimension(); int start = refToComponent[i]; double[][] values = new double[n][]; for (j=0; j<n; j++) values[j] = value[j + start]; ShadowRealTupleType component_reference = componentWithRef[i].getReference(); RealTupleType ref = (RealTupleType) component_reference.getType(); Unit[] range_units; CoordinateSystem range_coord_sys; if (i == 0 && componentWithRef[i].equals(this)) { range_units = value_units; range_coord_sys = ((RealTuple) data).getCoordinateSystem(); } else { range_units = new Unit[n]; for (j=0; j<n; j++) range_units[j] = value_units[j + start]; range_coord_sys = ((RealTuple) ((TupleIface) data). getComponent(componentIndex[i])).getCoordinateSystem(); } // MEM double[][] reference_values = CoordinateSystem.transformCoordinates( ref, null, ref.getDefaultUnits(), null, (RealTupleType) componentWithRef[i].getType(), range_coord_sys, range_units, null, values); // WLH 13 March 2000 // if (getAnyFlow()) { renderer.setEarthSpatialData(componentWithRef[i], component_reference, ref, ref.getDefaultUnits(), (RealTupleType) componentWithRef[i].getType(), new CoordinateSystem[] {range_coord_sys}, range_units); // WLH 13 March 2000 // } // map reference_values to appropriate DisplayRealType-s // MEM mapValues(display_values, reference_values, getComponents(component_reference, false)); // FREE reference_values = null; // FREE (redundant reference to range_values) values = null; } // end for (int i=0; i<refToComponent.length; i++) } // end if (refToComponent != null) // setEarthSpatialData calls when no CoordinateSystem // WLH 13 March 2000 // if (this instanceof ShadowTupleType && getAnyFlow()) { if (this instanceof ShadowTupleType) { if (this instanceof ShadowRealTupleType) { Unit[] range_units = value_units; CoordinateSystem range_coord_sys = ((RealTuple) data).getCoordinateSystem(); /* WLH 23 May 99 renderer.setEarthSpatialData((ShadowRealTupleType) this, null, null, null, (RealTupleType) this.getType(), new CoordinateSystem[] {range_coord_sys}, range_units); */ ShadowRealTupleType component_reference = ((ShadowRealTupleType) this).getReference(); RealTupleType ref = (component_reference == null) ? null : (RealTupleType) component_reference.getType(); Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits(); renderer.setEarthSpatialData((ShadowRealTupleType) this, component_reference, ref, ref_units, (RealTupleType) this.getType(), new CoordinateSystem[] {range_coord_sys}, range_units); } else { // if (!(this instanceof ShadowRealTupleType)) int start = 0; int n = ((ShadowTupleType) this).getDimension(); for (int i=0; i<n ;i++) { ShadowType component = ((ShadowTupleType) this).getComponent(i); if (component instanceof ShadowRealTupleType) { int m = ((ShadowRealTupleType) component).getDimension(); Unit[] range_units = new Unit[m]; for (j=0; j<m; j++) range_units[j] = value_units[j + start]; CoordinateSystem range_coord_sys = ((RealTuple) ((TupleIface) data).getComponent(i)).getCoordinateSystem(); /* WLH 23 May 99 renderer.setEarthSpatialData((ShadowRealTupleType) component, null, null, null, (RealTupleType) component.getType(), new CoordinateSystem[] {range_coord_sys}, range_units); */ ShadowRealTupleType component_reference = ((ShadowRealTupleType) component).getReference(); RealTupleType ref = (component_reference == null) ? null : (RealTupleType) component_reference.getType(); Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits(); renderer.setEarthSpatialData((ShadowRealTupleType) component, component_reference, ref, ref_units, (RealTupleType) component.getType(), new CoordinateSystem[] {range_coord_sys}, range_units); start += ((ShadowRealTupleType) component).getDimension(); } else if (component instanceof ShadowRealType) { start++; } } } // end if (!(this instanceof ShadowRealTupleType)) } // end if (this instanceof ShadowTupleType) } // end if (length > 0) // get any text String and TextControl inherited from parent String text_value = getParentText(); TextControl text_control = getParentTextControl(); boolean anyText = getAnyText(); if (anyText && text_value == null) { for (int i=0; i<valueArrayLength; i++) { if (display_values[i] != null) { int displayScalarIndex = valueToScalar[i]; ScalarType real = display.getScalar(displayScalarIndex); DisplayRealType dreal = display.getDisplayScalar(displayScalarIndex); if (dreal.equals(Display.Text) && real instanceof RealType) { ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]); text_control = (TextControl) map.getControl(); NumberFormat format = text_control.getNumberFormat(); if (format == null) { text_value = PlotText.shortString(display_values[i][0]); } else { text_value = format.format(display_values[i][0]); } break; } } } if (text_value == null) { for (int i=0; i<tuple.getDimension(); i++) { Data component = tuple.getComponent(i); if (component instanceof Text) { ShadowTextType type = (ShadowTextType) tupleComponents[i]; Vector maps = type.getSelectedMapVector(); if (!maps.isEmpty()) { text_value = ((Text) component).getValue(); ScalarMap map = (ScalarMap) maps.firstElement(); text_control = (TextControl) map.getControl(); } } } } } // end if (anyText && text_value == null) boolean[][] range_select = shadow_api.assembleSelect(display_values, 1, valueArrayLength, valueToScalar, display, shadow_api); if (range_select[0] != null && !range_select[0][0]) { // data not selected return false; } if (getIsTerminal()) { return terminalTupleOrScalar(group, display_values, text_value, text_control, valueArrayLength, valueToScalar, default_values, inherited_values, renderer, shadow_api); } else { // if (!isTerminal) boolean post = false; // add values to value_array according to SelectedMapVector-s // of RealType-s in components (including Reference), and // recursively call doTransform on other components for (int i=0; i<valueArrayLength; i++) { if (display_values[i] != null) { value_array[i] = display_values[i][0]; } } if (text_value != null && text_control != null) { setText(text_value, text_control); } else { setText(null, null); } for (int i=0; i<tuple.getDimension(); i++) { Data component = tuple.getComponent(i); if (!(component instanceof Real) && !(component instanceof RealTuple)) { // push lat_index and lon_index for flow navigation int[] lat_lon_indices = renderer.getLatLonIndices(); post |= shadow_api.recurseComponent(i, group, component, value_array, default_values, renderer); // pop lat_index and lon_index for flow navigation renderer.setLatLonIndices(lat_lon_indices); } } return post; } }
public boolean doTransform(Object group, Data data, float[] value_array, float[] default_values, DataRenderer renderer, ShadowType shadow_api) throws VisADException, RemoteException { if (data.isMissing()) return false; if (LevelOfDifficulty == NOTHING_MAPPED) return false; if (!(data instanceof TupleIface)) { throw new DisplayException("data must be Tuple: " + "ShadowTupleType.doTransform"); } // get some precomputed values useful for transform // length of ValueArray int valueArrayLength = display.getValueArrayLength(); // mapping from ValueArray to DisplayScalar int[] valueToScalar = display.getValueToScalar(); // mapping from ValueArray to MapVector int[] valueToMap = display.getValueToMap(); Vector MapVector = display.getMapVector(); // array to hold values for various mappings float[][] display_values = new float[valueArrayLength][]; // get values inherited from parent; // assume these do not include SelectRange, SelectValue // or Animation values - see temporary hack in // DataRenderer.isTransformControl int[] inherited_values = getInheritedValues(); for (int i=0; i<valueArrayLength; i++) { if (inherited_values[i] > 0) { display_values[i] = new float[1]; display_values[i][0] = value_array[i]; } } TupleIface tuple = (TupleIface) data; RealType[] realComponents = ((TupleType) data.getType()).getRealComponents(); int length = realComponents.length; if (length > 0) { double[][] value = new double[length][1]; Unit[] value_units = new Unit[length]; int j = 0; for (int i=0; i<tuple.getDimension(); i++) { Data component = tuple.getComponent(i); if (component instanceof Real) { value_units[j] = realComponents[j].getDefaultUnit(); value[j][0] = ((Real) component).getValue(value_units[j]); j++; } else if (component instanceof RealTuple) { for (int k=0; k<((RealTuple) component).getDimension(); k++) { value_units[j] = realComponents[j].getDefaultUnit(); value[j][0] = ((Real) ((RealTuple) component).getComponent(k)). getValue(value_units[j]); j++; } } } ShadowRealType[] RealComponents = getRealComponents(); mapValues(display_values, value, RealComponents); int[] refToComponent = getRefToComponent(); ShadowRealTupleType[] componentWithRef = getComponentWithRef(); int[] componentIndex = getComponentIndex(); if (refToComponent != null) { // TO_DO for (int i=0; i<refToComponent.length; i++) { int n = componentWithRef[i].getDimension(); int start = refToComponent[i]; double[][] values = new double[n][]; for (j=0; j<n; j++) values[j] = value[j + start]; ShadowRealTupleType component_reference = componentWithRef[i].getReference(); RealTupleType ref = (RealTupleType) component_reference.getType(); Unit[] range_units; CoordinateSystem range_coord_sys; if (i == 0 && componentWithRef[i].equals(this)) { range_units = value_units; range_coord_sys = ((RealTuple) data).getCoordinateSystem(); } else { range_units = new Unit[n]; for (j=0; j<n; j++) range_units[j] = value_units[j + start]; range_coord_sys = ((RealTuple) ((TupleIface) data). getComponent(componentIndex[i])).getCoordinateSystem(); } // MEM double[][] reference_values = CoordinateSystem.transformCoordinates( ref, null, ref.getDefaultUnits(), null, (RealTupleType) componentWithRef[i].getType(), range_coord_sys, range_units, null, values); // WLH 13 March 2000 // if (getAnyFlow()) { renderer.setEarthSpatialData(componentWithRef[i], component_reference, ref, ref.getDefaultUnits(), (RealTupleType) componentWithRef[i].getType(), new CoordinateSystem[] {range_coord_sys}, range_units); // WLH 13 March 2000 // } // map reference_values to appropriate DisplayRealType-s // MEM mapValues(display_values, reference_values, getComponents(component_reference, false)); // FREE reference_values = null; // FREE (redundant reference to range_values) values = null; } // end for (int i=0; i<refToComponent.length; i++) } // end if (refToComponent != null) // setEarthSpatialData calls when no CoordinateSystem // WLH 13 March 2000 // if (this instanceof ShadowTupleType && getAnyFlow()) { if (this instanceof ShadowTupleType) { if (this instanceof ShadowRealTupleType) { Unit[] range_units = value_units; CoordinateSystem range_coord_sys = ((RealTuple) data).getCoordinateSystem(); /* WLH 23 May 99 renderer.setEarthSpatialData((ShadowRealTupleType) this, null, null, null, (RealTupleType) this.getType(), new CoordinateSystem[] {range_coord_sys}, range_units); */ ShadowRealTupleType component_reference = ((ShadowRealTupleType) this).getReference(); RealTupleType ref = (component_reference == null) ? null : (RealTupleType) component_reference.getType(); Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits(); renderer.setEarthSpatialData((ShadowRealTupleType) this, component_reference, ref, ref_units, (RealTupleType) this.getType(), new CoordinateSystem[] {range_coord_sys}, range_units); } else { // if (!(this instanceof ShadowRealTupleType)) int start = 0; int n = ((ShadowTupleType) this).getDimension(); for (int i=0; i<n ;i++) { ShadowType component = ((ShadowTupleType) this).getComponent(i); if (component instanceof ShadowRealTupleType) { int m = ((ShadowRealTupleType) component).getDimension(); Unit[] range_units = new Unit[m]; for (j=0; j<m; j++) range_units[j] = value_units[j + start]; CoordinateSystem range_coord_sys = ((RealTuple) ((TupleIface) data).getComponent(i)).getCoordinateSystem(); /* WLH 23 May 99 renderer.setEarthSpatialData((ShadowRealTupleType) component, null, null, null, (RealTupleType) component.getType(), new CoordinateSystem[] {range_coord_sys}, range_units); */ ShadowRealTupleType component_reference = ((ShadowRealTupleType) component).getReference(); RealTupleType ref = (component_reference == null) ? null : (RealTupleType) component_reference.getType(); Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits(); renderer.setEarthSpatialData((ShadowRealTupleType) component, component_reference, ref, ref_units, (RealTupleType) component.getType(), new CoordinateSystem[] {range_coord_sys}, range_units); start += ((ShadowRealTupleType) component).getDimension(); } else if (component instanceof ShadowRealType) { start++; } } } // end if (!(this instanceof ShadowRealTupleType)) } // end if (this instanceof ShadowTupleType) } // end if (length > 0) // get any text String and TextControl inherited from parent String text_value = getParentText(); TextControl text_control = getParentTextControl(); boolean anyText = getAnyText(); if (anyText && text_value == null) { for (int i=0; i<valueArrayLength; i++) { if (display_values[i] != null) { int displayScalarIndex = valueToScalar[i]; ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]); ScalarType real = map.getScalar(); DisplayRealType dreal = display.getDisplayScalar(displayScalarIndex); if (dreal.equals(Display.Text) && real instanceof RealType) { text_control = (TextControl) map.getControl(); NumberFormat format = text_control.getNumberFormat(); if (format == null) { text_value = PlotText.shortString(display_values[i][0]); } else { text_value = format.format(display_values[i][0]); } break; } } } if (text_value == null) { for (int i=0; i<tuple.getDimension(); i++) { Data component = tuple.getComponent(i); if (component instanceof Text) { ShadowTextType type = (ShadowTextType) tupleComponents[i]; Vector maps = type.getSelectedMapVector(); if (!maps.isEmpty()) { text_value = ((Text) component).getValue(); ScalarMap map = (ScalarMap) maps.firstElement(); text_control = (TextControl) map.getControl(); } } } } } // end if (anyText && text_value == null) boolean[][] range_select = shadow_api.assembleSelect(display_values, 1, valueArrayLength, valueToScalar, display, shadow_api); if (range_select[0] != null && !range_select[0][0]) { // data not selected return false; } if (getIsTerminal()) { return terminalTupleOrScalar(group, display_values, text_value, text_control, valueArrayLength, valueToScalar, default_values, inherited_values, renderer, shadow_api); } else { // if (!isTerminal) boolean post = false; // add values to value_array according to SelectedMapVector-s // of RealType-s in components (including Reference), and // recursively call doTransform on other components for (int i=0; i<valueArrayLength; i++) { if (display_values[i] != null) { value_array[i] = display_values[i][0]; } } if (text_value != null && text_control != null) { setText(text_value, text_control); } else { setText(null, null); } for (int i=0; i<tuple.getDimension(); i++) { Data component = tuple.getComponent(i); if (!(component instanceof Real) && !(component instanceof RealTuple)) { // push lat_index and lon_index for flow navigation int[] lat_lon_indices = renderer.getLatLonIndices(); post |= shadow_api.recurseComponent(i, group, component, value_array, default_values, renderer); // pop lat_index and lon_index for flow navigation renderer.setLatLonIndices(lat_lon_indices); } } return post; } }
diff --git a/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java b/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java index 2ef58357b..7461ce52f 100644 --- a/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java +++ b/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java @@ -1,1161 +1,1161 @@ package org.apache.lucene.index; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.io.PrintStream; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.concurrent.atomic.AtomicLong; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.document.Document; import org.apache.lucene.search.Query; import org.apache.lucene.search.Similarity; import org.apache.lucene.store.AlreadyClosedException; import org.apache.lucene.store.Directory; import org.apache.lucene.store.RAMFile; import org.apache.lucene.util.ArrayUtil; import org.apache.lucene.util.RecyclingByteBlockAllocator; import org.apache.lucene.util.ThreadInterruptedException; import org.apache.lucene.util.RamUsageEstimator; import static org.apache.lucene.util.ByteBlockPool.BYTE_BLOCK_MASK; import static org.apache.lucene.util.ByteBlockPool.BYTE_BLOCK_SIZE; /** * This class accepts multiple added documents and directly * writes a single segment file. It does this more * efficiently than creating a single segment per document * (with DocumentWriter) and doing standard merges on those * segments. * * Each added document is passed to the {@link DocConsumer}, * which in turn processes the document and interacts with * other consumers in the indexing chain. Certain * consumers, like {@link StoredFieldsWriter} and {@link * TermVectorsTermsWriter}, digest a document and * immediately write bytes to the "doc store" files (ie, * they do not consume RAM per document, except while they * are processing the document). * * Other consumers, eg {@link FreqProxTermsWriter} and * {@link NormsWriter}, buffer bytes in RAM and flush only * when a new segment is produced. * Once we have used our allowed RAM buffer, or the number * of added docs is large enough (in the case we are * flushing by doc count instead of RAM usage), we create a * real segment and flush it to the Directory. * * Threads: * * Multiple threads are allowed into addDocument at once. * There is an initial synchronized call to getThreadState * which allocates a ThreadState for this thread. The same * thread will get the same ThreadState over time (thread * affinity) so that if there are consistent patterns (for * example each thread is indexing a different content * source) then we make better use of RAM. Then * processDocument is called on that ThreadState without * synchronization (most of the "heavy lifting" is in this * call). Finally the synchronized "finishDocument" is * called to flush changes to the directory. * * When flush is called by IndexWriter we forcefully idle * all threads and flush only once they are all idle. This * means you can call flush with a given thread even while * other threads are actively adding/deleting documents. * * * Exceptions: * * Because this class directly updates in-memory posting * lists, and flushes stored fields and term vectors * directly to files in the directory, there are certain * limited times when an exception can corrupt this state. * For example, a disk full while flushing stored fields * leaves this file in a corrupt state. Or, an OOM * exception while appending to the in-memory posting lists * can corrupt that posting list. We call such exceptions * "aborting exceptions". In these cases we must call * abort() to discard all docs added since the last flush. * * All other exceptions ("non-aborting exceptions") can * still partially update the index structures. These * updates are consistent, but, they represent only a part * of the document seen up until the exception was hit. * When this happens, we immediately mark the document as * deleted so that the document is always atomically ("all * or none") added to the index. */ final class DocumentsWriter { final AtomicLong bytesUsed = new AtomicLong(0); IndexWriter writer; Directory directory; String segment; // Current segment we are working on private int nextDocID; // Next docID to be added private int numDocs; // # of docs added, but not yet flushed // Max # ThreadState instances; if there are more threads // than this they share ThreadStates private DocumentsWriterThreadState[] threadStates = new DocumentsWriterThreadState[0]; private final HashMap<Thread,DocumentsWriterThreadState> threadBindings = new HashMap<Thread,DocumentsWriterThreadState>(); boolean bufferIsFull; // True when it's time to write segment private boolean aborting; // True if an abort is pending PrintStream infoStream; int maxFieldLength = IndexWriterConfig.UNLIMITED_FIELD_LENGTH; Similarity similarity; // max # simultaneous threads; if there are more than // this, they wait for others to finish first private final int maxThreadStates; // Deletes for our still-in-RAM (to be flushed next) segment private SegmentDeletes pendingDeletes = new SegmentDeletes(); static class DocState { DocumentsWriter docWriter; Analyzer analyzer; int maxFieldLength; PrintStream infoStream; Similarity similarity; int docID; Document doc; String maxTermPrefix; // Only called by asserts public boolean testPoint(String name) { return docWriter.writer.testPoint(name); } public void clear() { // don't hold onto doc nor analyzer, in case it is // largish: doc = null; analyzer = null; } } /** Consumer returns this on each doc. This holds any * state that must be flushed synchronized "in docID * order". We gather these and flush them in order. */ abstract static class DocWriter { DocWriter next; int docID; abstract void finish() throws IOException; abstract void abort(); abstract long sizeInBytes(); void setNext(DocWriter next) { this.next = next; } } /** * Create and return a new DocWriterBuffer. */ PerDocBuffer newPerDocBuffer() { return new PerDocBuffer(); } /** * RAMFile buffer for DocWriters. */ @SuppressWarnings("serial") class PerDocBuffer extends RAMFile { /** * Allocate bytes used from shared pool. */ protected byte[] newBuffer(int size) { assert size == PER_DOC_BLOCK_SIZE; return perDocAllocator.getByteBlock(); } /** * Recycle the bytes used. */ synchronized void recycle() { if (buffers.size() > 0) { setLength(0); // Recycle the blocks perDocAllocator.recycleByteBlocks(buffers); buffers.clear(); sizeInBytes = 0; assert numBuffers() == 0; } } } /** * The IndexingChain must define the {@link #getChain(DocumentsWriter)} method * which returns the DocConsumer that the DocumentsWriter calls to process the * documents. */ abstract static class IndexingChain { abstract DocConsumer getChain(DocumentsWriter documentsWriter); } static final IndexingChain defaultIndexingChain = new IndexingChain() { @Override DocConsumer getChain(DocumentsWriter documentsWriter) { /* This is the current indexing chain: DocConsumer / DocConsumerPerThread --> code: DocFieldProcessor / DocFieldProcessorPerThread --> DocFieldConsumer / DocFieldConsumerPerThread / DocFieldConsumerPerField --> code: DocFieldConsumers / DocFieldConsumersPerThread / DocFieldConsumersPerField --> code: DocInverter / DocInverterPerThread / DocInverterPerField --> InvertedDocConsumer / InvertedDocConsumerPerThread / InvertedDocConsumerPerField --> code: TermsHash / TermsHashPerThread / TermsHashPerField --> TermsHashConsumer / TermsHashConsumerPerThread / TermsHashConsumerPerField --> code: FreqProxTermsWriter / FreqProxTermsWriterPerThread / FreqProxTermsWriterPerField --> code: TermVectorsTermsWriter / TermVectorsTermsWriterPerThread / TermVectorsTermsWriterPerField --> InvertedDocEndConsumer / InvertedDocConsumerPerThread / InvertedDocConsumerPerField --> code: NormsWriter / NormsWriterPerThread / NormsWriterPerField --> code: StoredFieldsWriter / StoredFieldsWriterPerThread / StoredFieldsWriterPerField */ // Build up indexing chain: final TermsHashConsumer termVectorsWriter = new TermVectorsTermsWriter(documentsWriter); final TermsHashConsumer freqProxWriter = new FreqProxTermsWriter(); /* * nesting TermsHash instances here to allow the secondary (TermVectors) share the interned postings * via a shared ByteBlockPool. See TermsHashPerField for details. */ final TermsHash termVectorsTermHash = new TermsHash(documentsWriter, false, termVectorsWriter, null); final InvertedDocConsumer termsHash = new TermsHash(documentsWriter, true, freqProxWriter, termVectorsTermHash); final NormsWriter normsWriter = new NormsWriter(); final DocInverter docInverter = new DocInverter(termsHash, normsWriter); return new DocFieldProcessor(documentsWriter, docInverter); } }; final DocConsumer consumer; // How much RAM we can use before flushing. This is 0 if // we are flushing by doc count instead. private long ramBufferSize = (long) (IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB*1024*1024); private long waitQueuePauseBytes = (long) (ramBufferSize*0.1); private long waitQueueResumeBytes = (long) (ramBufferSize*0.05); // If we've allocated 5% over our RAM budget, we then // free down to 95% private long freeLevel = (long) (IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB*1024*1024*0.95); // Flush @ this number of docs. If ramBufferSize is // non-zero we will flush by RAM usage instead. private int maxBufferedDocs = IndexWriterConfig.DEFAULT_MAX_BUFFERED_DOCS; private boolean closed; private final FieldInfos fieldInfos; private final BufferedDeletes bufferedDeletes; private final IndexWriter.FlushControl flushControl; DocumentsWriter(Directory directory, IndexWriter writer, IndexingChain indexingChain, int maxThreadStates, FieldInfos fieldInfos, BufferedDeletes bufferedDeletes) throws IOException { this.directory = directory; this.writer = writer; this.similarity = writer.getConfig().getSimilarity(); this.maxThreadStates = maxThreadStates; this.fieldInfos = fieldInfos; this.bufferedDeletes = bufferedDeletes; flushControl = writer.flushControl; consumer = indexingChain.getChain(this); } // Buffer a specific docID for deletion. Currently only // used when we hit a exception when adding a document synchronized void deleteDocID(int docIDUpto) { pendingDeletes.addDocID(docIDUpto); // NOTE: we do not trigger flush here. This is // potentially a RAM leak, if you have an app that tries // to add docs but every single doc always hits a // non-aborting exception. Allowing a flush here gets // very messy because we are only invoked when handling // exceptions so to do this properly, while handling an // exception we'd have to go off and flush new deletes // which is risky (likely would hit some other // confounding exception). } boolean deleteQueries(Query... queries) { final boolean doFlush = flushControl.waitUpdate(0, queries.length); synchronized(this) { for (Query query : queries) { pendingDeletes.addQuery(query, numDocs); } } return doFlush; } boolean deleteQuery(Query query) { final boolean doFlush = flushControl.waitUpdate(0, 1); synchronized(this) { pendingDeletes.addQuery(query, numDocs); } return doFlush; } boolean deleteTerms(Term... terms) { final boolean doFlush = flushControl.waitUpdate(0, terms.length); synchronized(this) { for (Term term : terms) { pendingDeletes.addTerm(term, numDocs); } } return doFlush; } boolean deleteTerm(Term term, boolean skipWait) { final boolean doFlush = flushControl.waitUpdate(0, 1, skipWait); synchronized(this) { pendingDeletes.addTerm(term, numDocs); } return doFlush; } public FieldInfos getFieldInfos() { return fieldInfos; } /** If non-null, various details of indexing are printed * here. */ synchronized void setInfoStream(PrintStream infoStream) { this.infoStream = infoStream; for(int i=0;i<threadStates.length;i++) { threadStates[i].docState.infoStream = infoStream; } } synchronized void setMaxFieldLength(int maxFieldLength) { this.maxFieldLength = maxFieldLength; for(int i=0;i<threadStates.length;i++) { threadStates[i].docState.maxFieldLength = maxFieldLength; } } synchronized void setSimilarity(Similarity similarity) { this.similarity = similarity; for(int i=0;i<threadStates.length;i++) { threadStates[i].docState.similarity = similarity; } } /** Set how much RAM we can use before flushing. */ synchronized void setRAMBufferSizeMB(double mb) { if (mb == IndexWriterConfig.DISABLE_AUTO_FLUSH) { ramBufferSize = IndexWriterConfig.DISABLE_AUTO_FLUSH; waitQueuePauseBytes = 4*1024*1024; waitQueueResumeBytes = 2*1024*1024; } else { ramBufferSize = (long) (mb*1024*1024); waitQueuePauseBytes = (long) (ramBufferSize*0.1); waitQueueResumeBytes = (long) (ramBufferSize*0.05); freeLevel = (long) (0.95 * ramBufferSize); } } synchronized double getRAMBufferSizeMB() { if (ramBufferSize == IndexWriterConfig.DISABLE_AUTO_FLUSH) { return ramBufferSize; } else { return ramBufferSize/1024./1024.; } } /** Set max buffered docs, which means we will flush by * doc count instead of by RAM usage. */ void setMaxBufferedDocs(int count) { maxBufferedDocs = count; } int getMaxBufferedDocs() { return maxBufferedDocs; } /** Get current segment name we are writing. */ synchronized String getSegment() { return segment; } /** Returns how many docs are currently buffered in RAM. */ synchronized int getNumDocs() { return numDocs; } void message(String message) { if (infoStream != null) { writer.message("DW: " + message); } } synchronized void setAborting() { if (infoStream != null) { message("setAborting"); } aborting = true; } /** Called if we hit an exception at a bad time (when * updating the index files) and must discard all * currently buffered docs. This resets our state, * discarding any docs added since last flush. */ synchronized void abort() throws IOException { if (infoStream != null) { message("docWriter: abort"); } boolean success = false; try { // Forcefully remove waiting ThreadStates from line waitQueue.abort(); // Wait for all other threads to finish with // DocumentsWriter: waitIdle(); if (infoStream != null) { message("docWriter: abort waitIdle done"); } assert 0 == waitQueue.numWaiting: "waitQueue.numWaiting=" + waitQueue.numWaiting; waitQueue.waitingBytes = 0; pendingDeletes.clear(); for (DocumentsWriterThreadState threadState : threadStates) try { threadState.consumer.abort(); } catch (Throwable t) { } try { consumer.abort(); } catch (Throwable t) { } // Reset all postings data doAfterFlush(); success = true; } finally { aborting = false; notifyAll(); if (infoStream != null) { message("docWriter: done abort; success=" + success); } } } /** Reset after a flush */ private void doAfterFlush() throws IOException { // All ThreadStates should be idle when we are called assert allThreadsIdle(); threadBindings.clear(); waitQueue.reset(); segment = null; numDocs = 0; nextDocID = 0; bufferIsFull = false; for(int i=0;i<threadStates.length;i++) { threadStates[i].doAfterFlush(); } } private synchronized boolean allThreadsIdle() { for(int i=0;i<threadStates.length;i++) { if (!threadStates[i].isIdle) { return false; } } return true; } synchronized boolean anyChanges() { return numDocs != 0 || pendingDeletes.any(); } // for testing public SegmentDeletes getPendingDeletes() { return pendingDeletes; } private void pushDeletes(SegmentInfo newSegment, SegmentInfos segmentInfos) { // Lock order: DW -> BD if (pendingDeletes.any()) { if (newSegment != null) { if (infoStream != null) { message("flush: push buffered deletes to newSegment"); } bufferedDeletes.pushDeletes(pendingDeletes, newSegment); } else if (segmentInfos.size() > 0) { if (infoStream != null) { message("flush: push buffered deletes to previously flushed segment " + segmentInfos.lastElement()); } bufferedDeletes.pushDeletes(pendingDeletes, segmentInfos.lastElement(), true); } else { if (infoStream != null) { message("flush: drop buffered deletes: no segments"); } // We can safely discard these deletes: since // there are no segments, the deletions cannot // affect anything. } pendingDeletes = new SegmentDeletes(); } } public boolean anyDeletions() { return pendingDeletes.any(); } /** Flush all pending docs to a new segment */ // Lock order: IW -> DW synchronized SegmentInfo flush(IndexWriter writer, IndexFileDeleter deleter, MergePolicy mergePolicy, SegmentInfos segmentInfos) throws IOException { // We change writer's segmentInfos: assert Thread.holdsLock(writer); waitIdle(); if (numDocs == 0) { // nothing to do! if (infoStream != null) { message("flush: no docs; skipping"); } // Lock order: IW -> DW -> BD pushDeletes(null, segmentInfos); return null; } if (aborting) { if (infoStream != null) { message("flush: skip because aborting is set"); } return null; } boolean success = false; SegmentInfo newSegment; try { assert nextDocID == numDocs; assert waitQueue.numWaiting == 0; assert waitQueue.waitingBytes == 0; if (infoStream != null) { message("flush postings as segment " + segment + " numDocs=" + numDocs); } final SegmentWriteState flushState = new SegmentWriteState(infoStream, directory, segment, fieldInfos, numDocs, writer.getConfig().getTermIndexInterval(), SegmentCodecs.build(fieldInfos, writer.codecs)); newSegment = new SegmentInfo(segment, numDocs, directory, false, fieldInfos.hasProx(), flushState.segmentCodecs, false); Collection<DocConsumerPerThread> threads = new HashSet<DocConsumerPerThread>(); for (DocumentsWriterThreadState threadState : threadStates) { threads.add(threadState.consumer); } - long startNumBytesUsed = bytesUsed(); + double startMBUsed = bytesUsed()/1024./1024.; consumer.flush(threads, flushState); newSegment.setHasVectors(flushState.hasVectors); if (infoStream != null) { message("new segment has " + (flushState.hasVectors ? "vectors" : "no vectors")); message("flushedFiles=" + flushState.flushedFiles); message("flushed codecs=" + newSegment.getSegmentCodecs()); } if (mergePolicy.useCompoundFile(segmentInfos, newSegment)) { final String cfsFileName = IndexFileNames.segmentFileName(segment, "", IndexFileNames.COMPOUND_FILE_EXTENSION); if (infoStream != null) { message("flush: create compound file \"" + cfsFileName + "\""); } CompoundFileWriter cfsWriter = new CompoundFileWriter(directory, cfsFileName); for(String fileName : flushState.flushedFiles) { cfsWriter.addFile(fileName); } cfsWriter.close(); deleter.deleteNewFiles(flushState.flushedFiles); newSegment.setUseCompoundFile(true); } if (infoStream != null) { message("flush: segment=" + newSegment); - final long newSegmentSizeNoStore = newSegment.sizeInBytes(false); - final long newSegmentSize = newSegment.sizeInBytes(true); - message(" ramUsed=" + nf.format(startNumBytesUsed / 1024. / 1024.) + " MB" + - " newFlushedSize=" + nf.format(newSegmentSize / 1024 / 1024) + " MB" + - " (" + nf.format(newSegmentSizeNoStore / 1024 / 1024) + " MB w/o doc stores)" + - " docs/MB=" + nf.format(numDocs / (newSegmentSize / 1024. / 1024.)) + - " new/old=" + nf.format(100.0 * newSegmentSizeNoStore / startNumBytesUsed) + "%"); + final double newSegmentSizeNoStore = newSegment.sizeInBytes(false)/1024./1024.; + final double newSegmentSize = newSegment.sizeInBytes(true)/1024./1024.; + message(" ramUsed=" + nf.format(startMBUsed) + " MB" + + " newFlushedSize=" + nf.format(newSegmentSize) + " MB" + + " (" + nf.format(newSegmentSizeNoStore) + " MB w/o doc stores)" + + " docs/MB=" + nf.format(numDocs / newSegmentSize) + + " new/old=" + nf.format(100.0 * newSegmentSizeNoStore / startMBUsed) + "%"); } success = true; } finally { notifyAll(); if (!success) { if (segment != null) { deleter.refresh(segment); } abort(); } } doAfterFlush(); // Lock order: IW -> DW -> BD pushDeletes(newSegment, segmentInfos); return newSegment; } synchronized void close() { closed = true; notifyAll(); } /** Returns a free (idle) ThreadState that may be used for * indexing this one document. This call also pauses if a * flush is pending. If delTerm is non-null then we * buffer this deleted term after the thread state has * been acquired. */ synchronized DocumentsWriterThreadState getThreadState(Document doc, Term delTerm) throws IOException { final Thread currentThread = Thread.currentThread(); assert !Thread.holdsLock(writer); // First, find a thread state. If this thread already // has affinity to a specific ThreadState, use that one // again. DocumentsWriterThreadState state = threadBindings.get(currentThread); if (state == null) { // First time this thread has called us since last // flush. Find the least loaded thread state: DocumentsWriterThreadState minThreadState = null; for(int i=0;i<threadStates.length;i++) { DocumentsWriterThreadState ts = threadStates[i]; if (minThreadState == null || ts.numThreads < minThreadState.numThreads) { minThreadState = ts; } } if (minThreadState != null && (minThreadState.numThreads == 0 || threadStates.length >= maxThreadStates)) { state = minThreadState; state.numThreads++; } else { // Just create a new "private" thread state DocumentsWriterThreadState[] newArray = new DocumentsWriterThreadState[1+threadStates.length]; if (threadStates.length > 0) { System.arraycopy(threadStates, 0, newArray, 0, threadStates.length); } state = newArray[threadStates.length] = new DocumentsWriterThreadState(this); threadStates = newArray; } threadBindings.put(currentThread, state); } // Next, wait until my thread state is idle (in case // it's shared with other threads), and no flush/abort // pending waitReady(state); // Allocate segment name if this is the first doc since // last flush: if (segment == null) { segment = writer.newSegmentName(); assert numDocs == 0; } state.docState.docID = nextDocID++; if (delTerm != null) { pendingDeletes.addTerm(delTerm, state.docState.docID); } numDocs++; state.isIdle = false; return state; } boolean addDocument(Document doc, Analyzer analyzer) throws CorruptIndexException, IOException { return updateDocument(doc, analyzer, null); } boolean updateDocument(Document doc, Analyzer analyzer, Term delTerm) throws CorruptIndexException, IOException { // Possibly trigger a flush, or wait until any running flush completes: boolean doFlush = flushControl.waitUpdate(1, delTerm != null ? 1 : 0); // This call is synchronized but fast final DocumentsWriterThreadState state = getThreadState(doc, delTerm); final DocState docState = state.docState; docState.doc = doc; docState.analyzer = analyzer; boolean success = false; try { // This call is not synchronized and does all the // work final DocWriter perDoc; try { perDoc = state.consumer.processDocument(); } finally { docState.clear(); } // This call is synchronized but fast finishDocument(state, perDoc); success = true; } finally { if (!success) { // If this thread state had decided to flush, we // must clear it so another thread can flush if (doFlush) { flushControl.clearFlushPending(); } if (infoStream != null) { message("exception in updateDocument aborting=" + aborting); } synchronized(this) { state.isIdle = true; notifyAll(); if (aborting) { abort(); } else { skipDocWriter.docID = docState.docID; boolean success2 = false; try { waitQueue.add(skipDocWriter); success2 = true; } finally { if (!success2) { abort(); return false; } } // Immediately mark this document as deleted // since likely it was partially added. This // keeps indexing as "all or none" (atomic) when // adding a document: deleteDocID(state.docState.docID); } } } } doFlush |= flushControl.flushByRAMUsage("new document"); return doFlush; } public synchronized void waitIdle() { while (!allThreadsIdle()) { try { wait(); } catch (InterruptedException ie) { throw new ThreadInterruptedException(ie); } } } synchronized void waitReady(DocumentsWriterThreadState state) { while (!closed && (!state.isIdle || aborting)) { try { wait(); } catch (InterruptedException ie) { throw new ThreadInterruptedException(ie); } } if (closed) { throw new AlreadyClosedException("this IndexWriter is closed"); } } /** Does the synchronized work to finish/flush the * inverted document. */ private void finishDocument(DocumentsWriterThreadState perThread, DocWriter docWriter) throws IOException { // Must call this w/o holding synchronized(this) else // we'll hit deadlock: balanceRAM(); synchronized(this) { assert docWriter == null || docWriter.docID == perThread.docState.docID; if (aborting) { // We are currently aborting, and another thread is // waiting for me to become idle. We just forcefully // idle this threadState; it will be fully reset by // abort() if (docWriter != null) { try { docWriter.abort(); } catch (Throwable t) { } } perThread.isIdle = true; // wakes up any threads waiting on the wait queue notifyAll(); return; } final boolean doPause; if (docWriter != null) { doPause = waitQueue.add(docWriter); } else { skipDocWriter.docID = perThread.docState.docID; doPause = waitQueue.add(skipDocWriter); } if (doPause) { waitForWaitQueue(); } perThread.isIdle = true; // wakes up any threads waiting on the wait queue notifyAll(); } } synchronized void waitForWaitQueue() { do { try { wait(); } catch (InterruptedException ie) { throw new ThreadInterruptedException(ie); } } while (!waitQueue.doResume()); } private static class SkipDocWriter extends DocWriter { @Override void finish() { } @Override void abort() { } @Override long sizeInBytes() { return 0; } } final SkipDocWriter skipDocWriter = new SkipDocWriter(); NumberFormat nf = NumberFormat.getInstance(); /* Initial chunks size of the shared byte[] blocks used to store postings data */ final static int BYTE_BLOCK_NOT_MASK = ~BYTE_BLOCK_MASK; /* if you increase this, you must fix field cache impl for * getTerms/getTermsIndex requires <= 32768 */ final static int MAX_TERM_LENGTH_UTF8 = BYTE_BLOCK_SIZE-2; /* Initial chunks size of the shared int[] blocks used to store postings data */ final static int INT_BLOCK_SHIFT = 13; final static int INT_BLOCK_SIZE = 1 << INT_BLOCK_SHIFT; final static int INT_BLOCK_MASK = INT_BLOCK_SIZE - 1; private List<int[]> freeIntBlocks = new ArrayList<int[]>(); /* Allocate another int[] from the shared pool */ synchronized int[] getIntBlock() { final int size = freeIntBlocks.size(); final int[] b; if (0 == size) { b = new int[INT_BLOCK_SIZE]; bytesUsed.addAndGet(INT_BLOCK_SIZE*RamUsageEstimator.NUM_BYTES_INT); } else { b = freeIntBlocks.remove(size-1); } return b; } long bytesUsed() { return bytesUsed.get() + pendingDeletes.bytesUsed.get(); } /* Return int[]s to the pool */ synchronized void recycleIntBlocks(int[][] blocks, int start, int end) { for(int i=start;i<end;i++) { freeIntBlocks.add(blocks[i]); blocks[i] = null; } } final RecyclingByteBlockAllocator byteBlockAllocator = new RecyclingByteBlockAllocator(BYTE_BLOCK_SIZE, Integer.MAX_VALUE, bytesUsed); final static int PER_DOC_BLOCK_SIZE = 1024; final RecyclingByteBlockAllocator perDocAllocator = new RecyclingByteBlockAllocator(PER_DOC_BLOCK_SIZE, Integer.MAX_VALUE, bytesUsed); String toMB(long v) { return nf.format(v/1024./1024.); } /* We have three pools of RAM: Postings, byte blocks * (holds freq/prox posting data) and per-doc buffers * (stored fields/term vectors). Different docs require * varying amount of storage from these classes. For * example, docs with many unique single-occurrence short * terms will use up the Postings RAM and hardly any of * the other two. Whereas docs with very large terms will * use alot of byte blocks RAM. This method just frees * allocations from the pools once we are over-budget, * which balances the pools to match the current docs. */ void balanceRAM() { final boolean doBalance; final long deletesRAMUsed; deletesRAMUsed = bufferedDeletes.bytesUsed(); synchronized(this) { if (ramBufferSize == IndexWriterConfig.DISABLE_AUTO_FLUSH || bufferIsFull) { return; } doBalance = bytesUsed() + deletesRAMUsed >= ramBufferSize; } if (doBalance) { if (infoStream != null) { message(" RAM: balance allocations: usedMB=" + toMB(bytesUsed()) + " vs trigger=" + toMB(ramBufferSize) + " deletesMB=" + toMB(deletesRAMUsed) + " byteBlockFree=" + toMB(byteBlockAllocator.bytesUsed()) + " perDocFree=" + toMB(perDocAllocator.bytesUsed())); } final long startBytesUsed = bytesUsed() + deletesRAMUsed; int iter = 0; // We free equally from each pool in 32 KB // chunks until we are below our threshold // (freeLevel) boolean any = true; while(bytesUsed()+deletesRAMUsed > freeLevel) { synchronized(this) { if (0 == perDocAllocator.numBufferedBlocks() && 0 == byteBlockAllocator.numBufferedBlocks() && 0 == freeIntBlocks.size() && !any) { // Nothing else to free -- must flush now. bufferIsFull = bytesUsed()+deletesRAMUsed > ramBufferSize; if (infoStream != null) { if (bytesUsed()+deletesRAMUsed > ramBufferSize) { message(" nothing to free; set bufferIsFull"); } else { message(" nothing to free"); } } break; } if ((0 == iter % 4) && byteBlockAllocator.numBufferedBlocks() > 0) { byteBlockAllocator.freeBlocks(1); } if ((1 == iter % 4) && freeIntBlocks.size() > 0) { freeIntBlocks.remove(freeIntBlocks.size()-1); bytesUsed.addAndGet(-INT_BLOCK_SIZE * RamUsageEstimator.NUM_BYTES_INT); } if ((2 == iter % 4) && perDocAllocator.numBufferedBlocks() > 0) { perDocAllocator.freeBlocks(32); // Remove upwards of 32 blocks (each block is 1K) } } if ((3 == iter % 4) && any) { // Ask consumer to free any recycled state any = consumer.freeRAM(); } iter++; } if (infoStream != null) { message(" after free: freedMB=" + nf.format((startBytesUsed-bytesUsed()-deletesRAMUsed)/1024./1024.) + " usedMB=" + nf.format((bytesUsed()+deletesRAMUsed)/1024./1024.)); } } } final WaitQueue waitQueue = new WaitQueue(); private class WaitQueue { DocWriter[] waiting; int nextWriteDocID; int nextWriteLoc; int numWaiting; long waitingBytes; public WaitQueue() { waiting = new DocWriter[10]; } synchronized void reset() { // NOTE: nextWriteLoc doesn't need to be reset assert numWaiting == 0; assert waitingBytes == 0; nextWriteDocID = 0; } synchronized boolean doResume() { return waitingBytes <= waitQueueResumeBytes; } synchronized boolean doPause() { return waitingBytes > waitQueuePauseBytes; } synchronized void abort() { int count = 0; for(int i=0;i<waiting.length;i++) { final DocWriter doc = waiting[i]; if (doc != null) { doc.abort(); waiting[i] = null; count++; } } waitingBytes = 0; assert count == numWaiting; numWaiting = 0; } private void writeDocument(DocWriter doc) throws IOException { assert doc == skipDocWriter || nextWriteDocID == doc.docID; boolean success = false; try { doc.finish(); nextWriteDocID++; nextWriteLoc++; assert nextWriteLoc <= waiting.length; if (nextWriteLoc == waiting.length) { nextWriteLoc = 0; } success = true; } finally { if (!success) { setAborting(); } } } synchronized public boolean add(DocWriter doc) throws IOException { assert doc.docID >= nextWriteDocID; if (doc.docID == nextWriteDocID) { writeDocument(doc); while(true) { doc = waiting[nextWriteLoc]; if (doc != null) { numWaiting--; waiting[nextWriteLoc] = null; waitingBytes -= doc.sizeInBytes(); writeDocument(doc); } else { break; } } } else { // I finished before documents that were added // before me. This can easily happen when I am a // small doc and the docs before me were large, or, // just due to luck in the thread scheduling. Just // add myself to the queue and when that large doc // finishes, it will flush me: int gap = doc.docID - nextWriteDocID; if (gap >= waiting.length) { // Grow queue DocWriter[] newArray = new DocWriter[ArrayUtil.oversize(gap, RamUsageEstimator.NUM_BYTES_OBJECT_REF)]; assert nextWriteLoc >= 0; System.arraycopy(waiting, nextWriteLoc, newArray, 0, waiting.length-nextWriteLoc); System.arraycopy(waiting, 0, newArray, waiting.length-nextWriteLoc, nextWriteLoc); nextWriteLoc = 0; waiting = newArray; gap = doc.docID - nextWriteDocID; } int loc = nextWriteLoc + gap; if (loc >= waiting.length) { loc -= waiting.length; } // We should only wrap one time assert loc < waiting.length; // Nobody should be in my spot! assert waiting[loc] == null; waiting[loc] = doc; numWaiting++; waitingBytes += doc.sizeInBytes(); } return doPause(); } } }
false
true
synchronized SegmentInfo flush(IndexWriter writer, IndexFileDeleter deleter, MergePolicy mergePolicy, SegmentInfos segmentInfos) throws IOException { // We change writer's segmentInfos: assert Thread.holdsLock(writer); waitIdle(); if (numDocs == 0) { // nothing to do! if (infoStream != null) { message("flush: no docs; skipping"); } // Lock order: IW -> DW -> BD pushDeletes(null, segmentInfos); return null; } if (aborting) { if (infoStream != null) { message("flush: skip because aborting is set"); } return null; } boolean success = false; SegmentInfo newSegment; try { assert nextDocID == numDocs; assert waitQueue.numWaiting == 0; assert waitQueue.waitingBytes == 0; if (infoStream != null) { message("flush postings as segment " + segment + " numDocs=" + numDocs); } final SegmentWriteState flushState = new SegmentWriteState(infoStream, directory, segment, fieldInfos, numDocs, writer.getConfig().getTermIndexInterval(), SegmentCodecs.build(fieldInfos, writer.codecs)); newSegment = new SegmentInfo(segment, numDocs, directory, false, fieldInfos.hasProx(), flushState.segmentCodecs, false); Collection<DocConsumerPerThread> threads = new HashSet<DocConsumerPerThread>(); for (DocumentsWriterThreadState threadState : threadStates) { threads.add(threadState.consumer); } long startNumBytesUsed = bytesUsed(); consumer.flush(threads, flushState); newSegment.setHasVectors(flushState.hasVectors); if (infoStream != null) { message("new segment has " + (flushState.hasVectors ? "vectors" : "no vectors")); message("flushedFiles=" + flushState.flushedFiles); message("flushed codecs=" + newSegment.getSegmentCodecs()); } if (mergePolicy.useCompoundFile(segmentInfos, newSegment)) { final String cfsFileName = IndexFileNames.segmentFileName(segment, "", IndexFileNames.COMPOUND_FILE_EXTENSION); if (infoStream != null) { message("flush: create compound file \"" + cfsFileName + "\""); } CompoundFileWriter cfsWriter = new CompoundFileWriter(directory, cfsFileName); for(String fileName : flushState.flushedFiles) { cfsWriter.addFile(fileName); } cfsWriter.close(); deleter.deleteNewFiles(flushState.flushedFiles); newSegment.setUseCompoundFile(true); } if (infoStream != null) { message("flush: segment=" + newSegment); final long newSegmentSizeNoStore = newSegment.sizeInBytes(false); final long newSegmentSize = newSegment.sizeInBytes(true); message(" ramUsed=" + nf.format(startNumBytesUsed / 1024. / 1024.) + " MB" + " newFlushedSize=" + nf.format(newSegmentSize / 1024 / 1024) + " MB" + " (" + nf.format(newSegmentSizeNoStore / 1024 / 1024) + " MB w/o doc stores)" + " docs/MB=" + nf.format(numDocs / (newSegmentSize / 1024. / 1024.)) + " new/old=" + nf.format(100.0 * newSegmentSizeNoStore / startNumBytesUsed) + "%"); } success = true; } finally { notifyAll(); if (!success) { if (segment != null) { deleter.refresh(segment); } abort(); } } doAfterFlush(); // Lock order: IW -> DW -> BD pushDeletes(newSegment, segmentInfos); return newSegment; }
synchronized SegmentInfo flush(IndexWriter writer, IndexFileDeleter deleter, MergePolicy mergePolicy, SegmentInfos segmentInfos) throws IOException { // We change writer's segmentInfos: assert Thread.holdsLock(writer); waitIdle(); if (numDocs == 0) { // nothing to do! if (infoStream != null) { message("flush: no docs; skipping"); } // Lock order: IW -> DW -> BD pushDeletes(null, segmentInfos); return null; } if (aborting) { if (infoStream != null) { message("flush: skip because aborting is set"); } return null; } boolean success = false; SegmentInfo newSegment; try { assert nextDocID == numDocs; assert waitQueue.numWaiting == 0; assert waitQueue.waitingBytes == 0; if (infoStream != null) { message("flush postings as segment " + segment + " numDocs=" + numDocs); } final SegmentWriteState flushState = new SegmentWriteState(infoStream, directory, segment, fieldInfos, numDocs, writer.getConfig().getTermIndexInterval(), SegmentCodecs.build(fieldInfos, writer.codecs)); newSegment = new SegmentInfo(segment, numDocs, directory, false, fieldInfos.hasProx(), flushState.segmentCodecs, false); Collection<DocConsumerPerThread> threads = new HashSet<DocConsumerPerThread>(); for (DocumentsWriterThreadState threadState : threadStates) { threads.add(threadState.consumer); } double startMBUsed = bytesUsed()/1024./1024.; consumer.flush(threads, flushState); newSegment.setHasVectors(flushState.hasVectors); if (infoStream != null) { message("new segment has " + (flushState.hasVectors ? "vectors" : "no vectors")); message("flushedFiles=" + flushState.flushedFiles); message("flushed codecs=" + newSegment.getSegmentCodecs()); } if (mergePolicy.useCompoundFile(segmentInfos, newSegment)) { final String cfsFileName = IndexFileNames.segmentFileName(segment, "", IndexFileNames.COMPOUND_FILE_EXTENSION); if (infoStream != null) { message("flush: create compound file \"" + cfsFileName + "\""); } CompoundFileWriter cfsWriter = new CompoundFileWriter(directory, cfsFileName); for(String fileName : flushState.flushedFiles) { cfsWriter.addFile(fileName); } cfsWriter.close(); deleter.deleteNewFiles(flushState.flushedFiles); newSegment.setUseCompoundFile(true); } if (infoStream != null) { message("flush: segment=" + newSegment); final double newSegmentSizeNoStore = newSegment.sizeInBytes(false)/1024./1024.; final double newSegmentSize = newSegment.sizeInBytes(true)/1024./1024.; message(" ramUsed=" + nf.format(startMBUsed) + " MB" + " newFlushedSize=" + nf.format(newSegmentSize) + " MB" + " (" + nf.format(newSegmentSizeNoStore) + " MB w/o doc stores)" + " docs/MB=" + nf.format(numDocs / newSegmentSize) + " new/old=" + nf.format(100.0 * newSegmentSizeNoStore / startMBUsed) + "%"); } success = true; } finally { notifyAll(); if (!success) { if (segment != null) { deleter.refresh(segment); } abort(); } } doAfterFlush(); // Lock order: IW -> DW -> BD pushDeletes(newSegment, segmentInfos); return newSegment; }
diff --git a/src/main/java/jp/irof/ac/ImageRequestFilter.java b/src/main/java/jp/irof/ac/ImageRequestFilter.java index de9ad35..2f32468 100644 --- a/src/main/java/jp/irof/ac/ImageRequestFilter.java +++ b/src/main/java/jp/irof/ac/ImageRequestFilter.java @@ -1,105 +1,105 @@ package jp.irof.ac; import hudson.util.PluginServletFilter; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.regex.Pattern; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * サーブレットフィルタクラス。<br> * Jenkinsのアプリ中のURLにアクセスされた場合、それが「特定の画像のリクエスト」である場合、<br> * 別の画像にリダイレクトするフィルター。 * * @author Kazuhito Miura */ public class ImageRequestFilter extends PluginServletFilter { /* * url-pathの変換は正規表現を使って行う。 * 正規表現(Patternオブジェクト作成)は若干のコストがかかると思われるため、ClassLoad時 * (staticの確保時)に作ってしまう戦略で行く。 */ /** プラグインのイメージが置いてあるpath(URL内) */ private static String PATH = "/plugin/irofkins/irof-images/"; /** 一次フィルタリング条件 */ private static final Pattern FIRST_FILTER = Pattern .compile(".*/(title|jenkins|angry-jenkins|sad-jenkins).png"); /** 二次フィルタリング条件 & 置き換え文字Map */ @SuppressWarnings("serial") private static final Map<String, String> SECCOND_FILTERS = new LinkedHashMap<String, String>() { { put("/plugin/emotional-jenkins-plugin/images/angry-jenkins.png", PATH + "angry-jenkins.png"); put("/plugin/emotional-jenkins-plugin/images/sad-jenkins.png", PATH + "sad-jenkins.png"); put("/plugin/emotional-jenkins-plugin/images/jenkins.png", PATH + "jenkins.png"); put("/static/.*/images/jenkins.png", PATH + "jenkins.png"); put("/static/.*/images/title.png", PATH + "title.png"); put("/images/jenkins.png", PATH + "jenkins.png"); put("/images/title.png", PATH + "title.png"); } }; /** * フィルタ処理。 * * @param request HTTPリクエストオブジェクト。<br> * @param response HTTPレスポンスオブジェクト。 * @param chain 伝搬する次のフィルタ。 * @throws IOException IO例外。 * @throws ServletException サーブレット起因の例外。 */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 作業用に変数取る。 String path = ((HttpServletRequest) request).getRequestURI(); // デバッグソース FileWriter f = new FileWriter("./irofkins_test.log"); f.write("\npath:" + path); // 一次フィルタリング。 // すべてのリクエストに4回ずつ比較は無駄が多そうなので、一つの正規表現で篩にかける。 if (FIRST_FILTER.matcher(path).matches()) { f.write("\first match!"); // 引っかかったら、二次フィルタリング。 // 該当したら、その当該部分だけを文字列置換しリダイレクト。 for (String src : SECCOND_FILTERS.keySet()) { if (path.matches(".*" + src)) { String dest = SECCOND_FILTERS.get(src); String replacedPath = path.replaceAll(src, dest); f.write("\nsecand match!"); - f.write("\nsrc:" + src + " , dest:" + dest + " , replacedPath:" + replasedPath); + f.write("\nsrc:" + src + " , dest:" + dest + " , replacedPath:" + replacedPath); ((HttpServletResponse) response).sendRedirect(replacedPath); break; } } } f.close(); chain.doFilter(request, response); } /** * オブジェクト破棄時の処理(デストラクタ)。 */ @Override public void destroy() { } }
true
true
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 作業用に変数取る。 String path = ((HttpServletRequest) request).getRequestURI(); // デバッグソース FileWriter f = new FileWriter("./irofkins_test.log"); f.write("\npath:" + path); // 一次フィルタリング。 // すべてのリクエストに4回ずつ比較は無駄が多そうなので、一つの正規表現で篩にかける。 if (FIRST_FILTER.matcher(path).matches()) { f.write("\first match!"); // 引っかかったら、二次フィルタリング。 // 該当したら、その当該部分だけを文字列置換しリダイレクト。 for (String src : SECCOND_FILTERS.keySet()) { if (path.matches(".*" + src)) { String dest = SECCOND_FILTERS.get(src); String replacedPath = path.replaceAll(src, dest); f.write("\nsecand match!"); f.write("\nsrc:" + src + " , dest:" + dest + " , replacedPath:" + replasedPath); ((HttpServletResponse) response).sendRedirect(replacedPath); break; } } } f.close(); chain.doFilter(request, response); }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 作業用に変数取る。 String path = ((HttpServletRequest) request).getRequestURI(); // デバッグソース FileWriter f = new FileWriter("./irofkins_test.log"); f.write("\npath:" + path); // 一次フィルタリング。 // すべてのリクエストに4回ずつ比較は無駄が多そうなので、一つの正規表現で篩にかける。 if (FIRST_FILTER.matcher(path).matches()) { f.write("\first match!"); // 引っかかったら、二次フィルタリング。 // 該当したら、その当該部分だけを文字列置換しリダイレクト。 for (String src : SECCOND_FILTERS.keySet()) { if (path.matches(".*" + src)) { String dest = SECCOND_FILTERS.get(src); String replacedPath = path.replaceAll(src, dest); f.write("\nsecand match!"); f.write("\nsrc:" + src + " , dest:" + dest + " , replacedPath:" + replacedPath); ((HttpServletResponse) response).sendRedirect(replacedPath); break; } } } f.close(); chain.doFilter(request, response); }
diff --git a/src/main/java/org/jcwal/so/network/service/impl/NetworkSchemaRegistory.java b/src/main/java/org/jcwal/so/network/service/impl/NetworkSchemaRegistory.java index 2ca59e2..c4dc61b 100644 --- a/src/main/java/org/jcwal/so/network/service/impl/NetworkSchemaRegistory.java +++ b/src/main/java/org/jcwal/so/network/service/impl/NetworkSchemaRegistory.java @@ -1,1061 +1,1061 @@ package org.jcwal.so.network.service.impl; import javax.annotation.PostConstruct; import org.macula.base.data.vo.CriteriaType; import org.macula.base.data.vo.DataType; import org.macula.base.data.vo.FieldControl; import org.macula.plugins.mda.finder.domain.FinderAction; import org.macula.plugins.mda.finder.domain.FinderColumn; import org.macula.plugins.mda.finder.domain.FinderDataSet; import org.macula.plugins.mda.finder.domain.FinderDetailView; import org.macula.plugins.mda.finder.domain.FinderParam; import org.macula.plugins.mda.finder.domain.FinderSchema; import org.macula.plugins.mda.finder.domain.FinderTabView; import org.macula.plugins.mda.finder.service.FinderSchemaService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class NetworkSchemaRegistory { public static final String NETWORKRESOURCE_SCHEMA = "NETWORKRESOURCE_SCHEMA"; public static final String SEGMENTRESOURCE_SCHEMA = "SEGMENTRESOURCE_SCHEMA"; public static final String DOCTOR_SCHEMA = "DOCTOR_SCHEMA"; @Autowired private FinderSchemaService memorySchemaService; @PostConstruct public void registry() { memorySchemaService.add(createDoctorSchema()); memorySchemaService.add(createNetworkResourceSchema()); memorySchemaService.add(createSegmentResourceSchema()); } private FinderSchema createSegmentResourceSchema() { FinderSchema schema = new FinderSchema(); schema.setCode(SEGMENTRESOURCE_SCHEMA); schema.setTitle("网段资源管理"); schema.setRelativePath("admin/network/segmentresource/list"); FinderDataSet finderDataSet = new FinderDataSet("SEGMENT_RESOURCE_SET"); schema.setFinderDataSet(finderDataSet); FinderParam param = null; FinderColumn column = new FinderColumn(); column.setLabel("编号"); column.setColumn("id"); column.setName("id"); column.setType(DataType.Long); column.setPkey(true); column.setVisible(false); schema.addColumn(column); column = new FinderColumn(); column.setLabel("类型"); column.setColumn("TYPE"); column.setName("TYPE"); column.setType(DataType.String); column.setVisible(false); column.setWidth(100); schema.addColumn(column); // param = new FinderParam(column, "segment_type_list"); // param.setEnableSearch(true); // param.setEnableFilter(true); // param.setDefaultCriteriaType(CriteriaType.Equals); // param.setFieldControl(FieldControl.Combox); // schema.addParam(param); column = new FinderColumn(); column.setLabel("区域"); column.setColumn("tarea"); column.setName("tarea"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("IP地址段"); column.setColumn("tsegment"); column.setName("tsegment"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.StartWith); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("用途"); column.setColumn("tusage"); column.setName("tusage"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("获取方式"); column.setColumn("taccess"); column.setName("taccess"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("VLAN号"); column.setColumn("tvlanCode"); column.setName("tvlanCode"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("VLAN名"); column.setColumn("tvlanName"); column.setName("tvlanName"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("起始IP"); column.setColumn("tstartIp"); column.setName("tstartIp"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); column = new FinderColumn(); column.setLabel("终止IP"); column.setColumn("tendIp"); column.setName("tendIp"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); column = new FinderColumn(); column.setLabel("IP数"); column.setColumn("tipSize"); column.setName("tipSize"); column.setType(DataType.String); column.setVisible(true); column.setWidth(50); schema.addColumn(column); column = new FinderColumn(); column.setLabel("子网掩码"); column.setColumn("tmask"); column.setName("tmask"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); column = new FinderColumn(); column.setLabel("网关"); column.setColumn("tgateway"); column.setName("tgateway"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); column = new FinderColumn(); column.setLabel("网关设备"); column.setColumn("tgatewayType"); column.setName("tgatewayType"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); column = new FinderColumn(); column.setLabel("保留IP"); column.setColumn("tkeepIps"); column.setName("tkeepIps"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); column = new FinderColumn(); column.setLabel("保留IP数"); column.setColumn("tkeepIpSize"); column.setName("tkeepIpSize"); column.setType(DataType.String); column.setVisible(true); column.setWidth(50); schema.addColumn(column); column = new FinderColumn(); column.setLabel("启用日期"); column.setColumn("tvalidateDate"); column.setName("tvalidateDate"); column.setType(DataType.Date); column.setFormat("yyyy-MM-dd"); column.setVisible(true); column.setWidth(80); schema.addColumn(column); column = new FinderColumn(); column.setLabel("取消日期"); column.setColumn("tinvalidateDate"); column.setName("tinvalidateDate"); column.setType(DataType.Date); column.setFormat("yyyy-MM-dd"); column.setVisible(true); column.setWidth(80); schema.addColumn(column); column = new FinderColumn(); column.setLabel("线路名称"); column.setColumn("tline"); column.setName("tline"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); schema.addParam(param); column = new FinderColumn(); column.setLabel("电路编号"); column.setColumn("telec"); column.setName("telec"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); schema.addParam(param); column = new FinderColumn(); column.setLabel("端口"); column.setColumn("tport"); column.setName("tport"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); schema.addParam(param); column = new FinderColumn(); column.setLabel("主DNS"); column.setColumn("tmainDns"); column.setName("tmainDns"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); schema.addParam(param); column = new FinderColumn(); column.setLabel("备DNS"); column.setColumn("tsecondDns"); column.setName("tsecondDns"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); schema.addParam(param); column = new FinderColumn(); column.setLabel("备注"); column.setColumn("comments"); column.setName("comments"); column.setType(DataType.String); column.setVisible(false); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); schema.setEnableFilter(true); schema.setEnableSearch(true); FinderAction action = new FinderAction(); action.setLabel("新增IP段"); action.setHref("admin/network/segmentresource/create"); action.setTarget("dialog::{title: '新增IP段', width:'720',height:'680'}"); schema.addAction(action); action = new FinderAction(); action.setLabel("编辑IP段"); action.setHref("admin/network/segmentresource/edit"); action.setTarget("dialog::{title: '编辑IP资源', width:'720',height:'680'}"); action.setMaxRowSelected(1); action.setMinRowSelected(1); schema.addAction(action); action = new FinderAction(); action.setLabel("创建此段IP"); action.setHref("admin/network/segmentresource/segment"); action.setTarget("dialog::{title: '创建此段IP', width:'720',height:'280'}"); action.setMinRowSelected(1); action.setMaxRowSelected(1); schema.addAction(action); // action = new FinderAction(); // action.setLabel("导出IP段"); // action.setHref("admin/network/segmentresource/export"); // action.setTarget("blank"); // action.setMinRowSelected(1); // action.setConfirm("您确定要导出EXCEL吗?"); // schema.addAction(action); action = new FinderAction(); action.setLabel("删除IP段"); action.setHref("admin/network/segmentresource/delete"); action.setConfirm("您确定删除该IP段吗?"); action.setTarget("command"); action.setMinRowSelected(1); schema.addAction(action); FinderTabView tabView = new FinderTabView(); tabView.setCode("insidesegment"); tabView.setLabel("内网网段"); tabView.setFilter(" type = 'A' "); tabView.setOrder(0); tabView.addColumns( schema, "id,TYPE,tarea,tsegment,tusage,taccess,tvlanCode,tvlanName,tstartIp,tendIp,tipSize,tmask,tgateway,tgatewayType,tkeepIps,tkeepIpSize,tvalidateDate,tinvalidateDate,comments"); schema.addTabView(tabView); tabView = new FinderTabView(); tabView.setCode("outsidesegment"); tabView.setLabel("互联网网段"); tabView.setFilter(" type = 'B' "); tabView.setOrder(1); tabView.addColumns(schema, "id,TYPE,tline,telec,tport,tstartIp,tendIp,tipSize,tmask,tgateway,tmainDns,tsecondDns"); schema.addTabView(tabView); schema.setHiddenDetailColumn(true); return schema; } private FinderSchema createDoctorSchema() { FinderSchema schema = new FinderSchema(); schema.setCode(DOCTOR_SCHEMA); schema.setTitle("人员管理"); schema.setRelativePath("admin/network/doctor/list"); FinderDataSet finderDataSet = new FinderDataSet("NETWORK_USER_SET"); schema.setFinderDataSet(finderDataSet); FinderParam param = null; FinderColumn column = new FinderColumn(); column.setLabel("编号"); column.setColumn("id"); column.setName("id"); column.setType(DataType.Long); column.setPkey(true); column.setVisible(false); schema.addColumn(column); column = new FinderColumn(); column.setLabel("帐号"); column.setColumn("USERNAME"); column.setName("USERNAME"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("姓名"); column.setColumn("NICKNAME"); column.setName("NICKNAME"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("岗位"); column.setColumn("TITLE"); column.setName("TITLE"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("电话"); column.setColumn("TELEPHONE"); column.setName("TELEPHONE"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("手机"); column.setColumn("MOBILE"); column.setName("MOBILE"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); schema.setEnableFilter(true); schema.setEnableSearch(true); FinderAction action = new FinderAction(); action.setLabel("新增"); action.setHref("admin/network/doctor/create"); action.setTarget("dialog::{title: '新增', width:'720',height:'280'}"); schema.addAction(action); action = new FinderAction(); action.setLabel("编辑"); action.setHref("admin/network/doctor/edit"); action.setTarget("dialog::{title: '编辑', width:'720',height:'250'}"); action.setMaxRowSelected(1); action.setMinRowSelected(1); schema.addAction(action); action = new FinderAction(); action.setLabel("删除"); action.setHref("admin/network/doctor/delete"); action.setConfirm("您确定删除吗?"); action.setTarget("command"); action.setMinRowSelected(1); schema.addAction(action); action = new FinderAction(); action.setLabel("修改密码"); action.setHref("admin/network/doctor/changepassword"); action.setTarget("dialog::{title: '修改密码', width:'580',height:'280'}"); action.setMaxRowSelected(1); action.setMinRowSelected(1); schema.addAction(action); action = new FinderAction(); action.setLabel("角色授权"); action.setMinRowSelected(1); action.setMaxRowSelected(1); action.setTarget("dialog::{title:'角色授权',width:'800',height:'600',type:'POST'}"); action.setHref("admin/macula-base/sysuser/admingrant"); schema.addAction(action); schema.setHiddenDetailColumn(true); return schema; } private FinderSchema createNetworkResourceSchema() { FinderSchema schema = new FinderSchema(); schema.setCode(NETWORKRESOURCE_SCHEMA); schema.setTitle("IP资源管理"); schema.setRelativePath("admin/network/networkresource/list"); FinderDataSet finderDataSet = new FinderDataSet("NETWORK_RESOURCE_SET"); schema.setFinderDataSet(finderDataSet); FinderParam param = null; FinderColumn column = new FinderColumn(); column.setLabel("编号"); column.setColumn("id"); column.setName("id"); column.setType(DataType.Long); column.setPkey(true); column.setVisible(false); schema.addColumn(column); column = new FinderColumn(); column.setLabel("IP地址"); column.setColumn("IP"); column.setName("IP"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.StartWith); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("类型"); column.setColumn("TYPE"); column.setName("TYPE"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, "network_type_list"); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Equals); param.setFieldControl(FieldControl.Combox); schema.addParam(param); column = new FinderColumn(); column.setLabel("可用"); column.setColumn("tusable"); column.setName("tusable"); column.setType(DataType.Boolean); column.setVisible(true); column.setWidth(50); schema.addColumn(column); param = new FinderParam(column, "network_usable_list"); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Equals); param.setFieldControl(FieldControl.Combox); schema.addParam(param); column = new FinderColumn(); column.setLabel("MAC地址"); column.setColumn("tmac"); column.setName("tmac"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); column = new FinderColumn(); column.setLabel("设备类型"); column.setColumn("tgroup"); column.setName("tgroup"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, "network_group_list"); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Equals); param.setFieldControl(FieldControl.Combox); schema.addParam(param); column = new FinderColumn(); column.setLabel("用途"); column.setColumn("tusage"); column.setName("tusage"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("设备名称"); column.setColumn("tname"); column.setName("tname"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("应用系统"); column.setColumn("tapplication"); column.setName("tapplication"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("操作系统"); column.setColumn("toperation"); column.setName("toperation"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("网络区域"); column.setColumn("tarea"); column.setName("tarea"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("所在机房"); column.setColumn("troom"); column.setName("troom"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("机架位置"); column.setColumn("tposition"); column.setName("tposition"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("交换机IP"); column.setColumn("tswitchIp"); column.setName("tswitchIp"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("交换机端口"); column.setColumn("tswitchPort"); column.setName("tswitchPort"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("配线架号"); column.setColumn("tdist"); column.setName("tdist"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); //////////////////////////////////外网/////////////////////////////////// column = new FinderColumn(); column.setLabel("域名"); column.setColumn("tdomain"); column.setName("tdomain"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("VS IP"); column.setColumn("tvsIp"); column.setName("tvsIp"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("F5 IP"); column.setColumn("tf5Ip"); column.setName("tf5Ip"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("VS IP"); column.setColumn("tvsIp"); column.setName("tvsIp"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("内网发布端口"); column.setColumn("tinsidePort"); column.setName("tinsidePort"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("公网IP"); column.setColumn("toutsideIp"); column.setName("toutsideIp"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("公网发布端口"); column.setColumn("toutsidePort"); column.setName("toutsidePort"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("服务器IP"); column.setColumn("tserverIp"); column.setName("tserverIp"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("线路名称"); column.setColumn("tline"); column.setName("tline"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("备注"); column.setColumn("comments"); column.setName("comments"); column.setType(DataType.String); column.setVisible(false); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); schema.setEnableFilter(true); schema.setEnableSearch(true); FinderAction action = new FinderAction(); action.setLabel("新增IP资源"); action.setHref("admin/network/networkresource/create"); action.setTarget("dialog::{title: '新增IP资源', width:'720',height:'680'}"); schema.addAction(action); action = new FinderAction(); action.setLabel("编辑IP资源"); action.setHref("admin/network/networkresource/edit"); action.setTarget("dialog::{title: '编辑IP资源', width:'720',height:'680'}"); action.setMaxRowSelected(1); action.setMinRowSelected(1); schema.addAction(action); action = new FinderAction(); action.setLabel("导出IP资源"); action.setHref("admin/network/networkresource/export"); action.setTarget("blank"); action.setMinRowSelected(1); action.setConfirm("您确定要导出EXCEL吗?"); schema.addAction(action); action = new FinderAction(); action.setLabel("删除IP资源"); action.setHref("admin/network/networkresource/delete"); action.setConfirm("您确定删除该IP资源吗?"); action.setTarget("command"); action.setMinRowSelected(1); schema.addAction(action); FinderTabView tabView = new FinderTabView(); tabView.setCode("insideips"); tabView.setLabel("内网办公区"); tabView.setFilter(" type = 'A' "); tabView.setOrder(0); tabView.addColumns( schema, "id,IP,TYPE,tusable,tmac,tgroup,tmodel,tname,tapplication,tusage,toperation,tarea,troom,tposition,tswitchIp,tswitchPort,tdist"); schema.addTabView(tabView); tabView = new FinderTabView(); tabView.setCode("insideserver"); tabView.setLabel("内网服务器区"); tabView.setFilter(" type = 'B' "); tabView.setOrder(1); tabView.addColumns( schema, "id,IP,TYPE,tusable,tmac,tgroup,tmodel,tname,tapplication,tusage,toperation,tarea,troom,tposition,tswitchIp,tswitchPort,tdist"); schema.addTabView(tabView); tabView = new FinderTabView(); tabView.setCode("outsideserver"); tabView.setLabel("F5发布区"); tabView.setFilter(" type = 'C' "); tabView.setOrder(2); tabView.addColumns(schema, "id,IP,TYPE,tusable,tdomain,tvsIp,tf5Ip,tinsidePort,toutsideIp,toutsidePort,tserverIp,tusage,tapplication,troom"); schema.addTabView(tabView); tabView = new FinderTabView(); tabView.setCode("networkserver"); tabView.setLabel("互联网发布区"); tabView.setFilter(" type = 'D' "); tabView.setOrder(3); tabView.addColumns(schema, - "id,IP,TYPE,tusable,tdomain,tf5Ip,toutsideIp,tserverIp,tusage,tapplication,tline,troom"); + "id,IP,TYPE,tusable,tdomain,tf5Ip,toutsidePort,tserverIp,tusage,tapplication,tline,troom"); schema.addTabView(tabView); tabView = new FinderTabView(); tabView.setCode("allips"); tabView.setLabel("所有IP资源"); tabView.setFilter(" 1=1 "); tabView.setOrder(4); schema.addTabView(tabView); FinderDetailView detailView = new FinderDetailView(); detailView.setCode("detail"); detailView.setLabel("详细信息"); detailView.setHref("admin/network/networkresource/detail"); schema.addDetailView(detailView); detailView = new FinderDetailView(); detailView.setCode("segdetail"); detailView.setLabel("网段信息"); detailView.setHref("admin/network/networkresource/segdetail"); schema.addDetailView(detailView); return schema; } }
true
true
private FinderSchema createNetworkResourceSchema() { FinderSchema schema = new FinderSchema(); schema.setCode(NETWORKRESOURCE_SCHEMA); schema.setTitle("IP资源管理"); schema.setRelativePath("admin/network/networkresource/list"); FinderDataSet finderDataSet = new FinderDataSet("NETWORK_RESOURCE_SET"); schema.setFinderDataSet(finderDataSet); FinderParam param = null; FinderColumn column = new FinderColumn(); column.setLabel("编号"); column.setColumn("id"); column.setName("id"); column.setType(DataType.Long); column.setPkey(true); column.setVisible(false); schema.addColumn(column); column = new FinderColumn(); column.setLabel("IP地址"); column.setColumn("IP"); column.setName("IP"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.StartWith); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("类型"); column.setColumn("TYPE"); column.setName("TYPE"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, "network_type_list"); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Equals); param.setFieldControl(FieldControl.Combox); schema.addParam(param); column = new FinderColumn(); column.setLabel("可用"); column.setColumn("tusable"); column.setName("tusable"); column.setType(DataType.Boolean); column.setVisible(true); column.setWidth(50); schema.addColumn(column); param = new FinderParam(column, "network_usable_list"); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Equals); param.setFieldControl(FieldControl.Combox); schema.addParam(param); column = new FinderColumn(); column.setLabel("MAC地址"); column.setColumn("tmac"); column.setName("tmac"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); column = new FinderColumn(); column.setLabel("设备类型"); column.setColumn("tgroup"); column.setName("tgroup"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, "network_group_list"); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Equals); param.setFieldControl(FieldControl.Combox); schema.addParam(param); column = new FinderColumn(); column.setLabel("用途"); column.setColumn("tusage"); column.setName("tusage"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("设备名称"); column.setColumn("tname"); column.setName("tname"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("应用系统"); column.setColumn("tapplication"); column.setName("tapplication"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("操作系统"); column.setColumn("toperation"); column.setName("toperation"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("网络区域"); column.setColumn("tarea"); column.setName("tarea"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("所在机房"); column.setColumn("troom"); column.setName("troom"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("机架位置"); column.setColumn("tposition"); column.setName("tposition"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("交换机IP"); column.setColumn("tswitchIp"); column.setName("tswitchIp"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("交换机端口"); column.setColumn("tswitchPort"); column.setName("tswitchPort"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("配线架号"); column.setColumn("tdist"); column.setName("tdist"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); //////////////////////////////////外网/////////////////////////////////// column = new FinderColumn(); column.setLabel("域名"); column.setColumn("tdomain"); column.setName("tdomain"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("VS IP"); column.setColumn("tvsIp"); column.setName("tvsIp"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("F5 IP"); column.setColumn("tf5Ip"); column.setName("tf5Ip"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("VS IP"); column.setColumn("tvsIp"); column.setName("tvsIp"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("内网发布端口"); column.setColumn("tinsidePort"); column.setName("tinsidePort"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("公网IP"); column.setColumn("toutsideIp"); column.setName("toutsideIp"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("公网发布端口"); column.setColumn("toutsidePort"); column.setName("toutsidePort"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("服务器IP"); column.setColumn("tserverIp"); column.setName("tserverIp"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("线路名称"); column.setColumn("tline"); column.setName("tline"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("备注"); column.setColumn("comments"); column.setName("comments"); column.setType(DataType.String); column.setVisible(false); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); schema.setEnableFilter(true); schema.setEnableSearch(true); FinderAction action = new FinderAction(); action.setLabel("新增IP资源"); action.setHref("admin/network/networkresource/create"); action.setTarget("dialog::{title: '新增IP资源', width:'720',height:'680'}"); schema.addAction(action); action = new FinderAction(); action.setLabel("编辑IP资源"); action.setHref("admin/network/networkresource/edit"); action.setTarget("dialog::{title: '编辑IP资源', width:'720',height:'680'}"); action.setMaxRowSelected(1); action.setMinRowSelected(1); schema.addAction(action); action = new FinderAction(); action.setLabel("导出IP资源"); action.setHref("admin/network/networkresource/export"); action.setTarget("blank"); action.setMinRowSelected(1); action.setConfirm("您确定要导出EXCEL吗?"); schema.addAction(action); action = new FinderAction(); action.setLabel("删除IP资源"); action.setHref("admin/network/networkresource/delete"); action.setConfirm("您确定删除该IP资源吗?"); action.setTarget("command"); action.setMinRowSelected(1); schema.addAction(action); FinderTabView tabView = new FinderTabView(); tabView.setCode("insideips"); tabView.setLabel("内网办公区"); tabView.setFilter(" type = 'A' "); tabView.setOrder(0); tabView.addColumns( schema, "id,IP,TYPE,tusable,tmac,tgroup,tmodel,tname,tapplication,tusage,toperation,tarea,troom,tposition,tswitchIp,tswitchPort,tdist"); schema.addTabView(tabView); tabView = new FinderTabView(); tabView.setCode("insideserver"); tabView.setLabel("内网服务器区"); tabView.setFilter(" type = 'B' "); tabView.setOrder(1); tabView.addColumns( schema, "id,IP,TYPE,tusable,tmac,tgroup,tmodel,tname,tapplication,tusage,toperation,tarea,troom,tposition,tswitchIp,tswitchPort,tdist"); schema.addTabView(tabView); tabView = new FinderTabView(); tabView.setCode("outsideserver"); tabView.setLabel("F5发布区"); tabView.setFilter(" type = 'C' "); tabView.setOrder(2); tabView.addColumns(schema, "id,IP,TYPE,tusable,tdomain,tvsIp,tf5Ip,tinsidePort,toutsideIp,toutsidePort,tserverIp,tusage,tapplication,troom"); schema.addTabView(tabView); tabView = new FinderTabView(); tabView.setCode("networkserver"); tabView.setLabel("互联网发布区"); tabView.setFilter(" type = 'D' "); tabView.setOrder(3); tabView.addColumns(schema, "id,IP,TYPE,tusable,tdomain,tf5Ip,toutsideIp,tserverIp,tusage,tapplication,tline,troom"); schema.addTabView(tabView); tabView = new FinderTabView(); tabView.setCode("allips"); tabView.setLabel("所有IP资源"); tabView.setFilter(" 1=1 "); tabView.setOrder(4); schema.addTabView(tabView); FinderDetailView detailView = new FinderDetailView(); detailView.setCode("detail"); detailView.setLabel("详细信息"); detailView.setHref("admin/network/networkresource/detail"); schema.addDetailView(detailView); detailView = new FinderDetailView(); detailView.setCode("segdetail"); detailView.setLabel("网段信息"); detailView.setHref("admin/network/networkresource/segdetail"); schema.addDetailView(detailView); return schema; }
private FinderSchema createNetworkResourceSchema() { FinderSchema schema = new FinderSchema(); schema.setCode(NETWORKRESOURCE_SCHEMA); schema.setTitle("IP资源管理"); schema.setRelativePath("admin/network/networkresource/list"); FinderDataSet finderDataSet = new FinderDataSet("NETWORK_RESOURCE_SET"); schema.setFinderDataSet(finderDataSet); FinderParam param = null; FinderColumn column = new FinderColumn(); column.setLabel("编号"); column.setColumn("id"); column.setName("id"); column.setType(DataType.Long); column.setPkey(true); column.setVisible(false); schema.addColumn(column); column = new FinderColumn(); column.setLabel("IP地址"); column.setColumn("IP"); column.setName("IP"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.StartWith); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("类型"); column.setColumn("TYPE"); column.setName("TYPE"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, "network_type_list"); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Equals); param.setFieldControl(FieldControl.Combox); schema.addParam(param); column = new FinderColumn(); column.setLabel("可用"); column.setColumn("tusable"); column.setName("tusable"); column.setType(DataType.Boolean); column.setVisible(true); column.setWidth(50); schema.addColumn(column); param = new FinderParam(column, "network_usable_list"); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Equals); param.setFieldControl(FieldControl.Combox); schema.addParam(param); column = new FinderColumn(); column.setLabel("MAC地址"); column.setColumn("tmac"); column.setName("tmac"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); column = new FinderColumn(); column.setLabel("设备类型"); column.setColumn("tgroup"); column.setName("tgroup"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, "network_group_list"); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Equals); param.setFieldControl(FieldControl.Combox); schema.addParam(param); column = new FinderColumn(); column.setLabel("用途"); column.setColumn("tusage"); column.setName("tusage"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("设备名称"); column.setColumn("tname"); column.setName("tname"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("应用系统"); column.setColumn("tapplication"); column.setName("tapplication"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("操作系统"); column.setColumn("toperation"); column.setName("toperation"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("网络区域"); column.setColumn("tarea"); column.setName("tarea"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("所在机房"); column.setColumn("troom"); column.setName("troom"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("机架位置"); column.setColumn("tposition"); column.setName("tposition"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("交换机IP"); column.setColumn("tswitchIp"); column.setName("tswitchIp"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("交换机端口"); column.setColumn("tswitchPort"); column.setName("tswitchPort"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("配线架号"); column.setColumn("tdist"); column.setName("tdist"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); //////////////////////////////////外网/////////////////////////////////// column = new FinderColumn(); column.setLabel("域名"); column.setColumn("tdomain"); column.setName("tdomain"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("VS IP"); column.setColumn("tvsIp"); column.setName("tvsIp"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("F5 IP"); column.setColumn("tf5Ip"); column.setName("tf5Ip"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("VS IP"); column.setColumn("tvsIp"); column.setName("tvsIp"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("内网发布端口"); column.setColumn("tinsidePort"); column.setName("tinsidePort"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("公网IP"); column.setColumn("toutsideIp"); column.setName("toutsideIp"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("公网发布端口"); column.setColumn("toutsidePort"); column.setName("toutsidePort"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("服务器IP"); column.setColumn("tserverIp"); column.setName("tserverIp"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("线路名称"); column.setColumn("tline"); column.setName("tline"); column.setType(DataType.String); column.setVisible(true); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); column = new FinderColumn(); column.setLabel("备注"); column.setColumn("comments"); column.setName("comments"); column.setType(DataType.String); column.setVisible(false); column.setWidth(100); schema.addColumn(column); param = new FinderParam(column, null); param.setEnableSearch(true); param.setEnableFilter(true); param.setDefaultCriteriaType(CriteriaType.Contains); param.setFieldControl(FieldControl.Text); schema.addParam(param); schema.setEnableFilter(true); schema.setEnableSearch(true); FinderAction action = new FinderAction(); action.setLabel("新增IP资源"); action.setHref("admin/network/networkresource/create"); action.setTarget("dialog::{title: '新增IP资源', width:'720',height:'680'}"); schema.addAction(action); action = new FinderAction(); action.setLabel("编辑IP资源"); action.setHref("admin/network/networkresource/edit"); action.setTarget("dialog::{title: '编辑IP资源', width:'720',height:'680'}"); action.setMaxRowSelected(1); action.setMinRowSelected(1); schema.addAction(action); action = new FinderAction(); action.setLabel("导出IP资源"); action.setHref("admin/network/networkresource/export"); action.setTarget("blank"); action.setMinRowSelected(1); action.setConfirm("您确定要导出EXCEL吗?"); schema.addAction(action); action = new FinderAction(); action.setLabel("删除IP资源"); action.setHref("admin/network/networkresource/delete"); action.setConfirm("您确定删除该IP资源吗?"); action.setTarget("command"); action.setMinRowSelected(1); schema.addAction(action); FinderTabView tabView = new FinderTabView(); tabView.setCode("insideips"); tabView.setLabel("内网办公区"); tabView.setFilter(" type = 'A' "); tabView.setOrder(0); tabView.addColumns( schema, "id,IP,TYPE,tusable,tmac,tgroup,tmodel,tname,tapplication,tusage,toperation,tarea,troom,tposition,tswitchIp,tswitchPort,tdist"); schema.addTabView(tabView); tabView = new FinderTabView(); tabView.setCode("insideserver"); tabView.setLabel("内网服务器区"); tabView.setFilter(" type = 'B' "); tabView.setOrder(1); tabView.addColumns( schema, "id,IP,TYPE,tusable,tmac,tgroup,tmodel,tname,tapplication,tusage,toperation,tarea,troom,tposition,tswitchIp,tswitchPort,tdist"); schema.addTabView(tabView); tabView = new FinderTabView(); tabView.setCode("outsideserver"); tabView.setLabel("F5发布区"); tabView.setFilter(" type = 'C' "); tabView.setOrder(2); tabView.addColumns(schema, "id,IP,TYPE,tusable,tdomain,tvsIp,tf5Ip,tinsidePort,toutsideIp,toutsidePort,tserverIp,tusage,tapplication,troom"); schema.addTabView(tabView); tabView = new FinderTabView(); tabView.setCode("networkserver"); tabView.setLabel("互联网发布区"); tabView.setFilter(" type = 'D' "); tabView.setOrder(3); tabView.addColumns(schema, "id,IP,TYPE,tusable,tdomain,tf5Ip,toutsidePort,tserverIp,tusage,tapplication,tline,troom"); schema.addTabView(tabView); tabView = new FinderTabView(); tabView.setCode("allips"); tabView.setLabel("所有IP资源"); tabView.setFilter(" 1=1 "); tabView.setOrder(4); schema.addTabView(tabView); FinderDetailView detailView = new FinderDetailView(); detailView.setCode("detail"); detailView.setLabel("详细信息"); detailView.setHref("admin/network/networkresource/detail"); schema.addDetailView(detailView); detailView = new FinderDetailView(); detailView.setCode("segdetail"); detailView.setLabel("网段信息"); detailView.setHref("admin/network/networkresource/segdetail"); schema.addDetailView(detailView); return schema; }
diff --git a/src/org/perez/ga/algorithms/TGA.java b/src/org/perez/ga/algorithms/TGA.java index c11e49f..da7f1fa 100644 --- a/src/org/perez/ga/algorithms/TGA.java +++ b/src/org/perez/ga/algorithms/TGA.java @@ -1,257 +1,257 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.perez.ga.algorithms; import java.util.Comparator; import java.util.Random; import java.util.Properties; import java.io.File; import java.io.FileInputStream; import org.perez.ga.core.Genotipo; import org.perez.ga.core.GenotipoComparator; import org.perez.ga.core.IFitness; import org.perez.ga.core.Mode; import org.perez.ga.core.Poblacion; /** * Elitist Canonical Genetic Algorithm * - Linear offset scaling * - Sorted roulette selection * @author Fer */ public class TGA { /** Crossver probability */ private double P_c; /** Mutation probability */ private double P_m; /** Population size */ private int M; /** Number of generations */ private int G; /** String (Genotipe) length */ private int L; private Random rnd; private IFitness func; private GenotipoComparator comp; private int verboseLvl; private Poblacion pobActual; private Genotipo mejorInd; private int mejorGeneracion; public TGA(File f) { Properties p = null; try { p = new Properties(); p.load(new FileInputStream(f.getAbsoluteFile())); P_c = Double.valueOf(p.getProperty("P_c")); P_m = Double.valueOf(p.getProperty("P_m")); M = Integer.valueOf(p.getProperty("M")); G = Integer.valueOf(p.getProperty("G")); L = Integer.valueOf(p.getProperty("L")); func = (IFitness)Class.forName(p.getProperty("Func")).newInstance(); comp = new GenotipoComparator(func, Mode.valueOf(p.getProperty("Mode"))); if(p.containsKey("Verbose")) { this.verboseLvl = Integer.valueOf(p.getProperty("Verbose"));} if(p.containsKey("Seed")) { this.rnd = new Random(Integer.valueOf(p.getProperty("Seed")));} else { rnd = new Random();} } catch(Exception e) { System.err.println("Error al leer los parametros TGA"); System.err.println(e); System.exit(1); } } private void println(String s) { if(verboseLvl>0) { System.out.println(s); } } public Genotipo TGA() { Poblacion nva; double probs[]; Genotipo res[] = new Genotipo[2]; Genotipo g_x, g_y; int hechos; pobActual = new Poblacion(M, L, rnd); //1. Generate a random population //mejorInd = pobActual.getBest(func); mejorInd = pobActual.getIndividuo(rnd.nextInt(M));//2. Select randomly and individual from the population println("G,Best,Fitness"); //0. Make k <- 1 for(int k=1; k<=G; k++) { //4. If k = G return best and stop(done) probs = generaRuleta(pobActual); //5. Selection //6. Crossover nva = new Poblacion(pobActual.getSize()); hechos = 0; while(hechos < M) { // for i=1 to n step 2 g_x = pobActual.getIndividuo( this.escogeRuleta(probs) ); //Randomly select two individuals(i_x, i_y) with g_y = pobActual.getIndividuo( this.escogeRuleta(probs) ); //probabilities PS_x and PS_y, respect if(toss(P_c)) { //generate rand and if ro<=P_c do res = this.crossover(g_x, g_y); //do crossover } else { res[0] = (Genotipo)g_x.clone(); res[1] = (Genotipo)g_y.clone(); } this.mutate(res[0]); //7. Mutation nva.addIndividuo(res[0]); hechos++; if(hechos<M) { this.mutate(res[1]); //7. Mutation nva.addIndividuo(res[1]); hechos++; } } Genotipo b = pobActual.getBest(func); pobActual = nva; if( func.evalua(mejorInd) < func.evalua(b) ) { //max { mejorInd = b; } int idx = 0; b = pobActual.getIndividuo(0); for(int i=0; i<pobActual.getSize(); i++) { if(b.getFitness(func) > pobActual.getIndividuo(i).getFitness(func)) { b = pobActual.getIndividuo(i); idx = i; } } - pobActual.setIndividuo(idx, b); + pobActual.setIndividuo(idx, mejorInd); println(k +", " +func.getFenotipo(pobActual.getBest(func)) +", " +func.evalua(pobActual.getBest(func))); } System.out.println("Mejor: " +func.getFenotipo(mejorInd) +", Fitness: " +func.evalua(mejorInd)); return mejorInd; } double[] generaRuleta(Poblacion p) { int tam = p.getSize(); double[] vals = new double[tam]; double F = 0.0; this.escalaPoblacion(p); p.sort(comp); for(int i=0; i<tam; i++) { F += p.getIndividuo(i).getFitnessValue(); } for(int i=0; i<tam; i++) { //for i=1 to n PS_i = f(x_i)/F (done) vals[i] = p.getIndividuo(i).getFitnessValue(); vals[i] /= F; } return vals; } void escalaPoblacion(Poblacion p) { //Make F = sum fitness x_i (done) //for i=1 to n Select I(i) with probability PS_i (done) //its the probability int tam = p.getSize(); double[] vals = new double[tam]; double prom = 0.0; double v; double minv = Double.MAX_VALUE; //3. Evaluate get the data for offset linear scaling for(int i=0; i<tam; i++) { v = p.getIndividuo(i).getFitness(func); minv = Math.min(v, minv); prom += Math.abs(v); vals[i] = v; } prom /= this.M; minv = Math.abs(minv); // F_i = Phi(i), F, probs for(int i=0; i<tam; i++) { v = vals[i] + prom + minv; p.getIndividuo(i).setFitnessValue(v); } } /** * Executes a toss * @param p Probability of HEAD * @return True if HEAD, false else */ protected boolean toss(double p) { return rnd.nextDouble() <= p; } /** CAMBIA al genotipo dado como parametro * @param g El Genotipo a mutar */ protected void mutate(Genotipo g) { int tam = g.getSize(); for(int i=0; i<tam; i++) { //for j=1 to L if(toss(this.P_m)) { //if rand ro<=P_m make bit_j = !bit_j g.setGen(i, !g.getGen(i)); } } } /** * Given a vector or probabilities, select * proportionalitty a index * @param probs An array with the probabilites * @return and index corresponding to the individual * select via roulette */ int escogeRuleta(double probs[]) { double acum = 0; int res = 0; double tope = rnd.nextDouble(); while(res<probs.length && acum < tope) { acum += probs[res]; res++; } if(res==probs.length) { res--; } //System.out.println("tope="+tope +", suma=" +acum +", idx=" +res); //System.out.println(res +","); return res; } /** * Generate two new individuals with 1 point * crossover (1X) * @param a First parent * @param b Second parent * @return And array with 2 elements with the * parents gen */ protected Genotipo[] crossover(Genotipo a, Genotipo b) { Genotipo arr[] = new Genotipo[2]; arr[0] = new Genotipo(L); arr[1] = new Genotipo(L); //Randomly select a locus l(pto) of the chromosome int pto = (int)(rnd.nextDouble()*L); //System.out.println("Corte: " +pto); int i; //Pick the leftmost L-l bits of I(x) and the rightmost l bits of I(Y) //and concatenate them to form the new chromosome of I(X) for(i=0; i<pto; i++) { arr[0].setGen(i, b.getGen(i)); arr[1].setGen(i, a.getGen(i)); } for(; i<L; i++) { arr[0].setGen(i, a.getGen(i)); arr[1].setGen(i, b.getGen(i)); } return arr; } }
true
true
public Genotipo TGA() { Poblacion nva; double probs[]; Genotipo res[] = new Genotipo[2]; Genotipo g_x, g_y; int hechos; pobActual = new Poblacion(M, L, rnd); //1. Generate a random population //mejorInd = pobActual.getBest(func); mejorInd = pobActual.getIndividuo(rnd.nextInt(M));//2. Select randomly and individual from the population println("G,Best,Fitness"); //0. Make k <- 1 for(int k=1; k<=G; k++) { //4. If k = G return best and stop(done) probs = generaRuleta(pobActual); //5. Selection //6. Crossover nva = new Poblacion(pobActual.getSize()); hechos = 0; while(hechos < M) { // for i=1 to n step 2 g_x = pobActual.getIndividuo( this.escogeRuleta(probs) ); //Randomly select two individuals(i_x, i_y) with g_y = pobActual.getIndividuo( this.escogeRuleta(probs) ); //probabilities PS_x and PS_y, respect if(toss(P_c)) { //generate rand and if ro<=P_c do res = this.crossover(g_x, g_y); //do crossover } else { res[0] = (Genotipo)g_x.clone(); res[1] = (Genotipo)g_y.clone(); } this.mutate(res[0]); //7. Mutation nva.addIndividuo(res[0]); hechos++; if(hechos<M) { this.mutate(res[1]); //7. Mutation nva.addIndividuo(res[1]); hechos++; } } Genotipo b = pobActual.getBest(func); pobActual = nva; if( func.evalua(mejorInd) < func.evalua(b) ) { //max { mejorInd = b; } int idx = 0; b = pobActual.getIndividuo(0); for(int i=0; i<pobActual.getSize(); i++) { if(b.getFitness(func) > pobActual.getIndividuo(i).getFitness(func)) { b = pobActual.getIndividuo(i); idx = i; } } pobActual.setIndividuo(idx, b); println(k +", " +func.getFenotipo(pobActual.getBest(func)) +", " +func.evalua(pobActual.getBest(func))); } System.out.println("Mejor: " +func.getFenotipo(mejorInd) +", Fitness: " +func.evalua(mejorInd)); return mejorInd; } double[] generaRuleta(Poblacion p) { int tam = p.getSize(); double[] vals = new double[tam]; double F = 0.0; this.escalaPoblacion(p); p.sort(comp); for(int i=0; i<tam; i++) { F += p.getIndividuo(i).getFitnessValue(); } for(int i=0; i<tam; i++) { //for i=1 to n PS_i = f(x_i)/F (done) vals[i] = p.getIndividuo(i).getFitnessValue(); vals[i] /= F; } return vals; } void escalaPoblacion(Poblacion p) { //Make F = sum fitness x_i (done) //for i=1 to n Select I(i) with probability PS_i (done) //its the probability int tam = p.getSize(); double[] vals = new double[tam]; double prom = 0.0; double v; double minv = Double.MAX_VALUE; //3. Evaluate get the data for offset linear scaling for(int i=0; i<tam; i++) { v = p.getIndividuo(i).getFitness(func); minv = Math.min(v, minv); prom += Math.abs(v); vals[i] = v; } prom /= this.M; minv = Math.abs(minv); // F_i = Phi(i), F, probs for(int i=0; i<tam; i++) { v = vals[i] + prom + minv; p.getIndividuo(i).setFitnessValue(v); } } /** * Executes a toss * @param p Probability of HEAD * @return True if HEAD, false else */ protected boolean toss(double p) { return rnd.nextDouble() <= p; } /** CAMBIA al genotipo dado como parametro * @param g El Genotipo a mutar */ protected void mutate(Genotipo g) { int tam = g.getSize(); for(int i=0; i<tam; i++) { //for j=1 to L if(toss(this.P_m)) { //if rand ro<=P_m make bit_j = !bit_j g.setGen(i, !g.getGen(i)); } } } /** * Given a vector or probabilities, select * proportionalitty a index * @param probs An array with the probabilites * @return and index corresponding to the individual * select via roulette */ int escogeRuleta(double probs[]) { double acum = 0; int res = 0; double tope = rnd.nextDouble(); while(res<probs.length && acum < tope) { acum += probs[res]; res++; } if(res==probs.length) { res--; } //System.out.println("tope="+tope +", suma=" +acum +", idx=" +res); //System.out.println(res +","); return res; } /** * Generate two new individuals with 1 point * crossover (1X) * @param a First parent * @param b Second parent * @return And array with 2 elements with the * parents gen */ protected Genotipo[] crossover(Genotipo a, Genotipo b) { Genotipo arr[] = new Genotipo[2]; arr[0] = new Genotipo(L); arr[1] = new Genotipo(L); //Randomly select a locus l(pto) of the chromosome int pto = (int)(rnd.nextDouble()*L); //System.out.println("Corte: " +pto); int i; //Pick the leftmost L-l bits of I(x) and the rightmost l bits of I(Y) //and concatenate them to form the new chromosome of I(X) for(i=0; i<pto; i++) { arr[0].setGen(i, b.getGen(i)); arr[1].setGen(i, a.getGen(i)); } for(; i<L; i++) { arr[0].setGen(i, a.getGen(i)); arr[1].setGen(i, b.getGen(i)); } return arr; } }
public Genotipo TGA() { Poblacion nva; double probs[]; Genotipo res[] = new Genotipo[2]; Genotipo g_x, g_y; int hechos; pobActual = new Poblacion(M, L, rnd); //1. Generate a random population //mejorInd = pobActual.getBest(func); mejorInd = pobActual.getIndividuo(rnd.nextInt(M));//2. Select randomly and individual from the population println("G,Best,Fitness"); //0. Make k <- 1 for(int k=1; k<=G; k++) { //4. If k = G return best and stop(done) probs = generaRuleta(pobActual); //5. Selection //6. Crossover nva = new Poblacion(pobActual.getSize()); hechos = 0; while(hechos < M) { // for i=1 to n step 2 g_x = pobActual.getIndividuo( this.escogeRuleta(probs) ); //Randomly select two individuals(i_x, i_y) with g_y = pobActual.getIndividuo( this.escogeRuleta(probs) ); //probabilities PS_x and PS_y, respect if(toss(P_c)) { //generate rand and if ro<=P_c do res = this.crossover(g_x, g_y); //do crossover } else { res[0] = (Genotipo)g_x.clone(); res[1] = (Genotipo)g_y.clone(); } this.mutate(res[0]); //7. Mutation nva.addIndividuo(res[0]); hechos++; if(hechos<M) { this.mutate(res[1]); //7. Mutation nva.addIndividuo(res[1]); hechos++; } } Genotipo b = pobActual.getBest(func); pobActual = nva; if( func.evalua(mejorInd) < func.evalua(b) ) { //max { mejorInd = b; } int idx = 0; b = pobActual.getIndividuo(0); for(int i=0; i<pobActual.getSize(); i++) { if(b.getFitness(func) > pobActual.getIndividuo(i).getFitness(func)) { b = pobActual.getIndividuo(i); idx = i; } } pobActual.setIndividuo(idx, mejorInd); println(k +", " +func.getFenotipo(pobActual.getBest(func)) +", " +func.evalua(pobActual.getBest(func))); } System.out.println("Mejor: " +func.getFenotipo(mejorInd) +", Fitness: " +func.evalua(mejorInd)); return mejorInd; } double[] generaRuleta(Poblacion p) { int tam = p.getSize(); double[] vals = new double[tam]; double F = 0.0; this.escalaPoblacion(p); p.sort(comp); for(int i=0; i<tam; i++) { F += p.getIndividuo(i).getFitnessValue(); } for(int i=0; i<tam; i++) { //for i=1 to n PS_i = f(x_i)/F (done) vals[i] = p.getIndividuo(i).getFitnessValue(); vals[i] /= F; } return vals; } void escalaPoblacion(Poblacion p) { //Make F = sum fitness x_i (done) //for i=1 to n Select I(i) with probability PS_i (done) //its the probability int tam = p.getSize(); double[] vals = new double[tam]; double prom = 0.0; double v; double minv = Double.MAX_VALUE; //3. Evaluate get the data for offset linear scaling for(int i=0; i<tam; i++) { v = p.getIndividuo(i).getFitness(func); minv = Math.min(v, minv); prom += Math.abs(v); vals[i] = v; } prom /= this.M; minv = Math.abs(minv); // F_i = Phi(i), F, probs for(int i=0; i<tam; i++) { v = vals[i] + prom + minv; p.getIndividuo(i).setFitnessValue(v); } } /** * Executes a toss * @param p Probability of HEAD * @return True if HEAD, false else */ protected boolean toss(double p) { return rnd.nextDouble() <= p; } /** CAMBIA al genotipo dado como parametro * @param g El Genotipo a mutar */ protected void mutate(Genotipo g) { int tam = g.getSize(); for(int i=0; i<tam; i++) { //for j=1 to L if(toss(this.P_m)) { //if rand ro<=P_m make bit_j = !bit_j g.setGen(i, !g.getGen(i)); } } } /** * Given a vector or probabilities, select * proportionalitty a index * @param probs An array with the probabilites * @return and index corresponding to the individual * select via roulette */ int escogeRuleta(double probs[]) { double acum = 0; int res = 0; double tope = rnd.nextDouble(); while(res<probs.length && acum < tope) { acum += probs[res]; res++; } if(res==probs.length) { res--; } //System.out.println("tope="+tope +", suma=" +acum +", idx=" +res); //System.out.println(res +","); return res; } /** * Generate two new individuals with 1 point * crossover (1X) * @param a First parent * @param b Second parent * @return And array with 2 elements with the * parents gen */ protected Genotipo[] crossover(Genotipo a, Genotipo b) { Genotipo arr[] = new Genotipo[2]; arr[0] = new Genotipo(L); arr[1] = new Genotipo(L); //Randomly select a locus l(pto) of the chromosome int pto = (int)(rnd.nextDouble()*L); //System.out.println("Corte: " +pto); int i; //Pick the leftmost L-l bits of I(x) and the rightmost l bits of I(Y) //and concatenate them to form the new chromosome of I(X) for(i=0; i<pto; i++) { arr[0].setGen(i, b.getGen(i)); arr[1].setGen(i, a.getGen(i)); } for(; i<L; i++) { arr[0].setGen(i, a.getGen(i)); arr[1].setGen(i, b.getGen(i)); } return arr; } }
diff --git a/src/entities/BreakableWall.java b/src/entities/BreakableWall.java index 2e103c6..088078b 100644 --- a/src/entities/BreakableWall.java +++ b/src/entities/BreakableWall.java @@ -1,40 +1,40 @@ package entities; import game.Game; import graphics.Sprite; import java.util.Random; public class BreakableWall extends Wall { /** * @param x * @param y */ public BreakableWall(int x, int y) { super(x, y); - int z = new Random().nextInt(10); + int z = new Random().nextInt(12); // int z = (int) (Math.random() * 10); if (z < 4) { this.images = Sprite.load("w1.png", 100, 100); - } else if ((z >= 3) && (z < 8)) { + } else if ((z >= 4) && (z < 8)) { this.images = Sprite.load("w2.png", 100, 100); } else if (z >= 8) { this.images = Sprite.load("w3.png", 100, 100); } } /* * (non-Javadoc) * * @see entities.Entity#collide(entities.Entity) */ @Override public void collide(Entity e) { if (e instanceof BombAnimation) { this.removed = true; Game.staticBackground.add(new Background(this.x, this.y)); } } }
false
true
public BreakableWall(int x, int y) { super(x, y); int z = new Random().nextInt(10); // int z = (int) (Math.random() * 10); if (z < 4) { this.images = Sprite.load("w1.png", 100, 100); } else if ((z >= 3) && (z < 8)) { this.images = Sprite.load("w2.png", 100, 100); } else if (z >= 8) { this.images = Sprite.load("w3.png", 100, 100); } }
public BreakableWall(int x, int y) { super(x, y); int z = new Random().nextInt(12); // int z = (int) (Math.random() * 10); if (z < 4) { this.images = Sprite.load("w1.png", 100, 100); } else if ((z >= 4) && (z < 8)) { this.images = Sprite.load("w2.png", 100, 100); } else if (z >= 8) { this.images = Sprite.load("w3.png", 100, 100); } }
diff --git a/Sorry!/src/EngineNonGUITest.java b/Sorry!/src/EngineNonGUITest.java index 351f114..2ffaf3b 100644 --- a/Sorry!/src/EngineNonGUITest.java +++ b/Sorry!/src/EngineNonGUITest.java @@ -1,936 +1,936 @@ import static org.junit.Assert.*; import org.junit.Test; /** * Class for testing the Engine, using Non-GUI methods. * * @author TeamSorryDragons * */ public class EngineNonGUITest { @SuppressWarnings("javadoc") @Test public void test() { assertNotNull(new Engine(new BoardList(), "english")); } @SuppressWarnings("javadoc") @Test public void testMoveOnePieceOnce() { BoardList board = new BoardList(); Engine e = new Engine(board, "english"); e.newGame(); assertEquals( board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsn|rmn4|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nn|hbsn|bsn|bsf|bsf|bsf|bsf|bsf|bmn0|bsn|bsn|bmn4|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysn|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsn|gmn4|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"); try { e.move(1, e.pieces[0], e.board.getStartPointers()[0]); } catch (Exception exception) { } assertEquals( board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsnr|rmn3|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nn|hbsn|bsn|bsf|bsf|bsf|bsf|bsf|bmn0|bsn|bsn|bmn4|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysn|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsn|gmn4|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"); } @SuppressWarnings("javadoc") @Test public void testMoveOnePieceToEnd() { BoardList board = new BoardList(); Engine e = new Engine(board, "english"); e.newGame(); Piece pawn = e.pieces[5]; // that's a blue piece assertEquals(pawn.col, Piece.COLOR.blue); movePawn(1, pawn, e); assertEquals( board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsn|rmn4|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nn|hbsn|bsn|bsf|bsf|bsf|bsf|bsf|bmn0|bsn|bsnb|bmn3|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysn|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsn|gmn4|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"); movePawn(5, pawn, e); assertEquals( board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsn|rmn4|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nn|hbsn|bsn|bsf|bsf|bsf|bsf|bsf|bmn0|bsn|bsn|bmn3|nn|nn|nn|nn" + "|hbsnb|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysn|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsn|gmn4|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"); movePawn(8, pawn, e); assertEquals( board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsn|rmn4|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nn|hbsn|bsn|bsf|bsf|bsf|bsf|bsf|bmn0|bsn|bsn|bmn3|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysnb|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysn|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsn|gmn4|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"); movePawn(25, pawn, e); assertEquals( board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsn|rmn4|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nn|hbsn|bsn|bsf|bsf|bsf|bsf|bsf|bmn0|bsn|bsn|bmn3|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysn|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsn|gmn4|nn|nn|nn|nn|hgsn|gsn|gsn|gsnb|gsn|nn|nn|"); movePawn(19, pawn, e); assertEquals( board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsn|rmn4|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nn|hbsnb|bsn|bsf|bsf|bsf|bsf|bsf|bmn0|bsn|bsn|bmn3|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysn|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsn|gmn4|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"); movePawn(1, pawn, e); assertEquals( board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsn|rmn4|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nn|hbsn|bsnb|bsf|bsf|bsf|bsf|bsf|bmn0|bsn|bsn|bmn3|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysn|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsn|gmn4|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"); movePawn(2, pawn, e); assertEquals( board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsn|rmn4|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nn|hbsn|bsn|bsf|bsfb|bsf|bsf|bsf|bmn0|bsn|bsn|bmn3|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysn|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsn|gmn4|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"); movePawn(4, pawn, e); assertEquals( board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsn|rmn4|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nn|hbsn|bsn|bsf|bsf|bsf|bsf|bsf|bmn1|bsn|bsn|bmn3|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysn|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsn|gmn4|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"); } @SuppressWarnings("javadoc") @Test public void toStartTest() { BoardList board = new BoardList(); Engine e = new Engine(board, "english"); e.newGame(); movePawn(1, e.pieces[7], e); assertEquals( board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsn|rmn4|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nn|hbsn|bsn|bsf|bsf|bsf|bsf|bsf|bmn0|bsn|bsnb|bmn3|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysn|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsn|gmn4|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"); movePawn(1, e.pieces[1], e); movePawn(15, e.pieces[1], e); assertEquals( board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsn|rmn3|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nn|hbsn|bsn|bsf|bsf|bsf|bsf|bsf|bmn0|bsn|bsnr|bmn4|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysn|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsn|gmn4|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"); movePawn(1, e.pieces[9], e); assertEquals( board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsn|rmn3|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nn|hbsn|bsn|bsf|bsf|bsf|bsf|bsf|bmn0|bsn|bsnr|bmn4|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysny|ymn3" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsn|gmn4|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"); movePawn(15, e.pieces[1], e); assertEquals( board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsn|rmn3|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nn|hbsn|bsn|bsf|bsf|bsf|bsf|bsf|bmn0|bsn|bsn|bmn4|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysnr|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsn|gmn4|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"); movePawn(1, e.pieces[13], e); assertEquals( board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsn|rmn3|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nn|hbsn|bsn|bsf|bsf|bsf|bsf|bsf|bmn0|bsn|bsn|bmn4|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysnr|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsng|gmn3|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"); movePawn(15, e.pieces[1], e); assertEquals( board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsn|rmn3|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nn|hbsn|bsn|bsf|bsf|bsf|bsf|bsf|bmn0|bsn|bsn|bmn4|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysn|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsnr|gmn4|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"); movePawn(1, e.pieces[12], e); assertEquals( board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsn|rmn4|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nn|hbsn|bsn|bsf|bsf|bsf|bsf|bsf|bmn0|bsn|bsn|bmn4|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysn|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsng|gmn3|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"); } @Test public void testSlideMoves() { BoardList board = new BoardList(); Engine e = new Engine(board, "english"); e.newGame(); movePawn(1, e.pieces[0], e); movePawn(12, e.pieces[0], e); assertEquals( board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsn|rmn3|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nn|hbsn|bsn|bsf|bsf|bsf|bsf|bsf|bmn0|bsn|bsnr|bmn4|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysn|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsn|gmn4|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"); } @SuppressWarnings("javadoc") @Test public void testCoordinateToNodeCorners() { BoardList board = new BoardList(); Engine e = new Engine(board, "english"); e.newGame(); // assertEquals(e.convertCoordToNode(new SorryFrame.Coordinate(0, 0)), // board.getCornerPointers()[2]); } @SuppressWarnings("javadoc") @Test public void testCoordinateToIntCorners() { assertEquals(Engine.getNodePosition(new SorryFrame.Coordinate(15, 15)), 0); assertEquals(Engine.getNodePosition(new SorryFrame.Coordinate(0, 15)), 22); assertEquals(Engine.getNodePosition(new SorryFrame.Coordinate(0, 0)), 44); assertEquals(Engine.getNodePosition(new SorryFrame.Coordinate(15, 0)), 66); } @SuppressWarnings("javadoc") @Test public void testCoordinateToIntStarts() { for (int i = 10; i <= 12; i++) { for (int j = 12; j <= 14; j++) assertEquals( Engine.getNodePosition(new SorryFrame.Coordinate(i, j)), 11); } for (int i = 3; i <= 5; i++) { for (int j = 14; j >= 12; j--) assertEquals( Engine.getNodePosition(new SorryFrame.Coordinate(j, i)), 77); } for (int i = 3; i <= 5; i++) { for (int j = 1; j <= 3; j++) { assertEquals( Engine.getNodePosition(new SorryFrame.Coordinate(i, j)), 55); } } for (int i = 1; i <= 3; i++) { for (int j = 12; j >= 10; j--) { assertEquals( Engine.getNodePosition(new SorryFrame.Coordinate(i, j)), 33); } } } @SuppressWarnings("javadoc") @Test public void testCoordinateToIntHomeZones() { for (int i = 14; i >= 12; i--) { for (int j = 7; j <= 9; j++) assertEquals( Engine.getNodePosition(new SorryFrame.Coordinate(i, j)), 8); } for (int i = 9; i >= 7; i--) { for (int j = 1; j <= 3; j++) assertEquals( Engine.getNodePosition(new SorryFrame.Coordinate(i, j)), 74); } for (int i = 1; i <= 3; i++) for (int j = 6; j <= 8; j++) assertEquals( Engine.getNodePosition(new SorryFrame.Coordinate(i, j)), 52); for (int i = 6; i <= 8; i++) for (int j = 14; j >= 12; j--) assertEquals( Engine.getNodePosition(new SorryFrame.Coordinate(i, j)), 30); } @SuppressWarnings("javadoc") @Test public void testCoordinateToIntSafeZones() { int green = 68; for (int i = 15; i >= 10; i--) assertEquals( Engine.getNodePosition(new SorryFrame.Coordinate(i, 2)), green++); int red = 2; for (int i = 15; i >= 10; i--) assertEquals( Engine.getNodePosition(new SorryFrame.Coordinate(13, i)), red++); int blue = 24; for (int i = 0; i <= 5; i++) assertEquals( Engine.getNodePosition(new SorryFrame.Coordinate(i, 13)), blue++); int yellow = 46; for (int i = 0; i <= 5; i++) assertEquals( Engine.getNodePosition(new SorryFrame.Coordinate(2, i)), yellow++); } @SuppressWarnings("javadoc") @Test public void testCoordinateToIntSideLines() { checkCoordinateInt(15, 15, 0); checkCoordinateInt(14, 15, 1); checkCoordinateInt(13, 15, 2); checkCoordinateInt(12, 15, 9); checkCoordinateInt(11, 15, 10); checkCoordinateInt(10, 15, 12); int red = 13; for (int i = 9; i >= 0; i--) checkCoordinateInt(i, 15, red++); checkCoordinateInt(0, 15, 22); checkCoordinateInt(0, 14, 23); checkCoordinateInt(0, 13, 24); checkCoordinateInt(0, 12, 31); checkCoordinateInt(0, 11, 32); checkCoordinateInt(0, 10, 34); int blue = 35; for (int i = 9; i >= 0; i--) checkCoordinateInt(0, i, blue++); checkCoordinateInt(0, 0, 44); checkCoordinateInt(1, 0, 45); checkCoordinateInt(2, 0, 46); checkCoordinateInt(3, 0, 53); checkCoordinateInt(4, 0, 54); int yellow = 56; for (int i = 5; i <= 15; i++) checkCoordinateInt(i, 0, yellow++); checkCoordinateInt(15, 0, 66); checkCoordinateInt(15, 1, 67); checkCoordinateInt(15, 2, 68); checkCoordinateInt(15, 3, 75); checkCoordinateInt(15, 4, 76); int green = 78; for (int i = 5; i < 15; i++) checkCoordinateInt(15, i, green++); } private void checkCoordinateInt(int x, int y, int pos) { assertEquals(Engine.getNodePosition(new SorryFrame.Coordinate(x, y)), pos); } private void movePawn(int num, Piece p, Engine e) { try { e.move(num, p, e.findNode(p)); } catch (Exception exception) { } } @Test public void testFindNodeWithPiece() { BoardList temp = new BoardList(); Engine e = new Engine(temp, "english"); e.newGame(); Piece p = temp.getStartPointers()[0].getPieces()[0]; assertEquals(e.findNode(p), temp.getStartPointers()[0]); temp.getCornerPointers()[0].addPieceToPieces(p); try { temp.getCornerPointers()[0].findNodeWithPiece(new Piece()); } catch (Exception ex) { assertTrue(true); } } @Test public void testFindNodeWithPosition() { BoardList temp = new BoardList(); Engine e = new Engine(temp, "english"); e.newGame(); assertEquals(e.findNodeByPosition(87), temp.getCornerPointers()[0].getPrevious()); assertEquals(e.findNodeByPosition(11), temp.getStartPointers()[0]); assertEquals(e.findNodeByPosition(8), temp.getHomePointers()[0]); } @Test public void testIsValidMoveNoMove() { BoardList board = new BoardList(); Engine e = new Engine(board, "english"); e.newGame(); e.getNextCard(); assertTrue(e.isValidMove(e.pieces[0], e.currentCard.cardNum, new Player(Piece.COLOR.red, "Bob Dole"))); } @Test public void testPanwMovement() { BoardList board = new BoardList(); Engine e = new Engine(board, "english"); e.getNextCard(); assertEquals(e.pawnMove(new SorryFrame.Coordinate(0, 0), new SorryFrame.Coordinate(0, 0)), 0); } @Test public void testCountTo() { BoardList board = new BoardList(); Engine e = new Engine(board, "english"); int count = board.cornerPointers[0].countTo(board.cornerPointers[1]); assertEquals(count, 15); } @Test public void testIsValidPlayerCheck() { BoardList board = new BoardList(); Engine e = new Engine(board, "english"); Player p = new Player(Piece.COLOR.red, "James Bond"); e.newGame(); e.getNextCard(); assertTrue(e.isValidMove(e.pieces[0], e.currentCard.cardNum, p)); assertFalse(e.isValidMove(e.pieces[0], e.currentCard.cardNum, new Player(Piece.COLOR.blue, "Steve Jobs"))); for (int i = 1; i < 4; i++) assertTrue(e.isValidMove(e.pieces[i], e.currentCard.cardNum, p)); assertFalse(e.isValidMove(e.pieces[4], e.currentCard.cardNum, p)); assertFalse(e.isValidMove(null, e.currentCard.cardNum, p)); } @Test public void testPawnMoveSamePositions() { BoardList board = new BoardList(); Engine e = new Engine(board, "english"); e.newGame(); assertEquals(Engine.SAME_NODE_SELECTED, e.pawnMove( new SorryFrame.Coordinate(0, 0), new SorryFrame.Coordinate(0, 0))); for (int i = 0; i < 16; i++) { assertEquals(Engine.SAME_NODE_SELECTED, e.pawnMove( new SorryFrame.Coordinate(i, 0), new SorryFrame.Coordinate( i, 0))); assertEquals(0, e.pawnMove(new SorryFrame.Coordinate(0, i), new SorryFrame.Coordinate(0, i))); } } @Test public void testPawnMoveInvalidCoordinates() { BoardList board = new BoardList(); Engine e = new Engine(board, "english"); e.newGame(); assertEquals(Engine.NODE_NOT_FOUND, e.pawnMove( new SorryFrame.Coordinate(-1, -1), new SorryFrame.Coordinate(0, 0))); assertEquals(Engine.NODE_NOT_FOUND, e.pawnMove( new SorryFrame.Coordinate(0, 0), new SorryFrame.Coordinate(-1, -1))); assertEquals(Engine.NODE_NOT_FOUND, e.pawnMove( new SorryFrame.Coordinate(1, 1), new SorryFrame.Coordinate(0, 0))); assertEquals(Engine.NODE_NOT_FOUND, e.pawnMove( new SorryFrame.Coordinate(6, 6), new SorryFrame.Coordinate(-1, -1))); assertEquals(Engine.NODE_NOT_FOUND, e.pawnMove( new SorryFrame.Coordinate(7, 7), new SorryFrame.Coordinate(7, 7))); } @Test public void testInsertPlayers() { BoardList board = new BoardList(); Engine e = new Engine(board, "english"); Player john = new Player(Piece.COLOR.green, "Johnny Depp"); Player bill = new Player(Piece.COLOR.blue, "Bill Gates"); Player siriam = new Player(Piece.COLOR.yellow, "Whale Rider"); Player buffalo = new Player(Piece.COLOR.red, "Buffalo"); e.insertPlayer(john); e.insertPlayer(bill); e.rotatePlayers(); assertEquals(e.activePlayer, john); e.rotatePlayers(); assertEquals(e.activePlayer, bill); e.rotatePlayers(); assertEquals(e.activePlayer, john); e.insertPlayer(siriam); assertEquals(e.activePlayer, john); e.rotatePlayers(); assertEquals(e.activePlayer, bill); e.rotatePlayers(); assertEquals(e.activePlayer, john); e.rotatePlayers(); assertEquals(e.activePlayer, siriam); e.insertPlayer(buffalo); assertEquals(e.activePlayer, siriam); } @Test public void testBackwardsMove() { BoardList board = new BoardList(); Engine e = new Engine(board, "english"); e.newGame(); movePawn(1, e.pieces[7], e); assertEquals( board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsn|rmn4|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nn|hbsn|bsn|bsf|bsf|bsf|bsf|bsf|bmn0|bsn|bsnb|bmn3|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysn|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsn|gmn4|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"); movePawn(-4, e.pieces[7], e); assertEquals( board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsn|rmn4|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nnb|hbsn|bsn|bsf|bsf|bsf|bsf|bsf|bmn0|bsn|bsn|bmn3|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysn|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsn|gmn4|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"); movePawn(-1, e.pieces[7], e); assertEquals( board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsn|rmn4|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nnb|nn|hbsn|bsn|bsf|bsf|bsf|bsf|bsf|bmn0|bsn|bsn|bmn3|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysn|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsn|gmn4|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"); try { movePawn(-1, e.pieces[1], e); } catch (Exception ex) { } } @Test public void testHasWon() { BoardList board = new BoardList(); Engine e = new Engine(board, "english"); e.newGame(); Player john = new Player(Piece.COLOR.green, "Johnny Depp"); Player bill = new Player(Piece.COLOR.blue, "Bill Gates"); Player siriam = new Player(Piece.COLOR.yellow, "Whale Rider"); Player buffalo = new Player(Piece.COLOR.red, "Buffalo"); e.insertPlayer(buffalo); e.insertPlayer(bill); e.insertPlayer(siriam); e.insertPlayer(john); Piece[] temp = new Piece[4]; for (int i = 0; i < 4; i++) { e.rotatePlayers(); temp = board.getStartPointers()[i].getPieces(); board.getHomePointers()[i].setPieces(temp); assertTrue(e.hasWon()); } e.rotatePlayers(); temp = new Piece[4]; board.getHomePointers()[0].setPieces(temp); assertFalse(e.hasWon()); } @Test public void testValidMoves() { BoardList board = new BoardList(); Engine e = new Engine(board, "english"); e.newGame(); Node start = new Node(); Node end = new Node(); Piece pawn = new Piece(Piece.COLOR.red); start.addPieceToPieces(pawn); createNodeChain(start, end, 2); assertEquals(start.countTo(end), 1); e.currentCard = new Card(1, "Test CARD"); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 1, 0), 1); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 2, 0), Engine.INVALID_MOVE); start = new Node(); end = new Node(); end.addPieceToPieces(pawn); createNodeChain(start, end, 3); assertEquals(2, start.countTo(end)); assertEquals(2, end.countBack(start)); e.board = new BoardList(); e.currentCard = new Card(2, "Test"); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 2, 0), 2); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 1, 0), Engine.INVALID_MOVE); start = new Node(); end = new Node(); end.addPieceToPieces(pawn); createNodeChain(start, end, 5); assertEquals(4, start.countTo(end)); assertEquals(4, end.countBack(start)); e.currentCard = new Card(4, "Test CARD"); assertEquals(e.checkValidityOriginalRules(pawn, end, start, 0, 4), -4); assertEquals(e.checkValidityOriginalRules(pawn, end, start, 0, -5), Engine.INVALID_MOVE); start = new Node(); end = new Node(); start.addPieceToPieces(pawn); e.currentCard = new Card(7, "TEST"); createNodeChain(start, end, 8); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 7, 0), 7); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 8, 0), Engine.INVALID_MOVE); - assertEquals(e.checkValidityOriginalRules(pawn, start, end, 4, 0), 4); + assertEquals(e.checkValidityOriginalRules(pawn, start, end, 4, 0), Engine.VALID_MOVE_NO_FINALIZE); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 7, 0), Engine.INVALID_MOVE); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 3, 0), 3); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 7, 0), 7); start = new Node(); end = new Node(); start.addPieceToPieces(pawn); e.currentCard = new Card(10, "TEST"); createNodeChain(start, end, 11); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 10, 0), 10); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 8, 0), Engine.INVALID_MOVE); start = new Node(); end = new Node(); createNodeChain(start, end, 11); end.addPieceToPieces(pawn); assertEquals(e.checkValidityOriginalRules(pawn, end, start, 0, 1), -1); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 0, -2), Engine.INVALID_MOVE); start = new Node(); end = new Node(); createNodeChain(start, end, 12); e.currentCard = new Card(11, "TEST"); start.addPieceToPieces(pawn); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 11, 0), 11); end.removePieceFromPieces(pawn); start.removePieceFromPieces(pawn); start.addPieceToPieces(pawn); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 0, -2), Engine.INVALID_MOVE); start = new Node(); end = new Node(); start.addPieceToPieces(pawn); end.addPieceToPieces(new Piece(Piece.COLOR.blue)); createNodeChain(start, end, 4); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 3, 0), 3); start = new Node(); end = new Node(); createNodeChain(start, end, 13); e.currentCard = new Card(13, "TEST"); start.getPrevious().setColor(Piece.COLOR.red); start.getPrevious().addPieceToPieces(pawn); end.addPieceToPieces(new Piece(Piece.COLOR.blue)); assertEquals(e.checkValidityOriginalRules(pawn, start.getPrevious(), end, 12, 0), 12); end.removePieceFromPieces(pawn); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 4, 0), Engine.INVALID_MOVE); start = new Node(); end = new Node(); start.addPieceToPieces(pawn); createNodeChain(start, end, 3); Player phil = new Player(Piece.COLOR.red, "Phil"); Player phillis = new Player(Piece.COLOR.green, "Phillis"); e.currentCard = new Card(2, "Things to do"); e.insertPlayer(phil); e.insertPlayer(phillis); e.rotatePlayers(); assertEquals(e.activePlayer, phil); e.checkValidityOriginalRules(pawn, start, end, 2, 0); e.rotatePlayers(); assertEquals(e.activePlayer, phil); } @Test public void testPawnMovementSwapPiecesCardEleven() { String testingBoard = "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsn|rmn4|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nn|hbsn|bsnb|bsf|bsf|bsf|bsf|bsf|bmn0|bsn|bsn|bmn3|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysn|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsn|gmn4|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"; BoardList board = new BoardList(); Engine e = new Engine(board, "english"); e.newGame(); e.insertPlayer(new Player(Piece.COLOR.red, "Dave")); e.insertPlayer(new Player(Piece.COLOR.blue, "Whale Rider")); e.rotatePlayers(); e.currentCard = new Card(11, "TEST"); Piece pawn = board.homePointers[0].firstPiece(); int test = e.pawnMove(new SorryFrame.Coordinate(11, 14), new SorryFrame.Coordinate(11, 15)); assertEquals(test, Engine.INVALID_MOVE); test = e.pawnMove(new SorryFrame.Coordinate(11, 14), new SorryFrame.Coordinate(0, 0)); assertEquals(test, Engine.INVALID_MOVE); e.currentCard = new Card(1, "TEST"); test = e.pawnMove(new SorryFrame.Coordinate(11, 14), new SorryFrame.Coordinate(11, 15)); assertEquals(test, 1); e.rotatePlayers(); test = e.pawnMove(new SorryFrame.Coordinate(1, 11), new SorryFrame.Coordinate(0, 11)); assertEquals(test, 1); e.currentCard = new Card(11, "Test"); test = e.pawnMove(new SorryFrame.Coordinate(11, 14), new SorryFrame.Coordinate(0, 0)); assertEquals(test, Engine.INVALID_MOVE); e.rotatePlayers(); test = e.pawnMove(new SorryFrame.Coordinate(11, 15), new SorryFrame.Coordinate(0, 11)); assertEquals(test, 15); // pieces were just swapped, test that the pieces are now in the right // spots assertEquals( board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsnb|rmn3|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nn|hbsn|bsn|bsf|bsf|bsf|bsf|bsf|bmn0|bsn|bsnr|bmn3|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysn|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsn|gmn4|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"); // try it the other way for good measure e.rotatePlayers(); test = e.pawnMove(new SorryFrame.Coordinate(11, 15), new SorryFrame.Coordinate(0, 11)); assertEquals(test, 15); assertEquals( board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsnr|rmn3|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nn|hbsn|bsn|bsf|bsf|bsf|bsf|bsf|bmn0|bsn|bsnb|bmn3|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysn|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsn|gmn4|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"); } @Test public void testSwapPiecesCardElevenIllegals() { BoardList board = new BoardList(); Engine e = new Engine(board, "english"); e.newGame(); e.insertPlayer(new Player(Piece.COLOR.red, "Dave")); e.insertPlayer(new Player(Piece.COLOR.blue, "Whale Rider")); e.rotatePlayers(); // going to fiddle with the board in a hacky sorta way... Piece dave = board.startPointers[0].firstPiece(); board.startPointers[0].removePieceFromPieces(dave); assertEquals(dave.col, Piece.COLOR.red); Piece whale = board.startPointers[1].firstPiece(); board.startPointers[1].removePieceFromPieces(whale); assertEquals(whale.col, Piece.COLOR.blue); board.homePointers[0].getPrevious().addPieceToPieces(dave); board.homePointers[1].getPrevious().addPieceToPieces(whale); e.currentCard = new Card(1, "TEST"); assertEquals(e.pawnMove(new SorryFrame.Coordinate(11, 14), new SorryFrame.Coordinate(11, 15)), 1); e.currentCard = new Card(11, "TEST"); // now try an illegal move - swapping a piece in safe zone, lot of // freaking work String before = board.toString(); assertEquals(e.pawnMove(new SorryFrame.Coordinate(11, 15), new SorryFrame.Coordinate(5, 13)), Engine.INVALID_MOVE); assertEquals(board.toString(), before); e.rotatePlayers(); assertEquals(e.pawnMove(new SorryFrame.Coordinate(5, 13), new SorryFrame.Coordinate(11, 15)), Engine.INVALID_MOVE); // illegal because the swap FROM node is safe... subtle... // silly hobbitsies... } @Test public void testSwapCardSorryIllegal(){ BoardList board = new BoardList(); Engine e = new Engine(board, "english"); e.insertPlayer(new Player(Piece.COLOR.red, "Dave")); e.insertPlayer(new Player(Piece.COLOR.blue, "Whale Rider")); e.newGame(); e.rotatePlayers(); e.currentCard = new Card(13, "TEST"); assertEquals(e.pawnMove(new SorryFrame.Coordinate(11, 14), new SorryFrame.Coordinate(5, 1)), Engine.INVALID_MOVE); e.currentCard = new Card(1, "TEST"); assertEquals(e.pawnMove(new SorryFrame.Coordinate(11, 14), new SorryFrame.Coordinate(11, 15)), 1); e.rotatePlayers(); e.currentCard = new Card(13, "TEST"); assertTrue(e.pawnMove(new SorryFrame.Coordinate(1, 11), new SorryFrame.Coordinate(11, 15)) > 0); assertEquals(board.toString(), "hrsn|rsn|rsf|rsf|rsf|rsf|rsf|rmn0|rsn|rsnb|rmn4|nn|nn|nn|nn|hrsn|rsn|rsn" + "|rsn|rsn|nn|nn|hbsn|bsn|bsf|bsf|bsf|bsf|bsf|bmn0|bsn|bsn|bmn3|nn|nn|nn|nn" + "|hbsn|bsn|bsn|bsn|bsn|nn|nn|hysn|ysn|ysf|ysf|ysf|ysf|ysf|ymn0|ysn|ysn|ymn4" + "|nn|nn|nn|nn|hysn|ysn|ysn|ysn|ysn|nn|nn|hgsn|gsn|gsf|gsf|gsf|gsf|gsf|gmn0" + "|gsn|gsn|gmn4|nn|nn|nn|nn|hgsn|gsn|gsn|gsn|gsn|nn|nn|"); // sorry has now worked fine, try sorry on someone in safe position Piece dave = board.startPointers[0].firstPiece(); board.startPointers[0].removePieceFromPieces(dave); board.homePointers[0].getPrevious().addPieceToPieces(dave); String before = board.toString(); assertEquals(e.pawnMove(new SorryFrame.Coordinate(1, 11), new SorryFrame.Coordinate(13, 10)), Engine.INVALID_MOVE); assertEquals(board.toString(), before); e.rotatePlayers(); assertEquals(e.pawnMove(new SorryFrame.Coordinate(13, 10), new SorryFrame.Coordinate(1, 11)), Engine.INVALID_MOVE); } @Test public void testSevenSplit(){ } @Test public void testCreateNodeChain() { Node start = new Node(); Node end = new Node(); createNodeChain(start, end, 2); assertEquals(start.getNext(), end); assertEquals(end.getPrevious(), start); start = new Node(); end = new Node(); createNodeChain(start, end, 3); assertEquals(start.getNext().getNext(), end); assertNull(start.getNext().getNext().getNext()); assertEquals(end.getPrevious().getPrevious(), start); start = new Node(); end = new Node(); createNodeChain(start, end, 5); assertEquals(start.getNext().getNext().getNext().getNext(), end); assertEquals(end.getPrevious().getPrevious().getPrevious() .getPrevious(), start); } private static void createNodeChain(Node start, Node end, int length) { Node current = start; for (int i = 2; i < length; i++) { Node temp = new Node(); temp.setPrevious(current); current.setNext(temp); current = temp; } start.setPrevious(new MultiNode(start, null, Piece.COLOR.colorless)); current.setNext(end); end.setPrevious(current); } }
true
true
public void testValidMoves() { BoardList board = new BoardList(); Engine e = new Engine(board, "english"); e.newGame(); Node start = new Node(); Node end = new Node(); Piece pawn = new Piece(Piece.COLOR.red); start.addPieceToPieces(pawn); createNodeChain(start, end, 2); assertEquals(start.countTo(end), 1); e.currentCard = new Card(1, "Test CARD"); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 1, 0), 1); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 2, 0), Engine.INVALID_MOVE); start = new Node(); end = new Node(); end.addPieceToPieces(pawn); createNodeChain(start, end, 3); assertEquals(2, start.countTo(end)); assertEquals(2, end.countBack(start)); e.board = new BoardList(); e.currentCard = new Card(2, "Test"); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 2, 0), 2); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 1, 0), Engine.INVALID_MOVE); start = new Node(); end = new Node(); end.addPieceToPieces(pawn); createNodeChain(start, end, 5); assertEquals(4, start.countTo(end)); assertEquals(4, end.countBack(start)); e.currentCard = new Card(4, "Test CARD"); assertEquals(e.checkValidityOriginalRules(pawn, end, start, 0, 4), -4); assertEquals(e.checkValidityOriginalRules(pawn, end, start, 0, -5), Engine.INVALID_MOVE); start = new Node(); end = new Node(); start.addPieceToPieces(pawn); e.currentCard = new Card(7, "TEST"); createNodeChain(start, end, 8); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 7, 0), 7); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 8, 0), Engine.INVALID_MOVE); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 4, 0), 4); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 7, 0), Engine.INVALID_MOVE); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 3, 0), 3); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 7, 0), 7); start = new Node(); end = new Node(); start.addPieceToPieces(pawn); e.currentCard = new Card(10, "TEST"); createNodeChain(start, end, 11); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 10, 0), 10); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 8, 0), Engine.INVALID_MOVE); start = new Node(); end = new Node(); createNodeChain(start, end, 11); end.addPieceToPieces(pawn); assertEquals(e.checkValidityOriginalRules(pawn, end, start, 0, 1), -1); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 0, -2), Engine.INVALID_MOVE); start = new Node(); end = new Node(); createNodeChain(start, end, 12); e.currentCard = new Card(11, "TEST"); start.addPieceToPieces(pawn); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 11, 0), 11); end.removePieceFromPieces(pawn); start.removePieceFromPieces(pawn); start.addPieceToPieces(pawn); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 0, -2), Engine.INVALID_MOVE); start = new Node(); end = new Node(); start.addPieceToPieces(pawn); end.addPieceToPieces(new Piece(Piece.COLOR.blue)); createNodeChain(start, end, 4); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 3, 0), 3); start = new Node(); end = new Node(); createNodeChain(start, end, 13); e.currentCard = new Card(13, "TEST"); start.getPrevious().setColor(Piece.COLOR.red); start.getPrevious().addPieceToPieces(pawn); end.addPieceToPieces(new Piece(Piece.COLOR.blue)); assertEquals(e.checkValidityOriginalRules(pawn, start.getPrevious(), end, 12, 0), 12); end.removePieceFromPieces(pawn); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 4, 0), Engine.INVALID_MOVE); start = new Node(); end = new Node(); start.addPieceToPieces(pawn); createNodeChain(start, end, 3); Player phil = new Player(Piece.COLOR.red, "Phil"); Player phillis = new Player(Piece.COLOR.green, "Phillis"); e.currentCard = new Card(2, "Things to do"); e.insertPlayer(phil); e.insertPlayer(phillis); e.rotatePlayers(); assertEquals(e.activePlayer, phil); e.checkValidityOriginalRules(pawn, start, end, 2, 0); e.rotatePlayers(); assertEquals(e.activePlayer, phil); }
public void testValidMoves() { BoardList board = new BoardList(); Engine e = new Engine(board, "english"); e.newGame(); Node start = new Node(); Node end = new Node(); Piece pawn = new Piece(Piece.COLOR.red); start.addPieceToPieces(pawn); createNodeChain(start, end, 2); assertEquals(start.countTo(end), 1); e.currentCard = new Card(1, "Test CARD"); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 1, 0), 1); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 2, 0), Engine.INVALID_MOVE); start = new Node(); end = new Node(); end.addPieceToPieces(pawn); createNodeChain(start, end, 3); assertEquals(2, start.countTo(end)); assertEquals(2, end.countBack(start)); e.board = new BoardList(); e.currentCard = new Card(2, "Test"); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 2, 0), 2); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 1, 0), Engine.INVALID_MOVE); start = new Node(); end = new Node(); end.addPieceToPieces(pawn); createNodeChain(start, end, 5); assertEquals(4, start.countTo(end)); assertEquals(4, end.countBack(start)); e.currentCard = new Card(4, "Test CARD"); assertEquals(e.checkValidityOriginalRules(pawn, end, start, 0, 4), -4); assertEquals(e.checkValidityOriginalRules(pawn, end, start, 0, -5), Engine.INVALID_MOVE); start = new Node(); end = new Node(); start.addPieceToPieces(pawn); e.currentCard = new Card(7, "TEST"); createNodeChain(start, end, 8); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 7, 0), 7); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 8, 0), Engine.INVALID_MOVE); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 4, 0), Engine.VALID_MOVE_NO_FINALIZE); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 7, 0), Engine.INVALID_MOVE); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 3, 0), 3); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 7, 0), 7); start = new Node(); end = new Node(); start.addPieceToPieces(pawn); e.currentCard = new Card(10, "TEST"); createNodeChain(start, end, 11); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 10, 0), 10); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 8, 0), Engine.INVALID_MOVE); start = new Node(); end = new Node(); createNodeChain(start, end, 11); end.addPieceToPieces(pawn); assertEquals(e.checkValidityOriginalRules(pawn, end, start, 0, 1), -1); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 0, -2), Engine.INVALID_MOVE); start = new Node(); end = new Node(); createNodeChain(start, end, 12); e.currentCard = new Card(11, "TEST"); start.addPieceToPieces(pawn); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 11, 0), 11); end.removePieceFromPieces(pawn); start.removePieceFromPieces(pawn); start.addPieceToPieces(pawn); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 0, -2), Engine.INVALID_MOVE); start = new Node(); end = new Node(); start.addPieceToPieces(pawn); end.addPieceToPieces(new Piece(Piece.COLOR.blue)); createNodeChain(start, end, 4); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 3, 0), 3); start = new Node(); end = new Node(); createNodeChain(start, end, 13); e.currentCard = new Card(13, "TEST"); start.getPrevious().setColor(Piece.COLOR.red); start.getPrevious().addPieceToPieces(pawn); end.addPieceToPieces(new Piece(Piece.COLOR.blue)); assertEquals(e.checkValidityOriginalRules(pawn, start.getPrevious(), end, 12, 0), 12); end.removePieceFromPieces(pawn); assertEquals(e.checkValidityOriginalRules(pawn, start, end, 4, 0), Engine.INVALID_MOVE); start = new Node(); end = new Node(); start.addPieceToPieces(pawn); createNodeChain(start, end, 3); Player phil = new Player(Piece.COLOR.red, "Phil"); Player phillis = new Player(Piece.COLOR.green, "Phillis"); e.currentCard = new Card(2, "Things to do"); e.insertPlayer(phil); e.insertPlayer(phillis); e.rotatePlayers(); assertEquals(e.activePlayer, phil); e.checkValidityOriginalRules(pawn, start, end, 2, 0); e.rotatePlayers(); assertEquals(e.activePlayer, phil); }
diff --git a/src/main/java/org/spoutcraft/launcher/technic/skin/ImportOptions.java b/src/main/java/org/spoutcraft/launcher/technic/skin/ImportOptions.java index 827e42d..32cf83f 100644 --- a/src/main/java/org/spoutcraft/launcher/technic/skin/ImportOptions.java +++ b/src/main/java/org/spoutcraft/launcher/technic/skin/ImportOptions.java @@ -1,324 +1,324 @@ /* * This file is part of Technic Launcher. * * Copyright (c) 2013-2013, Technic <http://www.technicpack.net/> * Technic Launcher is licensed under the Spout License Version 1. * * Technic Launcher is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * In addition, 180 days after any changes are published, you can use the * software, incorporating those changes, under the terms of the MIT license, * as described in the Spout License Version 1. * * Technic Launcher is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License, * the MIT license and the Spout License Version 1 along with this program. * If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public * License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license, * including the MIT license. */ package org.spoutcraft.launcher.technic.skin; import java.awt.Color; import java.awt.Container; import java.awt.Font; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.io.File; import java.io.IOException; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.SimpleAttributeSet; import org.spoutcraft.launcher.Settings; import org.spoutcraft.launcher.api.Launcher; import org.spoutcraft.launcher.exceptions.RestfulAPIException; import org.spoutcraft.launcher.skin.MetroLoginFrame; import org.spoutcraft.launcher.skin.components.LiteButton; import org.spoutcraft.launcher.skin.components.LiteTextBox; import org.spoutcraft.launcher.technic.rest.RestAPI; import org.spoutcraft.launcher.technic.rest.info.CustomInfo; import org.spoutcraft.launcher.util.Utils; public class ImportOptions extends JDialog implements ActionListener, MouseListener, MouseMotionListener, DocumentListener { private static final long serialVersionUID = 1L; private static final String QUIT_ACTION = "quit"; private static final String IMPORT_ACTION = "import"; private static final String CHANGE_FOLDER = "folder"; private static final String PASTE_URL = "paste"; private static final int FRAME_WIDTH = 520; private static final int FRAME_HEIGHT = 222; private JLabel msgLabel; private JLabel background; private LiteButton save; private LiteButton folder; private LiteButton paste; private LiteTextBox install; private JFileChooser fileChooser; private int mouseX = 0, mouseY = 0; private CustomInfo info = null; private String url = ""; private Document urlDoc; private File installDir; public ImportOptions() { setTitle("Add a Pack"); setSize(FRAME_WIDTH, FRAME_HEIGHT); addMouseListener(this); addMouseMotionListener(this); setResizable(false); setUndecorated(true); initComponents(); } public void initComponents() { Font minecraft = MetroLoginFrame.getMinecraftFont(12); background = new JLabel(); background.setBounds(0,0, FRAME_WIDTH, FRAME_HEIGHT); MetroLoginFrame.setIcon(background, "platformBackground.png", background.getWidth(), background.getHeight()); Container contentPane = getContentPane(); contentPane.setLayout(null); ImageButton optionsQuit = new ImageButton(MetroLoginFrame.getIcon("quit.png", 28, 28), MetroLoginFrame.getIcon("quit.png", 28, 28)); optionsQuit.setRolloverIcon(MetroLoginFrame.getIcon("quitHover.png", 28, 28)); optionsQuit.setBounds(FRAME_WIDTH - 38, 10, 28, 28); optionsQuit.setActionCommand(QUIT_ACTION); optionsQuit.addActionListener(this); msgLabel = new JLabel(); msgLabel.setBounds(10, 75, FRAME_WIDTH - 20, 25); msgLabel.setText("Enter your Technic Platform delivery URL below to add a new pack:"); msgLabel.setForeground(Color.white); msgLabel.setFont(minecraft); LiteTextBox url = new LiteTextBox(this, "Paste Platform URL Here"); url.setBounds(10, msgLabel.getY() + msgLabel.getHeight() + 5, FRAME_WIDTH - 115, 30); url.setFont(minecraft); url.getDocument().addDocumentListener(this); urlDoc = url.getDocument(); save = new LiteButton("Add Modpack"); save.setFont(minecraft.deriveFont(14F)); - save.setBounds(FRAME_WIDTH - 130, FRAME_HEIGHT - 40, 120, 30); + save.setBounds(FRAME_WIDTH - 145, FRAME_HEIGHT - 40, 135, 30); save.setActionCommand(IMPORT_ACTION); save.addActionListener(this); fileChooser = new JFileChooser(Utils.getLauncherDirectory()); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - folder = new LiteButton("Folder"); + folder = new LiteButton("Change Folder"); folder.setFont(minecraft.deriveFont(14F)); - folder.setBounds(FRAME_WIDTH - 230, FRAME_HEIGHT - 40, 90, 30); + folder.setBounds(FRAME_WIDTH - 290, FRAME_HEIGHT - 40, 135, 30); folder.setActionCommand(CHANGE_FOLDER); folder.addActionListener(this); paste = new LiteButton("Paste"); paste.setFont(minecraft.deriveFont(14F)); - paste.setBounds(FRAME_WIDTH - 100, msgLabel.getY() + msgLabel.getHeight() + 5, 90, 30); + paste.setBounds(FRAME_WIDTH - 95, msgLabel.getY() + msgLabel.getHeight() + 5, 85, 30); paste.setActionCommand(PASTE_URL); paste.addActionListener(this); paste.setVisible(true); install = new LiteTextBox(this, ""); install.setBounds(10, FRAME_HEIGHT - 75, FRAME_WIDTH - 20, 25); install.setFont(minecraft.deriveFont(10F)); install.setEnabled(false); install.setVisible(false); enableComponent(save, false); enableComponent(folder, false); enableComponent(paste, true); contentPane.add(install); contentPane.add(optionsQuit); contentPane.add(msgLabel); contentPane.add(folder); contentPane.add(paste); contentPane.add(url); contentPane.add(save); contentPane.add(background); setLocationRelativeTo(this.getOwner()); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof JComponent) { action(e.getActionCommand(), (JComponent)e.getSource()); } } private void action(String action, JComponent c) { if (action.equals(QUIT_ACTION)) { dispose(); } else if (action.equals(CHANGE_FOLDER)) { int result = fileChooser.showOpenDialog(this); if (result == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); file.exists(); installDir = file; install.setText("Location: " + installDir.getPath()); } } else if (action.equals(IMPORT_ACTION)) { if (info != null || url.isEmpty()) { Settings.setCustomURL(info.getName(), url); Settings.setPackCustom(info.getName(), true); Settings.setPackDirectory(info.getName(), installDir.getAbsolutePath()); Settings.getYAML().save(); Launcher.getFrame().getModpackSelector().addPack(info.getPack()); dispose(); } } else if (action.equals(PASTE_URL)) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable clipData = clipboard.getContents(clipboard); if(clipData != null) { try { if(clipData.isDataFlavorSupported(DataFlavor.stringFlavor)) { String s = (String)(clipData.getTransferData(DataFlavor.stringFlavor)); urlDoc.remove(0, urlDoc.getLength()); urlDoc.insertString(0, s, new SimpleAttributeSet()); } } catch(UnsupportedFlavorException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } catch (BadLocationException e) { e.printStackTrace(); } } } } public void urlUpdated(Document doc) { try { String url = doc.getText(0, doc.getLength()); if (url.isEmpty()) { msgLabel.setText("Enter your Technic Platform delivery URL below to add a new pack:"); enableComponent(save, false); enableComponent(folder, false); info = null; this.url = ""; return; } else if (url.matches("http://beta.technicpack.net/api/modpack/([a-zA-Z0-9-]+)")) { try { info = RestAPI.getCustomModpack(url); msgLabel.setText("Modpack: " + info.getDisplayName()); this.url = url; enableComponent(save, true); enableComponent(folder, true); enableComponent(install, true); enableComponent(paste, true); installDir = new File(Utils.getLauncherDirectory(), info.getName()); install.setText("Location: " + installDir.getPath()); } catch (RestfulAPIException e) { msgLabel.setText("Error parsing platform response"); enableComponent(save, false); enableComponent(folder, false); enableComponent(install, false); info = null; this.url = ""; e.printStackTrace(); } } else { msgLabel.setText("Invalid Technic Platform delivery URL"); enableComponent(save, false); enableComponent(folder, false); enableComponent(install, false); info = null; this.url = ""; } } catch (BadLocationException e) { //This should never ever happen. //Java is stupid for not having a getAllText of some kind on the Document class e.printStackTrace(); } } public void enableComponent(JComponent component, boolean enable) { component.setEnabled(enable); component.setVisible(enable); } @Override public void mouseDragged(MouseEvent e) { this.setLocation(e.getXOnScreen() - mouseX, e.getYOnScreen() - mouseY); } @Override public void mouseMoved(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { mouseX = e.getX(); mouseY = e.getY(); } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void changedUpdate(DocumentEvent e) { urlUpdated(e.getDocument()); } @Override public void insertUpdate(DocumentEvent e) { urlUpdated(e.getDocument()); } @Override public void removeUpdate(DocumentEvent e) { urlUpdated(e.getDocument()); } }
false
true
public void initComponents() { Font minecraft = MetroLoginFrame.getMinecraftFont(12); background = new JLabel(); background.setBounds(0,0, FRAME_WIDTH, FRAME_HEIGHT); MetroLoginFrame.setIcon(background, "platformBackground.png", background.getWidth(), background.getHeight()); Container contentPane = getContentPane(); contentPane.setLayout(null); ImageButton optionsQuit = new ImageButton(MetroLoginFrame.getIcon("quit.png", 28, 28), MetroLoginFrame.getIcon("quit.png", 28, 28)); optionsQuit.setRolloverIcon(MetroLoginFrame.getIcon("quitHover.png", 28, 28)); optionsQuit.setBounds(FRAME_WIDTH - 38, 10, 28, 28); optionsQuit.setActionCommand(QUIT_ACTION); optionsQuit.addActionListener(this); msgLabel = new JLabel(); msgLabel.setBounds(10, 75, FRAME_WIDTH - 20, 25); msgLabel.setText("Enter your Technic Platform delivery URL below to add a new pack:"); msgLabel.setForeground(Color.white); msgLabel.setFont(minecraft); LiteTextBox url = new LiteTextBox(this, "Paste Platform URL Here"); url.setBounds(10, msgLabel.getY() + msgLabel.getHeight() + 5, FRAME_WIDTH - 115, 30); url.setFont(minecraft); url.getDocument().addDocumentListener(this); urlDoc = url.getDocument(); save = new LiteButton("Add Modpack"); save.setFont(minecraft.deriveFont(14F)); save.setBounds(FRAME_WIDTH - 130, FRAME_HEIGHT - 40, 120, 30); save.setActionCommand(IMPORT_ACTION); save.addActionListener(this); fileChooser = new JFileChooser(Utils.getLauncherDirectory()); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); folder = new LiteButton("Folder"); folder.setFont(minecraft.deriveFont(14F)); folder.setBounds(FRAME_WIDTH - 230, FRAME_HEIGHT - 40, 90, 30); folder.setActionCommand(CHANGE_FOLDER); folder.addActionListener(this); paste = new LiteButton("Paste"); paste.setFont(minecraft.deriveFont(14F)); paste.setBounds(FRAME_WIDTH - 100, msgLabel.getY() + msgLabel.getHeight() + 5, 90, 30); paste.setActionCommand(PASTE_URL); paste.addActionListener(this); paste.setVisible(true); install = new LiteTextBox(this, ""); install.setBounds(10, FRAME_HEIGHT - 75, FRAME_WIDTH - 20, 25); install.setFont(minecraft.deriveFont(10F)); install.setEnabled(false); install.setVisible(false); enableComponent(save, false); enableComponent(folder, false); enableComponent(paste, true); contentPane.add(install); contentPane.add(optionsQuit); contentPane.add(msgLabel); contentPane.add(folder); contentPane.add(paste); contentPane.add(url); contentPane.add(save); contentPane.add(background); setLocationRelativeTo(this.getOwner()); }
public void initComponents() { Font minecraft = MetroLoginFrame.getMinecraftFont(12); background = new JLabel(); background.setBounds(0,0, FRAME_WIDTH, FRAME_HEIGHT); MetroLoginFrame.setIcon(background, "platformBackground.png", background.getWidth(), background.getHeight()); Container contentPane = getContentPane(); contentPane.setLayout(null); ImageButton optionsQuit = new ImageButton(MetroLoginFrame.getIcon("quit.png", 28, 28), MetroLoginFrame.getIcon("quit.png", 28, 28)); optionsQuit.setRolloverIcon(MetroLoginFrame.getIcon("quitHover.png", 28, 28)); optionsQuit.setBounds(FRAME_WIDTH - 38, 10, 28, 28); optionsQuit.setActionCommand(QUIT_ACTION); optionsQuit.addActionListener(this); msgLabel = new JLabel(); msgLabel.setBounds(10, 75, FRAME_WIDTH - 20, 25); msgLabel.setText("Enter your Technic Platform delivery URL below to add a new pack:"); msgLabel.setForeground(Color.white); msgLabel.setFont(minecraft); LiteTextBox url = new LiteTextBox(this, "Paste Platform URL Here"); url.setBounds(10, msgLabel.getY() + msgLabel.getHeight() + 5, FRAME_WIDTH - 115, 30); url.setFont(minecraft); url.getDocument().addDocumentListener(this); urlDoc = url.getDocument(); save = new LiteButton("Add Modpack"); save.setFont(minecraft.deriveFont(14F)); save.setBounds(FRAME_WIDTH - 145, FRAME_HEIGHT - 40, 135, 30); save.setActionCommand(IMPORT_ACTION); save.addActionListener(this); fileChooser = new JFileChooser(Utils.getLauncherDirectory()); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); folder = new LiteButton("Change Folder"); folder.setFont(minecraft.deriveFont(14F)); folder.setBounds(FRAME_WIDTH - 290, FRAME_HEIGHT - 40, 135, 30); folder.setActionCommand(CHANGE_FOLDER); folder.addActionListener(this); paste = new LiteButton("Paste"); paste.setFont(minecraft.deriveFont(14F)); paste.setBounds(FRAME_WIDTH - 95, msgLabel.getY() + msgLabel.getHeight() + 5, 85, 30); paste.setActionCommand(PASTE_URL); paste.addActionListener(this); paste.setVisible(true); install = new LiteTextBox(this, ""); install.setBounds(10, FRAME_HEIGHT - 75, FRAME_WIDTH - 20, 25); install.setFont(minecraft.deriveFont(10F)); install.setEnabled(false); install.setVisible(false); enableComponent(save, false); enableComponent(folder, false); enableComponent(paste, true); contentPane.add(install); contentPane.add(optionsQuit); contentPane.add(msgLabel); contentPane.add(folder); contentPane.add(paste); contentPane.add(url); contentPane.add(save); contentPane.add(background); setLocationRelativeTo(this.getOwner()); }
diff --git a/integrationtest/src/test/java/org/biojava/bio/structure/scop/ScopTest.java b/integrationtest/src/test/java/org/biojava/bio/structure/scop/ScopTest.java index eba0565d5..875fa799b 100644 --- a/integrationtest/src/test/java/org/biojava/bio/structure/scop/ScopTest.java +++ b/integrationtest/src/test/java/org/biojava/bio/structure/scop/ScopTest.java @@ -1,161 +1,161 @@ package org.biojava.bio.structure.scop; import java.util.List; import org.biojava.bio.structure.Chain; import org.biojava.bio.structure.Group; import org.biojava.bio.structure.GroupIterator; import org.biojava.bio.structure.Structure; import org.biojava.bio.structure.align.util.AtomCache; import junit.framework.TestCase; public class ScopTest extends TestCase { boolean debug = false; public void testLocalScop(){ if ( debug ){ System.out.println("local"); } long timeS = System.currentTimeMillis(); ScopDatabase scop = new ScopInstallation(); ScopDatabase defaultScop = ScopFactory.getSCOP(); ScopFactory.setScopDatabase(scop); runSCOPTests(); ScopFactory.setScopDatabase(defaultScop); long timeE = System.currentTimeMillis(); if ( debug ){ System.out.println(timeE-timeS); } } public void testRemoteScop(){ if (debug) { System.out.println("remote"); } long timeS = System.currentTimeMillis(); ScopDatabase scop = new RemoteScopInstallation(); ScopDatabase defaultScop = ScopFactory.getSCOP(); ScopFactory.setScopDatabase(scop); runSCOPTests(); ScopFactory.setScopDatabase(defaultScop); long timeE = System.currentTimeMillis(); if ( debug ){ System.out.println(timeE-timeS); } } private void runSCOPTests(){ ScopDatabase scop = ScopFactory.getSCOP(); List<ScopDomain> domains = scop.getDomainsForPDB("4HHB"); assertTrue(domains.size() == 4); // test case sensitivity; List<ScopDomain> domains2 = scop.getDomainsForPDB("4hhb"); assertTrue(domains2.size() == domains.size()); //System.out.println(domains); - String scop1m02 = "d1m02a_ 1m02 A: k.36.1.1 74353 cl=58788,cf=75796,sf=75797,fa=75798,dm=75799,sp=75800,px=74353"; + String scop1m02 = "d1m02a_ 1m02 A: k.36.1.1 74353 cl=58788,cf=75796,sf=75798,fa=75797,dm=75799,sp=75800,px=74353"; List<ScopDomain> domains1m02 = scop.getDomainsForPDB("1m02"); assertTrue(domains1m02.size() == 1); ScopDomain d1 = domains1m02.get(0); assertNotNull(d1); assertEquals("The toString() methods for ScopDomains don't match the scop display",d1.toString(),scop1m02); List<ScopDomain> domains1cdg = scop.getDomainsForPDB("1CDG"); assertTrue(domains1cdg.size() == 4); ScopDomain d2 = domains1cdg.get(0); AtomCache cache = new AtomCache(); try { Structure s = cache.getStructureForDomain(d2); //checkRange(s,"A:496-581"); // now with ligands! checkRange(s,"A:496-692"); } catch (Exception e){ e.printStackTrace(); fail(e.getMessage()); } // check a domain with multiple ranges List<ScopDomain> domains1xzp = scop.getDomainsForPDB("1xzp"); assertTrue(domains1xzp.size() ==4 ); try { Structure s = cache.getStructureForDomain(domains1xzp.get(0)); Chain a = s.getChainByPDB("A"); // now with ligands... assertEquals(a.getAtomGroups().size(),176); }catch (Exception e){ e.printStackTrace(); fail(e.getMessage()); } // check insertion codes List<ScopDomain> domains2bq6 = scop.getDomainsForPDB("2bq6"); assertTrue(domains2bq6.size() == 2); ScopDomain target = scop.getDomainByScopID("d2bq6a1"); assertNotNull(target); try { Structure s = cache.getStructureForDomain(target); Chain a = s.getChainByPDB("A"); assertEquals(a.getAtomGroups().size(),52); checkRange(s,"A:1A-49"); }catch (Exception e){ e.printStackTrace(); fail(e.getMessage()); } } private void checkRange(Structure s, String range) { GroupIterator iter = new GroupIterator(s); Group g1 = iter.next(); Group g2 =null; while (iter.hasNext()){ g2 = iter.next(); } assertNotNull(g1); assertNotNull(g2); String chainId = g1.getChain().getChainID(); String rangeTest = chainId + ":"+ g1.getResidueNumber().toString()+"-"+ g2.getResidueNumber().toString(); assertEquals("The expected range and the detected range don;t match!", rangeTest, range); } }
true
true
private void runSCOPTests(){ ScopDatabase scop = ScopFactory.getSCOP(); List<ScopDomain> domains = scop.getDomainsForPDB("4HHB"); assertTrue(domains.size() == 4); // test case sensitivity; List<ScopDomain> domains2 = scop.getDomainsForPDB("4hhb"); assertTrue(domains2.size() == domains.size()); //System.out.println(domains); String scop1m02 = "d1m02a_ 1m02 A: k.36.1.1 74353 cl=58788,cf=75796,sf=75797,fa=75798,dm=75799,sp=75800,px=74353"; List<ScopDomain> domains1m02 = scop.getDomainsForPDB("1m02"); assertTrue(domains1m02.size() == 1); ScopDomain d1 = domains1m02.get(0); assertNotNull(d1); assertEquals("The toString() methods for ScopDomains don't match the scop display",d1.toString(),scop1m02); List<ScopDomain> domains1cdg = scop.getDomainsForPDB("1CDG"); assertTrue(domains1cdg.size() == 4); ScopDomain d2 = domains1cdg.get(0); AtomCache cache = new AtomCache(); try { Structure s = cache.getStructureForDomain(d2); //checkRange(s,"A:496-581"); // now with ligands! checkRange(s,"A:496-692"); } catch (Exception e){ e.printStackTrace(); fail(e.getMessage()); } // check a domain with multiple ranges List<ScopDomain> domains1xzp = scop.getDomainsForPDB("1xzp"); assertTrue(domains1xzp.size() ==4 ); try { Structure s = cache.getStructureForDomain(domains1xzp.get(0)); Chain a = s.getChainByPDB("A"); // now with ligands... assertEquals(a.getAtomGroups().size(),176); }catch (Exception e){ e.printStackTrace(); fail(e.getMessage()); } // check insertion codes List<ScopDomain> domains2bq6 = scop.getDomainsForPDB("2bq6"); assertTrue(domains2bq6.size() == 2); ScopDomain target = scop.getDomainByScopID("d2bq6a1"); assertNotNull(target); try { Structure s = cache.getStructureForDomain(target); Chain a = s.getChainByPDB("A"); assertEquals(a.getAtomGroups().size(),52); checkRange(s,"A:1A-49"); }catch (Exception e){ e.printStackTrace(); fail(e.getMessage()); } }
private void runSCOPTests(){ ScopDatabase scop = ScopFactory.getSCOP(); List<ScopDomain> domains = scop.getDomainsForPDB("4HHB"); assertTrue(domains.size() == 4); // test case sensitivity; List<ScopDomain> domains2 = scop.getDomainsForPDB("4hhb"); assertTrue(domains2.size() == domains.size()); //System.out.println(domains); String scop1m02 = "d1m02a_ 1m02 A: k.36.1.1 74353 cl=58788,cf=75796,sf=75798,fa=75797,dm=75799,sp=75800,px=74353"; List<ScopDomain> domains1m02 = scop.getDomainsForPDB("1m02"); assertTrue(domains1m02.size() == 1); ScopDomain d1 = domains1m02.get(0); assertNotNull(d1); assertEquals("The toString() methods for ScopDomains don't match the scop display",d1.toString(),scop1m02); List<ScopDomain> domains1cdg = scop.getDomainsForPDB("1CDG"); assertTrue(domains1cdg.size() == 4); ScopDomain d2 = domains1cdg.get(0); AtomCache cache = new AtomCache(); try { Structure s = cache.getStructureForDomain(d2); //checkRange(s,"A:496-581"); // now with ligands! checkRange(s,"A:496-692"); } catch (Exception e){ e.printStackTrace(); fail(e.getMessage()); } // check a domain with multiple ranges List<ScopDomain> domains1xzp = scop.getDomainsForPDB("1xzp"); assertTrue(domains1xzp.size() ==4 ); try { Structure s = cache.getStructureForDomain(domains1xzp.get(0)); Chain a = s.getChainByPDB("A"); // now with ligands... assertEquals(a.getAtomGroups().size(),176); }catch (Exception e){ e.printStackTrace(); fail(e.getMessage()); } // check insertion codes List<ScopDomain> domains2bq6 = scop.getDomainsForPDB("2bq6"); assertTrue(domains2bq6.size() == 2); ScopDomain target = scop.getDomainByScopID("d2bq6a1"); assertNotNull(target); try { Structure s = cache.getStructureForDomain(target); Chain a = s.getChainByPDB("A"); assertEquals(a.getAtomGroups().size(),52); checkRange(s,"A:1A-49"); }catch (Exception e){ e.printStackTrace(); fail(e.getMessage()); } }
diff --git a/src/main/java/com/laytonsmith/PureUtilities/ClassDiscovery.java b/src/main/java/com/laytonsmith/PureUtilities/ClassDiscovery.java index 63f53461..9ea3172a 100644 --- a/src/main/java/com/laytonsmith/PureUtilities/ClassDiscovery.java +++ b/src/main/java/com/laytonsmith/PureUtilities/ClassDiscovery.java @@ -1,458 +1,460 @@ package com.laytonsmith.PureUtilities; import java.io.File; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.URL; import java.net.URLDecoder; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public final class ClassDiscovery { private ClassDiscovery() { } /** * Adds a jar or file path location to be scanned by the default call to * GetClassesWithinPackageHierarchy. This is useful if an external library * wishes to be considered by the scanner. * * @param url */ public static void InstallDiscoveryLocation(String url) { additionalURLs.add(url); } /** * Clears the class cache. Upon the first call to the rather expensive * GetClassesWithinPackageHierarchy(String) method, the returned classes are * cached instead of being regenerated. This method is automatically called * if a new discovery location is installed, but if new classes are being * generated dynamically, this cache will become stale, and you should clear * the cache for a particular url. If url is null, all caches are cleared. */ public static void InvalidateCache(String url) { if (url == null) { for (String u : new HashSet<String>(classCache.keySet())) { InvalidateCache(u); } fuzzyClassCache.clear(); } else { classCache.remove(url); } classAnnotationCache.clear(); fieldAnnotationCache.clear(); methodAnnotationCache.clear(); } /** * Equivalent to InvalidateCache(null); */ public static void InvalidateCache() { InvalidateCache(null); } /** * There's no need to rescan the project every time * GetClassesWithinPackageHierarchy is called, unless we add a new discovery * location, or code is being generated on the fly or something crazy like * that, so let's cache unless told otherwise. */ private static Map<String, Class[]> classCache = new HashMap<String, Class[]>(); private static Map<String, Class> fuzzyClassCache = new HashMap<String, Class>(); private static Set<String> additionalURLs = new HashSet<String>(); private static Map<Class<? extends Annotation>, Set<Class>> classAnnotationCache = new HashMap<Class<? extends Annotation>, Set<Class>>(); private static Map<Class<? extends Annotation>, Set<Field>> fieldAnnotationCache = new HashMap<Class<? extends Annotation>, Set<Field>>(); private static Map<Class<? extends Annotation>, Set<Method>> methodAnnotationCache = new HashMap<Class<? extends Annotation>, Set<Method>>(); private static final Set<ClassLoader> defaultClassLoaders = new HashSet<ClassLoader>(); static{ defaultClassLoaders.add(ClassDiscovery.class.getClassLoader()); } public static Class[] GetClassesWithinPackageHierarchy() { List<Class> classes = new ArrayList<Class>(); classes.addAll(Arrays.asList(GetClassesWithinPackageHierarchy(null, null))); for (String url : additionalURLs) { classes.addAll(Arrays.asList(GetClassesWithinPackageHierarchy(url, null))); } return classes.toArray(new Class[classes.size()]); } public static void InstallClassLoader(ClassLoader cl){ defaultClassLoaders.add(cl); } /** * Gets all the classes in the specified location. The url can point to a * jar, or a file system location. If null, the binary in which * this particular class file is located is used. * * @param url The url to the jar/folder * @param loader The classloader to use to load the classes. If null, the default classloader list is used, which * can be added to with InstallClassLoader(). * @return */ public static Class[] GetClassesWithinPackageHierarchy(String url, Set<ClassLoader> loaders) { if (classCache.containsKey(url)) { return classCache.get(url); } if(loaders == null){ loaders = defaultClassLoaders; } String originalURL = url; if (url == null) { url = GetClassPackageHierachy(ClassDiscovery.class); } List<String> classNameList = new ArrayList<String>(); if (url.startsWith("file:")) { //We are running from the file system //First, get the "root" of the class structure. We assume it's //the root of this class String fileName = Pattern.quote(ClassDiscovery.class.getCanonicalName().replace(".", "/")); fileName = fileName/*.replaceAll("\\\\Q", "").replaceAll("\\\\E", "")*/ + ".class"; String root = url.replaceAll("file:" + (TermColors.SYSTEM == TermColors.SYS.WINDOWS ? "/" : ""), "").replaceAll(fileName, ""); //System.out.println(root); //Ok, now we have the "root" of the known class structure. Let's recursively //go through everything and pull out the files List<File> fileList = new ArrayList<File>(); descend(new File(root), fileList); //Now, we have all the class files in the package. But, it's the absolute path //to all of them. We have to first remove the "front" part for (File f : fileList) { classNameList.add(f.getAbsolutePath().replaceFirst(Pattern.quote(new File(root).getAbsolutePath() + File.separator), "")); } } else if (url.startsWith("jar:")) { //We are running from a jar if (url.endsWith("!/")) { url = StringUtils.replaceLast(url, "!/", ""); } url = url.replaceFirst("jar:", ""); ZipInputStream zip = null; try { URL jar = new URL(url); zip = new ZipInputStream(jar.openStream()); ZipEntry ze; while ((ze = zip.getNextEntry()) != null) { classNameList.add(ze.getName()); } } catch (IOException ex) { Logger.getLogger(ClassDiscovery.class.getName()).log(Level.SEVERE, null, ex); } finally { try { zip.close(); } catch (IOException ex) { //Logger.getLogger(ClassDiscovery.class.getName()).log(Level.SEVERE, null, ex); } } } //Ok, now we need to go through the list, and throw out entries //that are anonymously named (they end in $\d.class) because they //are inaccessible anyways List<Class> files = new ArrayList<Class>(); for (String s : classNameList) { //Don't consider anonymous inner classes if (!s.matches(".*\\$(?:\\d)*\\.class") && s.endsWith(".class")) { //Now, replace any \ with / and replace / with ., and remove the .class, //and forName it. String className = s.replaceAll("\\.class", "").replaceAll("\\\\", "/").replaceAll("[/]", "."); for(ClassLoader loader : loaders){ try { //Don't initialize it, so we don't have to deal with ExceptionInInitializer errors Class c = Class.forName(className, false, loader); files.add(c); } catch (ClassNotFoundException ex) { //It can't be loaded? O.o Oh well. } catch (NoClassDefFoundError ex) { //Must have been an external library + } catch (VerifyError ex){ + //Internal class error, ignore } } } } //Put the results in the cache Class[] ret = files.toArray(new Class[files.size()]); classCache.put(originalURL, ret); return ret; } public static Class[] GetClassesWithAnnotation(Class<? extends Annotation> annotation) { if(classAnnotationCache.containsKey(annotation)){ return new HashSet<Class>(classAnnotationCache.get(annotation)) .toArray(new Class[classAnnotationCache.get(annotation).size()]); } Set<Class> classes = new HashSet<Class>(); for (Class c : GetClassesWithinPackageHierarchy()) { if (c.getAnnotation(annotation) != null) { classes.add(c); } } classAnnotationCache.put(annotation, classes); return classes.toArray(new Class[classes.size()]); } public static Field[] GetFieldsWithAnnotation(Class<? extends Annotation> annotation){ if(fieldAnnotationCache.containsKey(annotation)){ return new HashSet<Field>(fieldAnnotationCache.get(annotation)) .toArray(new Field[fieldAnnotationCache.get(annotation).size()]); } Set<Field> fields = new HashSet<Field>(); for (Class c : GetClassesWithinPackageHierarchy()) { try{ for(Field f : c.getDeclaredFields()){ if (f.getAnnotation(annotation) != null) { fields.add(f); } } } catch(Throwable t){ //This can happen in any number of cases, but we don't care, we just want to skip the class. } } fieldAnnotationCache.put(annotation, fields); return fields.toArray(new Field[fields.size()]); } public static Method[] GetMethodsWithAnnotation(Class<? extends Annotation> annotation){ if(methodAnnotationCache.containsKey(annotation)){ return new HashSet<Method>(methodAnnotationCache.get(annotation)) .toArray(new Method[methodAnnotationCache.get(annotation).size()]); } Set<Method> methods = new HashSet<Method>(); for (Class c : GetClassesWithinPackageHierarchy()) { try{ for(Method m : c.getDeclaredMethods()){ if (m.getAnnotation(annotation) != null) { methods.add(m); } } } catch(Throwable t){ //This can happen in any number of cases, but we don't care, we just want to skip the class. } } methodAnnotationCache.put(annotation, methods); return methods.toArray(new Method[methods.size()]); } /** * Returns a list of all known or discoverable classes in this class loader. * @return */ static Set<Class> GetAllClasses(){ Set<Class> classes = new HashSet<Class>(); Set<ClassLoader> classLoaders = new HashSet<ClassLoader>(); classLoaders.add(ClassDiscovery.class.getClassLoader()); for(String url : additionalURLs){ classes.addAll(Arrays.asList(GetClassesWithinPackageHierarchy(url, classLoaders))); } return classes; } /** * Gets all the package hierarchies for all currently known classes. This is * a VERY expensive operation, and should be avoided as much as possible. * The set of ClassLoaders to search should be sent, which will each be * searched, including each ClassLoader's parent. If classLoaders is null, * the calling class's ClassLoader is used, if possible, otherwise the * current Thread's context class loader is used. This may not be a * reasonable default for your purposes, so it is best to * * @return */ @SuppressWarnings("UseOfObsoleteCollectionType") public static Set<String> GetKnownPackageHierarchies(Set<ClassLoader> classLoaders) { Set<String> list = new HashSet<String>(); if (classLoaders == null) { classLoaders = new HashSet<ClassLoader>(); //0 is the thread, 1 is us, and 2 is our caller. StackTraceElement ste = Thread.currentThread().getStackTrace()[2]; try { Class c = Class.forName(ste.getClassName()); classLoaders.add(c.getClassLoader()); } catch (ClassNotFoundException ex) { classLoaders.add(Thread.currentThread().getContextClassLoader()); } } //Go through and pull out all the parents, and we can just iterate through that, which allows //us to skip classloaders if multiple classloaders (which will ultimately all have at least one //classloader in common) are passed in, we aren't scanning them twice. Set<ClassLoader> classes = new HashSet<ClassLoader>(); for (ClassLoader cl : classLoaders) { while (cl != null) { classes.add(cl); cl = cl.getParent(); } } Set<String> foundClasses = new TreeSet<String>(); for (ClassLoader l : classes) { List v = new ArrayList((Vector) ReflectionUtils.get(ClassLoader.class, l, "classes")); for (Object o : v) { Class c = (Class) o; if (!foundClasses.contains(c.getName())) { String url = GetClassPackageHierachy(c); if (url != null) { list.add(url); } foundClasses.add(c.getName()); } } } return list; } /** * Works like Class.forName, but tries all the given ClassLoaders before * giving up. Eventually though, it will throw a ClassNotFoundException if * none of the classloaders know about it. * * @param name * @param initialize * @param loaders * @return */ public static Class<?> forName(String name, boolean initialize, Set<ClassLoader> loaders) throws ClassNotFoundException { Class c = null; for (ClassLoader loader : loaders) { try { c = Class.forName(name, initialize, loader); } catch (ClassNotFoundException e) { continue; } } if (c == null) { throw new ClassNotFoundException(name + " was not found in any ClassLoader!"); } return c; } public static Class<?> forFuzzyName(String packageRegex, String className){ return forFuzzyName(packageRegex, className, true, ClassDiscovery.class.getClassLoader()); } /** * Returns a class given a "fuzzy" package name, that is, the package name provided is a * regex. The class name must match exactly, but the package name will be the closest match, * or undefined if there is no clear candidate. If no matches are found, null is returned. * @param packageRegex * @param className * @param initialize * @param classLoader * @return */ public static Class<?> forFuzzyName(String packageRegex, String className, boolean initialize, ClassLoader classLoader){ String index = packageRegex + className; if(fuzzyClassCache.containsKey(index)){ return fuzzyClassCache.get(index); } else { Set<Class> found = new HashSet<Class>(); Set<Class> searchSpace = GetAllClasses(); for(Class c : searchSpace){ if(c.getPackage().getName().matches(packageRegex) && c.getSimpleName().equals(className)){ found.add(c); } } if(found.size() == 1){ return found.iterator().next(); } else if(found.isEmpty()){ return null; } else { Class candidate = null; int max = Integer.MAX_VALUE; for(Class f : found){ int distance = StringUtils.LevenshteinDistance(f.getPackage().getName(), packageRegex); if(distance < max){ candidate = f; max = distance; } } fuzzyClassCache.put(index, candidate); return candidate; } } } /** * Gets all concrete classes that either extend (in the case of a class) or implement * (in the case of an interface) this superType. Additionally, if superType is a concrete * class, it itself will be returned in the list. Note that by "concrete class" it is meant * that the class is instantiatable, so abstract classes would not be returned. * @param superType * @return */ public static Class[] GetAllClassesOfSubtype(Class superType, Set<ClassLoader> classLoaders){ Set<Class> list = new HashSet<Class>(); for(String url : additionalURLs){ list.addAll(Arrays.asList(GetClassesWithinPackageHierarchy(url, classLoaders))); } Set<Class> ret = new HashSet<Class>(); for(Class c : list){ if(superType.isAssignableFrom(c) && !c.isInterface()){ //Check to see if abstract if(!Modifier.isAbstract(c.getModifiers())){ ret.add(c); } } } return ret.toArray(new Class[ret.size()]); } /** * Returns the container url for this class. This varies based on whether or * not the class files are in a zip/jar or not, so this method standardizes * that. The method may return null, if the class is a dynamically generated * class (perhaps with asm, or a proxy class) * * @param c * @return */ public static String GetClassPackageHierachy(Class c) { if (c == null) { throw new NullPointerException("The Class passed to this method may not be null"); } try { while(c.isMemberClass() || c.isAnonymousClass()){ c = c.getEnclosingClass(); //Get the actual enclosing file } if (c.getProtectionDomain().getCodeSource() == null) { //This is a proxy or other dynamically generated class, and has no physical container, //so just return null. return null; } String packageRoot; try { //This is the full path to THIS file, but we need to get the package root. String thisClass = c.getResource(c.getSimpleName() + ".class").toString(); packageRoot = StringUtils.replaceLast(thisClass, Pattern.quote(c.getName().replaceAll("\\.", "/") + ".class"), ""); if(packageRoot.endsWith("!/")){ packageRoot = StringUtils.replaceLast(packageRoot, "!/", ""); } } catch (Exception e) { //Hmm, ok, try this then packageRoot = c.getProtectionDomain().getCodeSource().getLocation().toString(); } packageRoot = URLDecoder.decode(packageRoot, "UTF-8"); return packageRoot; } catch (Exception e) { throw new RuntimeException("While interrogating " + c.getName() + ", an unexpected exception was thrown.", e); } } private static void descend(File start, List<File> fileList) { if (start.isFile()) { if (start.getName().endsWith(".class")) { fileList.add(start); } } else { for (File child : start.listFiles()) { descend(child, fileList); } } } }
true
true
public static Class[] GetClassesWithinPackageHierarchy(String url, Set<ClassLoader> loaders) { if (classCache.containsKey(url)) { return classCache.get(url); } if(loaders == null){ loaders = defaultClassLoaders; } String originalURL = url; if (url == null) { url = GetClassPackageHierachy(ClassDiscovery.class); } List<String> classNameList = new ArrayList<String>(); if (url.startsWith("file:")) { //We are running from the file system //First, get the "root" of the class structure. We assume it's //the root of this class String fileName = Pattern.quote(ClassDiscovery.class.getCanonicalName().replace(".", "/")); fileName = fileName/*.replaceAll("\\\\Q", "").replaceAll("\\\\E", "")*/ + ".class"; String root = url.replaceAll("file:" + (TermColors.SYSTEM == TermColors.SYS.WINDOWS ? "/" : ""), "").replaceAll(fileName, ""); //System.out.println(root); //Ok, now we have the "root" of the known class structure. Let's recursively //go through everything and pull out the files List<File> fileList = new ArrayList<File>(); descend(new File(root), fileList); //Now, we have all the class files in the package. But, it's the absolute path //to all of them. We have to first remove the "front" part for (File f : fileList) { classNameList.add(f.getAbsolutePath().replaceFirst(Pattern.quote(new File(root).getAbsolutePath() + File.separator), "")); } } else if (url.startsWith("jar:")) { //We are running from a jar if (url.endsWith("!/")) { url = StringUtils.replaceLast(url, "!/", ""); } url = url.replaceFirst("jar:", ""); ZipInputStream zip = null; try { URL jar = new URL(url); zip = new ZipInputStream(jar.openStream()); ZipEntry ze; while ((ze = zip.getNextEntry()) != null) { classNameList.add(ze.getName()); } } catch (IOException ex) { Logger.getLogger(ClassDiscovery.class.getName()).log(Level.SEVERE, null, ex); } finally { try { zip.close(); } catch (IOException ex) { //Logger.getLogger(ClassDiscovery.class.getName()).log(Level.SEVERE, null, ex); } } } //Ok, now we need to go through the list, and throw out entries //that are anonymously named (they end in $\d.class) because they //are inaccessible anyways List<Class> files = new ArrayList<Class>(); for (String s : classNameList) { //Don't consider anonymous inner classes if (!s.matches(".*\\$(?:\\d)*\\.class") && s.endsWith(".class")) { //Now, replace any \ with / and replace / with ., and remove the .class, //and forName it. String className = s.replaceAll("\\.class", "").replaceAll("\\\\", "/").replaceAll("[/]", "."); for(ClassLoader loader : loaders){ try { //Don't initialize it, so we don't have to deal with ExceptionInInitializer errors Class c = Class.forName(className, false, loader); files.add(c); } catch (ClassNotFoundException ex) { //It can't be loaded? O.o Oh well. } catch (NoClassDefFoundError ex) { //Must have been an external library } } } } //Put the results in the cache Class[] ret = files.toArray(new Class[files.size()]); classCache.put(originalURL, ret); return ret; }
public static Class[] GetClassesWithinPackageHierarchy(String url, Set<ClassLoader> loaders) { if (classCache.containsKey(url)) { return classCache.get(url); } if(loaders == null){ loaders = defaultClassLoaders; } String originalURL = url; if (url == null) { url = GetClassPackageHierachy(ClassDiscovery.class); } List<String> classNameList = new ArrayList<String>(); if (url.startsWith("file:")) { //We are running from the file system //First, get the "root" of the class structure. We assume it's //the root of this class String fileName = Pattern.quote(ClassDiscovery.class.getCanonicalName().replace(".", "/")); fileName = fileName/*.replaceAll("\\\\Q", "").replaceAll("\\\\E", "")*/ + ".class"; String root = url.replaceAll("file:" + (TermColors.SYSTEM == TermColors.SYS.WINDOWS ? "/" : ""), "").replaceAll(fileName, ""); //System.out.println(root); //Ok, now we have the "root" of the known class structure. Let's recursively //go through everything and pull out the files List<File> fileList = new ArrayList<File>(); descend(new File(root), fileList); //Now, we have all the class files in the package. But, it's the absolute path //to all of them. We have to first remove the "front" part for (File f : fileList) { classNameList.add(f.getAbsolutePath().replaceFirst(Pattern.quote(new File(root).getAbsolutePath() + File.separator), "")); } } else if (url.startsWith("jar:")) { //We are running from a jar if (url.endsWith("!/")) { url = StringUtils.replaceLast(url, "!/", ""); } url = url.replaceFirst("jar:", ""); ZipInputStream zip = null; try { URL jar = new URL(url); zip = new ZipInputStream(jar.openStream()); ZipEntry ze; while ((ze = zip.getNextEntry()) != null) { classNameList.add(ze.getName()); } } catch (IOException ex) { Logger.getLogger(ClassDiscovery.class.getName()).log(Level.SEVERE, null, ex); } finally { try { zip.close(); } catch (IOException ex) { //Logger.getLogger(ClassDiscovery.class.getName()).log(Level.SEVERE, null, ex); } } } //Ok, now we need to go through the list, and throw out entries //that are anonymously named (they end in $\d.class) because they //are inaccessible anyways List<Class> files = new ArrayList<Class>(); for (String s : classNameList) { //Don't consider anonymous inner classes if (!s.matches(".*\\$(?:\\d)*\\.class") && s.endsWith(".class")) { //Now, replace any \ with / and replace / with ., and remove the .class, //and forName it. String className = s.replaceAll("\\.class", "").replaceAll("\\\\", "/").replaceAll("[/]", "."); for(ClassLoader loader : loaders){ try { //Don't initialize it, so we don't have to deal with ExceptionInInitializer errors Class c = Class.forName(className, false, loader); files.add(c); } catch (ClassNotFoundException ex) { //It can't be loaded? O.o Oh well. } catch (NoClassDefFoundError ex) { //Must have been an external library } catch (VerifyError ex){ //Internal class error, ignore } } } } //Put the results in the cache Class[] ret = files.toArray(new Class[files.size()]); classCache.put(originalURL, ret); return ret; }
diff --git a/svnkit-cli/src/org/tmatesoft/svn/cli2/svn/SVNCommandEnvironment.java b/svnkit-cli/src/org/tmatesoft/svn/cli2/svn/SVNCommandEnvironment.java index 2d1de00df..71b48657a 100644 --- a/svnkit-cli/src/org/tmatesoft/svn/cli2/svn/SVNCommandEnvironment.java +++ b/svnkit-cli/src/org/tmatesoft/svn/cli2/svn/SVNCommandEnvironment.java @@ -1,898 +1,898 @@ /* * ==================================================================== * Copyright (c) 2004-2007 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli2.svn; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.cli2.AbstractSVNCommand; import org.tmatesoft.svn.cli2.AbstractSVNCommandEnvironment; import org.tmatesoft.svn.cli2.AbstractSVNOption; import org.tmatesoft.svn.cli2.SVNCommandLine; import org.tmatesoft.svn.cli2.SVNCommandUtil; import org.tmatesoft.svn.cli2.SVNConsoleAuthenticationProvider; import org.tmatesoft.svn.cli2.SVNOptionValue; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNFileType; import org.tmatesoft.svn.core.internal.wc.SVNPropertiesManager; import org.tmatesoft.svn.core.wc.ISVNCommitHandler; import org.tmatesoft.svn.core.wc.ISVNOptions; import org.tmatesoft.svn.core.wc.SVNCommitItem; import org.tmatesoft.svn.core.wc.SVNDiffOptions; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNRevisionRange; import org.tmatesoft.svn.core.wc.SVNWCUtil; /** * @version 1.1.2 * @author TMate Software Ltd. */ public class SVNCommandEnvironment extends AbstractSVNCommandEnvironment implements ISVNCommitHandler { private static final String DEFAULT_LOG_MESSAGE_HEADER = "--This line, and those below, will be ignored--"; private SVNDepth myDepth; private SVNDepth mySetDepth; private boolean myIsVerbose; private boolean myIsUpdate; private boolean myIsQuiet; private boolean myIsIncremental; private boolean myIsHelp; private boolean myIsIgnoreExternals; private boolean myIsXML; private boolean myIsVersion; private String myChangelist; private boolean myIsNonInteractive; private boolean myIsNoAuthCache; private String myUserName; private String myPassword; private String myConfigDir; private boolean myIsDescend; private boolean myIsNoIgnore; private boolean myIsRevprop; private boolean myIsStrict; private SVNRevision myStartRevision; private SVNRevision myEndRevision; private boolean myIsForce; private String myFilePath; private byte[] myFileData; private List myTargets; private String myEncoding; private String myMessage; private boolean myIsForceLog; private String myEditorCommand; private SVNProperties myRevisionProperties; private boolean myIsNoUnlock; private boolean myIsDryRun; private boolean myIsRecordOnly; private boolean myIsUseMergeHistory; private Collection myExtensions; private boolean myIsIgnoreAncestry; private String myNativeEOL; private boolean myIsRelocate; private boolean myIsNoAutoProps; private boolean myIsAutoProps; private boolean myIsKeepChangelist; private boolean myIsParents; private boolean myIsKeepLocal; private SVNConflictAcceptPolicy myResolveAccept; private boolean myIsRemove; private String myNewTarget; private String myOldTarget; private boolean myIsNoticeAncestry; private boolean myIsSummarize; private boolean myIsNoDiffDeleted; private long myLimit; private boolean myIsStopOnCopy; private boolean myIsChangeOptionUsed; private boolean myIsWithAllRevprops; private boolean myIsReIntegrate; private List myRevisionRanges; private String myFromSource; private Collection myChangelists; public SVNCommandEnvironment(String programName, PrintStream out, PrintStream err, InputStream in) { super(programName, out, err, in); myIsDescend = true; myLimit = -1; myResolveAccept = SVNConflictAcceptPolicy.INVALID; myExtensions = new HashSet(); myDepth = SVNDepth.UNKNOWN; mySetDepth = SVNDepth.UNKNOWN; myStartRevision = SVNRevision.UNDEFINED; myEndRevision = SVNRevision.UNDEFINED; myRevisionRanges = new LinkedList(); myChangelists = new HashSet(); } public void initClientManager() throws SVNException { super.initClientManager(); getClientManager().setIgnoreExternals(myIsIgnoreExternals); } protected String refineCommandName(String commandName) throws SVNException { if (myIsHelp) { List newArguments = commandName != null ? Collections.singletonList(commandName) : Collections.EMPTY_LIST; setArguments(newArguments); return "help"; } if (commandName == null) { if (isVersion()) { SVNCommand versionCommand = new SVNCommand("--version", null) { protected Collection createSupportedOptions() { return Arrays.asList(new SVNOption[] {SVNOption.VERSION, SVNOption.CONFIG_DIR, SVNOption.QUIET}); } public void run() throws SVNException { AbstractSVNCommand helpCommand = AbstractSVNCommand.getCommand("help"); helpCommand.init(SVNCommandEnvironment.this); helpCommand.run(); } }; AbstractSVNCommand.registerCommand(versionCommand); return "--version"; } SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Subcommand argument required"); SVNErrorManager.error(err); } return commandName; } protected ISVNOptions createClientOptions() throws SVNException { File configDir = myConfigDir != null ? new File(myConfigDir) : SVNWCUtil.getDefaultConfigurationDirectory(); ISVNOptions options = SVNWCUtil.createDefaultOptions(configDir, true); options.setAuthStorageEnabled(!myIsNoAuthCache); if (myIsAutoProps) { options.setUseAutoProperties(true); } if (myIsNoAutoProps) { options.setUseAutoProperties(false); } if (myIsNoUnlock) { options.setKeepLocks(true); } if ((myResolveAccept == SVNConflictAcceptPolicy.INVALID && (!options.isInteractiveConflictResolution() || myIsNonInteractive)) || myResolveAccept == SVNConflictAcceptPolicy.POSTPONE) { options.setConflictHandler(null); } else { if (myIsNonInteractive) { if (myResolveAccept == SVNConflictAcceptPolicy.EDIT) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "--accept={0} incompatible with --non-interactive", SVNConflictAcceptPolicy.EDIT); SVNErrorManager.error(err); } if (myResolveAccept == SVNConflictAcceptPolicy.LAUNCH) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "--accept={0} incompatible with --non-interactive", SVNConflictAcceptPolicy.LAUNCH); SVNErrorManager.error(err); } } options.setConflictHandler(new SVNCommandLineConflictHandler(myResolveAccept, this)); } return options; } protected ISVNAuthenticationManager createClientAuthenticationManager() { File configDir = myConfigDir != null ? new File(myConfigDir) : SVNWCUtil.getDefaultConfigurationDirectory(); ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(configDir, myUserName, myPassword, !myIsNoAuthCache); if (!myIsNonInteractive) { authManager.setAuthenticationProvider(new SVNConsoleAuthenticationProvider()); } return authManager; } protected void initOptions(SVNCommandLine commandLine) throws SVNException { super.initOptions(commandLine); if (getCommand().getClass() != SVNMergeCommand.class) { if (myRevisionRanges.size() > 1) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Multiple revision argument encountered; " + "can't specify -c twice, or both -c and -r"); SVNErrorManager.error(err); } } else if (!myRevisionRanges.isEmpty() && myIsReIntegrate) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "-r and -c can't be used with --reintegrate"); SVNErrorManager.error(err); } if (myRevisionRanges.isEmpty()) { SVNRevisionRange range = new SVNRevisionRange(SVNRevision.UNDEFINED, SVNRevision.UNDEFINED); myRevisionRanges.add(range); } SVNRevisionRange range = (SVNRevisionRange) myRevisionRanges.get(0); myStartRevision = range.getStartRevision(); myEndRevision = range.getEndRevision(); if (myIsReIntegrate) { if (myIsIgnoreAncestry) { if (myIsRecordOnly) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS, "--reintegrate cannot be used with --ignore-ancestry or --record-only"); SVNErrorManager.error(err); } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS, "--reintegrate cannot be used with --ignore-ancestry"); SVNErrorManager.error(err); } } else if (myIsRecordOnly) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS, "--reintegrate cannot be used with --record-only"); SVNErrorManager.error(err); } } } protected void initOption(SVNOptionValue optionValue) throws SVNException { AbstractSVNOption option = optionValue.getOption(); if (option == SVNOption.LIMIT) { String limitStr = optionValue.getValue(); try { long limit = Long.parseLong(limitStr); if (limit <= 0) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.INCORRECT_PARAMS, "Argument to --limit must be positive"); SVNErrorManager.error(err); } myLimit = limit; } catch (NumberFormatException nfe) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Non-numeric limit argument given"); SVNErrorManager.error(err); } } else if (option == SVNOption.MESSAGE) { myMessage = optionValue.getValue(); } else if (option == SVNOption.CHANGE) { if (myOldTarget != null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Can't specify -c with --old"); SVNErrorManager.error(err); } String chValue = optionValue.getValue(); long change = 0; try { change = Long.parseLong(chValue); } catch (NumberFormatException nfe) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Non-numeric change argument given to -c"); SVNErrorManager.error(err); } SVNRevisionRange range = null; if (change == 0) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "There is no change 0"); SVNErrorManager.error(err); } else if (change > 0) { range = new SVNRevisionRange(SVNRevision.create(change - 1), SVNRevision.create(change)); } else { change = -change; range = new SVNRevisionRange(SVNRevision.create(change), SVNRevision.create(change - 1)); } myRevisionRanges.add(range); myIsChangeOptionUsed = true; } else if (option == SVNOption.REVISION) { String revStr = optionValue.getValue(); SVNRevision[] revisions = parseRevision(revStr); if (revisions == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Syntax error in revision argument ''{0}''", revStr); SVNErrorManager.error(err); } SVNRevisionRange range = new SVNRevisionRange(revisions[0], revisions[1]); myRevisionRanges.add(range); } else if (option == SVNOption.VERBOSE) { myIsVerbose = true; } else if (option == SVNOption.UPDATE) { myIsUpdate = true; } else if (option == SVNOption.HELP || option == SVNOption.QUESTION) { myIsHelp = true; } else if (option == SVNOption.QUIET) { myIsQuiet = true; } else if (option == SVNOption.INCREMENTAL) { myIsIncremental = true; } else if (option == SVNOption.FILE) { String fileName = optionValue.getValue(); myFilePath = fileName; myFileData = readFromFile(new File(fileName)); } else if (option == SVNOption.TARGETS) { String fileName = optionValue.getValue(); byte[] data = readFromFile(new File(fileName)); try { String[] targets = new String(data, "UTF-8").split("\n\r"); myTargets = new LinkedList(); for (int i = 0; i < targets.length; i++) { if (targets[i].trim().length() > 0) { myTargets.add(targets[i].trim()); } } } catch (UnsupportedEncodingException e) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e.getMessage()); SVNErrorManager.error(err); } } else if (option == SVNOption.FORCE) { myIsForce = true; } else if (option == SVNOption.FORCE_LOG) { myIsForceLog = true; } else if (option == SVNOption.DRY_RUN) { myIsDryRun = true; } else if (option == SVNOption.REVPROP) { myIsRevprop = true; } else if (option == SVNOption.RECURSIVE) { myDepth = SVNDepth.fromRecurse(true); } else if (option == SVNOption.NON_RECURSIVE) { myIsDescend = false; } else if (option == SVNOption.DEPTH) { String depth = optionValue.getValue(); if (SVNDepth.EMPTY.getName().equals(depth)) { myDepth = SVNDepth.EMPTY; } else if (SVNDepth.FILES.getName().equals(depth)) { myDepth = SVNDepth.FILES; } else if (SVNDepth.IMMEDIATES.getName().equals(depth)) { myDepth = SVNDepth.IMMEDIATES; } else if (SVNDepth.INFINITY.getName().equals(depth)) { myDepth = SVNDepth.INFINITY; } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "''{0}'' is not a valid depth; try ''empty'', ''files'', ''immediates'', or ''infinit''", depth); SVNErrorManager.error(err); } } else if (option == SVNOption.SET_DEPTH) { String depth = optionValue.getValue(); if (SVNDepth.EMPTY.getName().equals(depth)) { mySetDepth = SVNDepth.EMPTY; } else if (SVNDepth.FILES.getName().equals(depth)) { mySetDepth = SVNDepth.FILES; } else if (SVNDepth.IMMEDIATES.getName().equals(depth)) { mySetDepth = SVNDepth.IMMEDIATES; } else if (SVNDepth.INFINITY.getName().equals(depth)) { mySetDepth = SVNDepth.INFINITY; } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "''{0}'' is not a valid depth; try ''empty'', ''files'', ''immediates'', or ''infinit''", depth); SVNErrorManager.error(err); } } else if (option == SVNOption.VERSION) { myIsVersion = true; } else if (option == SVNOption.USERNAME) { myUserName = optionValue.getValue(); } else if (option == SVNOption.PASSWORD) { myPassword = optionValue.getValue(); } else if (option == SVNOption.ENCODING) { myEncoding = optionValue.getValue(); } else if (option == SVNOption.XML) { myIsXML = true; } else if (option == SVNOption.STOP_ON_COPY) { myIsStopOnCopy = true; } else if (option == SVNOption.STRICT) { myIsStrict = true; } else if (option == SVNOption.NO_AUTH_CACHE) { myIsNoAuthCache = true; } else if (option == SVNOption.NON_INTERACTIVE) { myIsNonInteractive = true; } else if (option == SVNOption.NO_DIFF_DELETED) { myIsNoDiffDeleted = true; } else if (option == SVNOption.NOTICE_ANCESTRY) { myIsNoticeAncestry = true; } else if (option == SVNOption.IGNORE_ANCESTRY) { myIsIgnoreAncestry = true; } else if (option == SVNOption.IGNORE_EXTERNALS) { myIsIgnoreExternals = true; } else if (option == SVNOption.RELOCATE) { if (myDepth != SVNDepth.UNKNOWN) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS, "--depth and --relocate are mutually exclusive")); } myIsRelocate = true; } else if (option == SVNOption.EXTENSIONS) { myExtensions.add(optionValue.getValue()); } else if (option == SVNOption.RECORD_ONLY) { myIsRecordOnly = true; } else if (option == SVNOption.EDITOR_CMD) { myEditorCommand = optionValue.getValue(); } else if (option == SVNOption.OLD) { if (myIsChangeOptionUsed) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Can't specify -c with --old")); } myOldTarget = optionValue.getValue(); } else if (option == SVNOption.NEW) { myNewTarget = optionValue.getValue(); } else if (option == SVNOption.CONFIG_DIR) { myConfigDir = optionValue.getValue(); } else if (option == SVNOption.AUTOPROPS) { if (myIsNoAutoProps) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS, "--auto-props and --no-auto-props are mutually exclusive")); } myIsAutoProps = true; } else if (option == SVNOption.NO_AUTOPROPS) { if (myIsAutoProps) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS, "--auto-props and --no-auto-props are mutually exclusive")); } myIsNoAutoProps = true; } else if (option == SVNOption.NATIVE_EOL) { myNativeEOL = optionValue.getValue(); } else if (option == SVNOption.NO_UNLOCK) { myIsNoUnlock = true; } else if (option == SVNOption.SUMMARIZE) { myIsSummarize = true; } else if (option == SVNOption.REMOVE) { myIsRemove = true; } else if (option == SVNOption.CHANGELIST) { myChangelist = optionValue.getValue(); myChangelists.add(myChangelist); } else if (option == SVNOption.KEEP_CHANGELIST) { myIsKeepChangelist = true; } else if (option == SVNOption.KEEP_LOCAL) { myIsKeepLocal = true; } else if (option == SVNOption.NO_IGNORE) { myIsNoIgnore = true; } else if (option == SVNOption.WITH_ALL_REVPROPS) { myIsWithAllRevprops = true; } else if (option == SVNOption.WITH_REVPROP) { parseRevisionProperty(optionValue); } else if (option == SVNOption.PARENTS) { myIsParents = true; } else if (option == SVNOption.USE_MERGE_HISTORY) { myIsUseMergeHistory = true; } else if (option == SVNOption.ACCEPT) { SVNConflictAcceptPolicy accept = SVNConflictAcceptPolicy.fromString(optionValue.getValue()); if (accept == SVNConflictAcceptPolicy.INVALID) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, - "'" + optionValue.getValue() + "' is not a valid accept value;"); + "'" + optionValue.getValue() + "' is not a valid --accept value;"); SVNErrorManager.error(err); } myResolveAccept = accept; } else if (option == SVNOption.FROM_SOURCE) { myFromSource = optionValue.getValue(); } else if (option == SVNOption.REINTEGRATE) { myIsReIntegrate = true; } } protected SVNCommand getSVNCommand() { return (SVNCommand) getCommand(); } protected void validateOptions(SVNCommandLine commandLine) throws SVNException { super.validateOptions(commandLine); if (!isForceLog() && getSVNCommand().isCommitter()) { if (myFilePath != null) { if (isVersioned(myFilePath)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_LOG_MESSAGE_IS_VERSIONED_FILE, getSVNCommand().getFileAmbigousErrorMessage()); SVNErrorManager.error(err); } } if (myMessage != null && !"".equals(myMessage)) { File file = new File(myMessage).getAbsoluteFile(); if (SVNFileType.getType(file) != SVNFileType.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_LOG_MESSAGE_IS_PATHNAME, getSVNCommand().getMessageAmbigousErrorMessage()); SVNErrorManager.error(err); } } } if (!getSVNCommand().acceptsRevisionRange() && getEndRevision() != SVNRevision.UNDEFINED) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_REVISION_RANGE); SVNErrorManager.error(err); } if (!myIsDescend) { if (getCommand() instanceof SVNStatusCommand) { myDepth = SVNDepth.IMMEDIATES; } else { myDepth = SVNDepth.fromRecurse(myIsDescend); } } } public boolean isReIntegrate() { return myIsReIntegrate; } public String getFromSource() { return myFromSource; } public boolean isChangeOptionUsed() { return myIsChangeOptionUsed; } public String getChangelist() { return myChangelist; } public String[] getChangelists() { if (myChangelists != null && !myChangelists.isEmpty()) { return (String[]) myChangelists.toArray(new String[myChangelists.size()]); } return null; } public Collection getChangelistsCollection() { return myChangelists; } public SVNDepth getDepth() { return myDepth; } public SVNDepth getSetDepth() { return mySetDepth; } public boolean isVerbose() { return myIsVerbose; } public boolean isNoIgnore() { return myIsNoIgnore; } public boolean isUpdate() { return myIsUpdate; } public boolean isQuiet() { return myIsQuiet; } public boolean isIncremental() { return myIsIncremental; } public boolean isRevprop() { return myIsRevprop; } public boolean isStrict() { return myIsStrict; } public List getRevisionRanges() { return myRevisionRanges; } public SVNRevision getStartRevision() { return myStartRevision; } public SVNRevision getEndRevision() { return myEndRevision; } public boolean isXML() { return myIsXML; } public boolean isVersion() { return myIsVersion; } public boolean isForce() { return myIsForce; } public String getEncoding() { return myEncoding; } public byte[] getFileData() { return myFileData; } public List getTargets() { return myTargets; } public boolean isForceLog() { return myIsForceLog; } public String getEditorCommand() { return myEditorCommand; } public String getMessage() { return myMessage; } public SVNProperties getRevisionProperties() { return myRevisionProperties; } public boolean isDryRun() { return myIsDryRun; } public boolean isIgnoreAncestry() { return myIsIgnoreAncestry; } public boolean isUseMergeHistory() { return myIsUseMergeHistory; } public boolean isRecordOnly() { return myIsRecordOnly; } public Collection getExtensions() { return myExtensions; } public String getNativeEOL() { return myNativeEOL; } public boolean isRelocate() { return myIsRelocate; } public boolean isNoUnlock() { return myIsNoUnlock; } public boolean isKeepChangelist() { return myIsKeepChangelist; } public boolean isParents() { return myIsParents; } public boolean isKeepLocal() { return myIsKeepLocal; } public SVNConflictAcceptPolicy getResolveAccept() { return myResolveAccept; } public boolean isRemove() { return myIsRemove; } public boolean isSummarize() { return myIsSummarize; } public boolean isNoticeAncestry() { return myIsNoticeAncestry; } public boolean isNoDiffDeleted() { return myIsNoDiffDeleted; } public String getOldTarget() { return myOldTarget; } public String getNewTarget() { return myNewTarget; } public long getLimit() { return myLimit; } public boolean isStopOnCopy() { return myIsStopOnCopy; } public boolean isAllRevisionProperties() { return myIsWithAllRevprops; } public SVNDiffOptions getDiffOptions() throws SVNException { LinkedList extensions = new LinkedList(myExtensions); boolean ignoreAllWS = myExtensions.contains("-w") || myExtensions.contains("--ignore-all-space"); if (ignoreAllWS) { extensions.remove("-w"); extensions.remove("--ignore-all-space"); } boolean ignoreAmountOfWS = myExtensions.contains("-b") || myExtensions.contains("--ignore-space-change"); if (ignoreAmountOfWS) { extensions.remove("-b"); extensions.remove("--ignore-space-change"); } boolean ignoreEOLStyle = myExtensions.contains("--ignore-eol-style"); if (ignoreEOLStyle) { extensions.remove("--ignore-eol-style"); } if (!extensions.isEmpty()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.INVALID_DIFF_OPTION, "Invalid argument ''{0}'' in diff options", extensions.get(0)); SVNErrorManager.error(err); } return new SVNDiffOptions(ignoreAllWS, ignoreAmountOfWS, ignoreEOLStyle); } public SVNProperties getRevisionProperties(String message, SVNCommitItem[] commitables, SVNProperties revisionProperties) throws SVNException { return revisionProperties == null ? new SVNProperties() : revisionProperties; } public String getCommitMessage(String message, SVNCommitItem[] commitables) throws SVNException { if (getFileData() != null) { byte[] data = getFileData(); for (int i = 0; i < data.length; i++) { if (data[i] == 0) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_BAD_LOG_MESSAGE, "Log message contains a zero byte")); } } try { return new String(getFileData(), getEncoding() != null ? getEncoding() : "UTF-8"); } catch (UnsupportedEncodingException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e.getMessage())); } } else if (getMessage() != null) { return getMessage(); } if (commitables == null || commitables.length == 0) { return ""; } // invoke editor (if non-interactive). if (myIsNonInteractive) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Cannot invoke editor to get log message when non-interactive"); SVNErrorManager.error(err); } message = null; while(message == null) { message = createCommitMessageTemplate(commitables); byte[] messageData = null; try { try { messageData = message.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { messageData = message.getBytes(); } messageData = SVNCommandUtil.runEditor(this, getEditorCommand(), messageData, "svn-commit"); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() == SVNErrorCode.CL_NO_EXTERNAL_EDITOR) { SVNErrorMessage err = e.getErrorMessage().wrap( "Could not use external editor to fetch log message; " + "consider setting the $SVN_EDITOR environment variable " + "or using the --message (-m) or --file (-F) options"); SVNErrorManager.error(err); } throw e; } if (messageData != null) { String editedMessage = null; try { editedMessage = getEncoding() != null ? new String(messageData, getEncoding()) : new String(messageData); } catch (UnsupportedEncodingException e) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e.getMessage()); SVNErrorManager.error(err); } if (editedMessage.indexOf(DEFAULT_LOG_MESSAGE_HEADER) >= 0) { editedMessage = editedMessage.substring(0, editedMessage.indexOf(DEFAULT_LOG_MESSAGE_HEADER)); } if (!"a".equals(editedMessage.trim())) { return editedMessage; } } message = null; getOut().println("\nLog message unchanged or not specified\n" + "a)bort, c)ontinue, e)dit"); try { char c = (char) getIn().read(); if (c == 'a') { SVNErrorManager.cancel(""); } else if (c == 'c') { return ""; } else if (c == 'e') { continue; } } catch (IOException e) { } } SVNErrorManager.cancel(""); return null; } private void parseRevisionProperty(SVNOptionValue optionValue) throws SVNException { if (myRevisionProperties == null) { myRevisionProperties = new SVNProperties(); } String revProp = optionValue.getValue(); if (revProp == null || "".equals(revProp)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Revision property pair is empty"); SVNErrorManager.error(err); } int index = revProp.indexOf('='); String revPropName = null; String revPropValue = null; if (index >= 0) { revPropName = revProp.substring(0, index); revPropValue = revProp.substring(index + 1); } else { revPropName = revProp; revPropValue = ""; } if (!SVNPropertiesManager.isValidPropertyName(revPropName)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_PROPERTY_NAME, "''{0}'' is not a valid Subversion property name", revPropName); SVNErrorManager.error(err); } myRevisionProperties.put(revPropName, revPropValue); } private String createCommitMessageTemplate(SVNCommitItem[] items) { StringBuffer buffer = new StringBuffer(); buffer.append(System.getProperty("line.separator")); buffer.append(DEFAULT_LOG_MESSAGE_HEADER); buffer.append(System.getProperty("line.separator")); buffer.append(System.getProperty("line.separator")); for (int i = 0; i < items.length; i++) { SVNCommitItem item = items[i]; String path = item.getPath() != null ? item.getPath() : item.getURL().toString(); if ("".equals(path) || path == null) { path = "."; } if (item.isDeleted() && item.isAdded()) { buffer.append('R'); } else if (item.isDeleted()) { buffer.append('D'); } else if (item.isAdded()) { buffer.append('A'); } else if (item.isContentsModified()) { buffer.append('M'); } else { buffer.append('_'); } if (item.isPropertiesModified()) { buffer.append('M'); } else { buffer.append(' '); } if (!myIsNoUnlock && item.isLocked()) { buffer.append('L'); } else { buffer.append(' '); } if (item.isCopied()) { buffer.append("+ "); } else { buffer.append(" "); } buffer.append(path); buffer.append(System.getProperty("line.separator")); } return buffer.toString(); } }
true
true
protected void initOption(SVNOptionValue optionValue) throws SVNException { AbstractSVNOption option = optionValue.getOption(); if (option == SVNOption.LIMIT) { String limitStr = optionValue.getValue(); try { long limit = Long.parseLong(limitStr); if (limit <= 0) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.INCORRECT_PARAMS, "Argument to --limit must be positive"); SVNErrorManager.error(err); } myLimit = limit; } catch (NumberFormatException nfe) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Non-numeric limit argument given"); SVNErrorManager.error(err); } } else if (option == SVNOption.MESSAGE) { myMessage = optionValue.getValue(); } else if (option == SVNOption.CHANGE) { if (myOldTarget != null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Can't specify -c with --old"); SVNErrorManager.error(err); } String chValue = optionValue.getValue(); long change = 0; try { change = Long.parseLong(chValue); } catch (NumberFormatException nfe) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Non-numeric change argument given to -c"); SVNErrorManager.error(err); } SVNRevisionRange range = null; if (change == 0) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "There is no change 0"); SVNErrorManager.error(err); } else if (change > 0) { range = new SVNRevisionRange(SVNRevision.create(change - 1), SVNRevision.create(change)); } else { change = -change; range = new SVNRevisionRange(SVNRevision.create(change), SVNRevision.create(change - 1)); } myRevisionRanges.add(range); myIsChangeOptionUsed = true; } else if (option == SVNOption.REVISION) { String revStr = optionValue.getValue(); SVNRevision[] revisions = parseRevision(revStr); if (revisions == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Syntax error in revision argument ''{0}''", revStr); SVNErrorManager.error(err); } SVNRevisionRange range = new SVNRevisionRange(revisions[0], revisions[1]); myRevisionRanges.add(range); } else if (option == SVNOption.VERBOSE) { myIsVerbose = true; } else if (option == SVNOption.UPDATE) { myIsUpdate = true; } else if (option == SVNOption.HELP || option == SVNOption.QUESTION) { myIsHelp = true; } else if (option == SVNOption.QUIET) { myIsQuiet = true; } else if (option == SVNOption.INCREMENTAL) { myIsIncremental = true; } else if (option == SVNOption.FILE) { String fileName = optionValue.getValue(); myFilePath = fileName; myFileData = readFromFile(new File(fileName)); } else if (option == SVNOption.TARGETS) { String fileName = optionValue.getValue(); byte[] data = readFromFile(new File(fileName)); try { String[] targets = new String(data, "UTF-8").split("\n\r"); myTargets = new LinkedList(); for (int i = 0; i < targets.length; i++) { if (targets[i].trim().length() > 0) { myTargets.add(targets[i].trim()); } } } catch (UnsupportedEncodingException e) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e.getMessage()); SVNErrorManager.error(err); } } else if (option == SVNOption.FORCE) { myIsForce = true; } else if (option == SVNOption.FORCE_LOG) { myIsForceLog = true; } else if (option == SVNOption.DRY_RUN) { myIsDryRun = true; } else if (option == SVNOption.REVPROP) { myIsRevprop = true; } else if (option == SVNOption.RECURSIVE) { myDepth = SVNDepth.fromRecurse(true); } else if (option == SVNOption.NON_RECURSIVE) { myIsDescend = false; } else if (option == SVNOption.DEPTH) { String depth = optionValue.getValue(); if (SVNDepth.EMPTY.getName().equals(depth)) { myDepth = SVNDepth.EMPTY; } else if (SVNDepth.FILES.getName().equals(depth)) { myDepth = SVNDepth.FILES; } else if (SVNDepth.IMMEDIATES.getName().equals(depth)) { myDepth = SVNDepth.IMMEDIATES; } else if (SVNDepth.INFINITY.getName().equals(depth)) { myDepth = SVNDepth.INFINITY; } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "''{0}'' is not a valid depth; try ''empty'', ''files'', ''immediates'', or ''infinit''", depth); SVNErrorManager.error(err); } } else if (option == SVNOption.SET_DEPTH) { String depth = optionValue.getValue(); if (SVNDepth.EMPTY.getName().equals(depth)) { mySetDepth = SVNDepth.EMPTY; } else if (SVNDepth.FILES.getName().equals(depth)) { mySetDepth = SVNDepth.FILES; } else if (SVNDepth.IMMEDIATES.getName().equals(depth)) { mySetDepth = SVNDepth.IMMEDIATES; } else if (SVNDepth.INFINITY.getName().equals(depth)) { mySetDepth = SVNDepth.INFINITY; } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "''{0}'' is not a valid depth; try ''empty'', ''files'', ''immediates'', or ''infinit''", depth); SVNErrorManager.error(err); } } else if (option == SVNOption.VERSION) { myIsVersion = true; } else if (option == SVNOption.USERNAME) { myUserName = optionValue.getValue(); } else if (option == SVNOption.PASSWORD) { myPassword = optionValue.getValue(); } else if (option == SVNOption.ENCODING) { myEncoding = optionValue.getValue(); } else if (option == SVNOption.XML) { myIsXML = true; } else if (option == SVNOption.STOP_ON_COPY) { myIsStopOnCopy = true; } else if (option == SVNOption.STRICT) { myIsStrict = true; } else if (option == SVNOption.NO_AUTH_CACHE) { myIsNoAuthCache = true; } else if (option == SVNOption.NON_INTERACTIVE) { myIsNonInteractive = true; } else if (option == SVNOption.NO_DIFF_DELETED) { myIsNoDiffDeleted = true; } else if (option == SVNOption.NOTICE_ANCESTRY) { myIsNoticeAncestry = true; } else if (option == SVNOption.IGNORE_ANCESTRY) { myIsIgnoreAncestry = true; } else if (option == SVNOption.IGNORE_EXTERNALS) { myIsIgnoreExternals = true; } else if (option == SVNOption.RELOCATE) { if (myDepth != SVNDepth.UNKNOWN) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS, "--depth and --relocate are mutually exclusive")); } myIsRelocate = true; } else if (option == SVNOption.EXTENSIONS) { myExtensions.add(optionValue.getValue()); } else if (option == SVNOption.RECORD_ONLY) { myIsRecordOnly = true; } else if (option == SVNOption.EDITOR_CMD) { myEditorCommand = optionValue.getValue(); } else if (option == SVNOption.OLD) { if (myIsChangeOptionUsed) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Can't specify -c with --old")); } myOldTarget = optionValue.getValue(); } else if (option == SVNOption.NEW) { myNewTarget = optionValue.getValue(); } else if (option == SVNOption.CONFIG_DIR) { myConfigDir = optionValue.getValue(); } else if (option == SVNOption.AUTOPROPS) { if (myIsNoAutoProps) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS, "--auto-props and --no-auto-props are mutually exclusive")); } myIsAutoProps = true; } else if (option == SVNOption.NO_AUTOPROPS) { if (myIsAutoProps) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS, "--auto-props and --no-auto-props are mutually exclusive")); } myIsNoAutoProps = true; } else if (option == SVNOption.NATIVE_EOL) { myNativeEOL = optionValue.getValue(); } else if (option == SVNOption.NO_UNLOCK) { myIsNoUnlock = true; } else if (option == SVNOption.SUMMARIZE) { myIsSummarize = true; } else if (option == SVNOption.REMOVE) { myIsRemove = true; } else if (option == SVNOption.CHANGELIST) { myChangelist = optionValue.getValue(); myChangelists.add(myChangelist); } else if (option == SVNOption.KEEP_CHANGELIST) { myIsKeepChangelist = true; } else if (option == SVNOption.KEEP_LOCAL) { myIsKeepLocal = true; } else if (option == SVNOption.NO_IGNORE) { myIsNoIgnore = true; } else if (option == SVNOption.WITH_ALL_REVPROPS) { myIsWithAllRevprops = true; } else if (option == SVNOption.WITH_REVPROP) { parseRevisionProperty(optionValue); } else if (option == SVNOption.PARENTS) { myIsParents = true; } else if (option == SVNOption.USE_MERGE_HISTORY) { myIsUseMergeHistory = true; } else if (option == SVNOption.ACCEPT) { SVNConflictAcceptPolicy accept = SVNConflictAcceptPolicy.fromString(optionValue.getValue()); if (accept == SVNConflictAcceptPolicy.INVALID) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "'" + optionValue.getValue() + "' is not a valid accept value;"); SVNErrorManager.error(err); } myResolveAccept = accept; } else if (option == SVNOption.FROM_SOURCE) { myFromSource = optionValue.getValue(); } else if (option == SVNOption.REINTEGRATE) { myIsReIntegrate = true; } }
protected void initOption(SVNOptionValue optionValue) throws SVNException { AbstractSVNOption option = optionValue.getOption(); if (option == SVNOption.LIMIT) { String limitStr = optionValue.getValue(); try { long limit = Long.parseLong(limitStr); if (limit <= 0) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.INCORRECT_PARAMS, "Argument to --limit must be positive"); SVNErrorManager.error(err); } myLimit = limit; } catch (NumberFormatException nfe) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Non-numeric limit argument given"); SVNErrorManager.error(err); } } else if (option == SVNOption.MESSAGE) { myMessage = optionValue.getValue(); } else if (option == SVNOption.CHANGE) { if (myOldTarget != null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Can't specify -c with --old"); SVNErrorManager.error(err); } String chValue = optionValue.getValue(); long change = 0; try { change = Long.parseLong(chValue); } catch (NumberFormatException nfe) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Non-numeric change argument given to -c"); SVNErrorManager.error(err); } SVNRevisionRange range = null; if (change == 0) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "There is no change 0"); SVNErrorManager.error(err); } else if (change > 0) { range = new SVNRevisionRange(SVNRevision.create(change - 1), SVNRevision.create(change)); } else { change = -change; range = new SVNRevisionRange(SVNRevision.create(change), SVNRevision.create(change - 1)); } myRevisionRanges.add(range); myIsChangeOptionUsed = true; } else if (option == SVNOption.REVISION) { String revStr = optionValue.getValue(); SVNRevision[] revisions = parseRevision(revStr); if (revisions == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Syntax error in revision argument ''{0}''", revStr); SVNErrorManager.error(err); } SVNRevisionRange range = new SVNRevisionRange(revisions[0], revisions[1]); myRevisionRanges.add(range); } else if (option == SVNOption.VERBOSE) { myIsVerbose = true; } else if (option == SVNOption.UPDATE) { myIsUpdate = true; } else if (option == SVNOption.HELP || option == SVNOption.QUESTION) { myIsHelp = true; } else if (option == SVNOption.QUIET) { myIsQuiet = true; } else if (option == SVNOption.INCREMENTAL) { myIsIncremental = true; } else if (option == SVNOption.FILE) { String fileName = optionValue.getValue(); myFilePath = fileName; myFileData = readFromFile(new File(fileName)); } else if (option == SVNOption.TARGETS) { String fileName = optionValue.getValue(); byte[] data = readFromFile(new File(fileName)); try { String[] targets = new String(data, "UTF-8").split("\n\r"); myTargets = new LinkedList(); for (int i = 0; i < targets.length; i++) { if (targets[i].trim().length() > 0) { myTargets.add(targets[i].trim()); } } } catch (UnsupportedEncodingException e) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e.getMessage()); SVNErrorManager.error(err); } } else if (option == SVNOption.FORCE) { myIsForce = true; } else if (option == SVNOption.FORCE_LOG) { myIsForceLog = true; } else if (option == SVNOption.DRY_RUN) { myIsDryRun = true; } else if (option == SVNOption.REVPROP) { myIsRevprop = true; } else if (option == SVNOption.RECURSIVE) { myDepth = SVNDepth.fromRecurse(true); } else if (option == SVNOption.NON_RECURSIVE) { myIsDescend = false; } else if (option == SVNOption.DEPTH) { String depth = optionValue.getValue(); if (SVNDepth.EMPTY.getName().equals(depth)) { myDepth = SVNDepth.EMPTY; } else if (SVNDepth.FILES.getName().equals(depth)) { myDepth = SVNDepth.FILES; } else if (SVNDepth.IMMEDIATES.getName().equals(depth)) { myDepth = SVNDepth.IMMEDIATES; } else if (SVNDepth.INFINITY.getName().equals(depth)) { myDepth = SVNDepth.INFINITY; } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "''{0}'' is not a valid depth; try ''empty'', ''files'', ''immediates'', or ''infinit''", depth); SVNErrorManager.error(err); } } else if (option == SVNOption.SET_DEPTH) { String depth = optionValue.getValue(); if (SVNDepth.EMPTY.getName().equals(depth)) { mySetDepth = SVNDepth.EMPTY; } else if (SVNDepth.FILES.getName().equals(depth)) { mySetDepth = SVNDepth.FILES; } else if (SVNDepth.IMMEDIATES.getName().equals(depth)) { mySetDepth = SVNDepth.IMMEDIATES; } else if (SVNDepth.INFINITY.getName().equals(depth)) { mySetDepth = SVNDepth.INFINITY; } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "''{0}'' is not a valid depth; try ''empty'', ''files'', ''immediates'', or ''infinit''", depth); SVNErrorManager.error(err); } } else if (option == SVNOption.VERSION) { myIsVersion = true; } else if (option == SVNOption.USERNAME) { myUserName = optionValue.getValue(); } else if (option == SVNOption.PASSWORD) { myPassword = optionValue.getValue(); } else if (option == SVNOption.ENCODING) { myEncoding = optionValue.getValue(); } else if (option == SVNOption.XML) { myIsXML = true; } else if (option == SVNOption.STOP_ON_COPY) { myIsStopOnCopy = true; } else if (option == SVNOption.STRICT) { myIsStrict = true; } else if (option == SVNOption.NO_AUTH_CACHE) { myIsNoAuthCache = true; } else if (option == SVNOption.NON_INTERACTIVE) { myIsNonInteractive = true; } else if (option == SVNOption.NO_DIFF_DELETED) { myIsNoDiffDeleted = true; } else if (option == SVNOption.NOTICE_ANCESTRY) { myIsNoticeAncestry = true; } else if (option == SVNOption.IGNORE_ANCESTRY) { myIsIgnoreAncestry = true; } else if (option == SVNOption.IGNORE_EXTERNALS) { myIsIgnoreExternals = true; } else if (option == SVNOption.RELOCATE) { if (myDepth != SVNDepth.UNKNOWN) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS, "--depth and --relocate are mutually exclusive")); } myIsRelocate = true; } else if (option == SVNOption.EXTENSIONS) { myExtensions.add(optionValue.getValue()); } else if (option == SVNOption.RECORD_ONLY) { myIsRecordOnly = true; } else if (option == SVNOption.EDITOR_CMD) { myEditorCommand = optionValue.getValue(); } else if (option == SVNOption.OLD) { if (myIsChangeOptionUsed) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Can't specify -c with --old")); } myOldTarget = optionValue.getValue(); } else if (option == SVNOption.NEW) { myNewTarget = optionValue.getValue(); } else if (option == SVNOption.CONFIG_DIR) { myConfigDir = optionValue.getValue(); } else if (option == SVNOption.AUTOPROPS) { if (myIsNoAutoProps) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS, "--auto-props and --no-auto-props are mutually exclusive")); } myIsAutoProps = true; } else if (option == SVNOption.NO_AUTOPROPS) { if (myIsAutoProps) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS, "--auto-props and --no-auto-props are mutually exclusive")); } myIsNoAutoProps = true; } else if (option == SVNOption.NATIVE_EOL) { myNativeEOL = optionValue.getValue(); } else if (option == SVNOption.NO_UNLOCK) { myIsNoUnlock = true; } else if (option == SVNOption.SUMMARIZE) { myIsSummarize = true; } else if (option == SVNOption.REMOVE) { myIsRemove = true; } else if (option == SVNOption.CHANGELIST) { myChangelist = optionValue.getValue(); myChangelists.add(myChangelist); } else if (option == SVNOption.KEEP_CHANGELIST) { myIsKeepChangelist = true; } else if (option == SVNOption.KEEP_LOCAL) { myIsKeepLocal = true; } else if (option == SVNOption.NO_IGNORE) { myIsNoIgnore = true; } else if (option == SVNOption.WITH_ALL_REVPROPS) { myIsWithAllRevprops = true; } else if (option == SVNOption.WITH_REVPROP) { parseRevisionProperty(optionValue); } else if (option == SVNOption.PARENTS) { myIsParents = true; } else if (option == SVNOption.USE_MERGE_HISTORY) { myIsUseMergeHistory = true; } else if (option == SVNOption.ACCEPT) { SVNConflictAcceptPolicy accept = SVNConflictAcceptPolicy.fromString(optionValue.getValue()); if (accept == SVNConflictAcceptPolicy.INVALID) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "'" + optionValue.getValue() + "' is not a valid --accept value;"); SVNErrorManager.error(err); } myResolveAccept = accept; } else if (option == SVNOption.FROM_SOURCE) { myFromSource = optionValue.getValue(); } else if (option == SVNOption.REINTEGRATE) { myIsReIntegrate = true; } }
diff --git a/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/reflect/ClassPropertyFetcher.java b/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/reflect/ClassPropertyFetcher.java index b6124819..2b0883bd 100644 --- a/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/reflect/ClassPropertyFetcher.java +++ b/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/reflect/ClassPropertyFetcher.java @@ -1,372 +1,373 @@ /* 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.grails.datastore.mapping.reflect; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Reads the properties of a class in an optimized manner avoiding exceptions. * * @author Graeme Rocher * @since 1.0 */ @SuppressWarnings("rawtypes") public class ClassPropertyFetcher { private static final Logger LOG = LoggerFactory.getLogger(ClassPropertyFetcher.class); private final Class clazz; final Map<String, PropertyFetcher> staticFetchers = new HashMap<String, PropertyFetcher>(); final Map<String, PropertyFetcher> instanceFetchers = new HashMap<String, PropertyFetcher>(); private final ReferenceInstanceCallback callback; private PropertyDescriptor[] propertyDescriptors; private Map<String, PropertyDescriptor> propertyDescriptorsByName = new HashMap<String, PropertyDescriptor>(); private Map<String, Field> fieldsByName = new HashMap<String, Field>(); private Map<Class, List<PropertyDescriptor>> typeToPropertyMap = new HashMap<Class, List<PropertyDescriptor>>(); private static Map<Class, ClassPropertyFetcher> cachedClassPropertyFetchers = new WeakHashMap<Class, ClassPropertyFetcher>(); public static ClassPropertyFetcher forClass(final Class c) { ClassPropertyFetcher cpf = cachedClassPropertyFetchers.get(c); if (cpf == null) { cpf = new ClassPropertyFetcher(c); cachedClassPropertyFetchers.put(c, cpf); } return cpf; } public static void clearCache() { cachedClassPropertyFetchers.clear(); } ClassPropertyFetcher(final Class clazz) { this.clazz = clazz; this.callback = new ReferenceInstanceCallback() { public Object getReferenceInstance() { return ReflectionUtils.instantiate(clazz); } }; init(); } /** * @return The Java that this ClassPropertyFetcher was constructor for */ public Class getJavaClass() { return clazz; } public Object getReference() { return callback == null ? null : callback.getReferenceInstance(); } public PropertyDescriptor[] getPropertyDescriptors() { return propertyDescriptors; } public boolean isReadableProperty(String name) { return staticFetchers.containsKey(name) || instanceFetchers.containsKey(name); } private void init() { List<Class> allClasses = resolveAllClasses(clazz); for (Class c : allClasses) { Field[] fields = c.getDeclaredFields(); for (Field field : fields) { processField(field); } Method[] methods = c.getDeclaredMethods(); for (Method method : methods) { processMethod(method); } } try { propertyDescriptors = Introspector.getBeanInfo(clazz).getPropertyDescriptors(); } catch (IntrospectionException e) { // ignore } if (propertyDescriptors == null) { return; } for (PropertyDescriptor desc : propertyDescriptors) { propertyDescriptorsByName.put(desc.getName(),desc); final Class<?> propertyType = desc.getPropertyType(); + if(propertyType == null) continue; List<PropertyDescriptor> pds = typeToPropertyMap.get(propertyType); if (pds == null) { pds = new ArrayList<PropertyDescriptor>(); typeToPropertyMap.put(propertyType, pds); } pds.add(desc); Method readMethod = desc.getReadMethod(); if (readMethod != null) { boolean staticReadMethod = Modifier.isStatic(readMethod.getModifiers()); if (staticReadMethod) { staticFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod)); } else { instanceFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod)); } } } } private void processMethod(Method method) { if (method.isSynthetic()) { return; } if (!Modifier.isPublic(method.getModifiers())) { return; } if (Modifier.isStatic(method.getModifiers()) && method.getReturnType() != Void.class) { if (method.getParameterTypes().length == 0) { String name = method.getName(); if (name.indexOf('$') == -1) { if (name.length() > 3 && name.startsWith("get") && Character.isUpperCase(name.charAt(3))) { name = name.substring(3); } else if (name.length() > 2 && name.startsWith("is") && Character.isUpperCase(name.charAt(2)) && (method.getReturnType() == Boolean.class || method.getReturnType() == boolean.class)) { name = name.substring(2); } PropertyFetcher fetcher = new GetterPropertyFetcher(method, true); staticFetchers.put(name, fetcher); staticFetchers.put(Introspector.decapitalize(name), fetcher); } } } } private void processField(Field field) { if (field.isSynthetic()) { return; } final int modifiers = field.getModifiers(); final String name = field.getName(); if (!Modifier.isPublic(modifiers)) { if (name.indexOf('$') == -1) { fieldsByName.put(name, field); } } else { if (name.indexOf('$') == -1) { boolean staticField = Modifier.isStatic(modifiers); if (staticField) { staticFetchers.put(name, new FieldReaderFetcher(field, staticField)); } else { instanceFetchers.put(name, new FieldReaderFetcher(field, staticField)); } } } } private List<Class> resolveAllClasses(Class c) { List<Class> list = new ArrayList<Class>(); Class currentClass = c; while (currentClass != null) { list.add(currentClass); currentClass = currentClass.getSuperclass(); } Collections.reverse(list); return list; } public Object getPropertyValue(String name) { return getPropertyValue(name, false); } public Object getPropertyValue(String name, boolean onlyInstanceProperties) { PropertyFetcher fetcher = resolveFetcher(name, onlyInstanceProperties); return getPropertyValueWithFetcher(name, fetcher); } private Object getPropertyValueWithFetcher(String name, PropertyFetcher fetcher) { if (fetcher != null) { try { return fetcher.get(callback); } catch (Exception e) { LOG.warn("Error fetching property's " + name + " value from class " + clazz.getName(), e); } } return null; } public <T> T getStaticPropertyValue(String name, Class<T> c) { PropertyFetcher fetcher = staticFetchers.get(name); if (fetcher == null) { return null; } Object v = getPropertyValueWithFetcher(name, fetcher); return returnOnlyIfInstanceOf(v, c); } public <T> T getPropertyValue(String name, Class<T> c) { return returnOnlyIfInstanceOf(getPropertyValue(name, false), c); } @SuppressWarnings("unchecked") private <T> T returnOnlyIfInstanceOf(Object value, Class<T> type) { if (value != null && (type == Object.class || ReflectionUtils.isAssignableFrom(type, value.getClass()))) { return (T)value; } return null; } private PropertyFetcher resolveFetcher(String name, boolean onlyInstanceProperties) { PropertyFetcher fetcher = null; if (!onlyInstanceProperties) { fetcher = staticFetchers.get(name); } if (fetcher == null) { fetcher = instanceFetchers.get(name); } return fetcher; } public Class getPropertyType(String name) { return getPropertyType(name, false); } public Class getPropertyType(String name, boolean onlyInstanceProperties) { PropertyFetcher fetcher = resolveFetcher(name, onlyInstanceProperties); return fetcher == null ? null : fetcher.getPropertyType(name); } public PropertyDescriptor getPropertyDescriptor(String name) { return propertyDescriptorsByName.get(name); } public List<PropertyDescriptor> getPropertiesOfType(Class javaClass) { final List<PropertyDescriptor> propertyDescriptorList = typeToPropertyMap.get(javaClass); if (propertyDescriptorList == null) return Collections.emptyList(); return propertyDescriptorList; } @SuppressWarnings("unchecked") public List<PropertyDescriptor> getPropertiesAssignableToType(Class assignableType) { List<PropertyDescriptor> properties = new ArrayList<PropertyDescriptor>(); for (Class type : typeToPropertyMap.keySet()) { if (assignableType.isAssignableFrom(type)) { properties.addAll(typeToPropertyMap.get(type)); } } return properties; } @SuppressWarnings("unchecked") public List<PropertyDescriptor> getPropertiesAssignableFromType(Class assignableType) { List<PropertyDescriptor> properties = new ArrayList<PropertyDescriptor>(); for (Class type : typeToPropertyMap.keySet()) { if (type.isAssignableFrom( assignableType )) { properties.addAll(typeToPropertyMap.get(type)); } } return properties; } public static interface ReferenceInstanceCallback { Object getReferenceInstance(); } static interface PropertyFetcher { Object get(ReferenceInstanceCallback callback) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException; Class getPropertyType(String name); } static class GetterPropertyFetcher implements PropertyFetcher { private final Method readMethod; private final boolean staticMethod; GetterPropertyFetcher(Method readMethod, boolean staticMethod) { this.readMethod = readMethod; this.staticMethod = staticMethod; ReflectionUtils.makeAccessible(readMethod); } public Object get(ReferenceInstanceCallback callback) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { if (staticMethod) { return readMethod.invoke(null, (Object[]) null); } if (callback != null) { return readMethod.invoke(callback.getReferenceInstance(), (Object[]) null); } return null; } public Class getPropertyType(String name) { return readMethod.getReturnType(); } } static class FieldReaderFetcher implements PropertyFetcher { private final Field field; private final boolean staticField; public FieldReaderFetcher(Field field, boolean staticField) { this.field = field; this.staticField = staticField; ReflectionUtils.makeAccessible(field); } public Object get(ReferenceInstanceCallback callback) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { if (staticField) { return field.get(null); } if (callback != null) { return field.get(callback.getReferenceInstance()); } return null; } public Class getPropertyType(String name) { return field.getType(); } } public Field getDeclaredField(String name) { return fieldsByName.get(name); } }
true
true
private void init() { List<Class> allClasses = resolveAllClasses(clazz); for (Class c : allClasses) { Field[] fields = c.getDeclaredFields(); for (Field field : fields) { processField(field); } Method[] methods = c.getDeclaredMethods(); for (Method method : methods) { processMethod(method); } } try { propertyDescriptors = Introspector.getBeanInfo(clazz).getPropertyDescriptors(); } catch (IntrospectionException e) { // ignore } if (propertyDescriptors == null) { return; } for (PropertyDescriptor desc : propertyDescriptors) { propertyDescriptorsByName.put(desc.getName(),desc); final Class<?> propertyType = desc.getPropertyType(); List<PropertyDescriptor> pds = typeToPropertyMap.get(propertyType); if (pds == null) { pds = new ArrayList<PropertyDescriptor>(); typeToPropertyMap.put(propertyType, pds); } pds.add(desc); Method readMethod = desc.getReadMethod(); if (readMethod != null) { boolean staticReadMethod = Modifier.isStatic(readMethod.getModifiers()); if (staticReadMethod) { staticFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod)); } else { instanceFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod)); } } } }
private void init() { List<Class> allClasses = resolveAllClasses(clazz); for (Class c : allClasses) { Field[] fields = c.getDeclaredFields(); for (Field field : fields) { processField(field); } Method[] methods = c.getDeclaredMethods(); for (Method method : methods) { processMethod(method); } } try { propertyDescriptors = Introspector.getBeanInfo(clazz).getPropertyDescriptors(); } catch (IntrospectionException e) { // ignore } if (propertyDescriptors == null) { return; } for (PropertyDescriptor desc : propertyDescriptors) { propertyDescriptorsByName.put(desc.getName(),desc); final Class<?> propertyType = desc.getPropertyType(); if(propertyType == null) continue; List<PropertyDescriptor> pds = typeToPropertyMap.get(propertyType); if (pds == null) { pds = new ArrayList<PropertyDescriptor>(); typeToPropertyMap.put(propertyType, pds); } pds.add(desc); Method readMethod = desc.getReadMethod(); if (readMethod != null) { boolean staticReadMethod = Modifier.isStatic(readMethod.getModifiers()); if (staticReadMethod) { staticFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod)); } else { instanceFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod)); } } } }
diff --git a/src/cz/muni/fi/pb138/log4jconverter/configuration/Logger.java b/src/cz/muni/fi/pb138/log4jconverter/configuration/Logger.java index 6737261..31c0179 100644 --- a/src/cz/muni/fi/pb138/log4jconverter/configuration/Logger.java +++ b/src/cz/muni/fi/pb138/log4jconverter/configuration/Logger.java @@ -1,187 +1,187 @@ package cz.muni.fi.pb138.log4jconverter.configuration; import cz.muni.fi.pb138.log4jconverter.PropertiesParser; import java.util.*; import java.util.Map.Entry; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * * @author Admin */ public class Logger { //required private String name; //implies private String className; //podle dtd je deafulat hodnota true private boolean additivity = true; //optional private HashMap<String, String> params; private HashSet<String> appenderRefs; private Level level; /* * Category is deprecated synonym of Logger, this boolean keeps information * about actual name of Logger. */ private boolean isCategory = false; public Logger() { this.params = new HashMap<String, String>(); this.appenderRefs = new LinkedHashSet<String>(); } public void isCategory(boolean b) { isCategory = b; } public boolean isAdditivity() { return additivity; } public void setAdditivity(boolean additivity) { this.additivity = additivity; } public void addAppenderRef(String appenderName) { appenderRefs.add(appenderName); } public HashSet<String> getAppenderRefs() { return appenderRefs; } public void setAppenderRefs(HashSet<String> appenderRefs) { this.appenderRefs = appenderRefs; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public HashMap<String, String> getParams() { return params; } public void setParams(HashMap<String, String> params) { this.params = params; } public void addParam(String key, String value) { params.put(key, value); } public Level getLevel() { return level; } public void setLevel(Level level) { this.level = level; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Logger other = (Logger) obj; if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } return true; } @Override public int hashCode() { int hash = 3; hash = 97 * hash + (this.name != null ? this.name.hashCode() : 0); return hash; } public void generateProperties(Properties p) { // log4j.logger.logger_name String prefixKey = ( isCategory ? PropertiesParser.CATEGORY_PREFIX : PropertiesParser.LOGGER_PREFIX ) + name; StringBuilder value = new StringBuilder(); // level, appdenderRefs if (level != null) value.append(level.getValues()); for (String appenderRef : appenderRefs) { value.append(", "); value.append(appenderRef); } p.setProperty(prefixKey, value.toString()); // additivity if (!additivity) p.setProperty(PropertiesParser.ADDITIVITY_PREFIX + name, "false"); } public void generateXML(Document doc, Element config) { Element logger; if (!isCategory) { logger = doc.createElement("logger"); } else { logger = doc.createElement("category"); } - logger.setAttribute("loggerName", name); + logger.setAttribute("name", name); if (className != null) { logger.setAttribute("class", className); } if (additivity) { logger.setAttribute("additivity", "true"); } else { logger.setAttribute("additivity", "false"); } if (!params.isEmpty()) { Iterator<Entry<String, String>> it = params.entrySet().iterator(); while (it.hasNext()) { Entry<String, String> e = it.next(); Element param = doc.createElement("param"); param.setAttribute("name", e.getKey()); param.setAttribute("value", e.getValue()); logger.appendChild(param); } } if (level != null) { level.generateXML(doc, logger); } for (String ref : appenderRefs) { Element apRef = doc.createElement("appender-ref"); apRef.setAttribute("ref", ref); logger.appendChild(apRef); } config.appendChild(logger); } }
true
true
public void generateXML(Document doc, Element config) { Element logger; if (!isCategory) { logger = doc.createElement("logger"); } else { logger = doc.createElement("category"); } logger.setAttribute("loggerName", name); if (className != null) { logger.setAttribute("class", className); } if (additivity) { logger.setAttribute("additivity", "true"); } else { logger.setAttribute("additivity", "false"); } if (!params.isEmpty()) { Iterator<Entry<String, String>> it = params.entrySet().iterator(); while (it.hasNext()) { Entry<String, String> e = it.next(); Element param = doc.createElement("param"); param.setAttribute("name", e.getKey()); param.setAttribute("value", e.getValue()); logger.appendChild(param); } } if (level != null) { level.generateXML(doc, logger); } for (String ref : appenderRefs) { Element apRef = doc.createElement("appender-ref"); apRef.setAttribute("ref", ref); logger.appendChild(apRef); } config.appendChild(logger); }
public void generateXML(Document doc, Element config) { Element logger; if (!isCategory) { logger = doc.createElement("logger"); } else { logger = doc.createElement("category"); } logger.setAttribute("name", name); if (className != null) { logger.setAttribute("class", className); } if (additivity) { logger.setAttribute("additivity", "true"); } else { logger.setAttribute("additivity", "false"); } if (!params.isEmpty()) { Iterator<Entry<String, String>> it = params.entrySet().iterator(); while (it.hasNext()) { Entry<String, String> e = it.next(); Element param = doc.createElement("param"); param.setAttribute("name", e.getKey()); param.setAttribute("value", e.getValue()); logger.appendChild(param); } } if (level != null) { level.generateXML(doc, logger); } for (String ref : appenderRefs) { Element apRef = doc.createElement("appender-ref"); apRef.setAttribute("ref", ref); logger.appendChild(apRef); } config.appendChild(logger); }
diff --git a/rmt/src/main/java/de/flower/rmt/ui/manager/page/players/PlayersPage.java b/rmt/src/main/java/de/flower/rmt/ui/manager/page/players/PlayersPage.java index 3efbc7c5..3ee35b95 100644 --- a/rmt/src/main/java/de/flower/rmt/ui/manager/page/players/PlayersPage.java +++ b/rmt/src/main/java/de/flower/rmt/ui/manager/page/players/PlayersPage.java @@ -1,93 +1,93 @@ package de.flower.rmt.ui.manager.page.players; import de.flower.common.ui.ajax.AjaxLinkWithConfirmation; import de.flower.common.ui.ajax.MyAjaxLink; import de.flower.common.ui.ajax.updatebehavior.AjaxRespondListener; import de.flower.common.ui.ajax.updatebehavior.AjaxUpdateBehavior; import de.flower.common.ui.ajax.updatebehavior.events.Event; import de.flower.rmt.model.Users; import de.flower.rmt.model.Users_; import de.flower.rmt.service.IUserManager; import de.flower.rmt.ui.common.page.ModalDialogWindow; import de.flower.rmt.ui.manager.ManagerBasePage; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; import org.apache.wicket.model.ResourceModel; import org.apache.wicket.spring.injection.annot.SpringBean; import java.util.List; /** * @author oblume */ public class PlayersPage extends ManagerBasePage { @SpringBean private IUserManager playerManager; public PlayersPage() { - final ModalDialogWindow modal = new ModalDialogWindow("playersDialog"); + final ModalDialogWindow modal = new ModalDialogWindow("playerDialog"); final PlayerEditPanel playerEditPanel = new PlayerEditPanel(modal.getContentId()); modal.setContent(playerEditPanel); add(modal); add(new MyAjaxLink("newButton") { @Override public void onClick(AjaxRequestTarget target) { - // show modal dialog with team edit form. + // show modal dialog with edit form. playerEditPanel.init(null); modal.show(target); } }); WebMarkupContainer playerListContainer = new WebMarkupContainer("playerListContainer"); add(playerListContainer); playerListContainer.add(new ListView<Users>("playerList", getPlayerListModel()) { @Override protected void populateItem(final ListItem<Users> item) { Users player = item.getModelObject(); item.add(new Label("fullname", player.getFullname())); item.add(new Label("email", player.getEmail())); Component manager; item.add(manager = new WebMarkupContainer("manager")); manager.setVisible(player.isManager()); item.add(new MyAjaxLink("editButton") { @Override public void onClick(AjaxRequestTarget target) { playerEditPanel.init(item.getModel()); modal.show(target); } }); item.add(new AjaxLinkWithConfirmation("deleteButton", new ResourceModel("manager.players.delete.confirm")) { @Override public void onClick(AjaxRequestTarget target) { playerManager.delete(item.getModelObject()); target.registerRespondListener(new AjaxRespondListener(Event.EntityDeleted(Users.class))); } }); } }); playerListContainer.add(new AjaxUpdateBehavior(Event.EntityAll(Users.class))); } private IModel<List<Users>> getPlayerListModel() { return new LoadableDetachableModel<List<Users>>() { @Override protected List<Users> load() { return playerManager.findAll(Users_.authorities); } }; } }
false
true
public PlayersPage() { final ModalDialogWindow modal = new ModalDialogWindow("playersDialog"); final PlayerEditPanel playerEditPanel = new PlayerEditPanel(modal.getContentId()); modal.setContent(playerEditPanel); add(modal); add(new MyAjaxLink("newButton") { @Override public void onClick(AjaxRequestTarget target) { // show modal dialog with team edit form. playerEditPanel.init(null); modal.show(target); } }); WebMarkupContainer playerListContainer = new WebMarkupContainer("playerListContainer"); add(playerListContainer); playerListContainer.add(new ListView<Users>("playerList", getPlayerListModel()) { @Override protected void populateItem(final ListItem<Users> item) { Users player = item.getModelObject(); item.add(new Label("fullname", player.getFullname())); item.add(new Label("email", player.getEmail())); Component manager; item.add(manager = new WebMarkupContainer("manager")); manager.setVisible(player.isManager()); item.add(new MyAjaxLink("editButton") { @Override public void onClick(AjaxRequestTarget target) { playerEditPanel.init(item.getModel()); modal.show(target); } }); item.add(new AjaxLinkWithConfirmation("deleteButton", new ResourceModel("manager.players.delete.confirm")) { @Override public void onClick(AjaxRequestTarget target) { playerManager.delete(item.getModelObject()); target.registerRespondListener(new AjaxRespondListener(Event.EntityDeleted(Users.class))); } }); } }); playerListContainer.add(new AjaxUpdateBehavior(Event.EntityAll(Users.class))); }
public PlayersPage() { final ModalDialogWindow modal = new ModalDialogWindow("playerDialog"); final PlayerEditPanel playerEditPanel = new PlayerEditPanel(modal.getContentId()); modal.setContent(playerEditPanel); add(modal); add(new MyAjaxLink("newButton") { @Override public void onClick(AjaxRequestTarget target) { // show modal dialog with edit form. playerEditPanel.init(null); modal.show(target); } }); WebMarkupContainer playerListContainer = new WebMarkupContainer("playerListContainer"); add(playerListContainer); playerListContainer.add(new ListView<Users>("playerList", getPlayerListModel()) { @Override protected void populateItem(final ListItem<Users> item) { Users player = item.getModelObject(); item.add(new Label("fullname", player.getFullname())); item.add(new Label("email", player.getEmail())); Component manager; item.add(manager = new WebMarkupContainer("manager")); manager.setVisible(player.isManager()); item.add(new MyAjaxLink("editButton") { @Override public void onClick(AjaxRequestTarget target) { playerEditPanel.init(item.getModel()); modal.show(target); } }); item.add(new AjaxLinkWithConfirmation("deleteButton", new ResourceModel("manager.players.delete.confirm")) { @Override public void onClick(AjaxRequestTarget target) { playerManager.delete(item.getModelObject()); target.registerRespondListener(new AjaxRespondListener(Event.EntityDeleted(Users.class))); } }); } }); playerListContainer.add(new AjaxUpdateBehavior(Event.EntityAll(Users.class))); }
diff --git a/com/buglabs/nmea2/NMEASentenceFactory.java b/com/buglabs/nmea2/NMEASentenceFactory.java index 9a3d136..55996b1 100644 --- a/com/buglabs/nmea2/NMEASentenceFactory.java +++ b/com/buglabs/nmea2/NMEASentenceFactory.java @@ -1,79 +1,79 @@ /******************************************************************************* * Copyright (c) 2008, 2009 Bug Labs, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of Bug Labs, Inc. nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ package com.buglabs.nmea2; import com.buglabs.nmea.sentences.NMEAParserException; /** * This factory will return a valid NMEA object based on a NMEA string, or null * if no match is available. * * @author kgilmer * */ public class NMEASentenceFactory { /** * An array of supported message types. */ public static final String[] SENTENCE_TYPES = { "$PTTK", "$GPGGA", "$GPRMC", "$GPGSV" }; /** * @param gpsData * @return A Concrete NMEA object or null if there is no match. * @throws NMEAParserException */ public static AbstractNMEASentence getSentence(String gpsData) throws NMEAParserException { if (gpsData == null) { throw new NMEAParserException("Input data is NULL."); } try { if (gpsData.startsWith(SENTENCE_TYPES[0])) { return new PTTK(gpsData); } if (gpsData.startsWith(SENTENCE_TYPES[1])) { return new GGA(gpsData); } if (gpsData.startsWith(SENTENCE_TYPES[2])) { return new RMC(gpsData); } if (gpsData.startsWith(SENTENCE_TYPES[3])) { return new GSV(gpsData); } } catch (RuntimeException e) { //Convert unchecked exceptions into parse exceptions. - throw new NMEAParserException(e.getMessage()); + throw new NMEAParserException("Runtime exception occurred: " + e.getMessage(), e); } return null; } }
true
true
public static AbstractNMEASentence getSentence(String gpsData) throws NMEAParserException { if (gpsData == null) { throw new NMEAParserException("Input data is NULL."); } try { if (gpsData.startsWith(SENTENCE_TYPES[0])) { return new PTTK(gpsData); } if (gpsData.startsWith(SENTENCE_TYPES[1])) { return new GGA(gpsData); } if (gpsData.startsWith(SENTENCE_TYPES[2])) { return new RMC(gpsData); } if (gpsData.startsWith(SENTENCE_TYPES[3])) { return new GSV(gpsData); } } catch (RuntimeException e) { //Convert unchecked exceptions into parse exceptions. throw new NMEAParserException(e.getMessage()); } return null; }
public static AbstractNMEASentence getSentence(String gpsData) throws NMEAParserException { if (gpsData == null) { throw new NMEAParserException("Input data is NULL."); } try { if (gpsData.startsWith(SENTENCE_TYPES[0])) { return new PTTK(gpsData); } if (gpsData.startsWith(SENTENCE_TYPES[1])) { return new GGA(gpsData); } if (gpsData.startsWith(SENTENCE_TYPES[2])) { return new RMC(gpsData); } if (gpsData.startsWith(SENTENCE_TYPES[3])) { return new GSV(gpsData); } } catch (RuntimeException e) { //Convert unchecked exceptions into parse exceptions. throw new NMEAParserException("Runtime exception occurred: " + e.getMessage(), e); } return null; }
diff --git a/data_structures/assignment_2/skeleton/Main.java b/data_structures/assignment_2/skeleton/Main.java index a03e030..51755a2 100644 --- a/data_structures/assignment_2/skeleton/Main.java +++ b/data_structures/assignment_2/skeleton/Main.java @@ -1,76 +1,76 @@ import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { boolean useLru = args[0].matches("1"); String inputFile = args[1]; String outputFile = args[2]; MemoryManagementSystem memory = new MemoryManagementSystem(useLru); read_From_File(inputFile,outputFile,memory); // MAKE SURE outputFile DOESN'T EXIST, OR ALL OUTPUT WILL BE APPENDED! } public static void read_From_File( - tring inputFilename, + String inputFilename, String outputFileName, MemoryManagementSystem memory) { try { File inFile = new File(inputFilename); FileReader ifr = new FileReader(inFile); BufferedReader ibr = new BufferedReader(ifr); String line = ""; while (line != null) { line = ibr.readLine(); if (line != null) { StringTokenizer st = new StringTokenizer(line); while (st.hasMoreTokens()) { String token = st.nextToken().trim(); if (token.equals("read")) { memory.read(Integer.parseInt(st.nextToken().trim())); } if (token.equals("write")) { int index = Integer.parseInt(st.nextToken().trim()); char c = st.nextToken().trim().charAt(0); memory.write(index, c); } if (token.equals("print")) { write_To_File(outputFileName, memory.toString()); } } } } ibr.close(); ifr.close(); } catch (Exception e) { System.out.println("Error \"" + e.toString() + "\" on file " + inputFilename); e.printStackTrace(); System.exit(-1); // Brutally exit the program. } } private static void write_To_File(String outputFilename, String toWrite) { try { File outFile = new File(outputFilename); FileWriter ofw = new FileWriter(outFile,true); // Writing to file ofw.append(toWrite); ofw.append("\n"); ofw.close(); } catch (Exception e) { System.out.println("Error \"" + e.toString() + "\" on file " + outputFilename); e.printStackTrace(); System.exit(-1); // brutally exit the program } } }
true
true
public static void read_From_File( tring inputFilename, String outputFileName, MemoryManagementSystem memory) { try { File inFile = new File(inputFilename); FileReader ifr = new FileReader(inFile); BufferedReader ibr = new BufferedReader(ifr); String line = ""; while (line != null) { line = ibr.readLine(); if (line != null) { StringTokenizer st = new StringTokenizer(line); while (st.hasMoreTokens()) { String token = st.nextToken().trim(); if (token.equals("read")) { memory.read(Integer.parseInt(st.nextToken().trim())); } if (token.equals("write")) { int index = Integer.parseInt(st.nextToken().trim()); char c = st.nextToken().trim().charAt(0); memory.write(index, c); } if (token.equals("print")) { write_To_File(outputFileName, memory.toString()); } } } } ibr.close(); ifr.close(); } catch (Exception e) { System.out.println("Error \"" + e.toString() + "\" on file " + inputFilename); e.printStackTrace(); System.exit(-1); // Brutally exit the program. } }
public static void read_From_File( String inputFilename, String outputFileName, MemoryManagementSystem memory) { try { File inFile = new File(inputFilename); FileReader ifr = new FileReader(inFile); BufferedReader ibr = new BufferedReader(ifr); String line = ""; while (line != null) { line = ibr.readLine(); if (line != null) { StringTokenizer st = new StringTokenizer(line); while (st.hasMoreTokens()) { String token = st.nextToken().trim(); if (token.equals("read")) { memory.read(Integer.parseInt(st.nextToken().trim())); } if (token.equals("write")) { int index = Integer.parseInt(st.nextToken().trim()); char c = st.nextToken().trim().charAt(0); memory.write(index, c); } if (token.equals("print")) { write_To_File(outputFileName, memory.toString()); } } } } ibr.close(); ifr.close(); } catch (Exception e) { System.out.println("Error \"" + e.toString() + "\" on file " + inputFilename); e.printStackTrace(); System.exit(-1); // Brutally exit the program. } }
diff --git a/plugins/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/presentation/aggregation/layout/RequesterFragment.java b/plugins/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/presentation/aggregation/layout/RequesterFragment.java index ca0ce55f..b2fbfffd 100644 --- a/plugins/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/presentation/aggregation/layout/RequesterFragment.java +++ b/plugins/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/presentation/aggregation/layout/RequesterFragment.java @@ -1,32 +1,33 @@ package org.eclipse.birt.report.presentation.aggregation.layout; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.birt.report.presentation.aggregation.BirtBaseFragment; public class RequesterFragment extends BirtBaseFragment { /** * Override implementation of doPostService. */ protected String doPostService( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { + //FIXME: workaround for Jetty request.setAttribute( "ServletPath", request.getServletPath( ) ); //$NON-NLS-1$ String className = getClass( ).getName( ) .substring( getClass( ).getName( ).lastIndexOf( '.' ) + 1 ); return JSPRootPath + "/pages/layout/" + className + ".jsp"; //$NON-NLS-1$ //$NON-NLS-2$ } /** * Override build method. */ protected void build( ) { addChild( new ParameterFragment( ) ); } }
true
true
protected String doPostService( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { request.setAttribute( "ServletPath", request.getServletPath( ) ); //$NON-NLS-1$ String className = getClass( ).getName( ) .substring( getClass( ).getName( ).lastIndexOf( '.' ) + 1 ); return JSPRootPath + "/pages/layout/" + className + ".jsp"; //$NON-NLS-1$ //$NON-NLS-2$ }
protected String doPostService( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { //FIXME: workaround for Jetty request.setAttribute( "ServletPath", request.getServletPath( ) ); //$NON-NLS-1$ String className = getClass( ).getName( ) .substring( getClass( ).getName( ).lastIndexOf( '.' ) + 1 ); return JSPRootPath + "/pages/layout/" + className + ".jsp"; //$NON-NLS-1$ //$NON-NLS-2$ }
diff --git a/runtime/src/com/sun/xml/bind/v2/model/annotation/LocatableAnnotation.java b/runtime/src/com/sun/xml/bind/v2/model/annotation/LocatableAnnotation.java index 6999e25d..addc8a22 100644 --- a/runtime/src/com/sun/xml/bind/v2/model/annotation/LocatableAnnotation.java +++ b/runtime/src/com/sun/xml/bind/v2/model/annotation/LocatableAnnotation.java @@ -1,95 +1,99 @@ package com.sun.xml.bind.v2.model.annotation; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashMap; import java.util.Map; import com.sun.xml.bind.v2.runtime.Location; /** * {@link Annotation} that also implements {@link Locatable}. * * @author Kohsuke Kawaguchi */ public class LocatableAnnotation implements InvocationHandler, Locatable, Location { private final Annotation core; private final Locatable upstream; /** * Wraps the annotation into a proxy so that the returned object will also implement * {@link Locatable}. */ public static <A extends Annotation> A create( A annotation, Locatable parentSourcePos ) { if(annotation==null) return null; Class<? extends Annotation> type = annotation.annotationType(); if(quicks.containsKey(type)) { // use the existing proxy implementation if available return (A)quicks.get(type).newInstance(parentSourcePos,annotation); } // otherwise take the slow route ClassLoader cl = LocatableAnnotation.class.getClassLoader(); try { Class loadableT = Class.forName(type.getName(), false, cl); if(loadableT !=type) return annotation; // annotation type not loadable from this class loader return (A)Proxy.newProxyInstance(cl, new Class[]{ type, Locatable.class }, new LocatableAnnotation(annotation,parentSourcePos)); } catch (ClassNotFoundException e) { // annotation not loadable return annotation; + } catch (IllegalArgumentException e) { + // Proxy.newProxyInstance throws this if it cannot resolve this annotation + // in this classloader + return annotation; } } LocatableAnnotation(Annotation core, Locatable upstream) { this.core = core; this.upstream = upstream; } public Locatable getUpstream() { return upstream; } public Location getLocation() { return this; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { if(method.getDeclaringClass()==Locatable.class) return method.invoke(this,args); else return method.invoke(core,args); } catch (InvocationTargetException e) { if(e.getTargetException()!=null) throw e.getTargetException(); throw e; } } public String toString() { return core.toString(); } /** * List of {@link Quick} implementations keyed by their annotation type. */ private static final Map<Class,Quick> quicks = new HashMap<Class, Quick>(); static { for( Quick q : Init.getAll() ) { quicks.put(q.annotationType(),q); } } }
true
true
public static <A extends Annotation> A create( A annotation, Locatable parentSourcePos ) { if(annotation==null) return null; Class<? extends Annotation> type = annotation.annotationType(); if(quicks.containsKey(type)) { // use the existing proxy implementation if available return (A)quicks.get(type).newInstance(parentSourcePos,annotation); } // otherwise take the slow route ClassLoader cl = LocatableAnnotation.class.getClassLoader(); try { Class loadableT = Class.forName(type.getName(), false, cl); if(loadableT !=type) return annotation; // annotation type not loadable from this class loader return (A)Proxy.newProxyInstance(cl, new Class[]{ type, Locatable.class }, new LocatableAnnotation(annotation,parentSourcePos)); } catch (ClassNotFoundException e) { // annotation not loadable return annotation; } }
public static <A extends Annotation> A create( A annotation, Locatable parentSourcePos ) { if(annotation==null) return null; Class<? extends Annotation> type = annotation.annotationType(); if(quicks.containsKey(type)) { // use the existing proxy implementation if available return (A)quicks.get(type).newInstance(parentSourcePos,annotation); } // otherwise take the slow route ClassLoader cl = LocatableAnnotation.class.getClassLoader(); try { Class loadableT = Class.forName(type.getName(), false, cl); if(loadableT !=type) return annotation; // annotation type not loadable from this class loader return (A)Proxy.newProxyInstance(cl, new Class[]{ type, Locatable.class }, new LocatableAnnotation(annotation,parentSourcePos)); } catch (ClassNotFoundException e) { // annotation not loadable return annotation; } catch (IllegalArgumentException e) { // Proxy.newProxyInstance throws this if it cannot resolve this annotation // in this classloader return annotation; } }
diff --git a/net.paissad.waqtsalat.ui/src/net/paissad/waqtsalat/ui/actions/StopPlayingAdhanAction.java b/net.paissad.waqtsalat.ui/src/net/paissad/waqtsalat/ui/actions/StopPlayingAdhanAction.java index 6155c95..ef4f570 100644 --- a/net.paissad.waqtsalat.ui/src/net/paissad/waqtsalat/ui/actions/StopPlayingAdhanAction.java +++ b/net.paissad.waqtsalat.ui/src/net/paissad/waqtsalat/ui/actions/StopPlayingAdhanAction.java @@ -1,78 +1,78 @@ package net.paissad.waqtsalat.ui.actions; import java.util.Collection; import net.paissad.eclipse.logger.ILogger; import net.paissad.waqtsalat.core.api.Pray; import net.paissad.waqtsalat.ui.WaqtSalatUIPlugin; import net.paissad.waqtsalat.ui.audio.api.ISoundPlayer; import org.eclipse.jface.action.Action; import org.eclipse.jface.resource.ImageDescriptor; public class StopPlayingAdhanAction extends Action { private static final ILogger logger = WaqtSalatUIPlugin.getPlugin().getLogger(); private Collection<Pray> prays; public StopPlayingAdhanAction(final Collection<Pray> prayTimes, String text, int style, ImageDescriptor image) { super(text, style); this.prays = prayTimes; setImageDescriptor(image); Thread t = new Thread(new Runnable() { @Override public void run() { while (true) { try { + boolean playing = false; if (prays != null) { - boolean playing = false; for (Pray pray : prays) { if (pray == null) continue; if (pray.isPlayingAdhan()) { playing = true; break; } } - setChecked(!playing); - setEnabled(playing); } + setChecked(!playing); + setEnabled(playing); Thread.sleep(200L); } catch (InterruptedException e) { } } } }); t.setDaemon(true); t.setName("Stop Playing Adhan Thread"); //$NON-NLS-1$ t.start(); } @Override public void run() { if (prays != null) { for (Pray pray : this.prays) { if (pray == null) continue; if (pray.isPlayingAdhan()) { Object adhanPlayer = pray.getAdhanPlayer(); if (adhanPlayer instanceof ISoundPlayer) { try { ((ISoundPlayer) adhanPlayer).stop(); } catch (Exception e) { logger.error( "Error while stopping adhan player for '" + pray.getName() + "' : " + e.getMessage(), e); //$NON-NLS-1$ //$NON-NLS-2$ } } else { logger.warn("Unable to stop adhan player for '" + pray.getName() + "' : unknown player type."); //$NON-NLS-1$ //$NON-NLS-2$ } } } } } public void setPrays(Collection<Pray> prays) { this.prays = prays; } }
false
true
public StopPlayingAdhanAction(final Collection<Pray> prayTimes, String text, int style, ImageDescriptor image) { super(text, style); this.prays = prayTimes; setImageDescriptor(image); Thread t = new Thread(new Runnable() { @Override public void run() { while (true) { try { if (prays != null) { boolean playing = false; for (Pray pray : prays) { if (pray == null) continue; if (pray.isPlayingAdhan()) { playing = true; break; } } setChecked(!playing); setEnabled(playing); } Thread.sleep(200L); } catch (InterruptedException e) { } } } }); t.setDaemon(true); t.setName("Stop Playing Adhan Thread"); //$NON-NLS-1$ t.start(); }
public StopPlayingAdhanAction(final Collection<Pray> prayTimes, String text, int style, ImageDescriptor image) { super(text, style); this.prays = prayTimes; setImageDescriptor(image); Thread t = new Thread(new Runnable() { @Override public void run() { while (true) { try { boolean playing = false; if (prays != null) { for (Pray pray : prays) { if (pray == null) continue; if (pray.isPlayingAdhan()) { playing = true; break; } } } setChecked(!playing); setEnabled(playing); Thread.sleep(200L); } catch (InterruptedException e) { } } } }); t.setDaemon(true); t.setName("Stop Playing Adhan Thread"); //$NON-NLS-1$ t.start(); }
diff --git a/Npr/src/org/npr/android/news/NewsListAdapter.java b/Npr/src/org/npr/android/news/NewsListAdapter.java index bcffdea..526089d 100644 --- a/Npr/src/org/npr/android/news/NewsListAdapter.java +++ b/Npr/src/org/npr/android/news/NewsListAdapter.java @@ -1,311 +1,315 @@ // Copyright 2009 Google Inc. // Copyright 2011 NPR // // 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.npr.android.news; import android.content.Context; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Message; import android.text.Html; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.*; import org.npr.android.util.PlaylistRepository; import org.npr.api.Client; import org.npr.api.Story; import org.npr.api.Story.Audio; import org.npr.api.Story.StoryFactory; import org.w3c.dom.Node; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.util.List; public class NewsListAdapter extends ArrayAdapter<Story> { private static final String LOG_TAG = NewsListAdapter.class.getName(); private final LayoutInflater inflater; private final ImageThreadLoader imageLoader; private RootActivity rootActivity = null; private final PlaylistRepository repository; private long lastUpdate = -1; private StoriesLoadedListener storiesLoadedListener; public NewsListAdapter(Context context) { super(context, R.layout.news_item); if (context instanceof RootActivity) { rootActivity = (RootActivity) context; } inflater = LayoutInflater.from(getContext()); imageLoader = ImageThreadLoader.getOnDiskInstance(context); repository = new PlaylistRepository(getContext().getApplicationContext(), context.getContentResolver()); } private List<Story> moreStories; private boolean endReached = false; private final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what >= 0) { if (moreStories != null) { lastUpdate = System.currentTimeMillis(); remove(null); for (Story s : moreStories) { if (getPosition(s) < 0) { add(s); } } if (!endReached) { add(null); } } if (storiesLoadedListener != null) { storiesLoadedListener.storiesLoaded(); } } else { Toast.makeText(rootActivity, rootActivity.getResources() .getText(R.string.msg_check_connection), Toast.LENGTH_LONG).show(); } if (rootActivity != null) { rootActivity.stopIndeterminateProgressIndicator(); } } }; private boolean isPlayable(Story story) { for (Audio a : story.getAudios()) { if (a.getType().equals("primary")) { for (Audio.Format f : a.getFormats()) { if (f.getMp3() != null) { return true; } } } } return false; } @Override public View getView(final int position, View convertView, final ViewGroup parent) { if (convertView == null) { convertView = inflater.inflate(R.layout.news_item, parent, false); } Story story = getItem(position); ImageView icon = (ImageView) convertView.findViewById(R.id.NewsItemIcon); TextView topic = (TextView) convertView.findViewById(R.id.NewsItemTopicText); TextView name = (TextView) convertView.findViewById(R.id.NewsItemNameText); final ImageView image = (ImageView) convertView.findViewById(R.id.NewsItemImage); if (story != null) { if (isPlayable(story)) { if (repository.getPlaylistItemFromStoryId(story.getId()) == null) { icon.setImageDrawable( getContext().getResources().getDrawable(R.drawable.speaker) ); } else { icon.setImageDrawable( getContext().getResources().getDrawable(R.drawable .news_item_in_playlist) ); } icon.setVisibility(View.VISIBLE); } else { // Because views are re-used we have to set this each time icon.setVisibility(View.INVISIBLE); } name.setText(Html.fromHtml(story.toString())); // Need to (re)set this because the views are reused. If we don't then // while scrolling, some items will replace the old "Load more stories" // view and will be in italics name.setTypeface(name.getTypeface(), Typeface.BOLD); String topicText = story.getSlug(); for (Story.Parent p : story.getParentTopics()) { if (p.isPrimary()) { topicText = p.getTitle(); } } - topic.setText(topicText.toLowerCase()); + if (topicText != null) { + topic.setText(topicText.toLowerCase()); + } else { + topic.setText(""); + } topic.setVisibility(View.VISIBLE); String imageUrl = null; if (story.getThumbnails().size() > 0) { imageUrl = story.getThumbnails().get(0).getMedium(); } else if (story.getImages().size() > 0) { imageUrl = story.getImages().get(0).getSrc(); } if (imageUrl != null) { Drawable cachedImage = imageLoader.loadImage( imageUrl, new ImageLoadListener(position, (ListView) parent) ); image.setImageDrawable(cachedImage); image.setVisibility(View.VISIBLE); } else { image.setVisibility(View.GONE); } } else { // null marker means it's the end of the list. icon.setVisibility(View.INVISIBLE); topic.setVisibility(View.GONE); image.setVisibility(View.GONE); name.setTypeface(name.getTypeface(), Typeface.ITALIC); name.setText(R.string.msg_load_more); } return convertView; } public void addMoreStories(final String url, final int count) { if (rootActivity != null) { rootActivity.startIndeterminateProgressIndicator(); } new Thread(new Runnable() { @Override public void run() { if (getMoreStories(url, count)) { handler.sendEmptyMessage(0); } else { handler.sendEmptyMessage(-1); } } }).start(); } private boolean getMoreStories(String url, int count) { Node stories = null; try { stories = new Client(url).execute(); } catch (IOException e) { Log.e(LOG_TAG, "", e); return false; } catch (SAXException e) { Log.e(LOG_TAG, "", e); } catch (ParserConfigurationException e) { Log.e(LOG_TAG, "", e); } if (stories == null) { Log.d(LOG_TAG, "stories: none"); } else { Log.d(LOG_TAG, "stories: " + stories.getNodeName()); moreStories = StoryFactory.parseStories(stories); if (moreStories != null) { if (moreStories.size() < count) { endReached = true; } NewsListActivity.addAllToStoryCache(moreStories); } } return true; } /** * @return a comma-separated list of story ID's */ public String getStoryIdList() { StringBuilder ids = new StringBuilder(); for (int i = 0; i < getCount(); i++) { Story story = getItem(i); if (story != null) { ids.append(story.getId()).append(","); } } String result = ids.toString(); if (result.endsWith(",")) { result = result.substring(0, result.length() - 1); } return result; } /** * Returns the time (in milliseconds since the epoch) of when * the last update was. * * @return A time unit in milliseconds since the epoch */ public long getLastUpdate() { return lastUpdate; } /** * A call back that can be used to be notified when stories are done * loading. */ public interface StoriesLoadedListener { void storiesLoaded(); } /** * Sets a listener to be notified when stories are done loading * @param listener A {@link StoriesLoadedListener} */ public void setStoriesLoadedListener(StoriesLoadedListener listener) { storiesLoadedListener = listener; } private class ImageLoadListener implements ImageThreadLoader.ImageLoadedListener { private int position; private ListView parent; public ImageLoadListener(int position, ListView parent) { this.position = position; this.parent = parent; } public void imageLoaded(Drawable imageBitmap) { // Offset 1 for header int storyPosition = position + 1; View itemView = parent.getChildAt(storyPosition - parent.getFirstVisiblePosition()); if (itemView == null) { Log.w(LOG_TAG, "Could not find list item at position " + storyPosition); return; } ImageView img = (ImageView) itemView.findViewById(R.id.NewsItemImage); if (img == null) { Log.w(LOG_TAG, "Could not find image for list item at " + "position " + storyPosition); return; } Log.d(LOG_TAG, "Drawing image at position " + storyPosition); img.setImageDrawable(imageBitmap); } } }
true
true
public View getView(final int position, View convertView, final ViewGroup parent) { if (convertView == null) { convertView = inflater.inflate(R.layout.news_item, parent, false); } Story story = getItem(position); ImageView icon = (ImageView) convertView.findViewById(R.id.NewsItemIcon); TextView topic = (TextView) convertView.findViewById(R.id.NewsItemTopicText); TextView name = (TextView) convertView.findViewById(R.id.NewsItemNameText); final ImageView image = (ImageView) convertView.findViewById(R.id.NewsItemImage); if (story != null) { if (isPlayable(story)) { if (repository.getPlaylistItemFromStoryId(story.getId()) == null) { icon.setImageDrawable( getContext().getResources().getDrawable(R.drawable.speaker) ); } else { icon.setImageDrawable( getContext().getResources().getDrawable(R.drawable .news_item_in_playlist) ); } icon.setVisibility(View.VISIBLE); } else { // Because views are re-used we have to set this each time icon.setVisibility(View.INVISIBLE); } name.setText(Html.fromHtml(story.toString())); // Need to (re)set this because the views are reused. If we don't then // while scrolling, some items will replace the old "Load more stories" // view and will be in italics name.setTypeface(name.getTypeface(), Typeface.BOLD); String topicText = story.getSlug(); for (Story.Parent p : story.getParentTopics()) { if (p.isPrimary()) { topicText = p.getTitle(); } } topic.setText(topicText.toLowerCase()); topic.setVisibility(View.VISIBLE); String imageUrl = null; if (story.getThumbnails().size() > 0) { imageUrl = story.getThumbnails().get(0).getMedium(); } else if (story.getImages().size() > 0) { imageUrl = story.getImages().get(0).getSrc(); } if (imageUrl != null) { Drawable cachedImage = imageLoader.loadImage( imageUrl, new ImageLoadListener(position, (ListView) parent) ); image.setImageDrawable(cachedImage); image.setVisibility(View.VISIBLE); } else { image.setVisibility(View.GONE); } } else { // null marker means it's the end of the list. icon.setVisibility(View.INVISIBLE); topic.setVisibility(View.GONE); image.setVisibility(View.GONE); name.setTypeface(name.getTypeface(), Typeface.ITALIC); name.setText(R.string.msg_load_more); } return convertView; }
public View getView(final int position, View convertView, final ViewGroup parent) { if (convertView == null) { convertView = inflater.inflate(R.layout.news_item, parent, false); } Story story = getItem(position); ImageView icon = (ImageView) convertView.findViewById(R.id.NewsItemIcon); TextView topic = (TextView) convertView.findViewById(R.id.NewsItemTopicText); TextView name = (TextView) convertView.findViewById(R.id.NewsItemNameText); final ImageView image = (ImageView) convertView.findViewById(R.id.NewsItemImage); if (story != null) { if (isPlayable(story)) { if (repository.getPlaylistItemFromStoryId(story.getId()) == null) { icon.setImageDrawable( getContext().getResources().getDrawable(R.drawable.speaker) ); } else { icon.setImageDrawable( getContext().getResources().getDrawable(R.drawable .news_item_in_playlist) ); } icon.setVisibility(View.VISIBLE); } else { // Because views are re-used we have to set this each time icon.setVisibility(View.INVISIBLE); } name.setText(Html.fromHtml(story.toString())); // Need to (re)set this because the views are reused. If we don't then // while scrolling, some items will replace the old "Load more stories" // view and will be in italics name.setTypeface(name.getTypeface(), Typeface.BOLD); String topicText = story.getSlug(); for (Story.Parent p : story.getParentTopics()) { if (p.isPrimary()) { topicText = p.getTitle(); } } if (topicText != null) { topic.setText(topicText.toLowerCase()); } else { topic.setText(""); } topic.setVisibility(View.VISIBLE); String imageUrl = null; if (story.getThumbnails().size() > 0) { imageUrl = story.getThumbnails().get(0).getMedium(); } else if (story.getImages().size() > 0) { imageUrl = story.getImages().get(0).getSrc(); } if (imageUrl != null) { Drawable cachedImage = imageLoader.loadImage( imageUrl, new ImageLoadListener(position, (ListView) parent) ); image.setImageDrawable(cachedImage); image.setVisibility(View.VISIBLE); } else { image.setVisibility(View.GONE); } } else { // null marker means it's the end of the list. icon.setVisibility(View.INVISIBLE); topic.setVisibility(View.GONE); image.setVisibility(View.GONE); name.setTypeface(name.getTypeface(), Typeface.ITALIC); name.setText(R.string.msg_load_more); } return convertView; }
diff --git a/morphia/src/main/java/com/google/code/morphia/query/QueryImpl.java b/morphia/src/main/java/com/google/code/morphia/query/QueryImpl.java index 51252f7..1cadf08 100644 --- a/morphia/src/main/java/com/google/code/morphia/query/QueryImpl.java +++ b/morphia/src/main/java/com/google/code/morphia/query/QueryImpl.java @@ -1,550 +1,550 @@ package com.google.code.morphia.query; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import org.bson.types.CodeWScope; import org.bson.types.ObjectId; import com.google.code.morphia.Datastore; import com.google.code.morphia.DatastoreImpl; import com.google.code.morphia.Key; import com.google.code.morphia.annotations.Reference; import com.google.code.morphia.annotations.Serialized; import com.google.code.morphia.logging.MorphiaLogger; import com.google.code.morphia.logging.MorphiaLoggerFactory; import com.google.code.morphia.mapping.MappedClass; import com.google.code.morphia.mapping.MappedField; import com.google.code.morphia.mapping.Mapper; import com.google.code.morphia.mapping.MappingException; import com.google.code.morphia.mapping.Serializer; import com.google.code.morphia.mapping.cache.EntityCache; import com.google.code.morphia.utils.Assert; import com.google.code.morphia.utils.ReflectionUtils; import com.mongodb.BasicDBObject; import com.mongodb.BasicDBObjectBuilder; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; /** * <p>Implementation of Query</p> * * @author Scott Hernandez * * @param <T> The type we will be querying for, and returning. */ public class QueryImpl<T> implements Query<T> { private static final MorphiaLogger log = MorphiaLoggerFactory.get(Mapper.class); private final EntityCache cache; private boolean validating = true; private Map<String, Object> query = null; private String[] fields = null; private Boolean includeFields = null; private BasicDBObjectBuilder sort = null; private DatastoreImpl ds = null; private DBCollection dbColl = null; private int offset = 0; private int limit = -1; private String indexHint; private Class<T> clazz = null; public QueryImpl(Class<T> clazz, DBCollection coll, Datastore ds) { this.clazz = clazz; this.ds = ((DatastoreImpl)ds); this.dbColl = coll; this.cache = this.ds.getMapper().createEntityCache(); } public QueryImpl(Class<T> clazz, DBCollection coll, Datastore ds, int offset, int limit) { this(clazz, coll, ds); this.offset = offset; this.limit = limit; } @SuppressWarnings("unchecked") public void setQueryObject(DBObject query) { this.query = (Map<String, Object>) query; } public DBObject getQueryObject() { return (query == null) ? null : new BasicDBObject(query); } public DBObject getFieldsObject() { if (fields == null || fields.length == 0) return null; Map<String, Boolean> fieldsFilter = new HashMap<String, Boolean>(); for(String field : this.fields) fieldsFilter.put(field, (includeFields)); return new BasicDBObject(fieldsFilter); } public DBObject getSortObject() { return (sort == null) ? null : sort.get(); } public long countAll() { return dbColl.getCount(getQueryObject()); } public DBCursor prepareCursor() { DBObject query = getQueryObject(); DBObject fields = getFieldsObject(); if (log.isDebugEnabled()) log.debug("Running query: " + query + ", " + fields + ",off:" + offset + ",limit:" + limit); DBCursor cursor = dbColl.find(query, fields); if (offset > 0) cursor.skip(offset); if (limit > 0) cursor.limit(limit); if (sort != null) cursor.sort(getSortObject()); if (indexHint != null) cursor.hint(indexHint); return cursor; } public Iterable<T> fetch() { DBCursor cursor = prepareCursor(); return new MorphiaIterator<T>(cursor, ds.getMapper(), clazz, dbColl.getName(), cache); } public Iterable<Key<T>> fetchKeys() { String[] oldFields = fields; Boolean oldInclude = includeFields; fields = new String[] {Mapper.ID_KEY}; includeFields = true; DBCursor cursor = prepareCursor(); fields = oldFields; includeFields = oldInclude; return new MorphiaKeyIterator<T>(cursor, ds.getMapper(), clazz, dbColl.getName()); } public List<T> asList() { List<T> results = new ArrayList<T>(); for(T ent : fetch()) results.add(ent); if (log.isTraceEnabled()) log.trace("\nasList: " + dbColl.getName() + "\n result size " + results.size() + "\n cache: " + (cache.stats()) + "\n for " + ((query != null) ? new BasicDBObject(query) : "{}")); return results; } public List<Key<T>> asKeyList() { List<Key<T>> results = new ArrayList<Key<T>>(); for(Key<T> key : fetchKeys()) results.add(key); return results; } public Iterable<T> fetchEmptyEntities() { String[] oldFields = fields; Boolean oldInclude = includeFields; fields = new String[] {Mapper.ID_KEY}; includeFields = true; Iterable<T> res = fetch(); fields = oldFields; includeFields = oldInclude; return res; } /** * Converts the textual operator (">", "<=", etc) into a FilterOperator. * Forgiving about the syntax; != and <> are NOT_EQUAL, = and == are EQUAL. */ protected FilterOperator translate(String operator) { operator = operator.trim(); if (operator.equals("=") || operator.equals("==")) return FilterOperator.EQUAL; else if (operator.equals(">")) return FilterOperator.GREATER_THAN; else if (operator.equals(">=")) return FilterOperator.GREATER_THAN_OR_EQUAL; else if (operator.equals("<")) return FilterOperator.LESS_THAN; else if (operator.equals("<=")) return FilterOperator.LESS_THAN_OR_EQUAL; else if (operator.equals("!=") || operator.equals("<>")) return FilterOperator.NOT_EQUAL; else if (operator.toLowerCase().equals("in")) return FilterOperator.IN; else if (operator.toLowerCase().equals("nin")) return FilterOperator.NOT_IN; else if (operator.toLowerCase().equals("all")) return FilterOperator.ALL; else if (operator.toLowerCase().equals("exists")) return FilterOperator.EXISTS; else if (operator.toLowerCase().equals("elem")) return FilterOperator.ELEMENT_MATCH; else if (operator.toLowerCase().equals("size")) return FilterOperator.SIZE; else throw new IllegalArgumentException("Unknown operator '" + operator + "'"); } @SuppressWarnings("unchecked") public Query<T> filter(String condition, Object value) { String[] parts = condition.trim().split(" "); if (parts.length < 1 || parts.length > 6) throw new IllegalArgumentException("'" + condition + "' is not a legal filter condition"); String prop = parts[0].trim(); FilterOperator op = (parts.length == 2) ? this.translate(parts[1]) : FilterOperator.EQUAL; //The field we are filtering on, in the java object MappedField mf = null; if (validating) mf = validate(prop, value); //TODO differentiate between the key/value for maps; we will just get the mf for the field, not which part we are looking for if (query == null) query = new HashMap<String, Object>(); Mapper mapr = ds.getMapper(); Object mappedValue; MappedClass mc = null; try { if (value != null && !ReflectionUtils.isPropertyType(value.getClass())) if (mf!=null && !mf.isTypeMongoCompatible()) mc=mapr.getMappedClass((mf.isSingleValue()) ? mf.getType() : mf.getSubType()); else mc = mapr.getMappedClass(value); } catch (Exception e) { //Ignore these. It is likely they related to mapping validation that is unimportant for queries (the query will fail/return-empty anyway) log.debug("Error during mapping filter criteria: ", e); } //convert the value to Key (DBRef) if it is a entity/@Reference or the field type is Key if ((mf!=null && (mf.hasAnnotation(Reference.class) || mf.getType().isAssignableFrom(Key.class))) || (mc != null && mc.getEntityAnnotation() != null)) { try { Key<?> k = (value instanceof Key) ? (Key<?>)value : ds.getKey(value); mappedValue = k.toRef(mapr); } catch (Exception e) { log.debug("Error converting value(" + value + ") to reference.", e); mappedValue = mapr.toMongoObject(value); } } else if (mf!=null && mf.hasAnnotation(Serialized.class)) try { mappedValue = Serializer.serialize(value, !mf.getAnnotation(Serialized.class).disableCompression()); } catch (IOException e) { throw new RuntimeException(e); } else mappedValue = ReflectionUtils.asObjectIdMaybe(mapr.toMongoObject(value)); Class<?> type = (mappedValue != null) ? mappedValue.getClass() : null; //convert single values into lists for $in/$nin if (type != null && (op == FilterOperator.IN || op == FilterOperator.NOT_IN) && !type.isArray() && !ReflectionUtils.implementsAnyInterface(type, Iterable.class) ) { mappedValue = Collections.singletonList(mappedValue); } if (FilterOperator.EQUAL.equals(op)) query.put(prop, mappedValue); // no operator, prop equals value else { Object inner = query.get(prop); // operator within inner object if (!(inner instanceof Map)) { inner = new HashMap<String, Object>(); query.put(prop, inner); } - ((Map)inner).put(op.val(), mappedValue); + ((Map<String, Object>)inner).put(op.val(), mappedValue); } return this; } protected Query<T> filterWhere(Object obj){ if (query == null) { query = new HashMap<String, Object>(); } query.put(FilterOperator.WHERE.val(), obj); return this; } public Query<T> where(String js) { return filterWhere(js); } public Query<T> where(CodeWScope cws) { return filterWhere(cws); } public Query<T> enableValidation(){ validating = true; return this; } public Query<T> disableValidation(){ validating = false; return this; } /** Validate the path, and value type, returning the mappedfield for the field at the path */ private MappedField validate(String prop, Object value) { String[] parts = prop.split("\\."); // if (parts.length == 0) parts = new String[]{prop}; if (this.clazz == null) return null; MappedClass mc = ds.getMapper().getMappedClass(this.clazz); MappedField mf; for(int i=0; ; ) { String part = parts[i]; mf = mc.getMappedField(part); if (mf == null) { mf = mc.getMappedFieldByJavaField(part); if (mf != null) throw new MappingException("The field '" + part + "' is named '" + mf.getNameToStore() + "' in '" + this.clazz.getName()+ "' " + "(while validating - '" + prop + "'); Please use '" + mf.getNameToStore() + "' in your query."); else throw new MappingException("The field '" + part + "' could not be found in '" + this.clazz.getName()+ "' while validating - " + prop); } i++; if (mf.isMap()) { //skip the map key validation, and move to the next part i++; } //catch people trying to search into @Reference/@Serialized fields if (i < parts.length && !canQueryPast(mf)) throw new MappingException("Can not use dot-notation past '" + part + "' could not be found in '" + this.clazz.getName()+ "' while validating - " + prop); if (i >= parts.length) break; mc = ds.getMapper().getMappedClass((mf.isSingleValue()) ? mf.getType() : mf.getSubType()); } if ( (mf.isSingleValue() && !isCompatibleForQuery(mf.getType(), value)) || ((mf.isMultipleValues() && !isCompatibleForQuery(mf.getSubType(), value)))) { Throwable t = new Throwable(); log.warning("Datatypes for the query may be inconsistent; searching with an instance of " + value.getClass().getName() + " when the field " + mf.getDeclaringClass().getName()+ "." + mf.getJavaFieldName() + " is a " + mf.getType().getName()); log.debug("Location of warning:\r\n", t); } return mf; } /** Returns if the MappedField is a Reference or Serilized */ public static boolean canQueryPast(MappedField mf) { return !(mf.hasAnnotation(Reference.class) || mf.hasAnnotation(Serialized.class)); } public static boolean isCompatibleForQuery(Class<?> type, Object value) { if (value == null || type == null) return true; else if (value instanceof Integer && (int.class.equals(type) || long.class.equals(type) || Long.class.equals(type))) return true; else if ((value instanceof Integer || value instanceof Long) && (double.class.equals(type) || Double.class.equals(type))) return true; else if (value instanceof Pattern && String.class.equals(type)) return true; else if (value instanceof List) return true; else if (value instanceof ObjectId && String.class.equals(type)) return true; else if (!value.getClass().isAssignableFrom(type) && //hack to let Long match long, and so on !value.getClass().getSimpleName().toLowerCase().equals(type.getSimpleName().toLowerCase())) { return false; } return true; } public T get() { int oldLimit = limit; limit = 1; Iterator<T> it = fetch().iterator(); limit = oldLimit; return (it.hasNext()) ? it.next() : null ; } public Key<T> getKey() { int oldLimit = limit; limit = 1; Iterator<Key<T>> it = fetchKeys().iterator(); limit = oldLimit; return (it.hasNext()) ? it.next() : null; } public Query<T> limit(int value) { this.limit = value; return this; } public Query<T> skip(int value) { this.offset = value; return this; } public Query<T> offset(int value) { this.offset = value; return this; } public Query<T> order(String condition) { sort = BasicDBObjectBuilder.start(); String[] sorts = condition.split(","); for (String s : sorts) { s = s.trim(); int dir = 1; if (s.startsWith("-")) { dir = -1; s = s.substring(1).trim(); } sort = sort.add(s, dir); } return this; } public Iterator<T> iterator() { return fetch().iterator(); } public Class<T> getEntityClass() { return this.clazz; } public static class QueryFieldEndImpl<T> implements QueryFieldEnd<T>{ protected final String fieldExpr; protected final QueryImpl<T> query; public QueryFieldEndImpl(String fe, QueryImpl<T> q) {this.fieldExpr = fe; this.query=q;} public Query<T> startsWith(String prefix) { Assert.parametersNotNull("prefix",prefix); query.filter("" + fieldExpr, Pattern.compile("^" + prefix)); return query; } public Query<T> startsWithIgnoreCase(String prefix) { Assert.parametersNotNull("prefix", prefix); query.filter("" + fieldExpr, Pattern.compile("^" + prefix, Pattern.CASE_INSENSITIVE)); return query; } public Query<T> doesNotExist() { query.filter("" + fieldExpr + " exists", 0); return query; } public Query<T> equal(Object val) { query.filter(fieldExpr + " =", val); return query; } public Query<T> exists() { query.filter("" + fieldExpr + " exists", true); return query; } public Query<T> greaterThan(Object val) { Assert.parametersNotNull("val",val); query.filter(fieldExpr + " >", val); return query; } public Query<T> greaterThanOrEq(Object val) { Assert.parametersNotNull("val",val); query.filter(fieldExpr + " >=", val); return query; } public Query<T> hasThisOne(Object val) { query.filter(fieldExpr + " =", val); return query; } public Query<T> hasAllOf(Iterable<?> vals) { Assert.parametersNotNull("vals",vals); Assert.parameterNotEmpty(vals,"vals"); query.filter(fieldExpr + " all", vals); return query; } public Query<T> hasAnyOf(Iterable<?> vals) { Assert.parametersNotNull("vals",vals); Assert.parameterNotEmpty(vals,"vals"); query.filter(fieldExpr + " in", vals); return query; } public Query<T> hasThisElement(Object val) { Assert.parametersNotNull("val",val); query.filter(fieldExpr + " elem", val); return query; } public Query<T> hasNoneOf(Iterable<?> vals) { Assert.parametersNotNull("vals",vals); Assert.parameterNotEmpty(vals,"vals"); query.filter(fieldExpr + " nin", vals); return query; } public Query<T> lessThan(Object val) { Assert.parametersNotNull("val",val); query.filter(fieldExpr + " <", val); return query; } public Query<T> lessThanOrEq(Object val) { Assert.parametersNotNull("val",val); query.filter(fieldExpr + " <=", val); return query; } public Query<T> notEqual(Object val) { query.filter(fieldExpr + " <>", val); return query; } public Query<T> sizeEq(int val) { Assert.parametersNotNull("val",val); query.filter(fieldExpr + " size", val); return query; } } public QueryFieldEnd<T> field(String fieldExpr) { return new QueryFieldEndImpl<T>(fieldExpr, this); } public Query<T> hintIndex(String idxName) { return null; } public Query<T> retrievedFields(boolean include, String...fields){ if (includeFields != null && include != includeFields) throw new IllegalStateException("You cannot mix include and excluded fields together!"); this.includeFields = include; this.fields = fields; return this; } }
true
true
public Query<T> filter(String condition, Object value) { String[] parts = condition.trim().split(" "); if (parts.length < 1 || parts.length > 6) throw new IllegalArgumentException("'" + condition + "' is not a legal filter condition"); String prop = parts[0].trim(); FilterOperator op = (parts.length == 2) ? this.translate(parts[1]) : FilterOperator.EQUAL; //The field we are filtering on, in the java object MappedField mf = null; if (validating) mf = validate(prop, value); //TODO differentiate between the key/value for maps; we will just get the mf for the field, not which part we are looking for if (query == null) query = new HashMap<String, Object>(); Mapper mapr = ds.getMapper(); Object mappedValue; MappedClass mc = null; try { if (value != null && !ReflectionUtils.isPropertyType(value.getClass())) if (mf!=null && !mf.isTypeMongoCompatible()) mc=mapr.getMappedClass((mf.isSingleValue()) ? mf.getType() : mf.getSubType()); else mc = mapr.getMappedClass(value); } catch (Exception e) { //Ignore these. It is likely they related to mapping validation that is unimportant for queries (the query will fail/return-empty anyway) log.debug("Error during mapping filter criteria: ", e); } //convert the value to Key (DBRef) if it is a entity/@Reference or the field type is Key if ((mf!=null && (mf.hasAnnotation(Reference.class) || mf.getType().isAssignableFrom(Key.class))) || (mc != null && mc.getEntityAnnotation() != null)) { try { Key<?> k = (value instanceof Key) ? (Key<?>)value : ds.getKey(value); mappedValue = k.toRef(mapr); } catch (Exception e) { log.debug("Error converting value(" + value + ") to reference.", e); mappedValue = mapr.toMongoObject(value); } } else if (mf!=null && mf.hasAnnotation(Serialized.class)) try { mappedValue = Serializer.serialize(value, !mf.getAnnotation(Serialized.class).disableCompression()); } catch (IOException e) { throw new RuntimeException(e); } else mappedValue = ReflectionUtils.asObjectIdMaybe(mapr.toMongoObject(value)); Class<?> type = (mappedValue != null) ? mappedValue.getClass() : null; //convert single values into lists for $in/$nin if (type != null && (op == FilterOperator.IN || op == FilterOperator.NOT_IN) && !type.isArray() && !ReflectionUtils.implementsAnyInterface(type, Iterable.class) ) { mappedValue = Collections.singletonList(mappedValue); } if (FilterOperator.EQUAL.equals(op)) query.put(prop, mappedValue); // no operator, prop equals value else { Object inner = query.get(prop); // operator within inner object if (!(inner instanceof Map)) { inner = new HashMap<String, Object>(); query.put(prop, inner); } ((Map)inner).put(op.val(), mappedValue); } return this; }
public Query<T> filter(String condition, Object value) { String[] parts = condition.trim().split(" "); if (parts.length < 1 || parts.length > 6) throw new IllegalArgumentException("'" + condition + "' is not a legal filter condition"); String prop = parts[0].trim(); FilterOperator op = (parts.length == 2) ? this.translate(parts[1]) : FilterOperator.EQUAL; //The field we are filtering on, in the java object MappedField mf = null; if (validating) mf = validate(prop, value); //TODO differentiate between the key/value for maps; we will just get the mf for the field, not which part we are looking for if (query == null) query = new HashMap<String, Object>(); Mapper mapr = ds.getMapper(); Object mappedValue; MappedClass mc = null; try { if (value != null && !ReflectionUtils.isPropertyType(value.getClass())) if (mf!=null && !mf.isTypeMongoCompatible()) mc=mapr.getMappedClass((mf.isSingleValue()) ? mf.getType() : mf.getSubType()); else mc = mapr.getMappedClass(value); } catch (Exception e) { //Ignore these. It is likely they related to mapping validation that is unimportant for queries (the query will fail/return-empty anyway) log.debug("Error during mapping filter criteria: ", e); } //convert the value to Key (DBRef) if it is a entity/@Reference or the field type is Key if ((mf!=null && (mf.hasAnnotation(Reference.class) || mf.getType().isAssignableFrom(Key.class))) || (mc != null && mc.getEntityAnnotation() != null)) { try { Key<?> k = (value instanceof Key) ? (Key<?>)value : ds.getKey(value); mappedValue = k.toRef(mapr); } catch (Exception e) { log.debug("Error converting value(" + value + ") to reference.", e); mappedValue = mapr.toMongoObject(value); } } else if (mf!=null && mf.hasAnnotation(Serialized.class)) try { mappedValue = Serializer.serialize(value, !mf.getAnnotation(Serialized.class).disableCompression()); } catch (IOException e) { throw new RuntimeException(e); } else mappedValue = ReflectionUtils.asObjectIdMaybe(mapr.toMongoObject(value)); Class<?> type = (mappedValue != null) ? mappedValue.getClass() : null; //convert single values into lists for $in/$nin if (type != null && (op == FilterOperator.IN || op == FilterOperator.NOT_IN) && !type.isArray() && !ReflectionUtils.implementsAnyInterface(type, Iterable.class) ) { mappedValue = Collections.singletonList(mappedValue); } if (FilterOperator.EQUAL.equals(op)) query.put(prop, mappedValue); // no operator, prop equals value else { Object inner = query.get(prop); // operator within inner object if (!(inner instanceof Map)) { inner = new HashMap<String, Object>(); query.put(prop, inner); } ((Map<String, Object>)inner).put(op.val(), mappedValue); } return this; }
diff --git a/projects/base/src/main/java/org/muis/base/widget/Button.java b/projects/base/src/main/java/org/muis/base/widget/Button.java index 523b1f06..0ffab3d3 100644 --- a/projects/base/src/main/java/org/muis/base/widget/Button.java +++ b/projects/base/src/main/java/org/muis/base/widget/Button.java @@ -1,197 +1,197 @@ package org.muis.base.widget; import static org.muis.core.LayoutContainer.LAYOUT_ATTR; import java.awt.Point; import org.muis.core.MuisConstants; import org.muis.core.MuisException; import org.muis.core.MuisLayout; import org.muis.core.event.*; import org.muis.core.layout.SizeGuide; import org.muis.core.mgr.MuisState; import org.muis.core.model.ModelAttributes; import org.muis.core.tags.Template; /** Implements a button. Buttons can be set to toggle mode or normal mode. Buttons are containers that may have any type of content in them. */ @Template(location = "../../../../button.muis") public class Button extends org.muis.core.MuisTemplate { private boolean theLayoutCallbackLock; /** Creates a button */ public Button() { setFocusable(true); atts().accept(new Object(), LAYOUT_ATTR); atts().accept(new Object(), ModelAttributes.action); life().runWhen(new Runnable() { @Override public void run() { - state().addListener(MuisConstants.States.CLICK_NAME, new org.muis.core.mgr.StateEngine.StateListener() { + state().addListener(MuisConstants.States.CLICK, new org.muis.core.mgr.StateEngine.StateListener() { private Point theClickLocation; @Override public void entered(MuisState state, MuisEvent<?> cause) { if(cause instanceof MouseEvent) { theClickLocation = ((MouseEvent) cause).getPosition(Button.this); } else theClickLocation = null; } @Override public void exited(MuisState state, MuisEvent<?> cause) { if(theClickLocation == null || !(cause instanceof MouseEvent)) return; Point click = theClickLocation; theClickLocation = null; Point unclick = ((MouseEvent) cause).getPosition(Button.this); int dx = click.x - unclick.x; int dy = click.y - unclick.y; double tol = Button.this.getStyle().getSelf().get(org.muis.base.style.ButtonStyles.clickTolerance); if(dx > tol || dy > tol) return; double dist2 = dx * dx + dy * dy; if(dist2 > tol * tol) return; org.muis.core.model.MuisActionListener listener = atts().get(ModelAttributes.action); if(listener == null) return; try { listener.actionPerformed((MouseEvent) cause); } catch(RuntimeException e) { msg().error("Action listener threw exception", e); } } }); addListener(MuisConstants.Events.ATTRIBUTE_CHANGED, new AttributeChangedListener<MuisLayout>(LAYOUT_ATTR) { @Override public void attributeChanged(AttributeChangedEvent<MuisLayout> event) { if(theLayoutCallbackLock) return; theLayoutCallbackLock = true; try { getContentPane().atts().set(LAYOUT_ATTR, event.getValue()); } catch(MuisException e) { throw new IllegalStateException(LAYOUT_ATTR + " not accepted by content pane?", e); } finally { theLayoutCallbackLock = false; } } }); MuisLayout layout = atts().get(LAYOUT_ATTR); if(layout != null) try { getContentPane().atts().set(LAYOUT_ATTR, layout); } catch(MuisException e) { throw new IllegalStateException(LAYOUT_ATTR + " not accepted by content pane?", e); } getContentPane().addListener(MuisConstants.Events.ATTRIBUTE_CHANGED, new AttributeChangedListener<MuisLayout>(LAYOUT_ATTR) { @Override public void attributeChanged(AttributeChangedEvent<MuisLayout> event) { if(theLayoutCallbackLock) return; theLayoutCallbackLock = true; try { atts().set(LAYOUT_ATTR, event.getValue()); } catch(MuisException e) { throw new IllegalStateException(LAYOUT_ATTR + " not accepted by button?", e); } finally { theLayoutCallbackLock = false; } } }); } }, MuisConstants.CoreStage.INITIALIZED.toString(), 1); } /** @return The panel containing the contents of this button */ public Block getContentPane() { return (Block) getElement(getTemplate().getAttachPoint("contents")); } @Override public void doLayout() { org.muis.core.style.Size radius = getStyle().getSelf().get(org.muis.core.style.BackgroundStyles.cornerRadius); int w = bounds().getWidth(); int h = bounds().getHeight(); int lOff = radius.evaluate(w); int tOff = radius.evaluate(h); getContentPane().bounds().setBounds(lOff, tOff, w - lOff - lOff, h - tOff - tOff); } @Override public SizeGuide getWSizer() { final org.muis.core.style.Size radius = getStyle().getSelf().get(org.muis.core.style.BackgroundStyles.cornerRadius); return new RadiusAddSizePolicy(getContentPane().getWSizer(), radius); } @Override public SizeGuide getHSizer() { final org.muis.core.style.Size radius = getStyle().getSelf().get(org.muis.core.style.BackgroundStyles.cornerRadius); return new RadiusAddSizePolicy(getContentPane().getHSizer(), radius); } private static class RadiusAddSizePolicy extends org.muis.core.layout.AbstractSizeGuide { private final SizeGuide theWrapped; private org.muis.core.style.Size theRadius; RadiusAddSizePolicy(SizeGuide wrap, org.muis.core.style.Size rad) { theWrapped = wrap; theRadius = rad; } @Override public int getMinPreferred(int crossSize, boolean csMax) { return addRadius(theWrapped.getMinPreferred(crossSize, csMax)); } @Override public int getMaxPreferred(int crossSize, boolean csMax) { return addRadius(theWrapped.getMaxPreferred(crossSize, csMax)); } @Override public int getMin(int crossSize, boolean csMax) { return addRadius(theWrapped.getMin(removeRadius(crossSize), csMax)); } @Override public int getPreferred(int crossSize, boolean csMax) { return addRadius(theWrapped.getPreferred(removeRadius(crossSize), csMax)); } @Override public int getMax(int crossSize, boolean csMax) { return addRadius(theWrapped.getMax(removeRadius(crossSize), csMax)); } @Override public int getBaseline(int size) { int remove = size - removeRadius(size); int ret = theWrapped.getBaseline(size - remove * 2); return ret + remove; } int addRadius(int size) { switch (theRadius.getUnit()) { case pixels: case lexips: size += theRadius.getValue() * 2; break; case percent: float radPercent = theRadius.getValue() * 2; if(radPercent >= 100) radPercent = 90; size = Math.round(size * 100 / (100f - radPercent)); break; } if(size < 0) return Integer.MAX_VALUE; return size; } int removeRadius(int size) { return size - theRadius.evaluate(size); } } }
true
true
public Button() { setFocusable(true); atts().accept(new Object(), LAYOUT_ATTR); atts().accept(new Object(), ModelAttributes.action); life().runWhen(new Runnable() { @Override public void run() { state().addListener(MuisConstants.States.CLICK_NAME, new org.muis.core.mgr.StateEngine.StateListener() { private Point theClickLocation; @Override public void entered(MuisState state, MuisEvent<?> cause) { if(cause instanceof MouseEvent) { theClickLocation = ((MouseEvent) cause).getPosition(Button.this); } else theClickLocation = null; } @Override public void exited(MuisState state, MuisEvent<?> cause) { if(theClickLocation == null || !(cause instanceof MouseEvent)) return; Point click = theClickLocation; theClickLocation = null; Point unclick = ((MouseEvent) cause).getPosition(Button.this); int dx = click.x - unclick.x; int dy = click.y - unclick.y; double tol = Button.this.getStyle().getSelf().get(org.muis.base.style.ButtonStyles.clickTolerance); if(dx > tol || dy > tol) return; double dist2 = dx * dx + dy * dy; if(dist2 > tol * tol) return; org.muis.core.model.MuisActionListener listener = atts().get(ModelAttributes.action); if(listener == null) return; try { listener.actionPerformed((MouseEvent) cause); } catch(RuntimeException e) { msg().error("Action listener threw exception", e); } } }); addListener(MuisConstants.Events.ATTRIBUTE_CHANGED, new AttributeChangedListener<MuisLayout>(LAYOUT_ATTR) { @Override public void attributeChanged(AttributeChangedEvent<MuisLayout> event) { if(theLayoutCallbackLock) return; theLayoutCallbackLock = true; try { getContentPane().atts().set(LAYOUT_ATTR, event.getValue()); } catch(MuisException e) { throw new IllegalStateException(LAYOUT_ATTR + " not accepted by content pane?", e); } finally { theLayoutCallbackLock = false; } } }); MuisLayout layout = atts().get(LAYOUT_ATTR); if(layout != null) try { getContentPane().atts().set(LAYOUT_ATTR, layout); } catch(MuisException e) { throw new IllegalStateException(LAYOUT_ATTR + " not accepted by content pane?", e); } getContentPane().addListener(MuisConstants.Events.ATTRIBUTE_CHANGED, new AttributeChangedListener<MuisLayout>(LAYOUT_ATTR) { @Override public void attributeChanged(AttributeChangedEvent<MuisLayout> event) { if(theLayoutCallbackLock) return; theLayoutCallbackLock = true; try { atts().set(LAYOUT_ATTR, event.getValue()); } catch(MuisException e) { throw new IllegalStateException(LAYOUT_ATTR + " not accepted by button?", e); } finally { theLayoutCallbackLock = false; } } }); } }, MuisConstants.CoreStage.INITIALIZED.toString(), 1); }
public Button() { setFocusable(true); atts().accept(new Object(), LAYOUT_ATTR); atts().accept(new Object(), ModelAttributes.action); life().runWhen(new Runnable() { @Override public void run() { state().addListener(MuisConstants.States.CLICK, new org.muis.core.mgr.StateEngine.StateListener() { private Point theClickLocation; @Override public void entered(MuisState state, MuisEvent<?> cause) { if(cause instanceof MouseEvent) { theClickLocation = ((MouseEvent) cause).getPosition(Button.this); } else theClickLocation = null; } @Override public void exited(MuisState state, MuisEvent<?> cause) { if(theClickLocation == null || !(cause instanceof MouseEvent)) return; Point click = theClickLocation; theClickLocation = null; Point unclick = ((MouseEvent) cause).getPosition(Button.this); int dx = click.x - unclick.x; int dy = click.y - unclick.y; double tol = Button.this.getStyle().getSelf().get(org.muis.base.style.ButtonStyles.clickTolerance); if(dx > tol || dy > tol) return; double dist2 = dx * dx + dy * dy; if(dist2 > tol * tol) return; org.muis.core.model.MuisActionListener listener = atts().get(ModelAttributes.action); if(listener == null) return; try { listener.actionPerformed((MouseEvent) cause); } catch(RuntimeException e) { msg().error("Action listener threw exception", e); } } }); addListener(MuisConstants.Events.ATTRIBUTE_CHANGED, new AttributeChangedListener<MuisLayout>(LAYOUT_ATTR) { @Override public void attributeChanged(AttributeChangedEvent<MuisLayout> event) { if(theLayoutCallbackLock) return; theLayoutCallbackLock = true; try { getContentPane().atts().set(LAYOUT_ATTR, event.getValue()); } catch(MuisException e) { throw new IllegalStateException(LAYOUT_ATTR + " not accepted by content pane?", e); } finally { theLayoutCallbackLock = false; } } }); MuisLayout layout = atts().get(LAYOUT_ATTR); if(layout != null) try { getContentPane().atts().set(LAYOUT_ATTR, layout); } catch(MuisException e) { throw new IllegalStateException(LAYOUT_ATTR + " not accepted by content pane?", e); } getContentPane().addListener(MuisConstants.Events.ATTRIBUTE_CHANGED, new AttributeChangedListener<MuisLayout>(LAYOUT_ATTR) { @Override public void attributeChanged(AttributeChangedEvent<MuisLayout> event) { if(theLayoutCallbackLock) return; theLayoutCallbackLock = true; try { atts().set(LAYOUT_ATTR, event.getValue()); } catch(MuisException e) { throw new IllegalStateException(LAYOUT_ATTR + " not accepted by button?", e); } finally { theLayoutCallbackLock = false; } } }); } }, MuisConstants.CoreStage.INITIALIZED.toString(), 1); }
diff --git a/src/net/slipcor/pvparena/PVPArena.java b/src/net/slipcor/pvparena/PVPArena.java index 06579c36..4e8f332b 100644 --- a/src/net/slipcor/pvparena/PVPArena.java +++ b/src/net/slipcor/pvparena/PVPArena.java @@ -1,338 +1,338 @@ package net.slipcor.pvparena; import java.io.File; import java.io.IOException; import net.slipcor.pvparena.arena.Arena; import net.slipcor.pvparena.arena.ArenaPlayer; import net.slipcor.pvparena.classes.PACheck; import net.slipcor.pvparena.commands.PAA_Edit; import net.slipcor.pvparena.commands.PAA_Reload; import net.slipcor.pvparena.commands.PAA__Command; import net.slipcor.pvparena.commands.PAG_Join; import net.slipcor.pvparena.commands.PAI_Stats; import net.slipcor.pvparena.commands.PA__Command; import net.slipcor.pvparena.core.*; import net.slipcor.pvparena.core.Config.CFG; import net.slipcor.pvparena.core.Language.MSG; import net.slipcor.pvparena.listeners.*; import net.slipcor.pvparena.loadables.*; import net.slipcor.pvparena.managers.ArenaManager; import net.slipcor.pvparena.managers.StatisticsManager; import net.slipcor.pvparena.metrics.Metrics; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; /** * <pre> * Main Plugin class * </pre> * * contains central elements like plugin handlers and listeners * * @author slipcor * * @version v0.10.2 */ public class PVPArena extends JavaPlugin { public static PVPArena instance = null; private final static Debug DEBUG = new Debug(1); private ArenaGoalManager agm = null; private ArenaModuleManager amm = null; private ArenaRegionShapeManager arsm = null; /** * Hand over the ArenaGoalManager instance * * @return the ArenaGoalManager instance */ public ArenaGoalManager getAgm() { return agm; } /** * Hand over the ArenaModuleManager instance * * @return the ArenaModuleManager instance */ public ArenaModuleManager getAmm() { return amm; } /** * Hand over the ArenaRegionShapeManager instance * * @return the ArenaRegionShapeManager instance */ public ArenaRegionShapeManager getArsm() { return arsm; } /** * Check if a CommandSender has admin permissions * * @param sender * the CommandSender to check * @return true if a CommandSender has admin permissions, false otherwise */ public static boolean hasAdminPerms(final CommandSender sender) { return sender.hasPermission("pvparena.admin"); } /** * Check if a CommandSender has creation permissions * * @param sender * the CommandSender to check * @param arena * the arena to check * @return true if the CommandSender has creation permissions, false * otherwise */ public static boolean hasCreatePerms(final CommandSender sender, final Arena arena) { return (sender.hasPermission("pvparena.create") && (arena == null || arena .getOwner().equals(sender.getName()))); } /** * Check if a CommandSender has permission for an arena * * @param sender * the CommandSender to check * @param arena * the arena to check * @return true if explicit permission not needed or granted, false * otherwise */ public static boolean hasPerms(final CommandSender sender, final Arena arena) { DEBUG.i("perm check.", sender); if (arena.getArenaConfig().getBoolean(CFG.PERMS_EXPLICITARENA)) { DEBUG.i(" - explicit: " + (sender.hasPermission("pvparena.join." + arena.getName().toLowerCase())), sender); } else { DEBUG.i(String.valueOf(sender.hasPermission("pvparena.user")), sender); } return arena.getArenaConfig().getBoolean(CFG.PERMS_EXPLICITARENA) ? sender .hasPermission("pvparena.join." + arena.getName().toLowerCase()) : sender.hasPermission("pvparena.user"); } @Override public boolean onCommand(final CommandSender sender, final Command cmd, final String commandLabel, final String[] args) { if (args.length < 1) { sender.sendMessage("�e�l|-- PVP Arena --|"); sender.sendMessage("�e�o--By slipcor--"); sender.sendMessage("�7�oDo �e/pa help �7�ofor help."); return true; } if (args.length > 1 && sender.hasPermission("pvparena.admin") && args[0].equalsIgnoreCase("ALL")) { final String [] newArgs = StringParser.shiftArrayBy(args, 1); for (Arena arena : ArenaManager.getArenas()) { try { Bukkit.getServer().dispatchCommand( sender, "pa " + arena.getName() + " " + StringParser.joinArray(newArgs, " ")); } catch (Exception e) { getLogger().warning("arena null!"); } } return true; } final PA__Command pacmd = PA__Command.getByName(args[0]); if (pacmd != null && !((ArenaPlayer.parsePlayer(sender.getName()).getArena() != null) && (pacmd .getName().contains("PAI_ArenaList")))) { DEBUG.i("committing: " + pacmd.getName(), sender); pacmd.commit(sender, StringParser.shiftArrayBy(args, 1)); return true; } if (args[0].equalsIgnoreCase("-s") || args[0].toLowerCase().contains("stats")) { final PAI_Stats scmd = new PAI_Stats(); DEBUG.i("committing: " + scmd.getName(), sender); scmd.commit(null, sender, new String[0]); return true; } else if (args[0].equalsIgnoreCase("!rl") || args[0].toLowerCase().contains("reload")) { final PAA_Reload scmd = new PAA_Reload(); DEBUG.i("committing: " + scmd.getName(), sender); final String[] emptyArray = new String[0]; for (Arena a : ArenaManager.getArenas()) { scmd.commit(a, sender, emptyArray); } return true; } Arena tempArena = ArenaManager.getArenaByName(args[0]); final String name = args[0]; String[] newArgs = args; if (tempArena == null) { if (sender instanceof Player && ArenaPlayer.parsePlayer(sender.getName()).getArena() != null) { tempArena = ArenaPlayer.parsePlayer(sender.getName()).getArena(); } else if (PAA_Edit.activeEdits.containsKey(sender.getName())) { tempArena = PAA_Edit.activeEdits.get(sender.getName()); } else if (ArenaManager.count() == 1) { tempArena = ArenaManager.getFirst(); } else if (ArenaManager.count() < 1) { Arena.pmsg(sender, Language.parse(MSG.ERROR_NO_ARENAS)); return true; } } else { if (args != null && args.length > 1) { newArgs = StringParser.shiftArrayBy(args, 1); } } if (tempArena == null) { Arena.pmsg(sender, Language.parse(MSG.ERROR_ARENA_NOTFOUND, name)); return true; } - PAA__Command paacmd = PAA__Command.getByName(args[0]); + PAA__Command paacmd = PAA__Command.getByName(newArgs[0]); if (paacmd == null && (PACheck.handleCommand(tempArena, sender, newArgs))) { return true; } if (paacmd == null && tempArena.getArenaConfig().getBoolean(CFG.CMDS_DEFAULTJOIN)) { paacmd = new PAG_Join(); if (newArgs.length > 1) { - newArgs = StringParser.shiftArrayBy(args, 1); + newArgs = StringParser.shiftArrayBy(newArgs, 1); } DEBUG.i("committing: " + paacmd.getName(), sender); paacmd.commit(tempArena, sender, newArgs); return true; } if (paacmd != null) { DEBUG.i("committing: " + paacmd.getName(), sender); paacmd.commit(tempArena, sender, StringParser.shiftArrayBy(newArgs, 1)); return true; } DEBUG.i("cmd null", sender); return false; } @Override public void onDisable() { ArenaManager.reset(true); Tracker.stop(); Language.log_info(MSG.LOG_PLUGIN_DISABLED, getDescription() .getFullName()); } @Override public void onEnable() { instance = this; getDataFolder().mkdir(); new File(getDataFolder().getPath() + "/arenas").mkdir(); new File(getDataFolder().getPath() + "/goals").mkdir(); new File(getDataFolder().getPath() + "/mods").mkdir(); new File(getDataFolder().getPath() + "/regionshapes").mkdir(); new File(getDataFolder().getPath() + "/dumps").mkdir(); new File(getDataFolder().getPath() + "/files").mkdir(); agm = new ArenaGoalManager(this); amm = new ArenaModuleManager(this); arsm = new ArenaRegionShapeManager(this); Language.init(getConfig().getString("language", "en")); Help.init(getConfig().getString("language", "en")); StatisticsManager.initialize(); ArenaPlayer.initiate(); getServer().getPluginManager() .registerEvents(new BlockListener(), this); getServer().getPluginManager().registerEvents(new EntityListener(), this); getServer().getPluginManager().registerEvents(new PlayerListener(), this); getServer().getPluginManager().registerEvents(new InventoryListener(), this); if (getConfig().getInt("ver", 0) < 1) { getConfig().options().copyDefaults(true); getConfig().set("ver", 1); saveConfig(); } Debug.load(this, Bukkit.getConsoleSender()); ArenaManager.load_arenas(); new Update(this); if (ArenaManager.count() > 0) { final Tracker trackMe = new Tracker(this); trackMe.start(); Metrics metrics; try { metrics = new Metrics(this); final Metrics.Graph atg = metrics.createGraph("Game modes installed"); for (ArenaGoal at : agm.getAllGoals()) { atg.addPlotter(new WrapPlotter(at.getName())); } final Metrics.Graph amg = metrics .createGraph("Enhancement modules installed"); for (ArenaModule am : amm.getAllMods()) { amg.addPlotter(new WrapPlotter(am.getName())); } final Metrics.Graph acg = metrics.createGraph("Arena count"); acg.addPlotter(new WrapPlotter("count", ArenaManager .getArenas().size())); metrics.start(); } catch (IOException e) { e.printStackTrace(); } } Language.log_info(MSG.LOG_PLUGIN_ENABLED, getDescription() .getFullName()); } private class WrapPlotter extends Metrics.Plotter { final private int arenaCount; public WrapPlotter(final String name) { super(name); arenaCount = 1; } public WrapPlotter(final String name, final int count) { super(name); arenaCount = count; } public int getValue() { return arenaCount; } } }
false
true
public boolean onCommand(final CommandSender sender, final Command cmd, final String commandLabel, final String[] args) { if (args.length < 1) { sender.sendMessage("�e�l|-- PVP Arena --|"); sender.sendMessage("�e�o--By slipcor--"); sender.sendMessage("�7�oDo �e/pa help �7�ofor help."); return true; } if (args.length > 1 && sender.hasPermission("pvparena.admin") && args[0].equalsIgnoreCase("ALL")) { final String [] newArgs = StringParser.shiftArrayBy(args, 1); for (Arena arena : ArenaManager.getArenas()) { try { Bukkit.getServer().dispatchCommand( sender, "pa " + arena.getName() + " " + StringParser.joinArray(newArgs, " ")); } catch (Exception e) { getLogger().warning("arena null!"); } } return true; } final PA__Command pacmd = PA__Command.getByName(args[0]); if (pacmd != null && !((ArenaPlayer.parsePlayer(sender.getName()).getArena() != null) && (pacmd .getName().contains("PAI_ArenaList")))) { DEBUG.i("committing: " + pacmd.getName(), sender); pacmd.commit(sender, StringParser.shiftArrayBy(args, 1)); return true; } if (args[0].equalsIgnoreCase("-s") || args[0].toLowerCase().contains("stats")) { final PAI_Stats scmd = new PAI_Stats(); DEBUG.i("committing: " + scmd.getName(), sender); scmd.commit(null, sender, new String[0]); return true; } else if (args[0].equalsIgnoreCase("!rl") || args[0].toLowerCase().contains("reload")) { final PAA_Reload scmd = new PAA_Reload(); DEBUG.i("committing: " + scmd.getName(), sender); final String[] emptyArray = new String[0]; for (Arena a : ArenaManager.getArenas()) { scmd.commit(a, sender, emptyArray); } return true; } Arena tempArena = ArenaManager.getArenaByName(args[0]); final String name = args[0]; String[] newArgs = args; if (tempArena == null) { if (sender instanceof Player && ArenaPlayer.parsePlayer(sender.getName()).getArena() != null) { tempArena = ArenaPlayer.parsePlayer(sender.getName()).getArena(); } else if (PAA_Edit.activeEdits.containsKey(sender.getName())) { tempArena = PAA_Edit.activeEdits.get(sender.getName()); } else if (ArenaManager.count() == 1) { tempArena = ArenaManager.getFirst(); } else if (ArenaManager.count() < 1) { Arena.pmsg(sender, Language.parse(MSG.ERROR_NO_ARENAS)); return true; } } else { if (args != null && args.length > 1) { newArgs = StringParser.shiftArrayBy(args, 1); } } if (tempArena == null) { Arena.pmsg(sender, Language.parse(MSG.ERROR_ARENA_NOTFOUND, name)); return true; } PAA__Command paacmd = PAA__Command.getByName(args[0]); if (paacmd == null && (PACheck.handleCommand(tempArena, sender, newArgs))) { return true; } if (paacmd == null && tempArena.getArenaConfig().getBoolean(CFG.CMDS_DEFAULTJOIN)) { paacmd = new PAG_Join(); if (newArgs.length > 1) { newArgs = StringParser.shiftArrayBy(args, 1); } DEBUG.i("committing: " + paacmd.getName(), sender); paacmd.commit(tempArena, sender, newArgs); return true; } if (paacmd != null) { DEBUG.i("committing: " + paacmd.getName(), sender); paacmd.commit(tempArena, sender, StringParser.shiftArrayBy(newArgs, 1)); return true; } DEBUG.i("cmd null", sender); return false; }
public boolean onCommand(final CommandSender sender, final Command cmd, final String commandLabel, final String[] args) { if (args.length < 1) { sender.sendMessage("�e�l|-- PVP Arena --|"); sender.sendMessage("�e�o--By slipcor--"); sender.sendMessage("�7�oDo �e/pa help �7�ofor help."); return true; } if (args.length > 1 && sender.hasPermission("pvparena.admin") && args[0].equalsIgnoreCase("ALL")) { final String [] newArgs = StringParser.shiftArrayBy(args, 1); for (Arena arena : ArenaManager.getArenas()) { try { Bukkit.getServer().dispatchCommand( sender, "pa " + arena.getName() + " " + StringParser.joinArray(newArgs, " ")); } catch (Exception e) { getLogger().warning("arena null!"); } } return true; } final PA__Command pacmd = PA__Command.getByName(args[0]); if (pacmd != null && !((ArenaPlayer.parsePlayer(sender.getName()).getArena() != null) && (pacmd .getName().contains("PAI_ArenaList")))) { DEBUG.i("committing: " + pacmd.getName(), sender); pacmd.commit(sender, StringParser.shiftArrayBy(args, 1)); return true; } if (args[0].equalsIgnoreCase("-s") || args[0].toLowerCase().contains("stats")) { final PAI_Stats scmd = new PAI_Stats(); DEBUG.i("committing: " + scmd.getName(), sender); scmd.commit(null, sender, new String[0]); return true; } else if (args[0].equalsIgnoreCase("!rl") || args[0].toLowerCase().contains("reload")) { final PAA_Reload scmd = new PAA_Reload(); DEBUG.i("committing: " + scmd.getName(), sender); final String[] emptyArray = new String[0]; for (Arena a : ArenaManager.getArenas()) { scmd.commit(a, sender, emptyArray); } return true; } Arena tempArena = ArenaManager.getArenaByName(args[0]); final String name = args[0]; String[] newArgs = args; if (tempArena == null) { if (sender instanceof Player && ArenaPlayer.parsePlayer(sender.getName()).getArena() != null) { tempArena = ArenaPlayer.parsePlayer(sender.getName()).getArena(); } else if (PAA_Edit.activeEdits.containsKey(sender.getName())) { tempArena = PAA_Edit.activeEdits.get(sender.getName()); } else if (ArenaManager.count() == 1) { tempArena = ArenaManager.getFirst(); } else if (ArenaManager.count() < 1) { Arena.pmsg(sender, Language.parse(MSG.ERROR_NO_ARENAS)); return true; } } else { if (args != null && args.length > 1) { newArgs = StringParser.shiftArrayBy(args, 1); } } if (tempArena == null) { Arena.pmsg(sender, Language.parse(MSG.ERROR_ARENA_NOTFOUND, name)); return true; } PAA__Command paacmd = PAA__Command.getByName(newArgs[0]); if (paacmd == null && (PACheck.handleCommand(tempArena, sender, newArgs))) { return true; } if (paacmd == null && tempArena.getArenaConfig().getBoolean(CFG.CMDS_DEFAULTJOIN)) { paacmd = new PAG_Join(); if (newArgs.length > 1) { newArgs = StringParser.shiftArrayBy(newArgs, 1); } DEBUG.i("committing: " + paacmd.getName(), sender); paacmd.commit(tempArena, sender, newArgs); return true; } if (paacmd != null) { DEBUG.i("committing: " + paacmd.getName(), sender); paacmd.commit(tempArena, sender, StringParser.shiftArrayBy(newArgs, 1)); return true; } DEBUG.i("cmd null", sender); return false; }
diff --git a/mcu/src/org/smbarbour/mcu/NativeLauncherThread.java b/mcu/src/org/smbarbour/mcu/NativeLauncherThread.java index 0f88926..d409905 100644 --- a/mcu/src/org/smbarbour/mcu/NativeLauncherThread.java +++ b/mcu/src/org/smbarbour/mcu/NativeLauncherThread.java @@ -1,222 +1,223 @@ package org.smbarbour.mcu; import java.awt.MenuItem; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import javax.swing.JButton; import javax.swing.JOptionPane; import org.smbarbour.mcu.util.MCUpdater; public class NativeLauncherThread implements Runnable { private MainForm parent; private String jrePath; private String minMem; private String maxMem; private File output; private ConsoleArea console; private Thread thread; private Process task; private MenuItem killItem; private boolean forceKilled = false; private LoginData session; private boolean ready; private JButton launchButton; public NativeLauncherThread(MainForm parent, LoginData session, String jrePath, String minMem, String maxMem, File output) { this.parent = parent; this.session = session; this.jrePath = jrePath; this.minMem = minMem; this.maxMem = maxMem; this.output = output; } public static NativeLauncherThread launch(MainForm parent, LoginData session, String jrePath, String minMem, String maxMem, File output, ConsoleArea console) { NativeLauncherThread me = new NativeLauncherThread(parent, session, jrePath, minMem, maxMem, output); me.console = console; console.setText(""); return me; } public void start() { thread = new Thread(this); thread.start(); } public void stop() { if( task != null ) { final int confirm = JOptionPane.showConfirmDialog(null, "Are you sure you want to kill Minecraft?\nThis could result in corrupted world save data.", "Kill Minecraft", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE ); if( confirm == JOptionPane.YES_OPTION ) { forceKilled = true; try { task.destroy(); } catch( Exception e ) { // maximum paranoia here e.printStackTrace(); } } } } private void log(String msg) { if( console == null ) return; console.log(msg); } @Override public void run() { String javaBin = "java"; File binDir = new File(jrePath+MCUpdater.sep+"bin"); if( binDir.exists() ) { javaBin = binDir + MCUpdater.sep + "java"; } StringBuilder sbClassPath = new StringBuilder(); String mcBinPath = parent.mcu.getMCFolder() + MCUpdater.sep + "bin" + MCUpdater.sep; - sbClassPath.append(MCUpdater.cpDelimiter() + mcBinPath + "minecraft.jar"); + sbClassPath.append(mcBinPath + "minecraft.jar"); sbClassPath.append(MCUpdater.cpDelimiter() + mcBinPath + "lwjgl.jar"); sbClassPath.append(MCUpdater.cpDelimiter() + mcBinPath + "lwjgl_util.jar"); sbClassPath.append(MCUpdater.cpDelimiter() + mcBinPath + "jinput.jar"); - String jlp = "-Djava.library.path=\"" + binDir + MCUpdater.sep + "natives\""; + String jlp = "-Djava.library.path=\"" + mcBinPath + MCUpdater.sep + "natives\""; String className = "net.minecraft.client.Minecraft"; List<String> args = new ArrayList<String>(); args.add(javaBin); args.add("-XX:+UseConcMarkSweepGC"); args.add("-XX:+CMSIncrementalMode"); args.add("-XX:+AggressiveOpts"); - args.add("-Xms=" + this.minMem); - args.add("-Xmx=" + this.maxMem); - args.add("-cp " + sbClassPath.toString()); + args.add("-Xms" + this.minMem); + args.add("-Xmx" + this.maxMem); + args.add("-cp"); + args.add(sbClassPath.toString()); args.add(jlp); args.add(className); args.add(session.getUserName()); args.add(session.getSessionId()); ProcessBuilder pb = new ProcessBuilder(args); pb.redirectErrorStream(true); BufferedWriter buffWrite = null; try { buffWrite = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output))); } catch (FileNotFoundException e) { log(e.getMessage()+"\n"); e.printStackTrace(); } try { task = pb.start(); BufferedReader buffRead = new BufferedReader(new InputStreamReader(task.getInputStream())); String line; buffRead.mark(1024); final String firstLine = buffRead.readLine(); setReady(); if (firstLine == null || firstLine.startsWith("Error occurred during initialization of VM") || firstLine.startsWith("Could not create the Java virtual machine.")) { log("!!! Failure to launch detected.\n"); // fetch the whole error message StringBuilder err = new StringBuilder(firstLine); while ((line = buffRead.readLine()) != null) { err.append('\n'); err.append(line); } log(err+"\n"); JOptionPane.showMessageDialog(null, err); } else { buffRead.reset(); minimizeFrame(); log("* Launching client...\n"); int counter = 0; while ((line = buffRead.readLine()) != null) { if (buffWrite != null) { buffWrite.write(line); buffWrite.newLine(); counter++; if (counter >= 20) { buffWrite.flush(); counter = 0; } } else { System.out.println(line); } if( line.length() > 0) { log(line+"\n"); } } } buffWrite.flush(); buffWrite.close(); restoreFrame(); log("* Exiting Minecraft"+(forceKilled?" (killed)":"")+"\n"); } catch (IOException ioe) { ioe.printStackTrace(); } } private void restoreFrame() { parent.restore(); toggleKillable(false); } private void minimizeFrame() { parent.minimize(true); toggleKillable(true); } private void setReady() { ready = true; if(launchButton != null) { launchButton.setEnabled(true); } } public void register(JButton btnLaunchMinecraft, MenuItem killItem) { launchButton = btnLaunchMinecraft; this.killItem = killItem; if( ready ) { setReady(); } } private void toggleKillable(boolean enabled) { if( killItem == null ) return; killItem.setEnabled(enabled); if( enabled ) { final NativeLauncherThread thread = this; killItem.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { thread.stop(); } }); } else { for( ActionListener listener : killItem.getActionListeners() ) { killItem.removeActionListener(listener); } killItem = null; } } }
false
true
public void run() { String javaBin = "java"; File binDir = new File(jrePath+MCUpdater.sep+"bin"); if( binDir.exists() ) { javaBin = binDir + MCUpdater.sep + "java"; } StringBuilder sbClassPath = new StringBuilder(); String mcBinPath = parent.mcu.getMCFolder() + MCUpdater.sep + "bin" + MCUpdater.sep; sbClassPath.append(MCUpdater.cpDelimiter() + mcBinPath + "minecraft.jar"); sbClassPath.append(MCUpdater.cpDelimiter() + mcBinPath + "lwjgl.jar"); sbClassPath.append(MCUpdater.cpDelimiter() + mcBinPath + "lwjgl_util.jar"); sbClassPath.append(MCUpdater.cpDelimiter() + mcBinPath + "jinput.jar"); String jlp = "-Djava.library.path=\"" + binDir + MCUpdater.sep + "natives\""; String className = "net.minecraft.client.Minecraft"; List<String> args = new ArrayList<String>(); args.add(javaBin); args.add("-XX:+UseConcMarkSweepGC"); args.add("-XX:+CMSIncrementalMode"); args.add("-XX:+AggressiveOpts"); args.add("-Xms=" + this.minMem); args.add("-Xmx=" + this.maxMem); args.add("-cp " + sbClassPath.toString()); args.add(jlp); args.add(className); args.add(session.getUserName()); args.add(session.getSessionId()); ProcessBuilder pb = new ProcessBuilder(args); pb.redirectErrorStream(true); BufferedWriter buffWrite = null; try { buffWrite = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output))); } catch (FileNotFoundException e) { log(e.getMessage()+"\n"); e.printStackTrace(); } try { task = pb.start(); BufferedReader buffRead = new BufferedReader(new InputStreamReader(task.getInputStream())); String line; buffRead.mark(1024); final String firstLine = buffRead.readLine(); setReady(); if (firstLine == null || firstLine.startsWith("Error occurred during initialization of VM") || firstLine.startsWith("Could not create the Java virtual machine.")) { log("!!! Failure to launch detected.\n"); // fetch the whole error message StringBuilder err = new StringBuilder(firstLine); while ((line = buffRead.readLine()) != null) { err.append('\n'); err.append(line); } log(err+"\n"); JOptionPane.showMessageDialog(null, err); } else { buffRead.reset(); minimizeFrame(); log("* Launching client...\n"); int counter = 0; while ((line = buffRead.readLine()) != null) { if (buffWrite != null) { buffWrite.write(line); buffWrite.newLine(); counter++; if (counter >= 20) { buffWrite.flush(); counter = 0; } } else { System.out.println(line); } if( line.length() > 0) { log(line+"\n"); } } } buffWrite.flush(); buffWrite.close(); restoreFrame(); log("* Exiting Minecraft"+(forceKilled?" (killed)":"")+"\n"); } catch (IOException ioe) { ioe.printStackTrace(); } }
public void run() { String javaBin = "java"; File binDir = new File(jrePath+MCUpdater.sep+"bin"); if( binDir.exists() ) { javaBin = binDir + MCUpdater.sep + "java"; } StringBuilder sbClassPath = new StringBuilder(); String mcBinPath = parent.mcu.getMCFolder() + MCUpdater.sep + "bin" + MCUpdater.sep; sbClassPath.append(mcBinPath + "minecraft.jar"); sbClassPath.append(MCUpdater.cpDelimiter() + mcBinPath + "lwjgl.jar"); sbClassPath.append(MCUpdater.cpDelimiter() + mcBinPath + "lwjgl_util.jar"); sbClassPath.append(MCUpdater.cpDelimiter() + mcBinPath + "jinput.jar"); String jlp = "-Djava.library.path=\"" + mcBinPath + MCUpdater.sep + "natives\""; String className = "net.minecraft.client.Minecraft"; List<String> args = new ArrayList<String>(); args.add(javaBin); args.add("-XX:+UseConcMarkSweepGC"); args.add("-XX:+CMSIncrementalMode"); args.add("-XX:+AggressiveOpts"); args.add("-Xms" + this.minMem); args.add("-Xmx" + this.maxMem); args.add("-cp"); args.add(sbClassPath.toString()); args.add(jlp); args.add(className); args.add(session.getUserName()); args.add(session.getSessionId()); ProcessBuilder pb = new ProcessBuilder(args); pb.redirectErrorStream(true); BufferedWriter buffWrite = null; try { buffWrite = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output))); } catch (FileNotFoundException e) { log(e.getMessage()+"\n"); e.printStackTrace(); } try { task = pb.start(); BufferedReader buffRead = new BufferedReader(new InputStreamReader(task.getInputStream())); String line; buffRead.mark(1024); final String firstLine = buffRead.readLine(); setReady(); if (firstLine == null || firstLine.startsWith("Error occurred during initialization of VM") || firstLine.startsWith("Could not create the Java virtual machine.")) { log("!!! Failure to launch detected.\n"); // fetch the whole error message StringBuilder err = new StringBuilder(firstLine); while ((line = buffRead.readLine()) != null) { err.append('\n'); err.append(line); } log(err+"\n"); JOptionPane.showMessageDialog(null, err); } else { buffRead.reset(); minimizeFrame(); log("* Launching client...\n"); int counter = 0; while ((line = buffRead.readLine()) != null) { if (buffWrite != null) { buffWrite.write(line); buffWrite.newLine(); counter++; if (counter >= 20) { buffWrite.flush(); counter = 0; } } else { System.out.println(line); } if( line.length() > 0) { log(line+"\n"); } } } buffWrite.flush(); buffWrite.close(); restoreFrame(); log("* Exiting Minecraft"+(forceKilled?" (killed)":"")+"\n"); } catch (IOException ioe) { ioe.printStackTrace(); } }
diff --git a/src/main/java/com/github/rnewson/couchdb/lucene/SearchServlet.java b/src/main/java/com/github/rnewson/couchdb/lucene/SearchServlet.java index 3352e4d..2b7ca8a 100644 --- a/src/main/java/com/github/rnewson/couchdb/lucene/SearchServlet.java +++ b/src/main/java/com/github/rnewson/couchdb/lucene/SearchServlet.java @@ -1,320 +1,320 @@ package com.github.rnewson.couchdb.lucene; import static com.github.rnewson.couchdb.lucene.ServletUtils.getBooleanParameter; import static com.github.rnewson.couchdb.lucene.ServletUtils.getIntParameter; import static com.github.rnewson.couchdb.lucene.ServletUtils.getParameter; import static java.lang.Math.max; import static java.lang.Math.min; import java.io.IOException; import java.io.Writer; import java.util.HashSet; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.Term; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.FieldDoc; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.TopFieldDocs; import com.github.rnewson.couchdb.lucene.LuceneGateway.SearcherCallback; import com.github.rnewson.couchdb.lucene.util.Analyzers; import com.github.rnewson.couchdb.lucene.util.StopWatch; /** * Perform queries against local indexes. * * @author rnewson * */ public final class SearchServlet extends HttpServlet { private static final long serialVersionUID = 1L; private final State state; SearchServlet(final State state) { this.state = state; } @Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { if (req.getParameter("q") == null) { resp.sendError(400, "Missing q attribute."); return; } final ViewSignature sig = state.locator.lookup(req); if (sig == null) { - resp.sendError(400, "Invalid path."); + resp.sendError(400, "Unknown index."); return; } final boolean staleOk = "ok".equals(req.getParameter("stale")); final boolean debug = getBooleanParameter(req, "debug"); final boolean rewrite_query = getBooleanParameter(req, "rewrite_query"); final String body = state.lucene.withSearcher(sig, staleOk, new SearcherCallback<String>() { public String callback(final IndexSearcher searcher, final String etag) throws IOException { // Check for 304 - Not Modified. if (!debug && etag.equals(req.getHeader("If-None-Match"))) { resp.setStatus(304); return null; } // Parse query. final Analyzer analyzer = Analyzers.getAnalyzer(getParameter(req, "analyzer", "standard")); final QueryParser parser = new QueryParser(Constants.DEFAULT_FIELD, analyzer); final Query q; try { q = parser.parse(req.getParameter("q")); } catch (final ParseException e) { resp.sendError(400, "Bad query syntax."); return null; } final JSONObject json = new JSONObject(); json.put("q", q.toString()); json.put("etag", etag); if (rewrite_query) { final Query rewritten_q = q.rewrite(searcher.getIndexReader()); json.put("rewritten_q", rewritten_q.toString()); final JSONObject freqs = new JSONObject(); final Set<Term> terms = new HashSet<Term>(); rewritten_q.extractTerms(terms); for (final Object term : terms) { final int freq = searcher.docFreq((Term) term); freqs.put(term, freq); } json.put("freqs", freqs); } else { // Perform the search. final TopDocs td; final StopWatch stopWatch = new StopWatch(); final boolean include_docs = getBooleanParameter(req, "include_docs"); final int limit = getIntParameter(req, "limit", 25); final Sort sort = toSort(req.getParameter("sort")); final int skip = getIntParameter(req, "skip", 0); if (sort == null) { td = searcher.search(q, null, skip + limit); } else { td = searcher.search(q, null, skip + limit, sort); } stopWatch.lap("search"); // Fetch matches (if any). final int max = max(0, min(td.totalHits - skip, limit)); final JSONArray rows = new JSONArray(); final String[] fetch_ids = new String[max]; for (int i = skip; i < skip + max; i++) { final Document doc = searcher.doc(td.scoreDocs[i].doc); final JSONObject row = new JSONObject(); final JSONObject fields = new JSONObject(); // Include stored fields. for (Object f : doc.getFields()) { Field fld = (Field) f; if (!fld.isStored()) continue; String name = fld.name(); String value = fld.stringValue(); if (value != null) { if ("_id".equals(name)) { row.put("id", value); } else { if (!fields.has(name)) { fields.put(name, value); } else { final Object obj = fields.get(name); if (obj instanceof String) { final JSONArray arr = new JSONArray(); arr.add((String) obj); arr.add(value); fields.put(name, arr); } else { assert obj instanceof JSONArray; ((JSONArray) obj).add(value); } } } } } if (!Float.isNaN(td.scoreDocs[i].score)) { row.put("score", td.scoreDocs[i].score); } // Include sort order (if any). if (td instanceof TopFieldDocs) { final FieldDoc fd = (FieldDoc) ((TopFieldDocs) td).scoreDocs[i]; row.put("sort_order", fd.fields); } // Fetch document (if requested). if (include_docs) { fetch_ids[i - skip] = doc.get("_id"); } if (fields.size() > 0) { row.put("fields", fields); } rows.add(row); } // Fetch documents (if requested). if (include_docs && fetch_ids.length > 0) { final JSONArray fetched_docs = state.couch.getDocs(sig.getDatabaseName(), fetch_ids).getJSONArray("rows"); for (int i = 0; i < max; i++) { rows.getJSONObject(i).put("doc", fetched_docs.getJSONObject(i).getJSONObject("doc")); } } stopWatch.lap("fetch"); json.put("skip", skip); json.put("limit", limit); json.put("total_rows", td.totalHits); json.put("search_duration", stopWatch.getElapsed("search")); json.put("fetch_duration", stopWatch.getElapsed("fetch")); // Include sort info (if requested). if (td instanceof TopFieldDocs) { json.put("sort_order", SearchServlet.toString(((TopFieldDocs) td).fields)); } json.put("rows", rows); } Utils.setResponseContentTypeAndEncoding(req, resp); // Cache-related headers. resp.setHeader("ETag", etag); resp.setHeader("Cache-Control", "must-revalidate"); // Format response body. final String callback = req.getParameter("callback"); if (callback != null) { return String.format("%s(%s)", callback, json); } else { return json.toString(debug ? 2 : 0); } } }); // Write response if we have one. if (body != null) { final Writer writer = resp.getWriter(); try { writer.write(body); } finally { writer.close(); } } } private static Sort toSort(final String sort) { if (sort == null) { return null; } else { final String[] split = sort.split(","); final SortField[] sort_fields = new SortField[split.length]; for (int i = 0; i < split.length; i++) { String tmp = split[i]; final boolean reverse = tmp.charAt(0) == '\\'; // Strip sort order character. if (tmp.charAt(0) == '\\' || tmp.charAt(0) == '/') { tmp = tmp.substring(1); } final boolean has_type = tmp.indexOf(':') != -1; if (!has_type) { sort_fields[i] = new SortField(tmp, SortField.STRING, reverse); } else { final String field = tmp.substring(0, tmp.indexOf(':')); final String type = tmp.substring(tmp.indexOf(':') + 1); int type_int = SortField.STRING; if ("int".equals(type)) { type_int = SortField.INT; } else if ("float".equals(type)) { type_int = SortField.FLOAT; } else if ("double".equals(type)) { type_int = SortField.DOUBLE; } else if ("long".equals(type)) { type_int = SortField.LONG; } else if ("date".equals(type)) { type_int = SortField.LONG; } else if ("string".equals(type)) { type_int = SortField.STRING; } sort_fields[i] = new SortField(field, type_int, reverse); } } return new Sort(sort_fields); } } private static String toString(final SortField[] sortFields) { final JSONArray result = new JSONArray(); for (final SortField field : sortFields) { final JSONObject col = new JSONObject(); col.element("field", field.getField()); col.element("reverse", field.getReverse()); final String type; switch (field.getType()) { case SortField.DOC: type = "doc"; break; case SortField.SCORE: type = "score"; break; case SortField.INT: type = "int"; break; case SortField.LONG: type = "long"; break; case SortField.BYTE: type = "byte"; break; case SortField.CUSTOM: type = "custom"; break; case SortField.DOUBLE: type = "double"; break; case SortField.FLOAT: type = "float"; break; case SortField.SHORT: type = "short"; break; case SortField.STRING: type = "string"; break; default: type = "unknown"; break; } col.element("type", type); result.add(col); } return result.toString(); } }
true
true
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { if (req.getParameter("q") == null) { resp.sendError(400, "Missing q attribute."); return; } final ViewSignature sig = state.locator.lookup(req); if (sig == null) { resp.sendError(400, "Invalid path."); return; } final boolean staleOk = "ok".equals(req.getParameter("stale")); final boolean debug = getBooleanParameter(req, "debug"); final boolean rewrite_query = getBooleanParameter(req, "rewrite_query"); final String body = state.lucene.withSearcher(sig, staleOk, new SearcherCallback<String>() { public String callback(final IndexSearcher searcher, final String etag) throws IOException { // Check for 304 - Not Modified. if (!debug && etag.equals(req.getHeader("If-None-Match"))) { resp.setStatus(304); return null; } // Parse query. final Analyzer analyzer = Analyzers.getAnalyzer(getParameter(req, "analyzer", "standard")); final QueryParser parser = new QueryParser(Constants.DEFAULT_FIELD, analyzer); final Query q; try { q = parser.parse(req.getParameter("q")); } catch (final ParseException e) { resp.sendError(400, "Bad query syntax."); return null; } final JSONObject json = new JSONObject(); json.put("q", q.toString()); json.put("etag", etag); if (rewrite_query) { final Query rewritten_q = q.rewrite(searcher.getIndexReader()); json.put("rewritten_q", rewritten_q.toString()); final JSONObject freqs = new JSONObject(); final Set<Term> terms = new HashSet<Term>(); rewritten_q.extractTerms(terms); for (final Object term : terms) { final int freq = searcher.docFreq((Term) term); freqs.put(term, freq); } json.put("freqs", freqs); } else { // Perform the search. final TopDocs td; final StopWatch stopWatch = new StopWatch(); final boolean include_docs = getBooleanParameter(req, "include_docs"); final int limit = getIntParameter(req, "limit", 25); final Sort sort = toSort(req.getParameter("sort")); final int skip = getIntParameter(req, "skip", 0); if (sort == null) { td = searcher.search(q, null, skip + limit); } else { td = searcher.search(q, null, skip + limit, sort); } stopWatch.lap("search"); // Fetch matches (if any). final int max = max(0, min(td.totalHits - skip, limit)); final JSONArray rows = new JSONArray(); final String[] fetch_ids = new String[max]; for (int i = skip; i < skip + max; i++) { final Document doc = searcher.doc(td.scoreDocs[i].doc); final JSONObject row = new JSONObject(); final JSONObject fields = new JSONObject(); // Include stored fields. for (Object f : doc.getFields()) { Field fld = (Field) f; if (!fld.isStored()) continue; String name = fld.name(); String value = fld.stringValue(); if (value != null) { if ("_id".equals(name)) { row.put("id", value); } else { if (!fields.has(name)) { fields.put(name, value); } else { final Object obj = fields.get(name); if (obj instanceof String) { final JSONArray arr = new JSONArray(); arr.add((String) obj); arr.add(value); fields.put(name, arr); } else { assert obj instanceof JSONArray; ((JSONArray) obj).add(value); } } } } } if (!Float.isNaN(td.scoreDocs[i].score)) { row.put("score", td.scoreDocs[i].score); } // Include sort order (if any). if (td instanceof TopFieldDocs) { final FieldDoc fd = (FieldDoc) ((TopFieldDocs) td).scoreDocs[i]; row.put("sort_order", fd.fields); } // Fetch document (if requested). if (include_docs) { fetch_ids[i - skip] = doc.get("_id"); } if (fields.size() > 0) { row.put("fields", fields); } rows.add(row); } // Fetch documents (if requested). if (include_docs && fetch_ids.length > 0) { final JSONArray fetched_docs = state.couch.getDocs(sig.getDatabaseName(), fetch_ids).getJSONArray("rows"); for (int i = 0; i < max; i++) { rows.getJSONObject(i).put("doc", fetched_docs.getJSONObject(i).getJSONObject("doc")); } } stopWatch.lap("fetch"); json.put("skip", skip); json.put("limit", limit); json.put("total_rows", td.totalHits); json.put("search_duration", stopWatch.getElapsed("search")); json.put("fetch_duration", stopWatch.getElapsed("fetch")); // Include sort info (if requested). if (td instanceof TopFieldDocs) { json.put("sort_order", SearchServlet.toString(((TopFieldDocs) td).fields)); } json.put("rows", rows); } Utils.setResponseContentTypeAndEncoding(req, resp); // Cache-related headers. resp.setHeader("ETag", etag); resp.setHeader("Cache-Control", "must-revalidate"); // Format response body. final String callback = req.getParameter("callback"); if (callback != null) { return String.format("%s(%s)", callback, json); } else { return json.toString(debug ? 2 : 0); } } }); // Write response if we have one. if (body != null) { final Writer writer = resp.getWriter(); try { writer.write(body); } finally { writer.close(); } } }
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { if (req.getParameter("q") == null) { resp.sendError(400, "Missing q attribute."); return; } final ViewSignature sig = state.locator.lookup(req); if (sig == null) { resp.sendError(400, "Unknown index."); return; } final boolean staleOk = "ok".equals(req.getParameter("stale")); final boolean debug = getBooleanParameter(req, "debug"); final boolean rewrite_query = getBooleanParameter(req, "rewrite_query"); final String body = state.lucene.withSearcher(sig, staleOk, new SearcherCallback<String>() { public String callback(final IndexSearcher searcher, final String etag) throws IOException { // Check for 304 - Not Modified. if (!debug && etag.equals(req.getHeader("If-None-Match"))) { resp.setStatus(304); return null; } // Parse query. final Analyzer analyzer = Analyzers.getAnalyzer(getParameter(req, "analyzer", "standard")); final QueryParser parser = new QueryParser(Constants.DEFAULT_FIELD, analyzer); final Query q; try { q = parser.parse(req.getParameter("q")); } catch (final ParseException e) { resp.sendError(400, "Bad query syntax."); return null; } final JSONObject json = new JSONObject(); json.put("q", q.toString()); json.put("etag", etag); if (rewrite_query) { final Query rewritten_q = q.rewrite(searcher.getIndexReader()); json.put("rewritten_q", rewritten_q.toString()); final JSONObject freqs = new JSONObject(); final Set<Term> terms = new HashSet<Term>(); rewritten_q.extractTerms(terms); for (final Object term : terms) { final int freq = searcher.docFreq((Term) term); freqs.put(term, freq); } json.put("freqs", freqs); } else { // Perform the search. final TopDocs td; final StopWatch stopWatch = new StopWatch(); final boolean include_docs = getBooleanParameter(req, "include_docs"); final int limit = getIntParameter(req, "limit", 25); final Sort sort = toSort(req.getParameter("sort")); final int skip = getIntParameter(req, "skip", 0); if (sort == null) { td = searcher.search(q, null, skip + limit); } else { td = searcher.search(q, null, skip + limit, sort); } stopWatch.lap("search"); // Fetch matches (if any). final int max = max(0, min(td.totalHits - skip, limit)); final JSONArray rows = new JSONArray(); final String[] fetch_ids = new String[max]; for (int i = skip; i < skip + max; i++) { final Document doc = searcher.doc(td.scoreDocs[i].doc); final JSONObject row = new JSONObject(); final JSONObject fields = new JSONObject(); // Include stored fields. for (Object f : doc.getFields()) { Field fld = (Field) f; if (!fld.isStored()) continue; String name = fld.name(); String value = fld.stringValue(); if (value != null) { if ("_id".equals(name)) { row.put("id", value); } else { if (!fields.has(name)) { fields.put(name, value); } else { final Object obj = fields.get(name); if (obj instanceof String) { final JSONArray arr = new JSONArray(); arr.add((String) obj); arr.add(value); fields.put(name, arr); } else { assert obj instanceof JSONArray; ((JSONArray) obj).add(value); } } } } } if (!Float.isNaN(td.scoreDocs[i].score)) { row.put("score", td.scoreDocs[i].score); } // Include sort order (if any). if (td instanceof TopFieldDocs) { final FieldDoc fd = (FieldDoc) ((TopFieldDocs) td).scoreDocs[i]; row.put("sort_order", fd.fields); } // Fetch document (if requested). if (include_docs) { fetch_ids[i - skip] = doc.get("_id"); } if (fields.size() > 0) { row.put("fields", fields); } rows.add(row); } // Fetch documents (if requested). if (include_docs && fetch_ids.length > 0) { final JSONArray fetched_docs = state.couch.getDocs(sig.getDatabaseName(), fetch_ids).getJSONArray("rows"); for (int i = 0; i < max; i++) { rows.getJSONObject(i).put("doc", fetched_docs.getJSONObject(i).getJSONObject("doc")); } } stopWatch.lap("fetch"); json.put("skip", skip); json.put("limit", limit); json.put("total_rows", td.totalHits); json.put("search_duration", stopWatch.getElapsed("search")); json.put("fetch_duration", stopWatch.getElapsed("fetch")); // Include sort info (if requested). if (td instanceof TopFieldDocs) { json.put("sort_order", SearchServlet.toString(((TopFieldDocs) td).fields)); } json.put("rows", rows); } Utils.setResponseContentTypeAndEncoding(req, resp); // Cache-related headers. resp.setHeader("ETag", etag); resp.setHeader("Cache-Control", "must-revalidate"); // Format response body. final String callback = req.getParameter("callback"); if (callback != null) { return String.format("%s(%s)", callback, json); } else { return json.toString(debug ? 2 : 0); } } }); // Write response if we have one. if (body != null) { final Writer writer = resp.getWriter(); try { writer.write(body); } finally { writer.close(); } } }
diff --git a/org.eclipse.mylyn.resources.ui/src/org/eclipse/mylyn/internal/resources/ui/ResourceInteractionMonitor.java b/org.eclipse.mylyn.resources.ui/src/org/eclipse/mylyn/internal/resources/ui/ResourceInteractionMonitor.java index e7892e93f..235bc7a99 100644 --- a/org.eclipse.mylyn.resources.ui/src/org/eclipse/mylyn/internal/resources/ui/ResourceInteractionMonitor.java +++ b/org.eclipse.mylyn.resources.ui/src/org/eclipse/mylyn/internal/resources/ui/ResourceInteractionMonitor.java @@ -1,56 +1,56 @@ /******************************************************************************* * Copyright (c) 2004, 2007 Mylyn project committers and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ /* * Created on Apr 20, 2005 */ package org.eclipse.mylyn.internal.resources.ui; import org.eclipse.core.internal.resources.File; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.mylyn.context.core.ContextCorePlugin; import org.eclipse.mylyn.monitor.core.StatusHandler; import org.eclipse.mylyn.monitor.ui.AbstractUserInteractionMonitor; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.part.EditorPart; /** * @author Mik Kersten */ public class ResourceInteractionMonitor extends AbstractUserInteractionMonitor { @Override protected void handleWorkbenchPartSelection(IWorkbenchPart part, ISelection selection, boolean contributeToContext) { if (selection instanceof StructuredSelection) { StructuredSelection structuredSelection = (StructuredSelection) selection; Object selectedObject = structuredSelection.getFirstElement(); if (selectedObject instanceof File) { File file = (File) selectedObject; super.handleElementSelection(part, file, contributeToContext); } } else if (selection instanceof TextSelection) { if (part instanceof EditorPart) { try { Object object = ((EditorPart) part).getEditorInput().getAdapter(IResource.class); if (object instanceof IFile) { IFile file = (IFile) object; - if (!ContextCorePlugin.getDefault().getKnownContentTypes().contains(file.getFileExtension())) { + if (file.getFileExtension() != null && !ContextCorePlugin.getDefault().getKnownContentTypes().contains(file.getFileExtension())) { super.handleElementEdit(part, object, contributeToContext); } } } catch (Throwable t) { StatusHandler.log(t, "failed to resolve resource edit"); } } } } }
true
true
protected void handleWorkbenchPartSelection(IWorkbenchPart part, ISelection selection, boolean contributeToContext) { if (selection instanceof StructuredSelection) { StructuredSelection structuredSelection = (StructuredSelection) selection; Object selectedObject = structuredSelection.getFirstElement(); if (selectedObject instanceof File) { File file = (File) selectedObject; super.handleElementSelection(part, file, contributeToContext); } } else if (selection instanceof TextSelection) { if (part instanceof EditorPart) { try { Object object = ((EditorPart) part).getEditorInput().getAdapter(IResource.class); if (object instanceof IFile) { IFile file = (IFile) object; if (!ContextCorePlugin.getDefault().getKnownContentTypes().contains(file.getFileExtension())) { super.handleElementEdit(part, object, contributeToContext); } } } catch (Throwable t) { StatusHandler.log(t, "failed to resolve resource edit"); } } } }
protected void handleWorkbenchPartSelection(IWorkbenchPart part, ISelection selection, boolean contributeToContext) { if (selection instanceof StructuredSelection) { StructuredSelection structuredSelection = (StructuredSelection) selection; Object selectedObject = structuredSelection.getFirstElement(); if (selectedObject instanceof File) { File file = (File) selectedObject; super.handleElementSelection(part, file, contributeToContext); } } else if (selection instanceof TextSelection) { if (part instanceof EditorPart) { try { Object object = ((EditorPart) part).getEditorInput().getAdapter(IResource.class); if (object instanceof IFile) { IFile file = (IFile) object; if (file.getFileExtension() != null && !ContextCorePlugin.getDefault().getKnownContentTypes().contains(file.getFileExtension())) { super.handleElementEdit(part, object, contributeToContext); } } } catch (Throwable t) { StatusHandler.log(t, "failed to resolve resource edit"); } } } }
diff --git a/java/src/com/google/template/soy/gosrc/internal/GoSrcMain.java b/java/src/com/google/template/soy/gosrc/internal/GoSrcMain.java index 088728f..443e646 100644 --- a/java/src/com/google/template/soy/gosrc/internal/GoSrcMain.java +++ b/java/src/com/google/template/soy/gosrc/internal/GoSrcMain.java @@ -1,121 +1,121 @@ /* * Copyright 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.template.soy.gosrc.internal; import java.util.List; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.template.soy.base.SoySyntaxException; import com.google.template.soy.gosrc.SoyGoSrcOptions; import com.google.template.soy.internal.base.Pair; import com.google.template.soy.internal.i18n.BidiGlobalDir; import com.google.template.soy.internal.i18n.SoyBidiUtils; import com.google.template.soy.msgs.SoyMsgBundle; import com.google.template.soy.msgs.internal.InsertMsgsVisitor; import com.google.template.soy.msgs.internal.InsertMsgsVisitor.EncounteredPluralSelectMsgException; import com.google.template.soy.shared.internal.ApiCallScopeUtils; import com.google.template.soy.shared.internal.GuiceSimpleScope; import com.google.template.soy.shared.restricted.ApiCallScopeBindingAnnotations.ApiCall; import com.google.template.soy.sharedpasses.opti.SimplifyVisitor; import com.google.template.soy.soytree.SoyFileSetNode; import javax.annotation.Nullable; /** * Main entry point for the Go Src backend (output target). * * <p> Important: Do not use outside of Soy code (treat as superpackage-private). * * @author Kai Huang */ public class GoSrcMain { /** The scope object that manages the API call scope. */ private final GuiceSimpleScope apiCallScope; /** The instanceof of SimplifyVisitor to use. */ private final SimplifyVisitor simplifyVisitor; /** Provider for getting an instance of OptimizeBidiCodeGenVisitor. */ private final Provider<OptimizeBidiCodeGenVisitor> optimizeBidiCodeGenVisitorProvider; /** Provider for getting an instance of GenGoCodeVisitor. */ private final Provider<GenGoCodeVisitor> genGoCodeVisitorProvider; /** * @param apiCallScope The scope object that manages the API call scope. * @param optimizeBidiCodeGenVisitorProvider Provider for getting an instance of * OptimizeBidiCodeGenVisitor. * @param genGoCodeVisitorProvider Provider for getting an instance of GenGoCodeVisitor. */ @Inject GoSrcMain(@ApiCall GuiceSimpleScope apiCallScope, SimplifyVisitor simplifyVisitor, Provider<OptimizeBidiCodeGenVisitor> optimizeBidiCodeGenVisitorProvider, Provider<GenGoCodeVisitor> genGoCodeVisitorProvider) { this.apiCallScope = apiCallScope; this.simplifyVisitor = simplifyVisitor; this.optimizeBidiCodeGenVisitorProvider = optimizeBidiCodeGenVisitorProvider; this.genGoCodeVisitorProvider = genGoCodeVisitorProvider; } /** * Generates Go source code given a Soy parse tree, an options object, and an optional bundle of * translated messages. * * @param soyTree The Soy parse tree to generate Go source code for. * @param goSrcOptions The compilation options relevant to this backend. * @param msgBundle The bundle of translated messages, or null to use the messages from the Soy * source. * @return A list of strings where each string represents the Go source code that belongs in one * Go file. The generated Go files correspond one-to-one to the original Soy source files. * @throws SoySyntaxException If a syntax error is found. */ public List<Pair<String,String>> genGoSrc( SoyFileSetNode soyTree, SoyGoSrcOptions goSrcOptions, @Nullable SoyMsgBundle msgBundle) throws SoySyntaxException { try { (new InsertMsgsVisitor(msgBundle, false)).exec(soyTree); } catch (EncounteredPluralSelectMsgException e) { - throw new SoySyntaxException("JavaSrc backend doesn't support plural/select messages."); + throw new SoySyntaxException("GoSrc backend doesn't support plural/select messages."); } apiCallScope.enter(); try { // Seed the scoped parameters. apiCallScope.seed(SoyGoSrcOptions.class, goSrcOptions); BidiGlobalDir bidiGlobalDir = SoyBidiUtils.decodeBidiGlobalDir(goSrcOptions.getBidiGlobalDir()); ApiCallScopeUtils.seedSharedParams( apiCallScope, msgBundle, bidiGlobalDir); // Do the code generation. optimizeBidiCodeGenVisitorProvider.get().exec(soyTree); simplifyVisitor.exec(soyTree); return genGoCodeVisitorProvider.get().exec(soyTree); } finally { apiCallScope.exit(); } } }
true
true
public List<Pair<String,String>> genGoSrc( SoyFileSetNode soyTree, SoyGoSrcOptions goSrcOptions, @Nullable SoyMsgBundle msgBundle) throws SoySyntaxException { try { (new InsertMsgsVisitor(msgBundle, false)).exec(soyTree); } catch (EncounteredPluralSelectMsgException e) { throw new SoySyntaxException("JavaSrc backend doesn't support plural/select messages."); } apiCallScope.enter(); try { // Seed the scoped parameters. apiCallScope.seed(SoyGoSrcOptions.class, goSrcOptions); BidiGlobalDir bidiGlobalDir = SoyBidiUtils.decodeBidiGlobalDir(goSrcOptions.getBidiGlobalDir()); ApiCallScopeUtils.seedSharedParams( apiCallScope, msgBundle, bidiGlobalDir); // Do the code generation. optimizeBidiCodeGenVisitorProvider.get().exec(soyTree); simplifyVisitor.exec(soyTree); return genGoCodeVisitorProvider.get().exec(soyTree); } finally { apiCallScope.exit(); } }
public List<Pair<String,String>> genGoSrc( SoyFileSetNode soyTree, SoyGoSrcOptions goSrcOptions, @Nullable SoyMsgBundle msgBundle) throws SoySyntaxException { try { (new InsertMsgsVisitor(msgBundle, false)).exec(soyTree); } catch (EncounteredPluralSelectMsgException e) { throw new SoySyntaxException("GoSrc backend doesn't support plural/select messages."); } apiCallScope.enter(); try { // Seed the scoped parameters. apiCallScope.seed(SoyGoSrcOptions.class, goSrcOptions); BidiGlobalDir bidiGlobalDir = SoyBidiUtils.decodeBidiGlobalDir(goSrcOptions.getBidiGlobalDir()); ApiCallScopeUtils.seedSharedParams( apiCallScope, msgBundle, bidiGlobalDir); // Do the code generation. optimizeBidiCodeGenVisitorProvider.get().exec(soyTree); simplifyVisitor.exec(soyTree); return genGoCodeVisitorProvider.get().exec(soyTree); } finally { apiCallScope.exit(); } }
diff --git a/Inventory/src/com/fnz/dao/IncomingStockDAO.java b/Inventory/src/com/fnz/dao/IncomingStockDAO.java index 3876922..ad4d261 100644 --- a/Inventory/src/com/fnz/dao/IncomingStockDAO.java +++ b/Inventory/src/com/fnz/dao/IncomingStockDAO.java @@ -1,241 +1,241 @@ package com.fnz.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Iterator; import java.util.Set; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.ObservableMap; import org.sqlite.SQLiteConfig; import com.fnz.VO.CategoryTypeVO; import com.fnz.VO.ItemTypeVO; import com.fnz.VO.ItemVO; import com.fnz.VO.StockVO; import com.fnz.common.CommonConstants; import com.fnz.common.SQLConstants; public class IncomingStockDAO { public String addIncomingStock(String invoiceNo, String date, ObservableList<ItemVO> listData, ObservableList<CategoryTypeVO> typeList) throws Exception { Connection conn = null; ResultSet resultSet = null; SQLiteConfig config = null; java.sql.Statement statement = null; Class.forName(CommonConstants.DRIVERNAME); String msg = CommonConstants.UPDATE_MSG; String sDbUrl = CommonConstants.sJdbc + ":" + CommonConstants.DB_LOCATION + CommonConstants.sTempDb; try { config = new SQLiteConfig(); config.enforceForeignKeys(true); conn = DriverManager.getConnection(sDbUrl, config.toProperties()); statement = conn.createStatement(); String splitsDate[] = date.split("/"); date = splitsDate[2]+"-"+splitsDate[1]+"-"+splitsDate[0]; /*statement.addBatch(SQLConstants.INSERT_INCOMING_STOCK_1+invoiceNo+SQLConstants.INSERT_INCOMING_STOCK_2+date+SQLConstants.INSERT_INCOMING_STOCK_2 +""+SQLConstants.INSERT_INCOMING_STOCK_3);*/ for(ItemVO itemVO : listData) { ObservableMap<String, ItemTypeVO> map = FXCollections.observableHashMap(); map=itemVO.getListType(); Set<String> keySet = map.keySet(); for(Iterator<String> iter=keySet.iterator();iter.hasNext();) { ItemTypeVO itemTypeVO = new ItemTypeVO(); String tempTypeName =""; itemTypeVO = map.get(iter.next()); /*for(CategoryTypeVO type:typeList) { if(type.getTypeId().equals(itemTypeVO.getTypeId())) { tempTypeName = type.getTypeName(); break; } }*/ if(itemTypeVO.getQuantity()>0) { statement.addBatch(SQLConstants.UPDATE_ADD_ITEMS_TYPES_1 + itemTypeVO.getQuantity()*CommonConstants.CASE_SIZE + SQLConstants.UPDATE_ADD_ITEMS_TYPES_2 + itemVO.getItemId() + SQLConstants.UPDATE_ADD_ITEMS_TYPES_3 + itemTypeVO.getTypeId() + SQLConstants.UPDATE_ADD_ITEMS_TYPES_4); statement.addBatch(SQLConstants.INSERT_INCOMING_STOCK_DETAILS_1+invoiceNo+SQLConstants.INSERT_INCOMING_STOCK_DETAILS_2+ date + SQLConstants.INSERT_INCOMING_STOCK_DETAILS_3+ itemVO.getItemId()+SQLConstants.INSERT_INCOMING_STOCK_DETAILS_3+itemTypeVO.getTypeId()+SQLConstants.INSERT_INCOMING_STOCK_DETAILS_4+ - itemTypeVO.getQuantity()+SQLConstants.INSERT_INCOMING_STOCK_DETAILS_5); + itemTypeVO.getQuantity()*CommonConstants.CASE_SIZE+SQLConstants.INSERT_INCOMING_STOCK_DETAILS_5); } } } statement.executeBatch(); } catch (Exception e) { throw e; } finally { if(conn !=null ) { conn.close(); } if(statement != null ) { statement.close(); } if(resultSet != null) { resultSet.close(); } } return msg; } public ObservableList<StockVO> fetchIncomingStockDetails(String initialDate, String finalDate) throws Exception { Connection conn = null; PreparedStatement pstmt = null; ResultSet resultSet = null; SQLiteConfig config = null; ObservableList<StockVO> listIncoming = FXCollections.observableArrayList(); Class.forName(CommonConstants.DRIVERNAME); String sDbUrl = CommonConstants.sJdbc + ":" + CommonConstants.DB_LOCATION + CommonConstants.sTempDb; try { config = new SQLiteConfig(); config.enforceForeignKeys(true); conn = DriverManager.getConnection(sDbUrl, config.toProperties()); pstmt = conn.prepareStatement(SQLConstants.FETCH_INCOMING_DETAILS_BY_DATE); String splitsInitialDate[] = initialDate.split("/"); initialDate = splitsInitialDate[2]+"-"+splitsInitialDate[1]+"-"+splitsInitialDate[0]; String splitsFinalDate[] = finalDate.split("/"); finalDate = splitsFinalDate[2]+"-"+splitsFinalDate[1]+"-"+splitsFinalDate[0]; pstmt.setString(1, initialDate); pstmt.setString(2, finalDate); resultSet = pstmt.executeQuery(); while(resultSet.next()) { StockVO incomingStockVO = new StockVO(); incomingStockVO.setInvoiceId(resultSet.getString(1)); String splitsDate[] = resultSet.getString(2).split("-"); incomingStockVO.setDate(splitsDate[2]+"/"+splitsDate[1]+"/"+splitsDate[0]); incomingStockVO.setItemId(resultSet.getString(3)); incomingStockVO.setItemName(resultSet.getString(4)); incomingStockVO.setTypeId(resultSet.getString(5)); incomingStockVO.setTypeName(resultSet.getString(6)); incomingStockVO.setQuantity(resultSet.getInt(7)); incomingStockVO.setCheck(false); listIncoming.add(incomingStockVO); } } catch (Exception e) { e.printStackTrace(); } finally { if(conn !=null ) { conn.close(); } if(pstmt != null ) { pstmt.close(); } if(resultSet != null) { resultSet.close(); } } return listIncoming; } public ObservableList<StockVO> fetchIncomingStockDetails(String invoiceId) throws Exception { Connection conn = null; PreparedStatement pstmt = null; ResultSet resultSet = null; SQLiteConfig config = null; ObservableList<StockVO> listIncoming = FXCollections.observableArrayList(); Class.forName(CommonConstants.DRIVERNAME); String sDbUrl = CommonConstants.sJdbc + ":" + CommonConstants.DB_LOCATION + CommonConstants.sTempDb; try { config = new SQLiteConfig(); config.enforceForeignKeys(true); conn = DriverManager.getConnection(sDbUrl, config.toProperties()); pstmt = conn.prepareStatement(SQLConstants.FETCH_INCOMING_DETAILS_BY_INVOICE); pstmt.setString(1, invoiceId); resultSet = pstmt.executeQuery(); while(resultSet.next()) { StockVO incomingStockVO = new StockVO(); incomingStockVO.setInvoiceId(resultSet.getString(1)); String splitsDate[] = resultSet.getString(2).split("-"); incomingStockVO.setDate(splitsDate[2]+"/"+splitsDate[1]+"/"+splitsDate[0]); incomingStockVO.setItemId(resultSet.getString(3)); incomingStockVO.setItemName(resultSet.getString(4)); incomingStockVO.setTypeId(resultSet.getString(5)); incomingStockVO.setTypeName(resultSet.getString(6)); incomingStockVO.setQuantity(resultSet.getInt(7)); listIncoming.add(incomingStockVO); } } catch (Exception e) { e.printStackTrace(); } finally { if(conn !=null ) { conn.close(); } if(pstmt != null ) { pstmt.close(); } if(resultSet != null) { resultSet.close(); } } return listIncoming; } }
true
true
public String addIncomingStock(String invoiceNo, String date, ObservableList<ItemVO> listData, ObservableList<CategoryTypeVO> typeList) throws Exception { Connection conn = null; ResultSet resultSet = null; SQLiteConfig config = null; java.sql.Statement statement = null; Class.forName(CommonConstants.DRIVERNAME); String msg = CommonConstants.UPDATE_MSG; String sDbUrl = CommonConstants.sJdbc + ":" + CommonConstants.DB_LOCATION + CommonConstants.sTempDb; try { config = new SQLiteConfig(); config.enforceForeignKeys(true); conn = DriverManager.getConnection(sDbUrl, config.toProperties()); statement = conn.createStatement(); String splitsDate[] = date.split("/"); date = splitsDate[2]+"-"+splitsDate[1]+"-"+splitsDate[0]; /*statement.addBatch(SQLConstants.INSERT_INCOMING_STOCK_1+invoiceNo+SQLConstants.INSERT_INCOMING_STOCK_2+date+SQLConstants.INSERT_INCOMING_STOCK_2 +""+SQLConstants.INSERT_INCOMING_STOCK_3);*/ for(ItemVO itemVO : listData) { ObservableMap<String, ItemTypeVO> map = FXCollections.observableHashMap(); map=itemVO.getListType(); Set<String> keySet = map.keySet(); for(Iterator<String> iter=keySet.iterator();iter.hasNext();) { ItemTypeVO itemTypeVO = new ItemTypeVO(); String tempTypeName =""; itemTypeVO = map.get(iter.next()); /*for(CategoryTypeVO type:typeList) { if(type.getTypeId().equals(itemTypeVO.getTypeId())) { tempTypeName = type.getTypeName(); break; } }*/ if(itemTypeVO.getQuantity()>0) { statement.addBatch(SQLConstants.UPDATE_ADD_ITEMS_TYPES_1 + itemTypeVO.getQuantity()*CommonConstants.CASE_SIZE + SQLConstants.UPDATE_ADD_ITEMS_TYPES_2 + itemVO.getItemId() + SQLConstants.UPDATE_ADD_ITEMS_TYPES_3 + itemTypeVO.getTypeId() + SQLConstants.UPDATE_ADD_ITEMS_TYPES_4); statement.addBatch(SQLConstants.INSERT_INCOMING_STOCK_DETAILS_1+invoiceNo+SQLConstants.INSERT_INCOMING_STOCK_DETAILS_2+ date + SQLConstants.INSERT_INCOMING_STOCK_DETAILS_3+ itemVO.getItemId()+SQLConstants.INSERT_INCOMING_STOCK_DETAILS_3+itemTypeVO.getTypeId()+SQLConstants.INSERT_INCOMING_STOCK_DETAILS_4+ itemTypeVO.getQuantity()+SQLConstants.INSERT_INCOMING_STOCK_DETAILS_5); } } } statement.executeBatch(); } catch (Exception e) { throw e; } finally { if(conn !=null ) { conn.close(); } if(statement != null ) { statement.close(); } if(resultSet != null) { resultSet.close(); } } return msg; }
public String addIncomingStock(String invoiceNo, String date, ObservableList<ItemVO> listData, ObservableList<CategoryTypeVO> typeList) throws Exception { Connection conn = null; ResultSet resultSet = null; SQLiteConfig config = null; java.sql.Statement statement = null; Class.forName(CommonConstants.DRIVERNAME); String msg = CommonConstants.UPDATE_MSG; String sDbUrl = CommonConstants.sJdbc + ":" + CommonConstants.DB_LOCATION + CommonConstants.sTempDb; try { config = new SQLiteConfig(); config.enforceForeignKeys(true); conn = DriverManager.getConnection(sDbUrl, config.toProperties()); statement = conn.createStatement(); String splitsDate[] = date.split("/"); date = splitsDate[2]+"-"+splitsDate[1]+"-"+splitsDate[0]; /*statement.addBatch(SQLConstants.INSERT_INCOMING_STOCK_1+invoiceNo+SQLConstants.INSERT_INCOMING_STOCK_2+date+SQLConstants.INSERT_INCOMING_STOCK_2 +""+SQLConstants.INSERT_INCOMING_STOCK_3);*/ for(ItemVO itemVO : listData) { ObservableMap<String, ItemTypeVO> map = FXCollections.observableHashMap(); map=itemVO.getListType(); Set<String> keySet = map.keySet(); for(Iterator<String> iter=keySet.iterator();iter.hasNext();) { ItemTypeVO itemTypeVO = new ItemTypeVO(); String tempTypeName =""; itemTypeVO = map.get(iter.next()); /*for(CategoryTypeVO type:typeList) { if(type.getTypeId().equals(itemTypeVO.getTypeId())) { tempTypeName = type.getTypeName(); break; } }*/ if(itemTypeVO.getQuantity()>0) { statement.addBatch(SQLConstants.UPDATE_ADD_ITEMS_TYPES_1 + itemTypeVO.getQuantity()*CommonConstants.CASE_SIZE + SQLConstants.UPDATE_ADD_ITEMS_TYPES_2 + itemVO.getItemId() + SQLConstants.UPDATE_ADD_ITEMS_TYPES_3 + itemTypeVO.getTypeId() + SQLConstants.UPDATE_ADD_ITEMS_TYPES_4); statement.addBatch(SQLConstants.INSERT_INCOMING_STOCK_DETAILS_1+invoiceNo+SQLConstants.INSERT_INCOMING_STOCK_DETAILS_2+ date + SQLConstants.INSERT_INCOMING_STOCK_DETAILS_3+ itemVO.getItemId()+SQLConstants.INSERT_INCOMING_STOCK_DETAILS_3+itemTypeVO.getTypeId()+SQLConstants.INSERT_INCOMING_STOCK_DETAILS_4+ itemTypeVO.getQuantity()*CommonConstants.CASE_SIZE+SQLConstants.INSERT_INCOMING_STOCK_DETAILS_5); } } } statement.executeBatch(); } catch (Exception e) { throw e; } finally { if(conn !=null ) { conn.close(); } if(statement != null ) { statement.close(); } if(resultSet != null) { resultSet.close(); } } return msg; }
diff --git a/modules/org.restlet/src/org/restlet/engine/local/LocalClientHelper.java b/modules/org.restlet/src/org/restlet/engine/local/LocalClientHelper.java index 2cc35f1f4..b928d1df7 100644 --- a/modules/org.restlet/src/org/restlet/engine/local/LocalClientHelper.java +++ b/modules/org.restlet/src/org/restlet/engine/local/LocalClientHelper.java @@ -1,142 +1,148 @@ /** * Copyright 2005-2010 Noelios Technologies. * * The contents of this file are subject to the terms of one of the following * open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the * "Licenses"). You can select the license that you prefer but you may not use * this file except in compliance with one of these Licenses. * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0.html * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1.php * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1.php * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0.php * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.noelios.com/products/restlet-engine * * Restlet is a registered trademark of Noelios Technologies. */ package org.restlet.engine.local; import org.restlet.Client; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Reference; import org.restlet.engine.ClientHelper; /** * Connector to the local resources accessible via file system, class loaders * and similar mechanisms. Here is the list of parameters that are supported. * They should be set in the Client's context before it is started: * <table> * <tr> * <th>Parameter name</th> * <th>Value type</th> * <th>Default value</th> * <th>Description</th> * </tr> * <tr> * <td>timeToLive</td> * <td>int</td> * <td>600</td> * <td>Time to live for a representation before it expires (in seconds). If you * set the value to '0', the representation will never expire.</td> * </tr> * <tr> * <td>defaultLanguage</td> * <td>String</td> * <td></td> * <td>When no metadata service is available (simple client connector with no * parent application), falls back on this default language. To indicate that no * default language should be set, "" can be used.</td> * </tr> * </table> * * @see org.restlet.data.LocalReference * @author Jerome Louvel * @author Thierry Boileau */ public abstract class LocalClientHelper extends ClientHelper { /** * Constructor. Note that the common list of metadata associations based on * extensions is added, see the addCommonExtensions() method. * * @param client * The client to help. */ public LocalClientHelper(Client client) { super(client); } /** * Returns the default language. When no metadata service is available * (simple client connector with no parent application), falls back on this * default language. * * @return The default language. */ public String getDefaultLanguage() { return getHelpedParameters().getFirstValue("defaultLanguage", ""); } /** * Returns the time to live for a file representation before it expires (in * seconds). * * @return The time to live for a file representation before it expires (in * seconds). */ public int getTimeToLive() { return Integer.parseInt(getHelpedParameters().getFirstValue( "timeToLive", "600")); } /** * Handles a call. Note that this implementation will systematically * normalize and URI-decode the resource reference. * * @param request * The request to handle. * @param response * The response to update. */ @Override public final void handle(Request request, Response response) { // Ensure that all ".." and "." are normalized into the path // to prevent unauthorized access to user directories. request.getResourceRef().normalize(); // As the path may be percent-encoded, it has to be percent-decoded. // Then, all generated URIs must be encoded. String path = request.getResourceRef().getPath(); String decodedPath = Reference.decode(path); - // Continue the local handling - handleLocal(request, response, decodedPath); + if (decodedPath != null) { + // Continue the local handling + handleLocal(request, response, decodedPath); + } else { + getLogger().warning( + "Unable to get the path of this local URI: " + + request.getResourceRef()); + } } /** * Handles a local call. * * @param request * The request to handle. * @param response * The response to update. * @param decodedPath * The decoded local path. */ protected abstract void handleLocal(Request request, Response response, String decodedPath); }
true
true
public final void handle(Request request, Response response) { // Ensure that all ".." and "." are normalized into the path // to prevent unauthorized access to user directories. request.getResourceRef().normalize(); // As the path may be percent-encoded, it has to be percent-decoded. // Then, all generated URIs must be encoded. String path = request.getResourceRef().getPath(); String decodedPath = Reference.decode(path); // Continue the local handling handleLocal(request, response, decodedPath); }
public final void handle(Request request, Response response) { // Ensure that all ".." and "." are normalized into the path // to prevent unauthorized access to user directories. request.getResourceRef().normalize(); // As the path may be percent-encoded, it has to be percent-decoded. // Then, all generated URIs must be encoded. String path = request.getResourceRef().getPath(); String decodedPath = Reference.decode(path); if (decodedPath != null) { // Continue the local handling handleLocal(request, response, decodedPath); } else { getLogger().warning( "Unable to get the path of this local URI: " + request.getResourceRef()); } }
diff --git a/ini/trakem2/display/graphics/TestGraphicsSource.java b/ini/trakem2/display/graphics/TestGraphicsSource.java index aab0071a..d5b521ab 100644 --- a/ini/trakem2/display/graphics/TestGraphicsSource.java +++ b/ini/trakem2/display/graphics/TestGraphicsSource.java @@ -1,42 +1,42 @@ package ini.trakem2.display.graphics; import ini.trakem2.display.Displayable; import ini.trakem2.display.Paintable; import ini.trakem2.display.Layer; import ini.trakem2.display.Patch; import java.util.Collection; import java.util.ArrayList; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Rectangle; public class TestGraphicsSource implements GraphicsSource { /** Replaces all Patch instances by a smiley face. */ public Collection<? extends Paintable> asPaintable(final Collection<? extends Paintable> ds) { - final ArrayList<? extends Paintable> a = new ArrayList<Paintable>(); + final ArrayList<Paintable> a = new ArrayList<Paintable>(); for (final Paintable p : ds) { if (p instanceof Patch) { final Paintable pa = new Paintable() { public void paint(Graphics2D g, double magnification, boolean active, int channels, Layer active_layer) { Patch patch = (Patch)p; Rectangle r = patch.getBoundingBox(); g.setColor(Color.magenta); g.fillRect(r.x, r.y, r.width, r.height); g.setColor(Color.green); g.fillOval(r.width/3, r.height/3, r.width/10, r.width/10); g.fillOval(2 * (r.width/3), r.height/3, r.width/10, r.width/10); g.drawOval(r.width/2, 2*(r.height/3), r.width/3, r.height/6); } public void prePaint(Graphics2D g, double magnification, boolean active, int channels, Layer active_layer) { this.paint(g, magnification, active, channels, active_layer); } }; a.add(pa); } else { a.add(p); } } return a; } }
true
true
public Collection<? extends Paintable> asPaintable(final Collection<? extends Paintable> ds) { final ArrayList<? extends Paintable> a = new ArrayList<Paintable>(); for (final Paintable p : ds) { if (p instanceof Patch) { final Paintable pa = new Paintable() { public void paint(Graphics2D g, double magnification, boolean active, int channels, Layer active_layer) { Patch patch = (Patch)p; Rectangle r = patch.getBoundingBox(); g.setColor(Color.magenta); g.fillRect(r.x, r.y, r.width, r.height); g.setColor(Color.green); g.fillOval(r.width/3, r.height/3, r.width/10, r.width/10); g.fillOval(2 * (r.width/3), r.height/3, r.width/10, r.width/10); g.drawOval(r.width/2, 2*(r.height/3), r.width/3, r.height/6); } public void prePaint(Graphics2D g, double magnification, boolean active, int channels, Layer active_layer) { this.paint(g, magnification, active, channels, active_layer); } }; a.add(pa); } else { a.add(p); } } return a; }
public Collection<? extends Paintable> asPaintable(final Collection<? extends Paintable> ds) { final ArrayList<Paintable> a = new ArrayList<Paintable>(); for (final Paintable p : ds) { if (p instanceof Patch) { final Paintable pa = new Paintable() { public void paint(Graphics2D g, double magnification, boolean active, int channels, Layer active_layer) { Patch patch = (Patch)p; Rectangle r = patch.getBoundingBox(); g.setColor(Color.magenta); g.fillRect(r.x, r.y, r.width, r.height); g.setColor(Color.green); g.fillOval(r.width/3, r.height/3, r.width/10, r.width/10); g.fillOval(2 * (r.width/3), r.height/3, r.width/10, r.width/10); g.drawOval(r.width/2, 2*(r.height/3), r.width/3, r.height/6); } public void prePaint(Graphics2D g, double magnification, boolean active, int channels, Layer active_layer) { this.paint(g, magnification, active, channels, active_layer); } }; a.add(pa); } else { a.add(p); } } return a; }
diff --git a/PullPit/src/kea/kme/pullpit/server/persistence/PodioObjectHandler.java b/PullPit/src/kea/kme/pullpit/server/persistence/PodioObjectHandler.java index 7f820bd..66f1fbf 100644 --- a/PullPit/src/kea/kme/pullpit/server/persistence/PodioObjectHandler.java +++ b/PullPit/src/kea/kme/pullpit/server/persistence/PodioObjectHandler.java @@ -1,62 +1,62 @@ package kea.kme.pullpit.server.persistence; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import kea.kme.pullpit.server.podio.PodioBand; import kea.kme.pullpit.server.podio.PodioShow; public class PodioObjectHandler { private static PodioObjectHandler podioObjectHandler; // TODO indl�sning af hele podio // TODO indl�sning af enkeltitems vha. webhooks // TODO create sql query private PodioObjectHandler() { } public static PodioObjectHandler getInstance() { if (podioObjectHandler == null) podioObjectHandler = new PodioObjectHandler(); return podioObjectHandler; } public void writeBands(PodioBand... pb) throws SQLException { Connection c = DBConnector.getInstance().getConnection(); PreparedStatement ps = c.prepareStatement("INSERT INTO bands VALUES (?, ?, ?, ?, ?)"); for (PodioBand p : pb) { ps.setInt(1, p.getBandID()); ps.setString(2, p.getBandName()); ps.setString(3, p.getBandCountry()); ps.setInt(4, p.getPromoterID()); ps.setTimestamp(5, p.getLastEdit()); ps.executeUpdate(); } } public void writeShows(PodioShow... pshow) throws SQLException { Connection c = DBConnector.getInstance().getConnection(); PreparedStatement ps = c.prepareStatement("INSERT INTO shows VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); for (PodioShow p : pshow) { - pshow.setInt(1, pshow.getShowID()); - pshow.setInt(2, pshow.getBandID()); - pshow.setDate(3, pshow.getDate()); - pshow.setInt(4, pshow.getState()); - pshow.setDouble(5, pshow.getFee()); - pshow.setString(6, pshow.getFeeCurrency()); - pshow.setDouble(7, pshow.getProvision()); - pshow.setString(8, pshow.getProvisionCurrency()); - pshow.setInt(9, pshow.getProductionType()); - pshow.setInt(10, pshow.getProfitSplit()); - pshow.setInt(11, pshow.getTicketPrice()); - pshow.setDouble(12, pshow.getKodaPct()); - pshow.setDouble(13, pshow.getVAT()); - pshow.setInt(14, pshow.getTicketsSold()); - pshow.setString(15, pshow.getComment()); - pshow.setTimestamp(16, pshow.getLastEdit()); + ps.setInt(1, p.getShowID()); + ps.setInt(2, p.getBandID()); + ps.setDate(3, p.getDate()); + ps.setInt(4, p.getState()); + ps.setDouble(5, p.getFee()); + ps.setString(6, p.getFeeCurrency()); + ps.setDouble(7, p.getProvision()); + ps.setString(8, p.getProvisionCurrency()); + ps.setInt(9, p.getProductionType()); + ps.setInt(10, p.getProfitSplit()); + ps.setInt(11, p.getTicketPrice()); + ps.setDouble(12, p.getKodaPct()); + ps.setDouble(13, p.getVAT()); + ps.setInt(14, p.getTicketsSold()); + ps.setString(15, p.getComments()); + ps.setTimestamp(16, p.getLastEdit()); ps.executeUpdate(); } } }
true
true
public void writeShows(PodioShow... pshow) throws SQLException { Connection c = DBConnector.getInstance().getConnection(); PreparedStatement ps = c.prepareStatement("INSERT INTO shows VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); for (PodioShow p : pshow) { pshow.setInt(1, pshow.getShowID()); pshow.setInt(2, pshow.getBandID()); pshow.setDate(3, pshow.getDate()); pshow.setInt(4, pshow.getState()); pshow.setDouble(5, pshow.getFee()); pshow.setString(6, pshow.getFeeCurrency()); pshow.setDouble(7, pshow.getProvision()); pshow.setString(8, pshow.getProvisionCurrency()); pshow.setInt(9, pshow.getProductionType()); pshow.setInt(10, pshow.getProfitSplit()); pshow.setInt(11, pshow.getTicketPrice()); pshow.setDouble(12, pshow.getKodaPct()); pshow.setDouble(13, pshow.getVAT()); pshow.setInt(14, pshow.getTicketsSold()); pshow.setString(15, pshow.getComment()); pshow.setTimestamp(16, pshow.getLastEdit()); ps.executeUpdate(); } }
public void writeShows(PodioShow... pshow) throws SQLException { Connection c = DBConnector.getInstance().getConnection(); PreparedStatement ps = c.prepareStatement("INSERT INTO shows VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); for (PodioShow p : pshow) { ps.setInt(1, p.getShowID()); ps.setInt(2, p.getBandID()); ps.setDate(3, p.getDate()); ps.setInt(4, p.getState()); ps.setDouble(5, p.getFee()); ps.setString(6, p.getFeeCurrency()); ps.setDouble(7, p.getProvision()); ps.setString(8, p.getProvisionCurrency()); ps.setInt(9, p.getProductionType()); ps.setInt(10, p.getProfitSplit()); ps.setInt(11, p.getTicketPrice()); ps.setDouble(12, p.getKodaPct()); ps.setDouble(13, p.getVAT()); ps.setInt(14, p.getTicketsSold()); ps.setString(15, p.getComments()); ps.setTimestamp(16, p.getLastEdit()); ps.executeUpdate(); } }
diff --git a/src/java/org/hibernate/tool/hbm2x/HibernateConfigurationExporter.java b/src/java/org/hibernate/tool/hbm2x/HibernateConfigurationExporter.java index 3b17e754..7a877c3f 100644 --- a/src/java/org/hibernate/tool/hbm2x/HibernateConfigurationExporter.java +++ b/src/java/org/hibernate/tool/hbm2x/HibernateConfigurationExporter.java @@ -1,196 +1,196 @@ /* * Created on 2004-12-03 * */ package org.hibernate.tool.hbm2x; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.RootClass; /** * @author max * */ public class HibernateConfigurationExporter extends AbstractExporter { private Writer output; private Properties customProperties = new Properties(); public HibernateConfigurationExporter(Configuration configuration, File outputdir) { super(configuration, outputdir); } public HibernateConfigurationExporter() { } public Properties getCustomProperties() { return customProperties; } public void setCustomProperties(Properties customProperties) { this.customProperties = customProperties; } public Writer getOutput() { return output; } public void setOutput(Writer output) { this.output = output; } /* (non-Javadoc) * @see org.hibernate.tool.hbm2x.Exporter#finish() */ public void doStart() throws ExporterException { PrintWriter pw = null; File file = null; try { if(output==null) { file = new File(getOutputDirectory(), "hibernate.cfg.xml"); getTemplateHelper().ensureExistence(file); pw = new PrintWriter(new FileWriter(file) ); getArtifactCollector().addFile(file, "cfg.xml"); } else { pw = new PrintWriter(output); } pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE hibernate-configuration PUBLIC\r\n" + " \"-//Hibernate/Hibernate Configuration DTD 3.0//EN\"\r\n" + - " \"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd\">\r\n" + + " \"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd\">\r\n" + "<hibernate-configuration>"); boolean ejb3 = Boolean.valueOf((String)getProperties().get("ejb3")).booleanValue(); Map props = new TreeMap(); if(getConfiguration()!=null) { props.putAll(getConfiguration().getProperties() ); } if(customProperties!=null) { props.putAll(customProperties); } String sfname = (String) props.get(Environment.SESSION_FACTORY_NAME); pw.println(" <session-factory" + (sfname==null?"":" name=\"" + sfname + "\"") + ">"); Map ignoredProperties = new HashMap(); ignoredProperties.put(Environment.SESSION_FACTORY_NAME, null); ignoredProperties.put(Environment.HBM2DDL_AUTO, "false" ); ignoredProperties.put("hibernate.temp.use_jdbc_metadata_defaults", null ); ignoredProperties.put(Environment.TRANSACTION_MANAGER_STRATEGY, "org.hibernate.console.FakeTransactionManagerLookup"); Set set = props.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext() ) { Map.Entry element = (Map.Entry) iterator.next(); String key = (String) element.getKey(); if(ignoredProperties.containsKey( key )) { Object ignoredValue = ignoredProperties.get( key ); if(ignoredValue == null || element.getValue().equals(ignoredValue)) { continue; } } if(key.startsWith("hibernate.") ) { // if not starting with hibernate. not relevant for cfg.xml pw.println(" <property name=\"" + key + "\">" + forXML(element.getValue().toString()) + "</property>"); } } if(getConfiguration()!=null) { Iterator classMappings = getConfiguration().getClassMappings(); while (classMappings.hasNext() ) { PersistentClass element = (PersistentClass) classMappings.next(); if(element instanceof RootClass) { dump(pw, ejb3, element); } } } pw.println(" </session-factory>\r\n" + "</hibernate-configuration>"); } catch (IOException e) { throw new ExporterException("Problems while creating hibernate.cfg.xml", e); } finally { if(pw!=null) { pw.flush(); pw.close(); } } } /** * @param pw * @param element */ private void dump(PrintWriter pw, boolean useClass, PersistentClass element) { if(useClass) { pw.println("<mapping class=\"" + element.getClassName() + "\"/>"); } else { pw.println("<mapping resource=\"" + getMappingFileResource(element) + "\"/>"); } Iterator directSubclasses = element.getDirectSubclasses(); while (directSubclasses.hasNext() ) { PersistentClass subclass = (PersistentClass) directSubclasses.next(); dump(pw, useClass, subclass); } } /** * @param element * @return */ private String getMappingFileResource(PersistentClass element) { return element.getClassName().replace('.', '/') + ".hbm.xml"; } public String getName() { return "cfg2cfgxml"; } /** * * @param text * @return String with escaped [<,>] special characters. */ public static String forXML(String text) { if (text == null) return null; final StringBuilder result = new StringBuilder(); char[] chars = text.toCharArray(); for (int i = 0; i < chars.length; i++){ char character = chars[i]; if (character == '<') { result.append("&lt;"); } else if (character == '>'){ result.append("&gt;"); } else { result.append(character); } } return result.toString(); } }
true
true
public void doStart() throws ExporterException { PrintWriter pw = null; File file = null; try { if(output==null) { file = new File(getOutputDirectory(), "hibernate.cfg.xml"); getTemplateHelper().ensureExistence(file); pw = new PrintWriter(new FileWriter(file) ); getArtifactCollector().addFile(file, "cfg.xml"); } else { pw = new PrintWriter(output); } pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE hibernate-configuration PUBLIC\r\n" + " \"-//Hibernate/Hibernate Configuration DTD 3.0//EN\"\r\n" + " \"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd\">\r\n" + "<hibernate-configuration>"); boolean ejb3 = Boolean.valueOf((String)getProperties().get("ejb3")).booleanValue(); Map props = new TreeMap(); if(getConfiguration()!=null) { props.putAll(getConfiguration().getProperties() ); } if(customProperties!=null) { props.putAll(customProperties); } String sfname = (String) props.get(Environment.SESSION_FACTORY_NAME); pw.println(" <session-factory" + (sfname==null?"":" name=\"" + sfname + "\"") + ">"); Map ignoredProperties = new HashMap(); ignoredProperties.put(Environment.SESSION_FACTORY_NAME, null); ignoredProperties.put(Environment.HBM2DDL_AUTO, "false" ); ignoredProperties.put("hibernate.temp.use_jdbc_metadata_defaults", null ); ignoredProperties.put(Environment.TRANSACTION_MANAGER_STRATEGY, "org.hibernate.console.FakeTransactionManagerLookup"); Set set = props.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext() ) { Map.Entry element = (Map.Entry) iterator.next(); String key = (String) element.getKey(); if(ignoredProperties.containsKey( key )) { Object ignoredValue = ignoredProperties.get( key ); if(ignoredValue == null || element.getValue().equals(ignoredValue)) { continue; } } if(key.startsWith("hibernate.") ) { // if not starting with hibernate. not relevant for cfg.xml pw.println(" <property name=\"" + key + "\">" + forXML(element.getValue().toString()) + "</property>"); } } if(getConfiguration()!=null) { Iterator classMappings = getConfiguration().getClassMappings(); while (classMappings.hasNext() ) { PersistentClass element = (PersistentClass) classMappings.next(); if(element instanceof RootClass) { dump(pw, ejb3, element); } } } pw.println(" </session-factory>\r\n" + "</hibernate-configuration>"); } catch (IOException e) { throw new ExporterException("Problems while creating hibernate.cfg.xml", e); } finally { if(pw!=null) { pw.flush(); pw.close(); } } }
public void doStart() throws ExporterException { PrintWriter pw = null; File file = null; try { if(output==null) { file = new File(getOutputDirectory(), "hibernate.cfg.xml"); getTemplateHelper().ensureExistence(file); pw = new PrintWriter(new FileWriter(file) ); getArtifactCollector().addFile(file, "cfg.xml"); } else { pw = new PrintWriter(output); } pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE hibernate-configuration PUBLIC\r\n" + " \"-//Hibernate/Hibernate Configuration DTD 3.0//EN\"\r\n" + " \"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd\">\r\n" + "<hibernate-configuration>"); boolean ejb3 = Boolean.valueOf((String)getProperties().get("ejb3")).booleanValue(); Map props = new TreeMap(); if(getConfiguration()!=null) { props.putAll(getConfiguration().getProperties() ); } if(customProperties!=null) { props.putAll(customProperties); } String sfname = (String) props.get(Environment.SESSION_FACTORY_NAME); pw.println(" <session-factory" + (sfname==null?"":" name=\"" + sfname + "\"") + ">"); Map ignoredProperties = new HashMap(); ignoredProperties.put(Environment.SESSION_FACTORY_NAME, null); ignoredProperties.put(Environment.HBM2DDL_AUTO, "false" ); ignoredProperties.put("hibernate.temp.use_jdbc_metadata_defaults", null ); ignoredProperties.put(Environment.TRANSACTION_MANAGER_STRATEGY, "org.hibernate.console.FakeTransactionManagerLookup"); Set set = props.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext() ) { Map.Entry element = (Map.Entry) iterator.next(); String key = (String) element.getKey(); if(ignoredProperties.containsKey( key )) { Object ignoredValue = ignoredProperties.get( key ); if(ignoredValue == null || element.getValue().equals(ignoredValue)) { continue; } } if(key.startsWith("hibernate.") ) { // if not starting with hibernate. not relevant for cfg.xml pw.println(" <property name=\"" + key + "\">" + forXML(element.getValue().toString()) + "</property>"); } } if(getConfiguration()!=null) { Iterator classMappings = getConfiguration().getClassMappings(); while (classMappings.hasNext() ) { PersistentClass element = (PersistentClass) classMappings.next(); if(element instanceof RootClass) { dump(pw, ejb3, element); } } } pw.println(" </session-factory>\r\n" + "</hibernate-configuration>"); } catch (IOException e) { throw new ExporterException("Problems while creating hibernate.cfg.xml", e); } finally { if(pw!=null) { pw.flush(); pw.close(); } } }
diff --git a/src/main/java/org/jmxexporter/QueryResult.java b/src/main/java/org/jmxexporter/QueryResult.java index 77a77a2..deab93e 100644 --- a/src/main/java/org/jmxexporter/QueryResult.java +++ b/src/main/java/org/jmxexporter/QueryResult.java @@ -1,77 +1,77 @@ /* * Copyright 2008-2012 Xebia and 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.jmxexporter; import org.jmxexporter.util.Preconditions; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.sql.Timestamp; import java.util.concurrent.TimeUnit; /** * Value of a collected metric. * * @author <a href="mailto:[email protected]">Cyrille Le Clerc</a> */ public class QueryResult { @Nonnull private final String name; private final long epochInMillis; @Nullable private final Object value; /** * @param name plain name of the metric (variables (e.g. <code>%my-jmx-attr%</code> must have been resolved). * @param value value of the collected metric * @param epochInMillis collect time in millis (see {@link System#currentTimeMillis()}) */ public QueryResult(@Nonnull String name, @Nullable Object value, long epochInMillis) { this.name = Preconditions.checkNotEmpty(name); this.value = value; this.epochInMillis = epochInMillis; } @Nonnull public String getName() { return name; } public long getEpochInMillis() { return epochInMillis; } public long getEpoch(TimeUnit timeUnit) { return timeUnit.convert(epochInMillis, TimeUnit.MILLISECONDS); } @Nullable public Object getValue() { return value; } @Override public String toString() { return "QueryResult{" + - ", epoch=" + new Timestamp(epochInMillis) + + " epoch=" + new Timestamp(epochInMillis) + ", name='" + name + '\'' + ", value=" + value + '}'; } }
true
true
public String toString() { return "QueryResult{" + ", epoch=" + new Timestamp(epochInMillis) + ", name='" + name + '\'' + ", value=" + value + '}'; }
public String toString() { return "QueryResult{" + " epoch=" + new Timestamp(epochInMillis) + ", name='" + name + '\'' + ", value=" + value + '}'; }
diff --git a/src/java/main/esg/node/filters/AccessLoggingFilter.java b/src/java/main/esg/node/filters/AccessLoggingFilter.java index ce89340..1f274f2 100644 --- a/src/java/main/esg/node/filters/AccessLoggingFilter.java +++ b/src/java/main/esg/node/filters/AccessLoggingFilter.java @@ -1,422 +1,423 @@ /*************************************************************************** * * * Organization: Earth System Grid Federation * * * **************************************************************************** * * * Copyright (c) 2009, Lawrence Livermore National Security, LLC. * * Produced at the Lawrence Livermore National Laboratory * * Written by: Gavin M. Bell ([email protected]) * * LLNL-CODE-420962 * * * * All rights reserved. This file is part of the: * * Earth System Grid Federation (ESGF) Data Node Software Stack * * * * For details, see http://esgf.org/ * * Please also read this link * * http://esgf.org/LICENSE * * * * * Redistribution and use in source and binary forms, with or * * without modification, are permitted provided that the following * * conditions are met: * * * * * Redistributions of source code must retain the above copyright * * notice, this list of conditions and the disclaimer below. * * * * * Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the disclaimer (as noted below) * * in the documentation and/or other materials provided with the * * distribution. * * * * Neither the name of the LLNS/LLNL nor the names of its contributors * * may be used to endorse or promote products derived from this * * software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE * * LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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. * * * ***************************************************************************/ /** Description: The web.xml entry... (NOTE: must appear AFTER all Authorization Filters because they put additional information in the request that we need like email address and/or userid) <!-- Filter for token-based authorization --> <filter> <filter-name>AccessLoggingFilter</filter-name> <filter-class>esg.node.filters.AccessLoggingFilter</filter-class> <!-- <init-param> <param-name>db.driver</param-name> <param-value>org.postgresql.Driver</param-value> </init-param> <init-param> <param-name>db.protocol</param-name> <param-value>jdbc:postgresql:</param-value> </init-param> <init-param> <param-name>db.host</param-name> <param-value>localhost</param-value> </init-param> <init-param> <param-name>db.port</param-name> <param-value>5432</param-value> </init-param> <init-param> <param-name>db.database</param-name> <param-value>esgcet</param-value> </init-param> <init-param> <param-name>db.user</param-name> <param-value>dbsuper</param-value> </init-param> <init-param> <param-name>db.password</param-name> <param-value>***</param-value> </init-param> --> <init-param> <param-name>service.name</param-name> <param-value>thredds</param-value> </init-param> <init-param> <param-name>exempt_extensions</param-name> <param-value>.xml</param-value> <param-name>extensions</param-name> <param-value>.nc,.foo,.bar</param-value> </init-param> </filter> <filter-mapping> <filter-name>AccessLoggingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> **/ package esg.node.filters; import java.io.File; import java.io.InputStream; import java.io.IOException; import java.util.Properties; import java.util.Map; import java.util.regex.*; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.impl.*; import esg.common.db.DatabaseResource; import esg.common.util.ESGFProperties; public class AccessLoggingFilter implements Filter { final static String AUTHORIZATION_REQUEST_ATTRIBUTE = "eske.model.security.AuthorizationToken"; // legacy value compatible with old TDS filter private static Log log = LogFactory.getLog(AccessLoggingFilter.class); FilterConfig filterConfig = null; AccessLoggingDAO accessLoggingDAO = null; Properties dbProperties = null; private Pattern urlExtensionPattern = null; private Pattern exemptUrlPattern = null; private Pattern mountedPathPattern; private Pattern urlPattern = null; private MountedPathResolver mpResolver = null; private String serviceName = null; public void init(FilterConfig filterConfig) throws ServletException { System.out.println("Initializing filter: "+this.getClass().getName()); this.filterConfig = filterConfig; ESGFProperties esgfProperties = null; try{ esgfProperties = new ESGFProperties(); }catch (java.io.IOException e) { e.printStackTrace(); log.error(e); } String value = null; dbProperties = new Properties(); log.debug("FilterConfig is : ["+filterConfig+"]"); log.debug("db.protocol is : ["+filterConfig.getInitParameter("db.protocol")+"]"); dbProperties.put("db.protocol",((null != (value = filterConfig.getInitParameter("db.protocol"))) ? value : esgfProperties.getProperty("db.protocol"))); value = null; dbProperties.put("db.host",((null != (value = filterConfig.getInitParameter("db.host"))) ? value : esgfProperties.getProperty("db.host"))); value = null; dbProperties.put("db.port",((null != (value = filterConfig.getInitParameter("db.port"))) ? value : esgfProperties.getProperty("db.port"))); value = null; dbProperties.put("db.database",((null != (value = filterConfig.getInitParameter("db.database"))) ? value : esgfProperties.getProperty("db.database"))); value = null; dbProperties.put("db.user",((null != (value = filterConfig.getInitParameter("db.user"))) ? value : esgfProperties.getProperty("db.user"))); value = null; dbProperties.put("db.password",((null != (value = filterConfig.getInitParameter("db.password"))) ? value : esgfProperties.getDatabasePassword())); value = null; dbProperties.put("db.driver",((null != (value = filterConfig.getInitParameter("db.driver"))) ? value : esgfProperties.getProperty("db.driver","org.postgresql.Driver"))); value = null; serviceName = (null != (value = filterConfig.getInitParameter("service.name"))) ? value : "thredds"; value = null; log.debug("Database parameters: "+dbProperties); DatabaseResource.init(dbProperties.getProperty("db.driver","org.postgresql.Driver")).setupDataSource(dbProperties); DatabaseResource.getInstance().showDriverStats(); accessLoggingDAO = new AccessLoggingDAO(DatabaseResource.getInstance().getDataSource()); //------------------------------------------------------------------------ // Extensions that this filter will handle... //------------------------------------------------------------------------ String extensionsParam = filterConfig.getInitParameter("extensions"); if (extensionsParam == null) { extensionsParam=""; } //defensive program against null for this param String[] extensions = (".nc,"+extensionsParam.toString()).split(","); StringBuffer sb = new StringBuffer(); for(int i=0 ; i<extensions.length; i++) { sb.append(extensions[i].trim()); if(i<extensions.length-1) sb.append("|"); } System.out.println("Looking for extensions: "+sb.toString()); String regex = "http.*(?:"+sb.toString()+")$"; System.out.println("Regex = "+regex); urlExtensionPattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE); //------------------------------------------------------------------------ //------------------------------------------------------------------------ // Extensions that this filter will NOT handle... //------------------------------------------------------------------------ String exemptExtensionsParam = filterConfig.getInitParameter("exempt_extensions"); if (exemptExtensionsParam == null) { exemptExtensionsParam=""; } //defensive program against null for this param String[] exemptExtensions = (".xml,"+exemptExtensionsParam.toString()).split(","); sb = new StringBuffer(); for(int i=0 ; i<exemptExtensions.length; i++) { sb.append(exemptExtensions[i].trim()); if(i<exemptExtensions.length-1) sb.append("|"); } System.out.println("Looking for exempt extensions: "+sb.toString()); regex = "http.*(?:"+sb.toString()+")$"; System.out.println("Exempt Regex = "+regex); exemptUrlPattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE); //------------------------------------------------------------------------ log.trace(accessLoggingDAO.toString()); String svc_prefix = esgfProperties.getProperty("node.download.svc.prefix","thredds/fileServer"); String mountedPathRegex = "http[s]?://([^:/]*)(:(?:[0-9]*))?/"+svc_prefix+"(.*$)"; mountedPathPattern = Pattern.compile(mountedPathRegex,Pattern.CASE_INSENSITIVE); String urlRegex = "http[s]?://([^:/]*)(:(?:[0-9]*))?/(.*$)"; urlPattern = Pattern.compile(urlRegex,Pattern.CASE_INSENSITIVE); mpResolver = new MountedPathResolver((new esg.common.util.ESGIni()).getMounts()); } public void destroy() { this.filterConfig = null; this.dbProperties.clear(); this.accessLoggingDAO = null; //Shutting down this resource under the assuption that no one //else is using this resource but us DatabaseResource.getInstance().shutdownResource(); } @SuppressWarnings("unchecked") public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if(filterConfig == null) return; int id = -1; //Record identifying tuple String userID = null; String email = null; String url = null; String fileID = null; String remoteAddress = null; String userAgent = null; long dateFetched = 0L; long batchUpdateTime = 0L; + boolean hasNoBackingFile = false; //(note: serviceName defined in global scope) //firewall off any errors so that nothing stops the show... try { log.debug("accessLogging DAO -> "+accessLoggingDAO); if(accessLoggingDAO != null) { //This filter should only appy to specific requests //in particular requests for data files (*.nc) HttpServletRequest req = (HttpServletRequest)request; url = req.getRequestURL().toString().trim(); System.out.println("Requested URL: ["+url+"]"); //Don't need this anymore... but too much of a pain at the moment to change //Remember to change the filter xml entry file in the installer //filters/esg-access-logging-filter b/filters/esg-access-logging-filter Matcher exemptFilesMatcher = exemptUrlPattern.matcher(url); if(exemptFilesMatcher.matches()) { System.out.println("I am not logging this, punting on: ["+url+"]"); chain.doFilter(request, response); return; } Matcher allowedFilesMatcher = urlExtensionPattern.matcher(url); if(!allowedFilesMatcher.matches()) { System.out.println("This is not a url that we are interested in logging: ["+url+"]"); chain.doFilter(request, response); return; } // only proceed if the request has been authorized final Boolean requestIsAuthorized = (Boolean)request.getAttribute(AUTHORIZATION_REQUEST_ATTRIBUTE); log.debug("AUTHORIZATION_REQUEST_ATTRIBUTE="+requestIsAuthorized); if (requestIsAuthorized==null || requestIsAuthorized==false) { System.out.println("**UnAuthorized Request, punting on: "+req.getRequestURL().toString().trim()); chain.doFilter(request, response); return; } System.out.println("Executing filter on: "+url); //------------------------------------------------------------------------------------------ //For Token authentication there is a Validation Map present with user and email information //------------------------------------------------------------------------------------------ Map<String,String> validationMap = (Map<String,String>)req.getAttribute("validationMap"); if(validationMap != null) { userID = validationMap.get("user"); email = validationMap.get("email"); //Want to make sure that any snooping filters //behind this one does not have access to this //information (posted by the //authorizationTokenValidationFilter, which should //immediately preceed this one). This is in //effort to limit information exposure the //best we can. req.removeAttribute("validationMap"); }else{ log.warn("Validation Map is ["+validationMap+"] - (not a token based request)"); } //------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------ //For TokenLESS authentication the userid information is in a parameter called "esg.openid" //------------------------------------------------------------------------------------------ if (userID == null || userID.isEmpty()) { userID = ((req.getAttribute("esg.openid") == null) ? "<no-id>" : req.getAttribute("esg.openid").toString()); if(userID == null || userID.isEmpty()) { log.warn("This request is apparently not a \"tokenless\" request either - no openid attribute!!!!!"); } log.warn("AccessLoggingFilter - Tokenless: UserID = ["+userID+"]"); } //------------------------------------------------------------------------------------------ fileID = "0A"; remoteAddress = req.getRemoteAddr(); userAgent = (String)req.getAttribute("userAgent"); dateFetched = System.currentTimeMillis()/1000; batchUpdateTime = dateFetched; //For the life of my I am not sure why this is there, something from the gridftp metrics collection. -gmb id = accessLoggingDAO.logIngressInfo(userID,email,url,fileID,remoteAddress,userAgent,serviceName,batchUpdateTime,dateFetched); System.out.println("myID: ["+id+"] = accessLoggingDAO.logIngressInfo(userID: ["+userID+"], email, url: ["+url+"], fileID, remoteAddress, userAgent, serviceName, batchUpdateTime, dateFetched)"); }else{ log.error("DAO is null :["+accessLoggingDAO+"]"); HttpServletResponse resp = (HttpServletResponse)response; resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid State Of ESG Access Logging Filter: DAO=["+accessLoggingDAO+"]"); } }catch(Throwable t) { log.error(t); HttpServletResponse resp = (HttpServletResponse)response; resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Caught unforseen Exception in ESG Access Logging Filter"); } try{ ByteCountListener byteCountListener = new ByteCountListener() { int myID = -1; long duration = -1; long startTime = -1; long dataSize = -1; long byteCount = -1; boolean success = false; public void setRecordID(int id) { this.myID = id; } public void setStartTime(long startTime) { this.startTime = startTime; } public void setDataSizeBytes(long dataSize) { this.dataSize = dataSize; } //This callback method should get called by the ByteCountingResponseStream when it is *closed* public void setByteCount(long xferSize) { byteCount=xferSize; System.out.println("**** setByteCount("+xferSize+")"); if((AccessLoggingFilter.this.accessLoggingDAO != null) && (myID > 0)) { if (dataSize == xferSize) { success = true; } duration = System.currentTimeMillis() - startTime; System.out.println("AccessLoggingFilter.this.accessLoggingDAO.logEgressInfo(myID: ["+myID+"], success: ["+success+"], duration: ["+duration+"]ms, dataSize ["+dataSize+"], xferSize: ["+xferSize+"] );"); AccessLoggingFilter.this.accessLoggingDAO.logEgressInfo(myID, success, duration, dataSize, xferSize); } } public long getByteCount() { return byteCount; } }; byteCountListener.setRecordID(id); byteCountListener.setDataSizeBytes(resolveUrlToFile(url).length()); byteCountListener.setStartTime(System.currentTimeMillis()); AccessLoggingResponseWrapper accessLoggingResponseWrapper = new AccessLoggingResponseWrapper((HttpServletResponse)response, byteCountListener); chain.doFilter(request, accessLoggingResponseWrapper); }catch(Throwable t) { log.error(t); HttpServletResponse resp = (HttpServletResponse)response; resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Caught unforseen Exception in ESG Access Logging Filter (url may not be resolvable to an exisiting file) "+t.getMessage()); } } //Here we resolve the URL passed in to where the bits reside on the filesystem. private File resolveUrlToFile(String url) { //Strip url down to just the path... System.out.println("AccessLoggingFilter.resolveUrlToFile("+url+")"); Matcher fsMatcher = mountedPathPattern.matcher(url); Matcher urlMatcher = urlPattern.matcher(url); String path = null; if (fsMatcher.find()) { System.out.println("Group 3 = "+fsMatcher.group(3)); path = mpResolver.resolve(fsMatcher.group(3)); System.out.println("Mountpoint transformation of url path: ["+url+"] -to-> ["+path+"]"); }else if (urlMatcher.find()) { System.out.println("Group 3 = "+urlMatcher.group(3)); path = urlMatcher.group(3); System.out.println("*NO Mountpoint transformation of url path: ["+url+"] -to-> ["+path+"]"); } File resolvedFile = null; try{ resolvedFile = new File(path); if ((resolvedFile != null) && resolvedFile.exists()) { return resolvedFile; }else{ log.error("Unable to resolve ["+path+"] to existing filesystem location"); } }catch(Exception e) { e.printStackTrace(); log.error(e); } return resolvedFile; } }
true
true
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if(filterConfig == null) return; int id = -1; //Record identifying tuple String userID = null; String email = null; String url = null; String fileID = null; String remoteAddress = null; String userAgent = null; long dateFetched = 0L; long batchUpdateTime = 0L; //(note: serviceName defined in global scope) //firewall off any errors so that nothing stops the show... try { log.debug("accessLogging DAO -> "+accessLoggingDAO); if(accessLoggingDAO != null) { //This filter should only appy to specific requests //in particular requests for data files (*.nc) HttpServletRequest req = (HttpServletRequest)request; url = req.getRequestURL().toString().trim(); System.out.println("Requested URL: ["+url+"]"); //Don't need this anymore... but too much of a pain at the moment to change //Remember to change the filter xml entry file in the installer //filters/esg-access-logging-filter b/filters/esg-access-logging-filter Matcher exemptFilesMatcher = exemptUrlPattern.matcher(url); if(exemptFilesMatcher.matches()) { System.out.println("I am not logging this, punting on: ["+url+"]"); chain.doFilter(request, response); return; } Matcher allowedFilesMatcher = urlExtensionPattern.matcher(url); if(!allowedFilesMatcher.matches()) { System.out.println("This is not a url that we are interested in logging: ["+url+"]"); chain.doFilter(request, response); return; } // only proceed if the request has been authorized final Boolean requestIsAuthorized = (Boolean)request.getAttribute(AUTHORIZATION_REQUEST_ATTRIBUTE); log.debug("AUTHORIZATION_REQUEST_ATTRIBUTE="+requestIsAuthorized); if (requestIsAuthorized==null || requestIsAuthorized==false) { System.out.println("**UnAuthorized Request, punting on: "+req.getRequestURL().toString().trim()); chain.doFilter(request, response); return; } System.out.println("Executing filter on: "+url); //------------------------------------------------------------------------------------------ //For Token authentication there is a Validation Map present with user and email information //------------------------------------------------------------------------------------------ Map<String,String> validationMap = (Map<String,String>)req.getAttribute("validationMap"); if(validationMap != null) { userID = validationMap.get("user"); email = validationMap.get("email"); //Want to make sure that any snooping filters //behind this one does not have access to this //information (posted by the //authorizationTokenValidationFilter, which should //immediately preceed this one). This is in //effort to limit information exposure the //best we can. req.removeAttribute("validationMap"); }else{ log.warn("Validation Map is ["+validationMap+"] - (not a token based request)"); } //------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------ //For TokenLESS authentication the userid information is in a parameter called "esg.openid" //------------------------------------------------------------------------------------------ if (userID == null || userID.isEmpty()) { userID = ((req.getAttribute("esg.openid") == null) ? "<no-id>" : req.getAttribute("esg.openid").toString()); if(userID == null || userID.isEmpty()) { log.warn("This request is apparently not a \"tokenless\" request either - no openid attribute!!!!!"); } log.warn("AccessLoggingFilter - Tokenless: UserID = ["+userID+"]"); } //------------------------------------------------------------------------------------------ fileID = "0A"; remoteAddress = req.getRemoteAddr(); userAgent = (String)req.getAttribute("userAgent"); dateFetched = System.currentTimeMillis()/1000; batchUpdateTime = dateFetched; //For the life of my I am not sure why this is there, something from the gridftp metrics collection. -gmb id = accessLoggingDAO.logIngressInfo(userID,email,url,fileID,remoteAddress,userAgent,serviceName,batchUpdateTime,dateFetched); System.out.println("myID: ["+id+"] = accessLoggingDAO.logIngressInfo(userID: ["+userID+"], email, url: ["+url+"], fileID, remoteAddress, userAgent, serviceName, batchUpdateTime, dateFetched)"); }else{ log.error("DAO is null :["+accessLoggingDAO+"]"); HttpServletResponse resp = (HttpServletResponse)response; resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid State Of ESG Access Logging Filter: DAO=["+accessLoggingDAO+"]"); } }catch(Throwable t) { log.error(t); HttpServletResponse resp = (HttpServletResponse)response; resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Caught unforseen Exception in ESG Access Logging Filter"); } try{ ByteCountListener byteCountListener = new ByteCountListener() { int myID = -1; long duration = -1; long startTime = -1; long dataSize = -1; long byteCount = -1; boolean success = false; public void setRecordID(int id) { this.myID = id; } public void setStartTime(long startTime) { this.startTime = startTime; } public void setDataSizeBytes(long dataSize) { this.dataSize = dataSize; } //This callback method should get called by the ByteCountingResponseStream when it is *closed* public void setByteCount(long xferSize) { byteCount=xferSize; System.out.println("**** setByteCount("+xferSize+")"); if((AccessLoggingFilter.this.accessLoggingDAO != null) && (myID > 0)) { if (dataSize == xferSize) { success = true; } duration = System.currentTimeMillis() - startTime; System.out.println("AccessLoggingFilter.this.accessLoggingDAO.logEgressInfo(myID: ["+myID+"], success: ["+success+"], duration: ["+duration+"]ms, dataSize ["+dataSize+"], xferSize: ["+xferSize+"] );"); AccessLoggingFilter.this.accessLoggingDAO.logEgressInfo(myID, success, duration, dataSize, xferSize); } } public long getByteCount() { return byteCount; } }; byteCountListener.setRecordID(id); byteCountListener.setDataSizeBytes(resolveUrlToFile(url).length()); byteCountListener.setStartTime(System.currentTimeMillis()); AccessLoggingResponseWrapper accessLoggingResponseWrapper = new AccessLoggingResponseWrapper((HttpServletResponse)response, byteCountListener); chain.doFilter(request, accessLoggingResponseWrapper); }catch(Throwable t) { log.error(t); HttpServletResponse resp = (HttpServletResponse)response; resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Caught unforseen Exception in ESG Access Logging Filter (url may not be resolvable to an exisiting file) "+t.getMessage()); } }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if(filterConfig == null) return; int id = -1; //Record identifying tuple String userID = null; String email = null; String url = null; String fileID = null; String remoteAddress = null; String userAgent = null; long dateFetched = 0L; long batchUpdateTime = 0L; boolean hasNoBackingFile = false; //(note: serviceName defined in global scope) //firewall off any errors so that nothing stops the show... try { log.debug("accessLogging DAO -> "+accessLoggingDAO); if(accessLoggingDAO != null) { //This filter should only appy to specific requests //in particular requests for data files (*.nc) HttpServletRequest req = (HttpServletRequest)request; url = req.getRequestURL().toString().trim(); System.out.println("Requested URL: ["+url+"]"); //Don't need this anymore... but too much of a pain at the moment to change //Remember to change the filter xml entry file in the installer //filters/esg-access-logging-filter b/filters/esg-access-logging-filter Matcher exemptFilesMatcher = exemptUrlPattern.matcher(url); if(exemptFilesMatcher.matches()) { System.out.println("I am not logging this, punting on: ["+url+"]"); chain.doFilter(request, response); return; } Matcher allowedFilesMatcher = urlExtensionPattern.matcher(url); if(!allowedFilesMatcher.matches()) { System.out.println("This is not a url that we are interested in logging: ["+url+"]"); chain.doFilter(request, response); return; } // only proceed if the request has been authorized final Boolean requestIsAuthorized = (Boolean)request.getAttribute(AUTHORIZATION_REQUEST_ATTRIBUTE); log.debug("AUTHORIZATION_REQUEST_ATTRIBUTE="+requestIsAuthorized); if (requestIsAuthorized==null || requestIsAuthorized==false) { System.out.println("**UnAuthorized Request, punting on: "+req.getRequestURL().toString().trim()); chain.doFilter(request, response); return; } System.out.println("Executing filter on: "+url); //------------------------------------------------------------------------------------------ //For Token authentication there is a Validation Map present with user and email information //------------------------------------------------------------------------------------------ Map<String,String> validationMap = (Map<String,String>)req.getAttribute("validationMap"); if(validationMap != null) { userID = validationMap.get("user"); email = validationMap.get("email"); //Want to make sure that any snooping filters //behind this one does not have access to this //information (posted by the //authorizationTokenValidationFilter, which should //immediately preceed this one). This is in //effort to limit information exposure the //best we can. req.removeAttribute("validationMap"); }else{ log.warn("Validation Map is ["+validationMap+"] - (not a token based request)"); } //------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------ //For TokenLESS authentication the userid information is in a parameter called "esg.openid" //------------------------------------------------------------------------------------------ if (userID == null || userID.isEmpty()) { userID = ((req.getAttribute("esg.openid") == null) ? "<no-id>" : req.getAttribute("esg.openid").toString()); if(userID == null || userID.isEmpty()) { log.warn("This request is apparently not a \"tokenless\" request either - no openid attribute!!!!!"); } log.warn("AccessLoggingFilter - Tokenless: UserID = ["+userID+"]"); } //------------------------------------------------------------------------------------------ fileID = "0A"; remoteAddress = req.getRemoteAddr(); userAgent = (String)req.getAttribute("userAgent"); dateFetched = System.currentTimeMillis()/1000; batchUpdateTime = dateFetched; //For the life of my I am not sure why this is there, something from the gridftp metrics collection. -gmb id = accessLoggingDAO.logIngressInfo(userID,email,url,fileID,remoteAddress,userAgent,serviceName,batchUpdateTime,dateFetched); System.out.println("myID: ["+id+"] = accessLoggingDAO.logIngressInfo(userID: ["+userID+"], email, url: ["+url+"], fileID, remoteAddress, userAgent, serviceName, batchUpdateTime, dateFetched)"); }else{ log.error("DAO is null :["+accessLoggingDAO+"]"); HttpServletResponse resp = (HttpServletResponse)response; resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid State Of ESG Access Logging Filter: DAO=["+accessLoggingDAO+"]"); } }catch(Throwable t) { log.error(t); HttpServletResponse resp = (HttpServletResponse)response; resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Caught unforseen Exception in ESG Access Logging Filter"); } try{ ByteCountListener byteCountListener = new ByteCountListener() { int myID = -1; long duration = -1; long startTime = -1; long dataSize = -1; long byteCount = -1; boolean success = false; public void setRecordID(int id) { this.myID = id; } public void setStartTime(long startTime) { this.startTime = startTime; } public void setDataSizeBytes(long dataSize) { this.dataSize = dataSize; } //This callback method should get called by the ByteCountingResponseStream when it is *closed* public void setByteCount(long xferSize) { byteCount=xferSize; System.out.println("**** setByteCount("+xferSize+")"); if((AccessLoggingFilter.this.accessLoggingDAO != null) && (myID > 0)) { if (dataSize == xferSize) { success = true; } duration = System.currentTimeMillis() - startTime; System.out.println("AccessLoggingFilter.this.accessLoggingDAO.logEgressInfo(myID: ["+myID+"], success: ["+success+"], duration: ["+duration+"]ms, dataSize ["+dataSize+"], xferSize: ["+xferSize+"] );"); AccessLoggingFilter.this.accessLoggingDAO.logEgressInfo(myID, success, duration, dataSize, xferSize); } } public long getByteCount() { return byteCount; } }; byteCountListener.setRecordID(id); byteCountListener.setDataSizeBytes(resolveUrlToFile(url).length()); byteCountListener.setStartTime(System.currentTimeMillis()); AccessLoggingResponseWrapper accessLoggingResponseWrapper = new AccessLoggingResponseWrapper((HttpServletResponse)response, byteCountListener); chain.doFilter(request, accessLoggingResponseWrapper); }catch(Throwable t) { log.error(t); HttpServletResponse resp = (HttpServletResponse)response; resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Caught unforseen Exception in ESG Access Logging Filter (url may not be resolvable to an exisiting file) "+t.getMessage()); } }
diff --git a/src/edu/gatech/oad/antlab/person/Person2.java b/src/edu/gatech/oad/antlab/person/Person2.java index 60b6702..108e9b4 100644 --- a/src/edu/gatech/oad/antlab/person/Person2.java +++ b/src/edu/gatech/oad/antlab/person/Person2.java @@ -1,63 +1,63 @@ package edu.gatech.oad.antlab.person; /** * A simple class for person 2 * returns their name and a * modified string * * @author Vraj Patel * @version 1.1 */ public class Person2 { /** Holds the persons real name */ private String name; /** * The constructor, takes in the persons * name * @param pname the person's real name */ public Person2(String pname) { name = pname; } /** * This method should take the string * input and return its characters in * random order. * given "gtg123b" it should return * something like "g3tb1g2". * * @param input the string to be modified * @return the modified string */ private String calc(String input) { //Person 2 put your implementation here char[] charArray = input.toCharArray(); int shuffle = input.length(); for (int i = 0; i < shuffle; i++) { - int index1 = (int) (Math.random() * turtle.length); - int index2 = (int) (Math.random() * turtle.length); + int index1 = (int) (Math.random() * charArray.length); + int index2 = (int) (Math.random() * charArray.length); char temp1 = turtle[index1]; char temp2 = turtle[index2]; charArray[index2] = temp1; charArray[index1] = temp2; } String newString = new String(charArray); return newString; } /** * Return a string rep of this object * that varies with an input string * * @param input the varying string * @return the string representing the * object */ public String toString(String input) { return name + calc(input); } }
true
true
private String calc(String input) { //Person 2 put your implementation here char[] charArray = input.toCharArray(); int shuffle = input.length(); for (int i = 0; i < shuffle; i++) { int index1 = (int) (Math.random() * turtle.length); int index2 = (int) (Math.random() * turtle.length); char temp1 = turtle[index1]; char temp2 = turtle[index2]; charArray[index2] = temp1; charArray[index1] = temp2; } String newString = new String(charArray); return newString; }
private String calc(String input) { //Person 2 put your implementation here char[] charArray = input.toCharArray(); int shuffle = input.length(); for (int i = 0; i < shuffle; i++) { int index1 = (int) (Math.random() * charArray.length); int index2 = (int) (Math.random() * charArray.length); char temp1 = turtle[index1]; char temp2 = turtle[index2]; charArray[index2] = temp1; charArray[index1] = temp2; } String newString = new String(charArray); return newString; }
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/RoutingServiceImpl.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/RoutingServiceImpl.java index ac2b745..5bc32f6 100644 --- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/RoutingServiceImpl.java +++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/RoutingServiceImpl.java @@ -1,37 +1,37 @@ package org.opentripplanner.routing.impl; import java.util.HashMap; import org.opentripplanner.routing.algorithm.AStar; import org.opentripplanner.routing.core.Edge; import org.opentripplanner.routing.core.Graph; import org.opentripplanner.routing.core.State; import org.opentripplanner.routing.core.TraverseOptions; import org.opentripplanner.routing.core.Vertex; import org.opentripplanner.routing.services.RoutingService; import org.opentripplanner.routing.spt.GraphPath; import org.opentripplanner.routing.spt.ShortestPathTree; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class RoutingServiceImpl implements RoutingService { private Graph _graph; @Autowired public void setGraph(Graph graph) { _graph = graph; } @Override public GraphPath route(Vertex fromVertex, Vertex toVertex, State state, TraverseOptions options) { HashMap<Vertex, Edge> extraEdges = new HashMap<Vertex, Edge>(); - ShortestPathTree spt = AStar.getShortestPathTree(_graph, fromVertex, toVertex, state, - options, extraEdges); + ShortestPathTree spt = AStar.getShortestPathTree(_graph, fromVertex.getLabel(), toVertex.getLabel(), state, + options); return spt.getPath(toVertex); } }
true
true
public GraphPath route(Vertex fromVertex, Vertex toVertex, State state, TraverseOptions options) { HashMap<Vertex, Edge> extraEdges = new HashMap<Vertex, Edge>(); ShortestPathTree spt = AStar.getShortestPathTree(_graph, fromVertex, toVertex, state, options, extraEdges); return spt.getPath(toVertex); }
public GraphPath route(Vertex fromVertex, Vertex toVertex, State state, TraverseOptions options) { HashMap<Vertex, Edge> extraEdges = new HashMap<Vertex, Edge>(); ShortestPathTree spt = AStar.getShortestPathTree(_graph, fromVertex.getLabel(), toVertex.getLabel(), state, options); return spt.getPath(toVertex); }
diff --git a/src/com/group7/dragonwars/GameActivity.java b/src/com/group7/dragonwars/GameActivity.java index 11ea84a..ff06439 100644 --- a/src/com/group7/dragonwars/GameActivity.java +++ b/src/com/group7/dragonwars/GameActivity.java @@ -1,1016 +1,1016 @@ package com.group7.dragonwars; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.res.Configuration; import android.content.DialogInterface; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff.*; import android.graphics.Rect; import android.graphics.RectF; import android.os.Bundle; import android.util.AttributeSet; import android.util.Log; import android.view.GestureDetector; import android.view.GestureDetector.OnDoubleTapListener; import android.view.GestureDetector.OnGestureListener; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.Window; import android.view.WindowManager; import android.widget.Toast; import com.group7.dragonwars.engine.Building; import com.group7.dragonwars.engine.DrawableMapObject; import com.group7.dragonwars.engine.Func; import com.group7.dragonwars.engine.GameField; import com.group7.dragonwars.engine.GameMap; import com.group7.dragonwars.engine.GameState; import com.group7.dragonwars.engine.Logic; import com.group7.dragonwars.engine.MapReader; import com.group7.dragonwars.engine.Position; import com.group7.dragonwars.engine.Pair; import com.group7.dragonwars.engine.Unit; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.json.JSONException; public class GameActivity extends Activity { private static final String TAG = "GameActivity"; private Integer orientation; private Boolean orientationChanged = false; @Override protected final void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); // remove the title bar requestWindowFeature(Window.FEATURE_NO_TITLE); // remove the status bar getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); Log.d(TAG, "in onCreate"); setContentView(R.layout.activity_game); } } class GameView extends SurfaceView implements SurfaceHolder.Callback, OnGestureListener, OnDoubleTapListener, DialogInterface.OnClickListener { private final String TAG = "GameView"; private final int tilesize = 64; private Bitmap bm; private GameState state; private Logic logic; private GameMap map; private Position selected; // Currently selected position private Position attack_location; private Position action_location; private FloatPair scrollOffset; // offset caused by scrolling, in pixels private GestureDetector gestureDetector; private DrawingThread dt; private Bitmap highlighter; private Bitmap selector; private Bitmap attack_highlighter; private Paint move_high_paint; // used to highlight movements private Paint attack_high_paint; // used to highlight possible attacks private Bitmap fullMap; private boolean unit_selected; // true if there is a unit at selection private boolean attack_action; /* true if during an attack action: * user selects a unit, selects a field * chooses attack **attack_move is now true * selects another field **attack_location is the location of the attack * */ private boolean build_menu; /* true if the build menu is being shown * for the building at selected * made false if the user presses elsewhere * (or actually builds something) */ private Context context; private HashMap<String, HashMap<String, Bitmap>> graphics; private Integer orientation; private GameField lastField; private Unit lastUnit; private List<Position> lastDestinations; private Long timeElapsed = 0L; private Long framesSinceLastSecond = 0L; private Long timeNow = 0L; private Double fps = 0.0; public GameView(final Context ctx, final AttributeSet attrset) { super(ctx, attrset); Log.d(TAG, "GameView ctor"); GameView gameView = (GameView) this.findViewById(R.id.game_view); GameMap gm = null; Log.d(TAG, "nulling GameMap"); try { gm = MapReader.readMap(readFile(R.raw.cornermap)); // ugh } catch (JSONException e) { Log.d(TAG, "Failed to load the map: " + e.getMessage()); } if (gm == null) { Log.d(TAG, "gm is null"); System.exit(1); } Log.d(TAG, "before setMap"); gameView.setMap(gm); this.logic = new Logic(); this.state = new GameState(map, logic, map.getPlayers()); context = ctx; bm = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher); SurfaceHolder holder = getHolder(); this.graphics = new HashMap<String, HashMap<String, Bitmap>>(); /* Register game fields */ putGroup("Fields", map.getGameFieldMap()); putGroup("Units", map.getUnitMap()); putGroup("Buildings", map.getBuildingMap()); loadBorders(); /* Load selector and highlighters */ selector = getResource("selector", "drawable", "com.group7.dragonwars"); highlighter = getResource("highlight", "drawable", "com.group7.dragonwars"); attack_highlighter = getResource("attack_highlight", "drawable", "com.group7.dragonwars"); holder.addCallback(this); selected = new Position(0, 0); action_location = new Position(0, 0); gestureDetector = new GestureDetector(this.getContext(), this); scrollOffset = new FloatPair(0f, 0f); move_high_paint = new Paint(); move_high_paint.setStyle(Paint.Style.FILL); move_high_paint.setARGB(150, 0, 0, 255); // semi-transparent blue attack_high_paint = new Paint(); attack_high_paint.setStyle(Paint.Style.FILL); attack_high_paint.setARGB(150, 255, 0, 0); // semi-transparent red build_menu = false; attack_action = false; /* Prerender combined map */ fullMap = combineMap(); } private <T extends DrawableMapObject> void putGroup(final String category, final Map<Character, T> objMap) { graphics.put(category, new HashMap<String, Bitmap>()); for (Map.Entry<Character, T> ent : objMap.entrySet()) { T f = ent.getValue(); putResource(category, f.getSpriteLocation(), f.getSpriteDir(), f.getSpritePack(), f.getName()); } } private void putResource(final String category, final String resName, final String resDir, final String resPack, final String regName) { Bitmap bMap = getResource(resName, resDir, resPack); graphics.get(category).put(regName, bMap); } private Bitmap getResource(final String resName, final String resDir, final String resPack) { Integer resourceID = getResources().getIdentifier(resName, resDir, resPack); Bitmap bMap = BitmapFactory.decodeResource(context.getResources(), resourceID); return bMap; } /* Helper for loadBorders() */ private void loadField(final String resName, final String regName) { putResource("Fields", resName, "drawable", "com.group7.dragonwars", regName); } /* TODO do not hardcode */ private void loadBorders() { loadField("water_grass_edge1", "Top grass->water border"); loadField("water_grass_edge2", "Right grass->water border"); loadField("water_grass_edge3", "Bottom grass->water border"); loadField("water_grass_edge4", "Left grass->water border"); loadField("grass_water_corner1", "Water->grass corner NE"); loadField("grass_water_corner2", "Water->grass corner SE"); loadField("grass_water_corner3", "Water->grass corner SW"); loadField("grass_water_corner4", "Water->grass corner NW"); loadField("water_grass_corner1", "Grass->water corner SW"); loadField("water_grass_corner2", "Grass->water corner NW"); loadField("water_grass_corner3", "Grass->water corner NE"); loadField("water_grass_corner4", "Grass->water corner SE"); } /* * This method will combine the static part of the map into * a single bitmap. This should make it far faster to render * and prevent any tearing while scrolling the map */ private Bitmap combineMap() { Bitmap result = null; Integer width = map.getWidth() * tilesize; Integer height = map.getHeight() * tilesize; result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas combined = new Canvas(result); for (int i = 0; i < map.getWidth(); ++i) { for (int j = 0; j < map.getHeight(); j++) { Position pos = new Position(i, j); GameField gf = map.getField(i, j); String gfn = gf.getName(); RectF dest = getSquare(tilesize * i, tilesize * j, tilesize); combined.drawBitmap(graphics.get("Fields").get(gfn), null, dest, null); drawBorder(combined, pos, dest); if (gf.hostsBuilding()) { Building b = gf.getBuilding(); String n = b.getName(); combined.drawBitmap(graphics.get("Buildings").get(n), null, dest, null); } } } return result; } private List<String> readFile(final int resourceid) { List<String> text = new ArrayList<String>(); try { BufferedReader in = new BufferedReader( new InputStreamReader(this.getResources() .openRawResource(resourceid))); String line; while ((line = in.readLine()) != null) { text.add(line); } in.close(); } catch (FileNotFoundException fnf) { System.err.println("Couldn't find " + fnf.getMessage()); System.exit(1); } catch (IOException ioe) { System.err.println("Couldn't read " + ioe.getMessage()); System.exit(1); } return text; } public void setMap(final GameMap newmap) { this.map = newmap; } @Override public void surfaceChanged(final SurfaceHolder arg0, final int arg1, final int arg2, final int arg3) { // TODO Auto-generated method stub } @Override public void surfaceCreated(final SurfaceHolder arg0) { dt = new DrawingThread(arg0, context, this); dt.setRunning(true); dt.start(); } @Override public void surfaceDestroyed(final SurfaceHolder arg0) { dt.setRunning(false); try { dt.join(); } catch (InterruptedException e) { // TODO something, perhaps, but what? return; } } @Override public boolean onTouchEvent(final MotionEvent event) { /* Functionality moved to onSingleTapConfirmed() */ gestureDetector.onTouchEvent(event); return true; } public RectF getSquare(final float x, final float y, final float length) { return new RectF(x, y, x + length, y + length); } public List<Position> getUnitDestinations(final GameField selectedField) { List<Position> unitDests = new ArrayList<Position>(0); /* First time clicking */ if (lastUnit == null || lastField == null || lastDestinations == null) { lastField = selectedField; if (selectedField.hostsUnit()) { Unit unit = selectedField.getUnit(); lastUnit = unit; unitDests = logic.destinations(map, unit); lastDestinations = unitDests; } else { unitDests = new ArrayList<Position>(0); lastDestinations = unitDests; } } if (selectedField.equals(lastField) && selectedField.hostsUnit()) { /* Same unit, same place */ if (selectedField.getUnit().equals(lastUnit)) { unitDests = lastDestinations; } } else { if (selectedField.hostsUnit()) { unitDests = logic.destinations(map, selectedField.getUnit()); } lastDestinations = unitDests; lastField = selectedField; lastUnit = selectedField.getUnit(); /* Fine if null */ } return unitDests; } public void drawBorder(final Canvas canvas, final Position currentField, final RectF dest) { /* TODO not hard-code this */ Integer i = currentField.getX(); Integer j = currentField.getY(); final String FAKE = "NoTaReAlTiL3"; String gfn = map.getField(currentField).getName(); Position nep, np, nwp, ep, cp, wp, sep, sp, swp; String ne, n, nw, e, c, w, se, s, sw; nep = new Position(i - 1, j - 1); np = new Position(i, j - 1); nwp = new Position(i + 1, j - 1); ep = new Position(i - 1, j); cp = new Position(i, j); wp = new Position(i + 1, j); sep = new Position(i - 1, j + 1); sp = new Position(i, j + 1); swp = new Position(i + 1, j + 1); ne = map.isValidField(nep) ? map.getField(nep).toString() : FAKE; n = map.isValidField(np) ? map.getField(np).toString() : FAKE; nw = map.isValidField(nwp) ? map.getField(nwp).toString() : FAKE; e = map.isValidField(ep) ? map.getField(ep).toString() : FAKE; c = map.isValidField(cp) ? map.getField(cp).toString() : FAKE; w = map.isValidField(wp) ? map.getField(wp).toString() : FAKE; se = map.isValidField(sep) ? map.getField(sep).toString() : FAKE; s = map.isValidField(sp) ? map.getField(sp).toString() : FAKE; sw = map.isValidField(swp) ? map.getField(swp).toString() : FAKE; Func<String, Void> drawer = new Func<String, Void>() { public Void apply(String sprite) { canvas.drawBitmap(graphics.get("Fields").get(sprite), null, dest, null); return null; /* Java strikes again */ } }; if (gfn.equals("Water")) { if (w.equals("Grass")) { drawer.apply("Right grass->water border"); } if (e.equals("Grass")) { drawer.apply("Left grass->water border"); } if (s.equals("Grass")) { drawer.apply("Top grass->water border"); } if (n.equals("Grass")) { drawer.apply("Bottom grass->water border"); } if (s.equals("Water") && w.equals("Water") && sw.equals("Grass")) { drawer.apply("Grass->water corner SW"); } if (s.equals("Water") && e.equals("Water") && se.equals("Grass")) { drawer.apply("Grass->water corner SE"); } if (n.equals("Water") && w.equals("Water") && nw.equals("Grass")) { drawer.apply("Grass->water corner NW"); } if (n.equals("Water") && e.equals("Water") && ne.equals("Grass")) { drawer.apply("Grass->water corner NE"); } if (w.equals("Grass") && s.equals("Grass") && sw.equals("Grass")) { drawer.apply("Water->grass corner SW"); } if (e.equals("Grass") && s.equals("Grass") && se.equals("Grass")) { drawer.apply("Water->grass corner SE"); } if (w.equals("Grass") && n.equals("Grass") && nw.equals("Grass")) { drawer.apply("Water->grass corner NW"); } if (e.equals("Grass") && n.equals("Grass") && ne.equals("Grass")) { drawer.apply("Water->grass corner NE"); } } } /* Debug method */ private List<String> getFieldSquare(final Position p) { List<String> r = new ArrayList<String>(); Integer i, j; i = p.getX(); j = p.getY(); Position nep, np, nwp, ep, cp, wp, sep, sp, swp; String ne, n, nw, e, c, w, se, s, sw; nep = new Position(i - 1, j - 1); np = new Position(i, j - 1); nwp = new Position(i + 1, j - 1); ep = new Position(i - 1, j); cp = new Position(i, j); wp = new Position(i + 1, j); sep = new Position(i - 1, j + 1); sp = new Position(i, j + 1); swp = new Position(i + 1, j + 1); ne = map.isValidField(nep) ? map.getField(nep).toString() : " "; n = map.isValidField(np) ? map.getField(np).toString() : " "; nw = map.isValidField(nwp) ? map.getField(nwp).toString() : " "; e = map.isValidField(ep) ? map.getField(ep).toString() : " "; c = map.isValidField(cp) ? map.getField(cp).toString() : " "; w = map.isValidField(wp) ? map.getField(wp).toString() : " "; se = map.isValidField(sep) ? map.getField(sep).toString() : " "; s = map.isValidField(sp) ? map.getField(sp).toString() : " "; sw = map.isValidField(swp) ? map.getField(swp).toString() : " "; r.add("" + ne.toString().charAt(0) + n.toString().charAt(0) + nw.toString().charAt(0)); r.add("" + e.toString().charAt(0) + c.toString().charAt(0) + w.toString().charAt(0)); r.add("" + se.toString().charAt(0) + s.toString().charAt(0) + sw.toString().charAt(0)); return r; } public void doDraw(final Canvas canvas) { Long startingTime = System.currentTimeMillis(); Configuration c = getResources().getConfiguration(); canvas.drawColor(Color.BLACK); - GameField selectedField = map.getField(selected); + GameField selectedField = map.isValidField(selected) ? map.getField(selected) : map.getField(0, 0); List<Position> unitDests = getUnitDestinations(selectedField); canvas.drawBitmap(fullMap, scrollOffset.getX(), scrollOffset.getY(), null); for (int i = 0; i < map.getWidth(); ++i) { for (int j = 0; j < map.getHeight(); j++) { GameField gf = map.getField(i, j); RectF dest = getSquare( tilesize * i + scrollOffset.getX(), tilesize * j + scrollOffset.getY(), tilesize); if (gf.hostsUnit()) { Unit unit = gf.getUnit(); if (unit != null) { String un = unit.toString(); canvas.drawBitmap(graphics.get("Units").get(un), null, dest, null); } } /* Uncomment to print red grid with some info */ // Paint p = new Paint(); // p.setColor(Color.RED); // canvas.drawText(pos.toString() + gfn.charAt(0), // tilesize * i + scrollOffset.getX(), // tilesize * j + scrollOffset.getY() + 64, p); // List<String> aoe = getFieldSquare(pos); // for (int x = 0; x < aoe.size(); ++x) // canvas.drawText(aoe.get(x), tilesize * i // + scrollOffset.getX(), // tilesize * j + scrollOffset.getY() // + 20 + (x * 10), p); // Paint r = new Paint(); // r.setStyle(Paint.Style.STROKE); // r.setColor(Color.RED); // canvas.drawRect(dest, r); } } /* Destination highlighting */ for (Position pos : unitDests) { RectF dest = getSquare( tilesize * pos.getX() + scrollOffset.getX(), tilesize * pos.getY() + scrollOffset.getY(), tilesize); canvas.drawBitmap(highlighter, null, dest, null); } /* Sometimes draw attackables */ if (attack_action && map.getField(selected).hostsUnit()) { Unit u = map.getField(selected).getUnit(); Set<Position> attack_destinations = logic.getAttackableUnitPositions(map, u, attack_location); //logic.getAttackableFields(map, u); for (Position pos : attack_destinations) { RectF attack_dest = getSquare( tilesize * pos.getX() + scrollOffset.getX(), tilesize * pos.getY() + scrollOffset.getY(), tilesize); canvas.drawBitmap(attack_highlighter, null, attack_dest, null); } } // /* Always draw attackables */ // if (map.getField(selected).hostsUnit()) { // Unit u = map.getField(selected).getUnit(); // Set<Position> attack_destinations = // logic.getAttackableUnitPositions(map, u, selected); // //logic.getAttackableFields(map, u); // for (Position pos : attack_destinations) { // RectF dest = getSquare( // tilesize * pos.getX() + scrollOffset.getX(), // tilesize * pos.getY() + scrollOffset.getY(), // tilesize); // canvas.drawRect(dest, attack_high_paint); // } // } // RectF dest = getSquare( // tilesize * selected.getX() + scrollOffset.getX(), // tilesize * selected.getY() + scrollOffset.getY(), // tilesize); // canvas.drawBitmap(selector, null, dest, null); RectF select_dest = getSquare( tilesize * selected.getX() + scrollOffset.getX(), tilesize * selected.getY() + scrollOffset.getY(), tilesize); canvas.drawBitmap(selector, null, select_dest, null); if (selectedField.hostsUnit()) { drawInfoBox(canvas, selectedField.getUnit(), selectedField, true); } else { drawInfoBox(canvas, null, selectedField, true); } framesSinceLastSecond++; timeElapsed += System.currentTimeMillis() - startingTime; if (timeElapsed >= 1000) { fps = framesSinceLastSecond / (timeElapsed * 0.001); framesSinceLastSecond = 0L; timeElapsed = 0L; } String fpsS = fps.toString(); Paint paint = new Paint(); paint.setARGB(255, 255, 255, 255); canvas.drawText("FPS: " + fpsS, this.getWidth() - 80, 20, paint); } public float getMapDrawWidth() { return map.getWidth() * tilesize; } public float getMapDrawHeight() { return map.getHeight() * tilesize; } public void drawInfoBox(final Canvas canvas, final Unit unit, final GameField field, final boolean left) { String info = field.getInfo(); if (unit != null) { info += unit.getInfo(); } if (field.hostsBuilding()) { info += field.getBuilding().getInfo(); } Paint textPaint = new Paint(); textPaint.setColor(Color.WHITE); String[] ss = info.split("\n"); String longestLine = ""; for (String s : ss) { if (s.length() > longestLine.length()) { longestLine = s; } } Rect bounds = new Rect(); Paint paintMeasure = new Paint(); paintMeasure.getTextBounds(longestLine, 0, longestLine.length(), bounds); Integer boxWidth = bounds.width(); /* Might have to Math.ceil first */ Integer boxHeight = ss.length * bounds.height(); Paint backPaint = new Paint(); backPaint.setColor(Color.BLACK); Rect backRect = new Rect(0, canvas.getHeight() - boxHeight, boxWidth, canvas.getHeight()); canvas.drawRect(backRect, backPaint); for (Integer i = 0; i < ss.length; ++i) { canvas.drawText(ss[i], 0, ss[i].length(), 0, canvas.getHeight() - (bounds.height() * (ss.length - 1 - i)), textPaint); } } @Override public boolean onDown(final MotionEvent e) { return false; } @Override public boolean onFling(final MotionEvent e1, final MotionEvent e2, final float velocityX, final float velocityY) { return false; } @Override public void onLongPress(final MotionEvent e) { } @Override public void onShowPress(final MotionEvent e) { } @Override public boolean onSingleTapUp(final MotionEvent e) { return false; } @Override public boolean onDoubleTap(final MotionEvent e) { return false; } @Override public boolean onDoubleTapEvent(final MotionEvent e) { return false; } @Override public boolean onSingleTapConfirmed(final MotionEvent event) { /* Coordinates of the pressed tile */ int touchX = (int) ((event.getX() - scrollOffset.getX()) / tilesize); int touchY = (int) ((event.getY() - scrollOffset.getY()) / tilesize); Position newselected = new Position(touchX, touchY); if (this.map.isValidField(touchX, touchY)) { build_menu = false; // the user selected another square if (!attack_action) { if (map.getField(selected).hostsUnit()) { //Log.v(null, "A unit is selected!"); /* If the user currently has a unit selected and * selects a field that this unit could move to * (and the unit has not finished it's turn) */ GameField selected_field = map.getField(selected); Unit unit = selected_field.getUnit(); if (!unit.hasFinishedTurn()) { List<Position> unit_destinations = getUnitDestinations(selected_field); // Log.v(null, "after destinations"); // FIXME: why doesn't // unit_destinations.contains(newselected) work? boolean contains = false; for (Position pos : unit_destinations) { if (pos.equals(newselected)) { contains = true; break; } } if (contains) { /* pop up a menu with options: * - Wait (go here and do nothing else * - Attack (if there are units to attack) * Currently, to dismiss/cancel the menu * press anywhere * other than the menu and it will go away. * */ AlertDialog.Builder actions_builder = new AlertDialog.Builder(this.getContext()); actions_builder.setTitle("Actions"); String[] actions = {"Wait here", "Attack"}; actions_builder.setItems(actions, this); actions_builder.create().show(); action_location = newselected; // onClick handles the result newselected = selected; // do not move the selection } } } else { // selected does not host a unit if (map.getField(newselected).hostsBuilding()) { Building building = map.getField(newselected).getBuilding(); if (building.getOwner().equals(state.getCurrentPlayer()) && building.canProduceUnits()) { AlertDialog.Builder buildmenu_builder = new AlertDialog.Builder(this.getContext()); buildmenu_builder.setTitle("Build"); List<Unit> units = building.getProducibleUnits(); String[] buildable_names = new String[units.size()]; for (int i = 0; i < units.size(); ++i) { buildable_names[i] = units.get(i).toString(); } //String[] actions = {"Wait here", "Attack"}; buildmenu_builder.setItems(buildable_names, this); buildmenu_builder.create().show(); build_menu = true; // build menu is being shown } // build menu isn't shown if it isn't the user's turn } } } else { // attack_action GameField field = map.getField(selected); if (field.hostsUnit()) { Unit attacker = field.getUnit(); Set<Position> attack_positions = logic.getAttackableUnitPositions(map, attacker, attack_location); // FIXME: copied this from above to ensure it works, // perhaps .contains(newselected) would work here? boolean contains = false; for (Position pos : attack_positions) { if (pos.equals(newselected)) { contains = true; break; } } if (contains && map.getField(newselected).hostsUnit()) { Unit defender = map.getField(newselected).getUnit(); field.setUnit(null); // move attacker to attack attacker.setPosition(attack_location); map.getField(attack_location).setUnit(attacker); Log.v(null, "attack(!): " + attacker + " attacks " + defender); state.attack(attacker, defender); } else { attack_action = false; // no target unit } } else { attack_action = false; // no unit to perform action } } } selected = newselected; return true; } @Override public boolean onScroll(final MotionEvent e1, final MotionEvent e2, final float distanceX, final float distanceY) { float newX = scrollOffset.getX() - distanceX; if (this.getWidth() >= this.getMapDrawWidth()) { newX = 0; } else if ((-newX) > (getMapDrawWidth() - getWidth())) { newX = -(getMapDrawWidth() - getWidth()); } else if (newX > 0) { newX = 0; } float newY = scrollOffset.getY() - distanceY; if (this.getHeight() >= this.getMapDrawHeight()) { newY = 0; } else if ((-newY) > (getMapDrawHeight() - getHeight())) { newY = -(getMapDrawHeight() - getHeight()); } else if (newY > 0) { newY = 0; } scrollOffset = new FloatPair(newX, newY); return true; } @Override public void onClick(final DialogInterface dialog, final int which) { Log.v(null, "selected option: " + which); if (!build_menu) { switch (which) { case 0: // move Unit unit = map.getField(selected).getUnit(); Boolean moved = state.move(unit, action_location); //TODO: end turn for unit break; case 1: // attack attack_location = action_location; attack_action = true; /* the user will then select one of the attackable spaces * (handled in onSingleTapConfirmed) to perform the attack * onDraw will highlight attackable locations in red */ break; case 2: // capture building // TODO: capture code } } else { // build_menu == true GameField field = map.getField(selected); if (field.hostsBuilding() && (field.getBuilding().getProducibleUnits().size() > which) && state.getCurrentPlayer().equals( field.getBuilding().getOwner())) { Unit unit = map.getField(selected) .getBuilding().getProducibleUnits().get(which); Log.v(null, "building a " + unit); Boolean result = state.produceUnit(map.getField(selected), unit); if (!result) { alertMessage(String.format( "Could not build unit %s (cost: %s)", unit, unit.getProductionCost())); } } else { // how did the user manage that? alertMessage("It's not the building's owner's turn" + ", or there is no building"); } build_menu = false; // build menu gone } } private void alertMessage(String text) { new AlertDialog.Builder(context).setMessage(text) .setPositiveButton("OK", null).show(); } } class DrawingThread extends Thread { private boolean run; private Canvas canvas; private SurfaceHolder surfaceholder; private Context context; private GameView gview; public DrawingThread(final SurfaceHolder sholder, final Context ctx, final GameView gv) { surfaceholder = sholder; context = ctx; run = false; gview = gv; } public void setRunning(final boolean newrun) { run = newrun; } @Override public void run() { super.run(); while (run) { canvas = surfaceholder.lockCanvas(); if (canvas != null) { gview.doDraw(canvas); surfaceholder.unlockCanvasAndPost(canvas); } } } } class FloatPair { private Pair<Float, Float> pair; public FloatPair(final Float x, final Float y) { this.pair = new Pair<Float, Float>(x, y); } public Float getX() { return this.pair.getLeft(); } public Float getY() { return this.pair.getRight(); } public Boolean equals(final FloatPair other) { return this.getX() == other.getX() && this.getY() == other.getY(); } public String toString() { return String.format("(%d, %d)", this.pair.getLeft(), this.pair.getRight()); } }
true
true
public void doDraw(final Canvas canvas) { Long startingTime = System.currentTimeMillis(); Configuration c = getResources().getConfiguration(); canvas.drawColor(Color.BLACK); GameField selectedField = map.getField(selected); List<Position> unitDests = getUnitDestinations(selectedField); canvas.drawBitmap(fullMap, scrollOffset.getX(), scrollOffset.getY(), null); for (int i = 0; i < map.getWidth(); ++i) { for (int j = 0; j < map.getHeight(); j++) { GameField gf = map.getField(i, j); RectF dest = getSquare( tilesize * i + scrollOffset.getX(), tilesize * j + scrollOffset.getY(), tilesize); if (gf.hostsUnit()) { Unit unit = gf.getUnit(); if (unit != null) { String un = unit.toString(); canvas.drawBitmap(graphics.get("Units").get(un), null, dest, null); } } /* Uncomment to print red grid with some info */ // Paint p = new Paint(); // p.setColor(Color.RED); // canvas.drawText(pos.toString() + gfn.charAt(0), // tilesize * i + scrollOffset.getX(), // tilesize * j + scrollOffset.getY() + 64, p); // List<String> aoe = getFieldSquare(pos); // for (int x = 0; x < aoe.size(); ++x) // canvas.drawText(aoe.get(x), tilesize * i // + scrollOffset.getX(), // tilesize * j + scrollOffset.getY() // + 20 + (x * 10), p); // Paint r = new Paint(); // r.setStyle(Paint.Style.STROKE); // r.setColor(Color.RED); // canvas.drawRect(dest, r); } } /* Destination highlighting */ for (Position pos : unitDests) { RectF dest = getSquare( tilesize * pos.getX() + scrollOffset.getX(), tilesize * pos.getY() + scrollOffset.getY(), tilesize); canvas.drawBitmap(highlighter, null, dest, null); } /* Sometimes draw attackables */ if (attack_action && map.getField(selected).hostsUnit()) { Unit u = map.getField(selected).getUnit(); Set<Position> attack_destinations = logic.getAttackableUnitPositions(map, u, attack_location); //logic.getAttackableFields(map, u); for (Position pos : attack_destinations) { RectF attack_dest = getSquare( tilesize * pos.getX() + scrollOffset.getX(), tilesize * pos.getY() + scrollOffset.getY(), tilesize); canvas.drawBitmap(attack_highlighter, null, attack_dest, null); } } // /* Always draw attackables */ // if (map.getField(selected).hostsUnit()) { // Unit u = map.getField(selected).getUnit(); // Set<Position> attack_destinations = // logic.getAttackableUnitPositions(map, u, selected); // //logic.getAttackableFields(map, u); // for (Position pos : attack_destinations) { // RectF dest = getSquare( // tilesize * pos.getX() + scrollOffset.getX(), // tilesize * pos.getY() + scrollOffset.getY(), // tilesize); // canvas.drawRect(dest, attack_high_paint); // } // } // RectF dest = getSquare( // tilesize * selected.getX() + scrollOffset.getX(), // tilesize * selected.getY() + scrollOffset.getY(), // tilesize); // canvas.drawBitmap(selector, null, dest, null); RectF select_dest = getSquare( tilesize * selected.getX() + scrollOffset.getX(), tilesize * selected.getY() + scrollOffset.getY(), tilesize); canvas.drawBitmap(selector, null, select_dest, null); if (selectedField.hostsUnit()) { drawInfoBox(canvas, selectedField.getUnit(), selectedField, true); } else { drawInfoBox(canvas, null, selectedField, true); } framesSinceLastSecond++; timeElapsed += System.currentTimeMillis() - startingTime; if (timeElapsed >= 1000) { fps = framesSinceLastSecond / (timeElapsed * 0.001); framesSinceLastSecond = 0L; timeElapsed = 0L; } String fpsS = fps.toString(); Paint paint = new Paint(); paint.setARGB(255, 255, 255, 255); canvas.drawText("FPS: " + fpsS, this.getWidth() - 80, 20, paint); }
public void doDraw(final Canvas canvas) { Long startingTime = System.currentTimeMillis(); Configuration c = getResources().getConfiguration(); canvas.drawColor(Color.BLACK); GameField selectedField = map.isValidField(selected) ? map.getField(selected) : map.getField(0, 0); List<Position> unitDests = getUnitDestinations(selectedField); canvas.drawBitmap(fullMap, scrollOffset.getX(), scrollOffset.getY(), null); for (int i = 0; i < map.getWidth(); ++i) { for (int j = 0; j < map.getHeight(); j++) { GameField gf = map.getField(i, j); RectF dest = getSquare( tilesize * i + scrollOffset.getX(), tilesize * j + scrollOffset.getY(), tilesize); if (gf.hostsUnit()) { Unit unit = gf.getUnit(); if (unit != null) { String un = unit.toString(); canvas.drawBitmap(graphics.get("Units").get(un), null, dest, null); } } /* Uncomment to print red grid with some info */ // Paint p = new Paint(); // p.setColor(Color.RED); // canvas.drawText(pos.toString() + gfn.charAt(0), // tilesize * i + scrollOffset.getX(), // tilesize * j + scrollOffset.getY() + 64, p); // List<String> aoe = getFieldSquare(pos); // for (int x = 0; x < aoe.size(); ++x) // canvas.drawText(aoe.get(x), tilesize * i // + scrollOffset.getX(), // tilesize * j + scrollOffset.getY() // + 20 + (x * 10), p); // Paint r = new Paint(); // r.setStyle(Paint.Style.STROKE); // r.setColor(Color.RED); // canvas.drawRect(dest, r); } } /* Destination highlighting */ for (Position pos : unitDests) { RectF dest = getSquare( tilesize * pos.getX() + scrollOffset.getX(), tilesize * pos.getY() + scrollOffset.getY(), tilesize); canvas.drawBitmap(highlighter, null, dest, null); } /* Sometimes draw attackables */ if (attack_action && map.getField(selected).hostsUnit()) { Unit u = map.getField(selected).getUnit(); Set<Position> attack_destinations = logic.getAttackableUnitPositions(map, u, attack_location); //logic.getAttackableFields(map, u); for (Position pos : attack_destinations) { RectF attack_dest = getSquare( tilesize * pos.getX() + scrollOffset.getX(), tilesize * pos.getY() + scrollOffset.getY(), tilesize); canvas.drawBitmap(attack_highlighter, null, attack_dest, null); } } // /* Always draw attackables */ // if (map.getField(selected).hostsUnit()) { // Unit u = map.getField(selected).getUnit(); // Set<Position> attack_destinations = // logic.getAttackableUnitPositions(map, u, selected); // //logic.getAttackableFields(map, u); // for (Position pos : attack_destinations) { // RectF dest = getSquare( // tilesize * pos.getX() + scrollOffset.getX(), // tilesize * pos.getY() + scrollOffset.getY(), // tilesize); // canvas.drawRect(dest, attack_high_paint); // } // } // RectF dest = getSquare( // tilesize * selected.getX() + scrollOffset.getX(), // tilesize * selected.getY() + scrollOffset.getY(), // tilesize); // canvas.drawBitmap(selector, null, dest, null); RectF select_dest = getSquare( tilesize * selected.getX() + scrollOffset.getX(), tilesize * selected.getY() + scrollOffset.getY(), tilesize); canvas.drawBitmap(selector, null, select_dest, null); if (selectedField.hostsUnit()) { drawInfoBox(canvas, selectedField.getUnit(), selectedField, true); } else { drawInfoBox(canvas, null, selectedField, true); } framesSinceLastSecond++; timeElapsed += System.currentTimeMillis() - startingTime; if (timeElapsed >= 1000) { fps = framesSinceLastSecond / (timeElapsed * 0.001); framesSinceLastSecond = 0L; timeElapsed = 0L; } String fpsS = fps.toString(); Paint paint = new Paint(); paint.setARGB(255, 255, 255, 255); canvas.drawText("FPS: " + fpsS, this.getWidth() - 80, 20, paint); }
diff --git a/src/be/ibridge/kettle/trans/step/mergejoin/MergeJoin.java b/src/be/ibridge/kettle/trans/step/mergejoin/MergeJoin.java index 61176918..510727b8 100644 --- a/src/be/ibridge/kettle/trans/step/mergejoin/MergeJoin.java +++ b/src/be/ibridge/kettle/trans/step/mergejoin/MergeJoin.java @@ -1,475 +1,475 @@ /********************************************************************** ** ** ** 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.mergejoin; import java.util.ArrayList; import java.util.Iterator; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleStepException; import be.ibridge.kettle.core.value.Value; import be.ibridge.kettle.trans.Trans; import be.ibridge.kettle.trans.TransMeta; import be.ibridge.kettle.trans.step.BaseStep; import be.ibridge.kettle.trans.step.StepDataInterface; import be.ibridge.kettle.trans.step.StepInterface; import be.ibridge.kettle.trans.step.StepMeta; import be.ibridge.kettle.trans.step.StepMetaInterface; /** * Merge rows from 2 sorted streams and output joined rows with matched key fields. * Use this instead of hash join is both your input streams are too big to fit in * memory. Note that both the inputs must be sorted on the join key. * * This is a first prototype implementation that only handles two streams and * inner join. It also always outputs all values from both streams. Ideally, we should: * 1) Support any number of incoming streams * 2) Allow user to choose the join type (inner, outer) for each stream * 3) Allow user to choose which fields to push to next step * 4) Have multiple output ports as follows: * a) Containing matched records * b) Unmatched records for each input port * 5) Support incoming rows to be sorted either on ascending or descending order. * The currently implementation only supports ascending * @author Biswapesh * @since 24-nov-2006 */ public class MergeJoin extends BaseStep implements StepInterface { private MergeJoinMeta meta; private MergeJoinData data; public MergeJoin(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta=(MergeJoinMeta)smi; data=(MergeJoinData)sdi; int compare; if (first) { first = false; data.one=getRowFrom(meta.getStepName1()); data.two=getRowFrom(meta.getStepName2()); if (!isInputLayoutValid(data.one, data.two)) { throw new KettleException(Messages.getString("MergeJoin.Exception.InvalidLayoutDetected")); } if (data.one!=null) { // Find the key indexes: data.keyNrs1 = new int[meta.getKeyFields1().length]; for (int i=0;i<data.keyNrs1.length;i++) { data.keyNrs1[i] = data.one.searchValueIndex(meta.getKeyFields1()[i]); if (data.keyNrs1[i]<0) { String message = Messages.getString("MergeJoin.Exception.UnableToFindFieldInReferenceStream",meta.getKeyFields1()[i]); //$NON-NLS-1$ //$NON-NLS-2$ logError(message); throw new KettleStepException(message); } } } if (data.two!=null) { // Find the key indexes: data.keyNrs2 = new int[meta.getKeyFields2().length]; for (int i=0;i<data.keyNrs2.length;i++) { data.keyNrs2[i] = data.two.searchValueIndex(meta.getKeyFields2()[i]); if (data.keyNrs2[i]<0) { String message = Messages.getString("MergeJoin.Exception.UnableToFindFieldInReferenceStream",meta.getKeyFields2()[i]); //$NON-NLS-1$ //$NON-NLS-2$ logError(message); throw new KettleStepException(message); } } } Value v; - data.one_dummy = new Row(data.one); + data.one_dummy = data.one!=null ? new Row(data.one) : new Row(); for (int i=0; i < data.one_dummy.size(); ++i) { v = data.one_dummy.getValue(i); v.setNull(); data.one_dummy.setValue(i, v); } - data.two_dummy = new Row(data.two); + data.two_dummy = data.two!=null ? new Row(data.two) : new Row(); for (int i=0; i < data.two_dummy.size(); ++i) { v = data.two_dummy.getValue(i); v.setNull(); data.two_dummy.setValue(i, v); } } if (log.isRowLevel()) logRowlevel(Messages.getString("MergeJoin.Log.DataInfo",data.one+"")+data.two); //$NON-NLS-1$ //$NON-NLS-2$ /* * We can stop processing if any of the following is true: * a) Both streams are empty * b) First stream is empty and join type is INNER or LEFT OUTER * c) Second stream is empty and join type is INNER or RIGHT OUTER */ if ((data.one == null && data.two == null) || (data.one == null && data.one_optional == false) || (data.two == null && data.two_optional == false)) { setOutputDone(); return false; } if (data.one == null) { compare = -1; } else { if (data.two == null) { compare = 1; } else { int cmp = data.one.compare(data.two, data.keyNrs1, data.keyNrs2, null, null); compare = cmp>0?1 : cmp<0?-1 : 0; } } switch (compare) { case 0: /* * We've got a match. This is what we do next (to handle duplicate keys correctly): * Read the next record from both streams * If any of the keys match, this means we have duplicates. We therefore * Create an array of all rows that have the same keys * Push a cartesian product of the two arrays to output * Else * Just push the combined rowset to output */ data.one_next = getRowFrom(meta.getStepName1()); data.two_next = getRowFrom(meta.getStepName2()); int compare1 = (data.one_next == null) ? -1 : data.one.compare(data.one_next, data.keyNrs1, data.keyNrs1, null, null); int compare2 = (data.two_next == null) ? -1 : data.two.compare(data.two_next, data.keyNrs2, data.keyNrs2, null, null); if (compare1 == 0 || compare2 == 0) // Duplicate keys { if (data.ones == null) data.ones = new ArrayList(); else data.ones.clear(); if (data.twos == null) data.twos = new ArrayList(); else data.twos.clear(); data.ones.add(data.one); if (compare1 == 0) // First stream has duplicates { data.ones.add(data.one_next); for (;;) { data.one_next = getRowFrom(meta.getStepName1()); if (0 != ((data.one_next == null) ? -1 : data.one.compare(data.one_next, data.keyNrs1, data.keyNrs1, null, null))) break; data.ones.add(data.one_next); } } data.twos.add(data.two); if (compare2 == 0) // Second stream has duplicates { data.twos.add(data.two_next); for (;;) { data.two_next = getRowFrom(meta.getStepName2()); if (0 != ((data.two_next == null) ? -1 : data.two.compare(data.two_next, data.keyNrs2, data.keyNrs2, null, null))) break; data.twos.add(data.two_next); } } Iterator one_iter = data.ones.iterator(); while (one_iter.hasNext()) { Row one = (Row) one_iter.next(); Iterator two_iter = data.twos.iterator(); while (two_iter.hasNext()) { Row combi = new Row(one); combi.addRow((Row) two_iter.next()); putRow(combi); } } data.ones.clear(); data.twos.clear(); } else // No duplicates { data.one.addRow(data.two); putRow(data.one); } data.one = data.one_next; data.two = data.two_next; break; case 1: logDebug("First stream has missing key"); /* * First stream is greater than the second stream. This means: * a) This key is missing in the first stream * b) Second stream may have finished * So, if full/right outer join is set and 2nd stream is not null, * we push a record to output with only the values for the second * row populated. Next, if 2nd stream is not finished, we get a row * from it; otherwise signal that we are done */ if (data.one_optional == true) { if (data.two != null) { Row combi = new Row(data.one_dummy); combi.addRow(data.two); putRow(combi); data.two = getRowFrom(meta.getStepName2()); } else if (data.two_optional == false) { /* * If we are doing right outer join then we are done since * there are no more rows in the second set */ setOutputDone(); return false; } else { /* * We are doing full outer join so print the 1st stream and * get the next row from 1st stream */ Row combi = new Row(data.one); combi.addRow(data.two_dummy); putRow(combi); data.one = getRowFrom(meta.getStepName1()); } } else if (data.two == null && data.two_optional == true) { /** * We have reached the end of stream 2 and there are records * present in the first stream. Also, join is left or full outer. * So, create a row with just the values in the first stream * and push it forward */ Row combi = new Row(data.one); combi.addRow(data.two_dummy); putRow(combi); data.one = getRowFrom(meta.getStepName1()); } else if (data.two != null) { /* * We are doing an inner or left outer join, so throw this row away * from the 2nd stream */ data.two = getRowFrom(meta.getStepName2()); } break; case -1: logDebug("Second stream has missing key"); /* * Second stream is greater than the first stream. This means: * a) This key is missing in the second stream * b) First stream may have finished * So, if full/left outer join is set and 1st stream is not null, * we push a record to output with only the values for the first * row populated. Next, if 1st stream is not finished, we get a row * from it; otherwise signal that we are done */ if (data.two_optional == true) { if (data.one != null) { Row combi = new Row(data.one); combi.addRow(data.two_dummy); putRow(combi); data.one = getRowFrom(meta.getStepName1()); } else if (data.one_optional == false) { /* * We are doing a left outer join and there are no more rows * in the first stream; so we are done */ setOutputDone(); return false; } else { /* * We are doing a full outer join so print the 2nd stream and * get the next row from the 2nd stream */ Row combi = new Row(data.one_dummy); combi.addRow(data.two); putRow(combi); data.two = getRowFrom(meta.getStepName2()); } } else if (data.one == null && data.one_optional == true) { /* * We have reached the end of stream 1 and there are records * present in the second stream. Also, join is right or full outer. * So, create a row with just the values in the 2nd stream * and push it forward */ Row combi = new Row(data.one_dummy); combi.addRow(data.two); putRow(combi); data.two = getRowFrom(meta.getStepName2()); } else if (data.one != null) { /* * We are doing an inner or right outer join so a non-matching row * in the first stream is of no use to us - throw it away and get the * next row */ data.one = getRowFrom(meta.getStepName1()); } break; default: logDebug("We shouldn't be here!!"); // Make sure we do not go into an infinite loop by continuing to read data data.one = getRowFrom(meta.getStepName1()); data.two = getRowFrom(meta.getStepName2()); break; } if (checkFeedback(linesRead)) logBasic(Messages.getString("MergeJoin.LineNumber")+linesRead); //$NON-NLS-1$ return true; } /** * @see StepInterface#init( be.ibridge.kettle.trans.step.StepMetaInterface , be.ibridge.kettle.trans.step.StepDataInterface) */ public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta=(MergeJoinMeta)smi; data=(MergeJoinData)sdi; if (super.init(smi, sdi)) { if (meta.getStepName1()==null || meta.getStepName2()==null) { logError(Messages.getString("MergeJoin.Log.BothTrueAndFalseNeeded")); //$NON-NLS-1$ return false; } String joinType = meta.getJoinType(); for (int i = 0; i < MergeJoinMeta.join_types.length; ++i) { if (joinType.equalsIgnoreCase(MergeJoinMeta.join_types[i])) { data.one_optional = MergeJoinMeta.one_optionals[i]; data.two_optional = MergeJoinMeta.two_optionals[i]; return true; } } logError(Messages.getString("MergeJoin.Log.InvalidJoinType", meta.getJoinType())); //$NON-NLS-1$ return false; } return true; } /** * Checks whether incoming rows are join compatible. This essentially * means that the keys being compared should be of the same datatype * and both rows should have the same number of keys specified * @param row1 Reference row * @param row2 Row to compare to * * @return true when templates are compatible. */ protected boolean isInputLayoutValid(Row row1, Row row2) { if (row1!=null && row2!=null) { // Compare the key types String keyFields1[] = meta.getKeyFields1(); int nrKeyFields1 = keyFields1.length; String keyFields2[] = meta.getKeyFields2(); int nrKeyFields2 = keyFields2.length; if (nrKeyFields1 != nrKeyFields2) { logError("Number of keys do not match " + nrKeyFields1 + " vs " + nrKeyFields2); return false; } for (int i=0;i<nrKeyFields1;i++) { Value v1 = row1.searchValue(keyFields1[i]); if (v1 == null) { return false; } Value v2 = row2.searchValue(keyFields2[i]); if (v2 == null) { return false; } if ( ! v1.equalValueType(v2, true) ) { return false; } } } // we got here, all seems to be ok. return true; } // // Run is were the action happens! public void run() { try { logBasic(Messages.getString("MergeJoin.Log.StartingToRun")); //$NON-NLS-1$ while (processRow(meta, data) && !isStopped()); } catch(Exception e) { logError(Messages.getString("MergeJoin.Log.UnexpectedError")+" : "+e.toString()); //$NON-NLS-1$ //$NON-NLS-2$ logError(Const.getStackTracker(e)); setErrors(1); stopAll(); } finally { dispose(meta, data); logSummary(); markStop(); } } }
false
true
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta=(MergeJoinMeta)smi; data=(MergeJoinData)sdi; int compare; if (first) { first = false; data.one=getRowFrom(meta.getStepName1()); data.two=getRowFrom(meta.getStepName2()); if (!isInputLayoutValid(data.one, data.two)) { throw new KettleException(Messages.getString("MergeJoin.Exception.InvalidLayoutDetected")); } if (data.one!=null) { // Find the key indexes: data.keyNrs1 = new int[meta.getKeyFields1().length]; for (int i=0;i<data.keyNrs1.length;i++) { data.keyNrs1[i] = data.one.searchValueIndex(meta.getKeyFields1()[i]); if (data.keyNrs1[i]<0) { String message = Messages.getString("MergeJoin.Exception.UnableToFindFieldInReferenceStream",meta.getKeyFields1()[i]); //$NON-NLS-1$ //$NON-NLS-2$ logError(message); throw new KettleStepException(message); } } } if (data.two!=null) { // Find the key indexes: data.keyNrs2 = new int[meta.getKeyFields2().length]; for (int i=0;i<data.keyNrs2.length;i++) { data.keyNrs2[i] = data.two.searchValueIndex(meta.getKeyFields2()[i]); if (data.keyNrs2[i]<0) { String message = Messages.getString("MergeJoin.Exception.UnableToFindFieldInReferenceStream",meta.getKeyFields2()[i]); //$NON-NLS-1$ //$NON-NLS-2$ logError(message); throw new KettleStepException(message); } } } Value v; data.one_dummy = new Row(data.one); for (int i=0; i < data.one_dummy.size(); ++i) { v = data.one_dummy.getValue(i); v.setNull(); data.one_dummy.setValue(i, v); } data.two_dummy = new Row(data.two); for (int i=0; i < data.two_dummy.size(); ++i) { v = data.two_dummy.getValue(i); v.setNull(); data.two_dummy.setValue(i, v); } } if (log.isRowLevel()) logRowlevel(Messages.getString("MergeJoin.Log.DataInfo",data.one+"")+data.two); //$NON-NLS-1$ //$NON-NLS-2$ /* * We can stop processing if any of the following is true: * a) Both streams are empty * b) First stream is empty and join type is INNER or LEFT OUTER * c) Second stream is empty and join type is INNER or RIGHT OUTER */ if ((data.one == null && data.two == null) || (data.one == null && data.one_optional == false) || (data.two == null && data.two_optional == false)) { setOutputDone(); return false; } if (data.one == null) { compare = -1; } else { if (data.two == null) { compare = 1; } else { int cmp = data.one.compare(data.two, data.keyNrs1, data.keyNrs2, null, null); compare = cmp>0?1 : cmp<0?-1 : 0; } } switch (compare) { case 0: /* * We've got a match. This is what we do next (to handle duplicate keys correctly): * Read the next record from both streams * If any of the keys match, this means we have duplicates. We therefore * Create an array of all rows that have the same keys * Push a cartesian product of the two arrays to output * Else * Just push the combined rowset to output */ data.one_next = getRowFrom(meta.getStepName1()); data.two_next = getRowFrom(meta.getStepName2()); int compare1 = (data.one_next == null) ? -1 : data.one.compare(data.one_next, data.keyNrs1, data.keyNrs1, null, null); int compare2 = (data.two_next == null) ? -1 : data.two.compare(data.two_next, data.keyNrs2, data.keyNrs2, null, null); if (compare1 == 0 || compare2 == 0) // Duplicate keys { if (data.ones == null) data.ones = new ArrayList(); else data.ones.clear(); if (data.twos == null) data.twos = new ArrayList(); else data.twos.clear(); data.ones.add(data.one); if (compare1 == 0) // First stream has duplicates { data.ones.add(data.one_next); for (;;) { data.one_next = getRowFrom(meta.getStepName1()); if (0 != ((data.one_next == null) ? -1 : data.one.compare(data.one_next, data.keyNrs1, data.keyNrs1, null, null))) break; data.ones.add(data.one_next); } } data.twos.add(data.two); if (compare2 == 0) // Second stream has duplicates { data.twos.add(data.two_next); for (;;) { data.two_next = getRowFrom(meta.getStepName2()); if (0 != ((data.two_next == null) ? -1 : data.two.compare(data.two_next, data.keyNrs2, data.keyNrs2, null, null))) break; data.twos.add(data.two_next); } } Iterator one_iter = data.ones.iterator(); while (one_iter.hasNext()) { Row one = (Row) one_iter.next(); Iterator two_iter = data.twos.iterator(); while (two_iter.hasNext()) { Row combi = new Row(one); combi.addRow((Row) two_iter.next()); putRow(combi); } } data.ones.clear(); data.twos.clear(); } else // No duplicates { data.one.addRow(data.two); putRow(data.one); } data.one = data.one_next; data.two = data.two_next; break; case 1: logDebug("First stream has missing key"); /* * First stream is greater than the second stream. This means: * a) This key is missing in the first stream * b) Second stream may have finished * So, if full/right outer join is set and 2nd stream is not null, * we push a record to output with only the values for the second * row populated. Next, if 2nd stream is not finished, we get a row * from it; otherwise signal that we are done */ if (data.one_optional == true) { if (data.two != null) { Row combi = new Row(data.one_dummy); combi.addRow(data.two); putRow(combi); data.two = getRowFrom(meta.getStepName2()); } else if (data.two_optional == false) { /* * If we are doing right outer join then we are done since * there are no more rows in the second set */ setOutputDone(); return false; } else { /* * We are doing full outer join so print the 1st stream and * get the next row from 1st stream */ Row combi = new Row(data.one); combi.addRow(data.two_dummy); putRow(combi); data.one = getRowFrom(meta.getStepName1()); } } else if (data.two == null && data.two_optional == true) { /** * We have reached the end of stream 2 and there are records * present in the first stream. Also, join is left or full outer. * So, create a row with just the values in the first stream * and push it forward */ Row combi = new Row(data.one); combi.addRow(data.two_dummy); putRow(combi); data.one = getRowFrom(meta.getStepName1()); } else if (data.two != null) { /* * We are doing an inner or left outer join, so throw this row away * from the 2nd stream */ data.two = getRowFrom(meta.getStepName2()); } break; case -1: logDebug("Second stream has missing key"); /* * Second stream is greater than the first stream. This means: * a) This key is missing in the second stream * b) First stream may have finished * So, if full/left outer join is set and 1st stream is not null, * we push a record to output with only the values for the first * row populated. Next, if 1st stream is not finished, we get a row * from it; otherwise signal that we are done */ if (data.two_optional == true) { if (data.one != null) { Row combi = new Row(data.one); combi.addRow(data.two_dummy); putRow(combi); data.one = getRowFrom(meta.getStepName1()); } else if (data.one_optional == false) { /* * We are doing a left outer join and there are no more rows * in the first stream; so we are done */ setOutputDone(); return false; } else { /* * We are doing a full outer join so print the 2nd stream and * get the next row from the 2nd stream */ Row combi = new Row(data.one_dummy); combi.addRow(data.two); putRow(combi); data.two = getRowFrom(meta.getStepName2()); } } else if (data.one == null && data.one_optional == true) { /* * We have reached the end of stream 1 and there are records * present in the second stream. Also, join is right or full outer. * So, create a row with just the values in the 2nd stream * and push it forward */ Row combi = new Row(data.one_dummy); combi.addRow(data.two); putRow(combi); data.two = getRowFrom(meta.getStepName2()); } else if (data.one != null) { /* * We are doing an inner or right outer join so a non-matching row * in the first stream is of no use to us - throw it away and get the * next row */ data.one = getRowFrom(meta.getStepName1()); } break; default: logDebug("We shouldn't be here!!"); // Make sure we do not go into an infinite loop by continuing to read data data.one = getRowFrom(meta.getStepName1()); data.two = getRowFrom(meta.getStepName2()); break; } if (checkFeedback(linesRead)) logBasic(Messages.getString("MergeJoin.LineNumber")+linesRead); //$NON-NLS-1$ return true; }
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta=(MergeJoinMeta)smi; data=(MergeJoinData)sdi; int compare; if (first) { first = false; data.one=getRowFrom(meta.getStepName1()); data.two=getRowFrom(meta.getStepName2()); if (!isInputLayoutValid(data.one, data.two)) { throw new KettleException(Messages.getString("MergeJoin.Exception.InvalidLayoutDetected")); } if (data.one!=null) { // Find the key indexes: data.keyNrs1 = new int[meta.getKeyFields1().length]; for (int i=0;i<data.keyNrs1.length;i++) { data.keyNrs1[i] = data.one.searchValueIndex(meta.getKeyFields1()[i]); if (data.keyNrs1[i]<0) { String message = Messages.getString("MergeJoin.Exception.UnableToFindFieldInReferenceStream",meta.getKeyFields1()[i]); //$NON-NLS-1$ //$NON-NLS-2$ logError(message); throw new KettleStepException(message); } } } if (data.two!=null) { // Find the key indexes: data.keyNrs2 = new int[meta.getKeyFields2().length]; for (int i=0;i<data.keyNrs2.length;i++) { data.keyNrs2[i] = data.two.searchValueIndex(meta.getKeyFields2()[i]); if (data.keyNrs2[i]<0) { String message = Messages.getString("MergeJoin.Exception.UnableToFindFieldInReferenceStream",meta.getKeyFields2()[i]); //$NON-NLS-1$ //$NON-NLS-2$ logError(message); throw new KettleStepException(message); } } } Value v; data.one_dummy = data.one!=null ? new Row(data.one) : new Row(); for (int i=0; i < data.one_dummy.size(); ++i) { v = data.one_dummy.getValue(i); v.setNull(); data.one_dummy.setValue(i, v); } data.two_dummy = data.two!=null ? new Row(data.two) : new Row(); for (int i=0; i < data.two_dummy.size(); ++i) { v = data.two_dummy.getValue(i); v.setNull(); data.two_dummy.setValue(i, v); } } if (log.isRowLevel()) logRowlevel(Messages.getString("MergeJoin.Log.DataInfo",data.one+"")+data.two); //$NON-NLS-1$ //$NON-NLS-2$ /* * We can stop processing if any of the following is true: * a) Both streams are empty * b) First stream is empty and join type is INNER or LEFT OUTER * c) Second stream is empty and join type is INNER or RIGHT OUTER */ if ((data.one == null && data.two == null) || (data.one == null && data.one_optional == false) || (data.two == null && data.two_optional == false)) { setOutputDone(); return false; } if (data.one == null) { compare = -1; } else { if (data.two == null) { compare = 1; } else { int cmp = data.one.compare(data.two, data.keyNrs1, data.keyNrs2, null, null); compare = cmp>0?1 : cmp<0?-1 : 0; } } switch (compare) { case 0: /* * We've got a match. This is what we do next (to handle duplicate keys correctly): * Read the next record from both streams * If any of the keys match, this means we have duplicates. We therefore * Create an array of all rows that have the same keys * Push a cartesian product of the two arrays to output * Else * Just push the combined rowset to output */ data.one_next = getRowFrom(meta.getStepName1()); data.two_next = getRowFrom(meta.getStepName2()); int compare1 = (data.one_next == null) ? -1 : data.one.compare(data.one_next, data.keyNrs1, data.keyNrs1, null, null); int compare2 = (data.two_next == null) ? -1 : data.two.compare(data.two_next, data.keyNrs2, data.keyNrs2, null, null); if (compare1 == 0 || compare2 == 0) // Duplicate keys { if (data.ones == null) data.ones = new ArrayList(); else data.ones.clear(); if (data.twos == null) data.twos = new ArrayList(); else data.twos.clear(); data.ones.add(data.one); if (compare1 == 0) // First stream has duplicates { data.ones.add(data.one_next); for (;;) { data.one_next = getRowFrom(meta.getStepName1()); if (0 != ((data.one_next == null) ? -1 : data.one.compare(data.one_next, data.keyNrs1, data.keyNrs1, null, null))) break; data.ones.add(data.one_next); } } data.twos.add(data.two); if (compare2 == 0) // Second stream has duplicates { data.twos.add(data.two_next); for (;;) { data.two_next = getRowFrom(meta.getStepName2()); if (0 != ((data.two_next == null) ? -1 : data.two.compare(data.two_next, data.keyNrs2, data.keyNrs2, null, null))) break; data.twos.add(data.two_next); } } Iterator one_iter = data.ones.iterator(); while (one_iter.hasNext()) { Row one = (Row) one_iter.next(); Iterator two_iter = data.twos.iterator(); while (two_iter.hasNext()) { Row combi = new Row(one); combi.addRow((Row) two_iter.next()); putRow(combi); } } data.ones.clear(); data.twos.clear(); } else // No duplicates { data.one.addRow(data.two); putRow(data.one); } data.one = data.one_next; data.two = data.two_next; break; case 1: logDebug("First stream has missing key"); /* * First stream is greater than the second stream. This means: * a) This key is missing in the first stream * b) Second stream may have finished * So, if full/right outer join is set and 2nd stream is not null, * we push a record to output with only the values for the second * row populated. Next, if 2nd stream is not finished, we get a row * from it; otherwise signal that we are done */ if (data.one_optional == true) { if (data.two != null) { Row combi = new Row(data.one_dummy); combi.addRow(data.two); putRow(combi); data.two = getRowFrom(meta.getStepName2()); } else if (data.two_optional == false) { /* * If we are doing right outer join then we are done since * there are no more rows in the second set */ setOutputDone(); return false; } else { /* * We are doing full outer join so print the 1st stream and * get the next row from 1st stream */ Row combi = new Row(data.one); combi.addRow(data.two_dummy); putRow(combi); data.one = getRowFrom(meta.getStepName1()); } } else if (data.two == null && data.two_optional == true) { /** * We have reached the end of stream 2 and there are records * present in the first stream. Also, join is left or full outer. * So, create a row with just the values in the first stream * and push it forward */ Row combi = new Row(data.one); combi.addRow(data.two_dummy); putRow(combi); data.one = getRowFrom(meta.getStepName1()); } else if (data.two != null) { /* * We are doing an inner or left outer join, so throw this row away * from the 2nd stream */ data.two = getRowFrom(meta.getStepName2()); } break; case -1: logDebug("Second stream has missing key"); /* * Second stream is greater than the first stream. This means: * a) This key is missing in the second stream * b) First stream may have finished * So, if full/left outer join is set and 1st stream is not null, * we push a record to output with only the values for the first * row populated. Next, if 1st stream is not finished, we get a row * from it; otherwise signal that we are done */ if (data.two_optional == true) { if (data.one != null) { Row combi = new Row(data.one); combi.addRow(data.two_dummy); putRow(combi); data.one = getRowFrom(meta.getStepName1()); } else if (data.one_optional == false) { /* * We are doing a left outer join and there are no more rows * in the first stream; so we are done */ setOutputDone(); return false; } else { /* * We are doing a full outer join so print the 2nd stream and * get the next row from the 2nd stream */ Row combi = new Row(data.one_dummy); combi.addRow(data.two); putRow(combi); data.two = getRowFrom(meta.getStepName2()); } } else if (data.one == null && data.one_optional == true) { /* * We have reached the end of stream 1 and there are records * present in the second stream. Also, join is right or full outer. * So, create a row with just the values in the 2nd stream * and push it forward */ Row combi = new Row(data.one_dummy); combi.addRow(data.two); putRow(combi); data.two = getRowFrom(meta.getStepName2()); } else if (data.one != null) { /* * We are doing an inner or right outer join so a non-matching row * in the first stream is of no use to us - throw it away and get the * next row */ data.one = getRowFrom(meta.getStepName1()); } break; default: logDebug("We shouldn't be here!!"); // Make sure we do not go into an infinite loop by continuing to read data data.one = getRowFrom(meta.getStepName1()); data.two = getRowFrom(meta.getStepName2()); break; } if (checkFeedback(linesRead)) logBasic(Messages.getString("MergeJoin.LineNumber")+linesRead); //$NON-NLS-1$ return true; }
diff --git a/app/controllers/Application.java b/app/controllers/Application.java index 08fb047..f27a900 100644 --- a/app/controllers/Application.java +++ b/app/controllers/Application.java @@ -1,45 +1,45 @@ package controllers; import static play.data.Form.*; import java.util.List; import models.MyData; import play.*; import play.mvc.*; import play.data.Form; import views.html.*; public class Application extends Controller { public static class MyForm { public String name; public String mail; public String tel; @Override public String toString() { return String.format("NAME:%s MAIL:%s TEL:%s", name, mail, tel); } } public static Result index() { - String title = "play"; + String title = "あなたはどこに行きたい?????"; String msg = "フォーム"; Form<MyData> mydata = form(MyData.class); List<MyData> mydatas = MyData.find.all(); return ok(index.render(title, msg, mydatas, mydata)); } public static Result add() { Form<MyData> mydata = form(MyData.class).bindFromRequest(); if (mydata.hasErrors() == false) { mydata.get().save(); flash(); } return redirect(routes.Application.index()); } }
true
true
public static Result index() { String title = "play"; String msg = "フォーム"; Form<MyData> mydata = form(MyData.class); List<MyData> mydatas = MyData.find.all(); return ok(index.render(title, msg, mydatas, mydata)); }
public static Result index() { String title = "あなたはどこに行きたい?????"; String msg = "フォーム"; Form<MyData> mydata = form(MyData.class); List<MyData> mydatas = MyData.find.all(); return ok(index.render(title, msg, mydatas, mydata)); }
diff --git a/src/main/java/org/logblock/Commands.java b/src/main/java/org/logblock/Commands.java index 0383183..0283b00 100644 --- a/src/main/java/org/logblock/Commands.java +++ b/src/main/java/org/logblock/Commands.java @@ -1,100 +1,107 @@ package org.logblock; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandException; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; public class Commands implements CommandExecutor { private static final Map<String, Method> commandMap = new HashMap<String, Method>(); static { for (Method m : Commands.class.getDeclaredMethods()) { if (Modifier.isStatic(m.getModifiers())) { Class<?>[] params = m.getParameterTypes(); if (params.length == 2) { if (params[0] == CommandSender.class && params[1] == String[].class) { AnnotatedCommand annotation = m.getAnnotation(AnnotatedCommand.class); if (annotation != null) { commandMap.put(annotation.name(), m); } } } } } } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { Method method = commandMap.get(label); if (method != null) { AnnotatedCommand annotation = method.getAnnotation(AnnotatedCommand.class); if (!sender.hasPermission("logblock." + label)) { sender.sendMessage(ChatColor.RED + "You do not have permission to perform the specified command!"); } else if (args.length < annotation.minArgs()) { sender.sendMessage(ChatColor.RED + "Please check your argument count, the command you have requested requires " + annotation.minArgs() + " or more arguments."); } else if (args.length > annotation.maxArgs()) { sender.sendMessage(ChatColor.RED + "Please check your argument count, the command you have requested only accepts up to " + annotation.maxArgs() + " arguments."); } else { - try + invoker: { - method.invoke(null, sender, args); - } catch (Exception ex) - { - throw new CommandException("Error occured whilst executing LogBlock subcommand " + label, ex); + try + { + method.invoke(null, sender, args); + } catch (CommandException e) + { + sender.sendMessage(ChatColor.RED + e.getMessage()); + break invoker; + } catch (Exception ex) + { + throw new CommandException("Error occured whilst executing LogBlock subcommand " + label, ex); + } } } } else { sender.sendMessage(ChatColor.RED + "The command you have specified does not exist. Below is a list of all commands"); help(sender, args); } return true; } @AnnotatedCommand(name = "help") public static void help(CommandSender sender, String[] args) { } @AnnotatedCommand(name = "version") public static void version(CommandSender sender, String[] args) { sender.sendMessage(ChatColor.GREEN + "This server is running LogBlock version " + LogBlock.getInstance().getDescription().getVersion()); } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface AnnotatedCommand { String name(); int minArgs() default 0; int maxArgs() default 0; } }
false
true
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { Method method = commandMap.get(label); if (method != null) { AnnotatedCommand annotation = method.getAnnotation(AnnotatedCommand.class); if (!sender.hasPermission("logblock." + label)) { sender.sendMessage(ChatColor.RED + "You do not have permission to perform the specified command!"); } else if (args.length < annotation.minArgs()) { sender.sendMessage(ChatColor.RED + "Please check your argument count, the command you have requested requires " + annotation.minArgs() + " or more arguments."); } else if (args.length > annotation.maxArgs()) { sender.sendMessage(ChatColor.RED + "Please check your argument count, the command you have requested only accepts up to " + annotation.maxArgs() + " arguments."); } else { try { method.invoke(null, sender, args); } catch (Exception ex) { throw new CommandException("Error occured whilst executing LogBlock subcommand " + label, ex); } } } else { sender.sendMessage(ChatColor.RED + "The command you have specified does not exist. Below is a list of all commands"); help(sender, args); } return true; }
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { Method method = commandMap.get(label); if (method != null) { AnnotatedCommand annotation = method.getAnnotation(AnnotatedCommand.class); if (!sender.hasPermission("logblock." + label)) { sender.sendMessage(ChatColor.RED + "You do not have permission to perform the specified command!"); } else if (args.length < annotation.minArgs()) { sender.sendMessage(ChatColor.RED + "Please check your argument count, the command you have requested requires " + annotation.minArgs() + " or more arguments."); } else if (args.length > annotation.maxArgs()) { sender.sendMessage(ChatColor.RED + "Please check your argument count, the command you have requested only accepts up to " + annotation.maxArgs() + " arguments."); } else { invoker: { try { method.invoke(null, sender, args); } catch (CommandException e) { sender.sendMessage(ChatColor.RED + e.getMessage()); break invoker; } catch (Exception ex) { throw new CommandException("Error occured whilst executing LogBlock subcommand " + label, ex); } } } } else { sender.sendMessage(ChatColor.RED + "The command you have specified does not exist. Below is a list of all commands"); help(sender, args); } return true; }
diff --git a/farrago/src/net/sf/farrago/type/runtime/NullablePrimitive.java b/farrago/src/net/sf/farrago/type/runtime/NullablePrimitive.java index a8f235d9a..9ba08d261 100644 --- a/farrago/src/net/sf/farrago/type/runtime/NullablePrimitive.java +++ b/farrago/src/net/sf/farrago/type/runtime/NullablePrimitive.java @@ -1,364 +1,365 @@ /* // $Id$ // Farrago is an extensible data management system. // Copyright (C) 2005-2005 The Eigenbase Project // Copyright (C) 2005-2005 Disruptive Tech // Copyright (C) 2005-2005 LucidEra, Inc. // Portions Copyright (C) 2003-2005 John V. Sichi // // This program is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by the Free // Software Foundation; either version 2 of the License, or (at your option) // any later version approved by The Eigenbase Project. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package net.sf.farrago.type.runtime; import java.math.*; import net.sf.farrago.resource.*; import org.eigenbase.util.*; /** * NullablePrimitive is the abstract superclass for implementations of * NullableValue corresponding to Java primitives. These holder classes are * declared as static inner classes of NullablePrimitive with names taken * from the standard holder classes in java.lang. * * @author John V. Sichi * @version $Id$ */ public abstract class NullablePrimitive implements NullableValue, AssignableValue { //~ Static fields/initializers -------------------------------------------- /** * Name of field storing value. */ public static final String VALUE_FIELD_NAME = "value"; /** * Name of field storing null indicator. */ public static final String NULL_IND_FIELD_NAME = NULL_IND_ACCESSOR_NAME; private static final Integer INT_ONE = new Integer(1); private static final Integer INT_ZERO = new Integer(0); //~ Instance fields ------------------------------------------------------- /** Whether this value is null. */ public boolean isNull; //~ Methods --------------------------------------------------------------- // implement NullableValue public void setNull(boolean isNull) { this.isNull = isNull; } // implement NullableValue public boolean isNull() { return isNull; } // implement NullableValue public Object getNullableData() { if (isNull) { return null; } try { return getClass().getField(VALUE_FIELD_NAME).get(this); } catch (Exception ex) { throw Util.newInternal(ex); } } // implement AssignableValue public void assignFrom(Object obj) { if (obj == null) { setNull(true); } else if (obj instanceof Number) { setNull(false); setNumber((Number) obj); } else if (obj instanceof NullablePrimitive) { NullablePrimitive nullable = (NullablePrimitive) obj; assignFrom(nullable.getNullableData()); } else if (obj instanceof Boolean) { setNull(false); Boolean b = (Boolean) obj; setNumber(b.booleanValue() ? INT_ONE : INT_ZERO); } else { + setNull(false); String s = obj.toString(); Number n; try { n = new BigDecimal(s.trim()); } catch (NumberFormatException ex) { // NOTE jvs 11-Oct-2005: leave ex out entirely, because // it doesn't contain useful information and causes // test diffs due to JVM variance throw FarragoResource.instance().AssignFromFailed.ex( s, "NUMERIC", "NumberFormatException"); } setNumber(n); } } /** * Assignment from abstract Number object. * * @param number a new non-null value to be assigned */ protected abstract void setNumber(Number number); //~ Inner Classes --------------------------------------------------------- /** * Nullable wrapper for boolean. */ public static final class NullableBoolean extends NullablePrimitive implements BitReference { /** Wrapped primitive */ public boolean value; // implement AssignableValue for String public void assignFrom(Object obj) { if (obj == null) { setNull(true); } else if (obj instanceof String) { String s = (String) obj; s = s.trim(); if (s.equalsIgnoreCase("true")) { value = true; } else if (s.equalsIgnoreCase("false")) { value = false; } else if (s.equalsIgnoreCase("unknown")) { setNull(true); } else { super.assignFrom(obj); } } else { super.assignFrom(obj); } } // implement NullablePrimitive protected void setNumber(Number number) { value = (number.longValue() != 0); } // implement BitReference public void setBit(boolean bit) { value = bit; } // implement BitReference public boolean getBit() { return value; } /** * Implements the three-valued-logic version of the AND operator. * Invoked by generated code. * * @param n0 null indictator for arg0 * * @param v0 truth value of arg0 when !n0 * * @param n1 null indicator for arg1 * * @param v1 truth value of arg1 when !n1 */ public final void assignFromAnd3VL( boolean n0, boolean v0, boolean n1, boolean v1) { if (n0 && n1) { // (UNKNOWN AND UNKNOWN) == UNKNOWN isNull = true; } else if (n0) { if (v1) { // (UNKNOWN AND TRUE) == UNKNOWN isNull = true; } else { // (UNKNOWN AND FALSE) == FALSE isNull = false; value = false; } } else if (n1) { if (v0) { // (TRUE AND UNKNOWN) == UNKNOWN isNull = true; } else { // (FALSE AND UNKOWN) == FALSE isNull = false; value = false; } } else { // (KNOWN AND KNOWN) == KNOWN isNull = false; value = v0 && v1; } } /** * Implements the three-valued-logic version of the OR operator. * Invoked by generated code. * * @param n0 null indictator for arg0 * * @param v0 truth value of arg0 when !n0 * * @param n1 null indicator for arg1 * * @param v1 truth value of arg1 when !n1 */ public final void assignFromOr3VL( boolean n0, boolean v0, boolean n1, boolean v1) { if (n0 && n1) { // (UNKNOWN OR UNKNOWN) == UNKNOWN isNull = true; } else if (n0) { if (v1) { // (UNKNOWN OR TRUE) == TRUE isNull = false; value = true; } else { // (UNKNOWN OR FALSE) == UKNOWN isNull = true; } } else if (n1) { if (v0) { // (TRUE OR UNKNOWN) == TRUE isNull = false; value = true; } else { // (FALSE OR UNKOWN) == UNKNOWN isNull = true; } } else { // (KNOWN OR KNOWN) == KNOWN isNull = false; value = v0 || v1; } } } /** * Nullable wrapper for byte. */ public static final class NullableByte extends NullablePrimitive { /** Wrapped primitive */ public byte value; // implement NullablePrimitive protected void setNumber(Number number) { value = number.byteValue(); } } /** * Nullable wrapper for double. */ public static final class NullableDouble extends NullablePrimitive { /** Wrapped primitive */ public double value; // implement NullablePrimitive protected void setNumber(Number number) { value = number.doubleValue(); } } /** * Nullable wrapper for float. */ public static final class NullableFloat extends NullablePrimitive { /** Wrapped primitive */ public float value; // implement NullablePrimitive protected void setNumber(Number number) { value = number.floatValue(); } } /** * Nullable wrapper for int. */ public static final class NullableInteger extends NullablePrimitive { /** Wrapped primitive */ public int value; // implement NullablePrimitive protected void setNumber(Number number) { value = number.intValue(); } } /** * Nullable wrapper for long. */ public static class NullableLong extends NullablePrimitive { /** Wrapped primitive */ public long value; // implement NullablePrimitive protected void setNumber(Number number) { value = number.longValue(); } } /** * Nullable wrapper for short. */ public static final class NullableShort extends NullablePrimitive { /** Wrapped primitive */ public short value; // implement NullablePrimitive protected void setNumber(Number number) { value = number.shortValue(); } } } // End NullablePrimitive.java
true
true
public void assignFrom(Object obj) { if (obj == null) { setNull(true); } else if (obj instanceof Number) { setNull(false); setNumber((Number) obj); } else if (obj instanceof NullablePrimitive) { NullablePrimitive nullable = (NullablePrimitive) obj; assignFrom(nullable.getNullableData()); } else if (obj instanceof Boolean) { setNull(false); Boolean b = (Boolean) obj; setNumber(b.booleanValue() ? INT_ONE : INT_ZERO); } else { String s = obj.toString(); Number n; try { n = new BigDecimal(s.trim()); } catch (NumberFormatException ex) { // NOTE jvs 11-Oct-2005: leave ex out entirely, because // it doesn't contain useful information and causes // test diffs due to JVM variance throw FarragoResource.instance().AssignFromFailed.ex( s, "NUMERIC", "NumberFormatException"); } setNumber(n); } }
public void assignFrom(Object obj) { if (obj == null) { setNull(true); } else if (obj instanceof Number) { setNull(false); setNumber((Number) obj); } else if (obj instanceof NullablePrimitive) { NullablePrimitive nullable = (NullablePrimitive) obj; assignFrom(nullable.getNullableData()); } else if (obj instanceof Boolean) { setNull(false); Boolean b = (Boolean) obj; setNumber(b.booleanValue() ? INT_ONE : INT_ZERO); } else { setNull(false); String s = obj.toString(); Number n; try { n = new BigDecimal(s.trim()); } catch (NumberFormatException ex) { // NOTE jvs 11-Oct-2005: leave ex out entirely, because // it doesn't contain useful information and causes // test diffs due to JVM variance throw FarragoResource.instance().AssignFromFailed.ex( s, "NUMERIC", "NumberFormatException"); } setNumber(n); } }
diff --git a/cas-client-core/src/main/java/org/jasig/cas/client/util/AbstractConfigurationFilter.java b/cas-client-core/src/main/java/org/jasig/cas/client/util/AbstractConfigurationFilter.java index 2e2fdfb..1db5838 100644 --- a/cas-client-core/src/main/java/org/jasig/cas/client/util/AbstractConfigurationFilter.java +++ b/cas-client-core/src/main/java/org/jasig/cas/client/util/AbstractConfigurationFilter.java @@ -1,117 +1,117 @@ /** * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig 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.jasig.cas.client.util; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.Filter; import javax.servlet.FilterConfig; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Abstracts out the ability to configure the filters from the initial properties provided. * * @author Scott Battaglia * @version $Revision$ $Date$ * @since 3.1 */ public abstract class AbstractConfigurationFilter implements Filter { protected final Log log = LogFactory.getLog(getClass()); private boolean ignoreInitConfiguration = false; /** * Retrieves the property from the FilterConfig. First it checks the FilterConfig's initParameters to see if it * has a value. * If it does, it returns that, otherwise it retrieves the ServletContext's initParameters and returns that value if any. * <p> * Finally, it will check JNDI if all other methods fail. All the JNDI properties should be stored under java:comp/env/cas/{propertyName} * * @param filterConfig the Filter Configuration. * @param propertyName the property to retrieve. * @param defaultValue the default value if the property is not found. * @return the property value, following the above conventions. It will always return the more specific value (i.e. * filter vs. context). */ protected final String getPropertyFromInitParams(final FilterConfig filterConfig, final String propertyName, final String defaultValue) { final String value = filterConfig.getInitParameter(propertyName); if (CommonUtils.isNotBlank(value)) { log.info("Property [" + propertyName + "] loaded from FilterConfig.getInitParameter with value [" + value + "]"); return value; } final String value2 = filterConfig.getServletContext().getInitParameter(propertyName); if (CommonUtils.isNotBlank(value2)) { log.info("Property [" + propertyName + "] loaded from ServletContext.getInitParameter with value [" + value2 + "]"); return value2; } InitialContext context; try { context = new InitialContext(); } catch (final NamingException e) { log.warn(e,e); return defaultValue; } final String shortName = this.getClass().getName().substring(this.getClass().getName().lastIndexOf(".")+1); final String value3 = loadFromContext(context, "java:comp/env/cas/" + shortName + "/" + propertyName); if (CommonUtils.isNotBlank(value3)) { log.info("Property [" + propertyName + "] loaded from JNDI Filter Specific Property with value [" + value3 + "]"); return value3; } final String value4 = loadFromContext(context, "java:comp/env/cas/" + propertyName); if (CommonUtils.isNotBlank(value4)) { - log.info("Property [" + propertyName + "] loaded from JNDI with value [" + value3 + "]"); + log.info("Property [" + propertyName + "] loaded from JNDI with value [" + value4 + "]"); return value4; } log.info("Property [" + propertyName + "] not found. Using default value [" + defaultValue + "]"); return defaultValue; } protected final boolean parseBoolean(final String value) { return ((value != null) && value.equalsIgnoreCase("true")); } protected final String loadFromContext(final InitialContext context, final String path) { try { return (String) context.lookup(path); } catch (final NamingException e) { return null; } } public final void setIgnoreInitConfiguration(boolean ignoreInitConfiguration) { this.ignoreInitConfiguration = ignoreInitConfiguration; } protected final boolean isIgnoreInitConfiguration() { return this.ignoreInitConfiguration; } }
true
true
protected final String getPropertyFromInitParams(final FilterConfig filterConfig, final String propertyName, final String defaultValue) { final String value = filterConfig.getInitParameter(propertyName); if (CommonUtils.isNotBlank(value)) { log.info("Property [" + propertyName + "] loaded from FilterConfig.getInitParameter with value [" + value + "]"); return value; } final String value2 = filterConfig.getServletContext().getInitParameter(propertyName); if (CommonUtils.isNotBlank(value2)) { log.info("Property [" + propertyName + "] loaded from ServletContext.getInitParameter with value [" + value2 + "]"); return value2; } InitialContext context; try { context = new InitialContext(); } catch (final NamingException e) { log.warn(e,e); return defaultValue; } final String shortName = this.getClass().getName().substring(this.getClass().getName().lastIndexOf(".")+1); final String value3 = loadFromContext(context, "java:comp/env/cas/" + shortName + "/" + propertyName); if (CommonUtils.isNotBlank(value3)) { log.info("Property [" + propertyName + "] loaded from JNDI Filter Specific Property with value [" + value3 + "]"); return value3; } final String value4 = loadFromContext(context, "java:comp/env/cas/" + propertyName); if (CommonUtils.isNotBlank(value4)) { log.info("Property [" + propertyName + "] loaded from JNDI with value [" + value3 + "]"); return value4; } log.info("Property [" + propertyName + "] not found. Using default value [" + defaultValue + "]"); return defaultValue; }
protected final String getPropertyFromInitParams(final FilterConfig filterConfig, final String propertyName, final String defaultValue) { final String value = filterConfig.getInitParameter(propertyName); if (CommonUtils.isNotBlank(value)) { log.info("Property [" + propertyName + "] loaded from FilterConfig.getInitParameter with value [" + value + "]"); return value; } final String value2 = filterConfig.getServletContext().getInitParameter(propertyName); if (CommonUtils.isNotBlank(value2)) { log.info("Property [" + propertyName + "] loaded from ServletContext.getInitParameter with value [" + value2 + "]"); return value2; } InitialContext context; try { context = new InitialContext(); } catch (final NamingException e) { log.warn(e,e); return defaultValue; } final String shortName = this.getClass().getName().substring(this.getClass().getName().lastIndexOf(".")+1); final String value3 = loadFromContext(context, "java:comp/env/cas/" + shortName + "/" + propertyName); if (CommonUtils.isNotBlank(value3)) { log.info("Property [" + propertyName + "] loaded from JNDI Filter Specific Property with value [" + value3 + "]"); return value3; } final String value4 = loadFromContext(context, "java:comp/env/cas/" + propertyName); if (CommonUtils.isNotBlank(value4)) { log.info("Property [" + propertyName + "] loaded from JNDI with value [" + value4 + "]"); return value4; } log.info("Property [" + propertyName + "] not found. Using default value [" + defaultValue + "]"); return defaultValue; }
diff --git a/Core/src/java/de/hattrickorganizer/net/ConvertXml2Hrf.java b/Core/src/java/de/hattrickorganizer/net/ConvertXml2Hrf.java index ad7db0a3..cbfd35c0 100644 --- a/Core/src/java/de/hattrickorganizer/net/ConvertXml2Hrf.java +++ b/Core/src/java/de/hattrickorganizer/net/ConvertXml2Hrf.java @@ -1,644 +1,644 @@ // %929884203:de.hattrickorganizer.net% /* * ConvertXml2Hrf.java * * Created on 12. Januar 2004, 09:44 */ package de.hattrickorganizer.net; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.util.Hashtable; import java.util.Vector; import plugins.ISpielerPosition; import de.hattrickorganizer.gui.login.LoginWaitDialog; import de.hattrickorganizer.logik.xml.XMLArenaParser; import de.hattrickorganizer.logik.xml.XMLClubParser; import de.hattrickorganizer.logik.xml.XMLMatchLineupParser; import de.hattrickorganizer.logik.xml.XMLMatchesParser; import de.hattrickorganizer.logik.xml.XMLTrainingParser; import de.hattrickorganizer.logik.xml.xmlEconomyParser; import de.hattrickorganizer.logik.xml.xmlLeagueDetailsParser; import de.hattrickorganizer.logik.xml.xmlMatchOrderParser; import de.hattrickorganizer.logik.xml.xmlMatchdetailsParser; import de.hattrickorganizer.logik.xml.xmlPlayersParser; import de.hattrickorganizer.logik.xml.xmlTeamDetailsParser; import de.hattrickorganizer.logik.xml.xmlWorldDetailsParser; import de.hattrickorganizer.model.Team; import de.hattrickorganizer.model.matches.MatchKurzInfo; import de.hattrickorganizer.model.matches.MatchLineup; import de.hattrickorganizer.model.matches.MatchLineupTeam; import de.hattrickorganizer.model.matches.Matchdetails; import de.hattrickorganizer.tools.HOLogger; import de.hattrickorganizer.tools.PlayerHelper; /** * Convert the necessary xml data into a HRF file. * * @author thomas.werth */ public class ConvertXml2Hrf { //~ Instance fields ---------------------------------------------------------------------------- protected Hashtable<?, ?> m_htArena; protected Hashtable<?, ?> m_htClub; protected Hashtable<?, ?> m_htEconomy; protected Hashtable<?, ?> m_htLiga; protected Hashtable<?, ?> m_htNextLineup; protected Hashtable<?, ?> m_htTeamdetails; protected Hashtable<?, ?> m_htTraining; protected Hashtable<?, ?> m_htWorld; protected MatchLineup m_clLineUp; protected MatchLineupTeam m_clTeam; protected StringBuffer m_sHRFBuffer; //enthält eine Liste an Hashtable die je einen Spieler beschreiben protected Vector<?> m_vSpieler; //MatchOrder protected MatchKurzInfo[] m_aMatches; int m_iLastAttitude; int m_iLastTactic; //~ Constructors ------------------------------------------------------------------------------- /** * Creates a new instance of ConvertXml2Hrf */ public ConvertXml2Hrf() { } //~ Methods ------------------------------------------------------------------------------------ /** * Create the HRF data and return it in one string. */ public final String createHrf(LoginWaitDialog waitDialog) throws Exception { //init m_sHRFBuffer = new StringBuffer(); try { //Hashtable's füllen final MyConnector mc = MyConnector.instance(); waitDialog.setValue(5); - m_htTeamdeatils = new xmlTeamDetailsParser().parseTeamdetailsFromString(mc.getTeamdetails(-1)); + m_htTeamdetails = new xmlTeamDetailsParser().parseTeamdetailsFromString(mc.getTeamdetails(-1)); waitDialog.setValue(10); m_htClub = new XMLClubParser().parseClubFromString(mc.getVerein()); waitDialog.setValue(15); m_htLiga = new xmlLeagueDetailsParser().parseLeagueDetailsFromString(mc.getLeagueDetails(),m_htTeamdetails.get("TeamID").toString()); waitDialog.setValue(20); m_htWorld = new xmlWorldDetailsParser().parseWorldDetailsFromString(mc.getWorldDetails(),m_htTeamdetails.get("LeagueID").toString()); waitDialog.setValue(25); m_clLineUp = new XMLMatchLineupParser().parseMatchLineupFromString(mc.getMatchLineup(-1,-1).toString()); waitDialog.setValue(30); m_vSpieler = new xmlPlayersParser().parsePlayersFromString(mc.getPlayersAsp()); waitDialog.setValue(35); m_htEconomy = new xmlEconomyParser().parseEconomyFromString(mc.getEconomy()); waitDialog.setValue(40); m_htTraining = new XMLTrainingParser().parseTrainingFromString(mc.getTraining()); waitDialog.setValue(45); m_htArena = new XMLArenaParser().parseArenaFromString(mc.getArena()); //MatchOrder waitDialog.setValue(50); m_aMatches = new XMLMatchesParser().parseMatchesFromString(mc.getMatchesASP(Integer.parseInt(m_htTeamdetails.get("TeamID").toString()), false)); waitDialog.setValue(52); // Automatisch alle MatchLineups runterladen for (int i = 0; (m_aMatches != null) && (i < m_aMatches.length); i++) { if (m_aMatches[i].getMatchStatus() == MatchKurzInfo.UPCOMING) { waitDialog.setValue(54); m_htNextLineup = new xmlMatchOrderParser().parseMatchOrderFromString(mc.getMatchOrder(m_aMatches[i].getMatchID())); break; } } waitDialog.setValue(55); // Team ermitteln, für Ratings der Player wichtig if (m_clLineUp != null) { final Matchdetails md = new xmlMatchdetailsParser().parseMachtdetailsFromString(mc.getMatchdetails(m_clLineUp.getMatchID())); if (m_clLineUp.getHeimId() == Integer.parseInt(m_htTeamdetails.get("TeamID").toString())) { m_clTeam = (de.hattrickorganizer.model.matches.MatchLineupTeam) m_clLineUp.getHeim(); if (md != null) { m_iLastAttitude = md.getHomeEinstellung(); m_iLastTactic = md.getHomeTacticType(); } } else { m_clTeam = (de.hattrickorganizer.model.matches.MatchLineupTeam) m_clLineUp.getGast(); if (md != null) { m_iLastAttitude = md.getGuestEinstellung(); m_iLastTactic = md.getGuestTacticType(); } } m_clTeam.getTeamID(); } //Abschnitte erstellen waitDialog.setValue(60); //basics createBasics(); waitDialog.setValue(65); //Liga createLeague(); waitDialog.setValue(70); //Club createClub(); waitDialog.setValue(75); //team createTeam(); waitDialog.setValue(80); //lineup createLineUp(); waitDialog.setValue(85); //economy createEconemy(); waitDialog.setValue(90); //Arena createArena(); waitDialog.setValue(93); //players createPlayers(); waitDialog.setValue(96); //xtra Data createWorld(); waitDialog.setValue(99); //lineup from the last match createLastLineUp(); waitDialog.setValue(100); } catch (Exception e) { HOLogger.instance().log(getClass(),"convertxml2hrf: Exception: " + e); HOLogger.instance().log(getClass(),e); throw new Exception(e); } //dialog zum Saven anzeigen //speichern //writeHRF( dateiname ); return m_sHRFBuffer.toString(); } /** * Create the arena data. */ protected final void createArena() throws Exception { m_sHRFBuffer.append("[arena]" + "\n"); m_sHRFBuffer.append("arenaname=" + m_htArena.get("ArenaName") + "\n"); m_sHRFBuffer.append("arenaid=" + m_htArena.get("ArenaID") + "\n"); m_sHRFBuffer.append("antalStaplats=" + m_htArena.get("Terraces") + "\n"); m_sHRFBuffer.append("antalSitt=" + m_htArena.get("Basic") + "\n"); m_sHRFBuffer.append("antalTak=" + m_htArena.get("Roof") + "\n"); m_sHRFBuffer.append("antalVIP=" + m_htArena.get("VIP") + "\n"); m_sHRFBuffer.append("seatTotal=" + m_htArena.get("Total") + "\n"); m_sHRFBuffer.append("expandingStaplats=" + m_htArena.get("ExTerraces") + "\n"); m_sHRFBuffer.append("expandingSitt=" + m_htArena.get("ExBasic") + "\n"); m_sHRFBuffer.append("expandingTak=" + m_htArena.get("ExRoof") + "\n"); m_sHRFBuffer.append("expandingVIP=" + m_htArena.get("ExVIP") + "\n"); m_sHRFBuffer.append("expandingSseatTotal=" + m_htArena.get("ExTotal") + "\n"); m_sHRFBuffer.append("isExpanding=" + m_htArena.get("isExpanding") + "\n"); //Achtung bei keiner Erweiterung = 0! m_sHRFBuffer.append("ExpansionDate=" + m_htArena.get("ExpansionDate") + "\n"); } //////////////////////////////////////////////////////////////////////////////// //Helper //////////////////////////////////////////////////////////////////////////////// /** * Create the basic data. */ protected final void createBasics() throws Exception { m_sHRFBuffer.append("[basics]\n"); m_sHRFBuffer.append("application=HO\n"); m_sHRFBuffer.append("appversion=" + de.hattrickorganizer.gui.HOMainFrame.VERSION + "\n"); m_sHRFBuffer.append("date=" + m_htTeamdetails.get("FetchedDate") + "\n"); m_sHRFBuffer.append("season=" + m_htWorld.get("Season") + "\n"); m_sHRFBuffer.append("matchround=" + m_htWorld.get("MatchRound") + "\n"); m_sHRFBuffer.append("teamID=" + m_htTeamdetails.get("TeamID") + "\n"); m_sHRFBuffer.append("teamName=" + m_htTeamdetails.get("TeamName") + "\n"); m_sHRFBuffer.append("owner=" + m_htTeamdetails.get("Loginname") + "\n"); m_sHRFBuffer.append("ownerEmail=" + m_htTeamdetails.get("Email") + "\n"); m_sHRFBuffer.append("ownerICQ=" + m_htTeamdetails.get("ICQ") + "\n"); m_sHRFBuffer.append("ownerHomepage=" + m_htTeamdetails.get("HomePage") + "\n"); m_sHRFBuffer.append("countryID=" + m_htWorld.get("CountryID") + "\n"); m_sHRFBuffer.append("leagueID=" + m_htTeamdetails.get("LeagueID") + "\n"); // m_sHRFBuffer.append("arenaID=" + m_htArena.get("ArenaID") + "\n"); m_sHRFBuffer.append("regionID=" + m_htTeamdetails.get("RegionID") + "\n"); m_sHRFBuffer.append("hasSupporter=" + m_htTeamdetails.get("HasSupporter") + "\n"); } /** * Create the club data. */ protected final void createClub() throws Exception { m_sHRFBuffer.append("[club]\n"); m_sHRFBuffer.append("mvTranare=" + m_htClub.get("KeeperTrainers") + "\n"); m_sHRFBuffer.append("hjTranare=" + m_htClub.get("AssistantTrainers") + "\n"); m_sHRFBuffer.append("psykolog=" + m_htClub.get("Psychologists") + "\n"); m_sHRFBuffer.append("presstalesman=" + m_htClub.get("PressSpokesmen") + "\n"); m_sHRFBuffer.append("ekonom=" + m_htClub.get("Economists") + "\n"); m_sHRFBuffer.append("massor=" + m_htClub.get("Physiotherapists") + "\n"); m_sHRFBuffer.append("lakare=" + m_htClub.get("Doctors") + "\n"); m_sHRFBuffer.append("juniorverksamhet=" + m_htClub.get("YouthLevel") + "\n"); m_sHRFBuffer.append("undefeated=" + m_htTeamdetails.get("NumberOfUndefeated") + "\n"); m_sHRFBuffer.append("victories=" + m_htTeamdetails.get("NumberOfVictories") + "\n"); m_sHRFBuffer.append("fanclub=" + m_htEconomy.get("FanClubSize") + "\n"); } /** * Create the economy data. */ protected final void createEconemy() throws Exception { //wahrscheinlich in Training.asp fehlt noch m_sHRFBuffer.append("[economy]" + "\n"); if (m_htEconomy.get("SponsorsPopularity") != null) { m_sHRFBuffer.append("supporters=" + m_htEconomy.get("SupportersPopularity") + "\n"); m_sHRFBuffer.append("sponsors=" + m_htEconomy.get("SponsorsPopularity") + "\n"); //es wird grad gespielt flag setzen } else { m_sHRFBuffer.append("playingMatch=true"); } m_sHRFBuffer.append("cash=" + m_htEconomy.get("Cash") + "\n"); m_sHRFBuffer.append("IncomeSponsorer=" + m_htEconomy.get("IncomeSponsors") + "\n"); m_sHRFBuffer.append("incomePublik=" + m_htEconomy.get("IncomeSpectators") + "\n"); m_sHRFBuffer.append("incomeFinansiella=" + m_htEconomy.get("IncomeFinancial") + "\n"); m_sHRFBuffer.append("incomeTillfalliga=" + m_htEconomy.get("IncomeTemporary") + "\n"); m_sHRFBuffer.append("incomeSumma=" + m_htEconomy.get("IncomeSum") + "\n"); m_sHRFBuffer.append("costsSpelare=" + m_htEconomy.get("CostsPlayers") + "\n"); m_sHRFBuffer.append("costsPersonal=" + m_htEconomy.get("CostsStaff") + "\n"); m_sHRFBuffer.append("costsArena=" + m_htEconomy.get("CostsArena") + "\n"); m_sHRFBuffer.append("costsJuniorverksamhet=" + m_htEconomy.get("CostsYouth") + "\n"); m_sHRFBuffer.append("costsRantor=" + m_htEconomy.get("CostsFinancial") + "\n"); m_sHRFBuffer.append("costsTillfalliga=" + m_htEconomy.get("CostsTemporary") + "\n"); m_sHRFBuffer.append("costsSumma=" + m_htEconomy.get("CostsSum") + "\n"); m_sHRFBuffer.append("total=" + m_htEconomy.get("ExpectedWeeksTotal") + "\n"); m_sHRFBuffer.append("lastIncomeSponsorer=" + m_htEconomy.get("LastIncomeSponsors") + "\n"); m_sHRFBuffer.append("lastIncomePublik=" + m_htEconomy.get("LastIncomeSpectators") + "\n"); m_sHRFBuffer.append("lastIncomeFinansiella=" + m_htEconomy.get("LastIncomeFinancial") + "\n"); m_sHRFBuffer.append("lastIncomeTillfalliga=" + m_htEconomy.get("LastIncomeTemporary") + "\n"); m_sHRFBuffer.append("lastIncomeSumma=" + m_htEconomy.get("LastIncomeSum") + "\n"); m_sHRFBuffer.append("lastCostsSpelare=" + m_htEconomy.get("LastCostsPlayers") + "\n"); m_sHRFBuffer.append("lastCostsPersonal=" + m_htEconomy.get("LastCostsStaff") + "\n"); m_sHRFBuffer.append("lastCostsArena=" + m_htEconomy.get("LastCostsArena") + "\n"); m_sHRFBuffer.append("lastCostsJuniorverksamhet=" + m_htEconomy.get("LastCostsYouth") + "\n"); m_sHRFBuffer.append("lastCostsRantor=" + m_htEconomy.get("LastCostsFinancial") + "\n"); m_sHRFBuffer.append("lastCostsTillfalliga=" + m_htEconomy.get("LastCostsTemporary") + "\n"); m_sHRFBuffer.append("lastCostsSumma=" + m_htEconomy.get("LastCostsSum") + "\n"); m_sHRFBuffer.append("lastTotal=" + m_htEconomy.get("LastWeeksTotal") + "\n"); } /** * Create last lineup section. */ protected final void createLastLineUp() { m_sHRFBuffer.append("[lastlineup]" + "\n"); m_sHRFBuffer.append("trainer=" + m_htTeamdetails.get("TrainerID") + "\n"); try { m_sHRFBuffer.append("installning=" + m_iLastAttitude + "\n"); m_sHRFBuffer.append("tactictype=" + m_iLastTactic + "\n"); m_sHRFBuffer.append("keeper=" + m_clTeam.getPlayerByPosition(ISpielerPosition.keeper).getSpielerId() + "\n"); m_sHRFBuffer.append("rightBack=" + m_clTeam.getPlayerByPosition(ISpielerPosition.rightBack).getSpielerId() + "\n"); m_sHRFBuffer.append("insideBack1=" + m_clTeam.getPlayerByPosition(ISpielerPosition.rightCentralDefender).getSpielerId() + "\n"); m_sHRFBuffer.append("insideBack2=" + m_clTeam.getPlayerByPosition(ISpielerPosition.leftCentralDefender).getSpielerId() + "\n"); m_sHRFBuffer.append("insideBack3=" + m_clTeam.getPlayerByPosition(ISpielerPosition.middleCentralDefender).getSpielerId() + "\n"); m_sHRFBuffer.append("leftBack=" + m_clTeam.getPlayerByPosition(ISpielerPosition.leftBack).getSpielerId() + "\n"); m_sHRFBuffer.append("rightWinger=" + m_clTeam.getPlayerByPosition(ISpielerPosition.rightWinger).getSpielerId() + "\n"); m_sHRFBuffer.append("insideMid1=" + m_clTeam.getPlayerByPosition(ISpielerPosition.rightInnerMidfield).getSpielerId() + "\n"); m_sHRFBuffer.append("insideMid2=" + m_clTeam.getPlayerByPosition(ISpielerPosition.leftInnerMidfield).getSpielerId() + "\n"); m_sHRFBuffer.append("insideMid3=" + m_clTeam.getPlayerByPosition(ISpielerPosition.centralInnerMidfield).getSpielerId() + "\n"); m_sHRFBuffer.append("leftWinger=" + m_clTeam.getPlayerByPosition(ISpielerPosition.leftWinger).getSpielerId() + "\n"); m_sHRFBuffer.append("forward1=" + m_clTeam.getPlayerByPosition(ISpielerPosition.rightForward).getSpielerId() + "\n"); m_sHRFBuffer.append("forward2=" + m_clTeam.getPlayerByPosition(ISpielerPosition.leftForward).getSpielerId() + "\n"); m_sHRFBuffer.append("forward3=" + m_clTeam.getPlayerByPosition(ISpielerPosition.centralForward).getSpielerId() + "\n"); m_sHRFBuffer.append("substBack=" + m_clTeam.getPlayerByPosition(ISpielerPosition.substDefender).getSpielerId() + "\n"); m_sHRFBuffer.append("substInsideMid=" + m_clTeam.getPlayerByPosition(ISpielerPosition.substInnerMidfield).getSpielerId() + "\n"); m_sHRFBuffer.append("substWinger=" + m_clTeam.getPlayerByPosition(ISpielerPosition.substWinger).getSpielerId() + "\n"); m_sHRFBuffer.append("substKeeper=" + m_clTeam.getPlayerByPosition(ISpielerPosition.substKeeper).getSpielerId() + "\n"); m_sHRFBuffer.append("substForward=" + m_clTeam.getPlayerByPosition(ISpielerPosition.substForward).getSpielerId() + "\n"); m_sHRFBuffer.append("captain=" + m_clTeam.getPlayerByPosition(ISpielerPosition.captain).getSpielerId() + "\n"); m_sHRFBuffer.append("kicker1=" + m_clTeam.getPlayerByPosition(ISpielerPosition.setPieces).getSpielerId() + "\n"); m_sHRFBuffer.append("behrightBack=" + m_clTeam.getPlayerByPosition(ISpielerPosition.rightBack).getTaktik() + "\n"); m_sHRFBuffer.append("behinsideBack1=" + m_clTeam.getPlayerByPosition(ISpielerPosition.rightCentralDefender).getTaktik() + "\n"); m_sHRFBuffer.append("behinsideBack2=" + m_clTeam.getPlayerByPosition(ISpielerPosition.leftCentralDefender).getTaktik() + "\n"); m_sHRFBuffer.append("behinsideBack3=" + m_clTeam.getPlayerByPosition(ISpielerPosition.middleCentralDefender).getTaktik() + "\n"); m_sHRFBuffer.append("behleftBack=" + m_clTeam.getPlayerByPosition(ISpielerPosition.leftWinger).getTaktik() + "\n"); m_sHRFBuffer.append("behrightWinger=" + m_clTeam.getPlayerByPosition(ISpielerPosition.rightWinger).getTaktik() + "\n"); m_sHRFBuffer.append("behinsideMid1=" + m_clTeam.getPlayerByPosition(ISpielerPosition.rightInnerMidfield).getTaktik() + "\n"); m_sHRFBuffer.append("behinsideMid2=" + m_clTeam.getPlayerByPosition(ISpielerPosition.leftInnerMidfield).getTaktik() + "\n"); m_sHRFBuffer.append("behinsideMid3=" + m_clTeam.getPlayerByPosition(ISpielerPosition.centralInnerMidfield).getTaktik() + "\n"); m_sHRFBuffer.append("behleftWinger=" + m_clTeam.getPlayerByPosition(ISpielerPosition.leftWinger).getTaktik() + "\n"); m_sHRFBuffer.append("behforward1=" + m_clTeam.getPlayerByPosition(ISpielerPosition.rightForward).getTaktik() + "\n"); m_sHRFBuffer.append("behforward2=" + m_clTeam.getPlayerByPosition(ISpielerPosition.leftForward).getTaktik() + "\n"); m_sHRFBuffer.append("behforward3=" + m_clTeam.getPlayerByPosition(ISpielerPosition.centralForward).getTaktik() + "\n"); } catch (Exception e) { HOLogger.instance().debug(getClass(), "Error(last lineup): " + e); } } /** * Create the league data. */ protected final void createLeague() throws Exception { m_sHRFBuffer.append("[league]\n"); m_sHRFBuffer.append("serie=" + m_htLiga.get("LeagueLevelUnitName") + "\n"); m_sHRFBuffer.append("spelade=" + m_htLiga.get("Matches") + "\n"); m_sHRFBuffer.append("gjorda=" + m_htLiga.get("GoalsFor") + "\n"); m_sHRFBuffer.append("inslappta=" + m_htLiga.get("GoalsAgainst") + "\n"); m_sHRFBuffer.append("poang=" + m_htLiga.get("Points") + "\n"); m_sHRFBuffer.append("placering=" + m_htLiga.get("Position") + "\n"); } private String getPlayerForNextLineup(String position) { if (m_htNextLineup != null) { final Object ret = m_htNextLineup.get(position); if (ret != null) { return ret.toString(); } } return "0"; } private String getPlayerOrderForNextLineup(String position) { if (m_htNextLineup != null) { String ret = (String)m_htNextLineup.get(position); if (ret != null) { ret = ret.trim(); if (!"null".equals(ret) && !"".equals(ret)) { return ret.trim(); } } } return "0"; } /** * Erstellt die LineUp Daten */ protected final void createLineUp() throws Exception { m_sHRFBuffer.append("[lineup]" + "\n"); try { m_sHRFBuffer.append("trainer=" + m_htTeamdetails.get("TrainerID") + "\n"); m_sHRFBuffer.append("installning=" + m_htNextLineup.get("Attitude") + "\n"); m_sHRFBuffer.append("tactictype="+ (m_htNextLineup.get("TacticType").toString().trim().equals("") ? "0" : m_htNextLineup.get("TacticType").toString().trim()) + "\n"); m_sHRFBuffer.append("keeper=" + getPlayerForNextLineup("KeeperID") + "\n"); m_sHRFBuffer.append("rightBack=" + getPlayerForNextLineup("RightBackID") + "\n"); m_sHRFBuffer.append("insideBack1=" + getPlayerForNextLineup("RightCentralDefenderID") + "\n"); m_sHRFBuffer.append("insideBack2=" + getPlayerForNextLineup("LeftCentralDefenderID") + "\n"); m_sHRFBuffer.append("insideBack3=" + getPlayerForNextLineup("MiddleCentralDefenderID") + "\n"); m_sHRFBuffer.append("leftBack=" + getPlayerForNextLineup("LeftBackID") + "\n"); m_sHRFBuffer.append("rightWinger=" + getPlayerForNextLineup("RightWingerID") + "\n"); m_sHRFBuffer.append("insideMid1=" + getPlayerForNextLineup("RightInnerMidfieldID") + "\n"); m_sHRFBuffer.append("insideMid2=" + getPlayerForNextLineup("LeftInnerMidfieldID") + "\n"); m_sHRFBuffer.append("insideMid3=" + getPlayerForNextLineup("CentralInnerMidfieldID") + "\n"); m_sHRFBuffer.append("leftWinger=" + getPlayerForNextLineup("LeftWingerID") + "\n"); m_sHRFBuffer.append("forward1=" + getPlayerForNextLineup("RightForwardID") + "\n"); m_sHRFBuffer.append("forward2=" + getPlayerForNextLineup("LeftForwardID") + "\n"); m_sHRFBuffer.append("forward3=" + getPlayerForNextLineup("CentralForwardID") + "\n"); m_sHRFBuffer.append("substBack=" + getPlayerForNextLineup("SubstBackID") + "\n"); m_sHRFBuffer.append("substInsideMid=" + getPlayerForNextLineup("SubstInsideMidID") + "\n"); m_sHRFBuffer.append("substWinger=" + getPlayerForNextLineup("SubstWingerID") + "\n"); m_sHRFBuffer.append("substKeeper=" + getPlayerForNextLineup("SubstKeeperID") + "\n"); m_sHRFBuffer.append("substForward=" + getPlayerForNextLineup("SubstForwardID") + "\n"); m_sHRFBuffer.append("captain=" + getPlayerForNextLineup("CaptainID") + "\n"); m_sHRFBuffer.append("kicker1=" + getPlayerForNextLineup("KickerID") + "\n"); m_sHRFBuffer.append("behrightBack=" + getPlayerOrderForNextLineup("RightBackOrder") + "\n"); m_sHRFBuffer.append("behinsideBack1=" + getPlayerOrderForNextLineup("RightCentralDefenderOrder") + "\n"); m_sHRFBuffer.append("behinsideBack2=" + getPlayerOrderForNextLineup("LeftCentralDefenderOrder") + "\n"); m_sHRFBuffer.append("behinsideBack3=" + getPlayerOrderForNextLineup("MiddleCentralDefenderOrder") + "\n"); m_sHRFBuffer.append("behleftBack=" + getPlayerOrderForNextLineup("LeftBackOrder") + "\n"); m_sHRFBuffer.append("behrightWinger=" + getPlayerOrderForNextLineup("RightWingerOrder") + "\n"); m_sHRFBuffer.append("behinsideMid1=" + getPlayerOrderForNextLineup("RightInnerMidfieldOrder") + "\n"); m_sHRFBuffer.append("behinsideMid2=" + getPlayerOrderForNextLineup("LeftInnerMidfieldOrder") + "\n"); m_sHRFBuffer.append("behinsideMid3=" + getPlayerOrderForNextLineup("CentralInnerMidfieldOrder") + "\n"); m_sHRFBuffer.append("behleftWinger=" + getPlayerOrderForNextLineup("LeftWingerOrder") + "\n"); m_sHRFBuffer.append("behforward1=" + getPlayerOrderForNextLineup("RightForwardOrder") + "\n"); m_sHRFBuffer.append("behforward2=" + getPlayerOrderForNextLineup("LeftForwardOrder") + "\n"); m_sHRFBuffer.append("behforward3=" + getPlayerOrderForNextLineup("CentralForwardOrder") + "\n"); } catch (Exception e) { HOLogger.instance().debug(getClass(), "Error(lineup): " + e); } } /** * Create the player data. */ protected final void createPlayers() throws Exception { Hashtable<?, ?> ht = null; for (int i = 0; (m_vSpieler != null) && (i < m_vSpieler.size()); i++) { ht = (Hashtable<?, ?>) m_vSpieler.elementAt(i); m_sHRFBuffer.append("[player" + ht.get("PlayerID").toString() + "]" + "\n"); m_sHRFBuffer.append("name=" + ht.get("PlayerName").toString() + "\n"); m_sHRFBuffer.append("ald=" + ht.get("Age").toString() + "\n"); m_sHRFBuffer.append("agedays=" + ht.get("AgeDays").toString() + "\n"); m_sHRFBuffer.append("ska=" + ht.get("InjuryLevel").toString() + "\n"); m_sHRFBuffer.append("for=" + ht.get("PlayerForm").toString() + "\n"); m_sHRFBuffer.append("uth=" + ht.get("StaminaSkill").toString() + "\n"); m_sHRFBuffer.append("spe=" + ht.get("PlaymakerSkill").toString() + "\n"); m_sHRFBuffer.append("mal=" + ht.get("ScorerSkill").toString() + "\n"); m_sHRFBuffer.append("fra=" + ht.get("PassingSkill").toString() + "\n"); m_sHRFBuffer.append("ytt=" + ht.get("WingerSkill").toString() + "\n"); m_sHRFBuffer.append("fas=" + ht.get("SetPiecesSkill").toString() + "\n"); m_sHRFBuffer.append("bac=" + ht.get("DefenderSkill").toString() + "\n"); m_sHRFBuffer.append("mlv=" + ht.get("KeeperSkill").toString() + "\n"); m_sHRFBuffer.append("rut=" + ht.get("Experience").toString() + "\n"); m_sHRFBuffer.append("led=" + ht.get("Leadership").toString() + "\n"); m_sHRFBuffer.append("sal=" + ht.get("Salary").toString() + "\n"); m_sHRFBuffer.append("mkt=" + ht.get("MarketValue").toString() + "\n"); m_sHRFBuffer.append("gev=" + ht.get("CareerGoals").toString() + "\n"); m_sHRFBuffer.append("gtl=" + ht.get("LeagueGoals").toString() + "\n"); m_sHRFBuffer.append("gtc=" + ht.get("CupGoals").toString() + "\n"); m_sHRFBuffer.append("gtt=" + ht.get("FriendliesGoals").toString() + "\n"); m_sHRFBuffer.append("hat=" + ht.get("CareerHattricks").toString() + "\n"); m_sHRFBuffer.append("CountryID=" + ht.get("CountryID").toString() + "\n"); m_sHRFBuffer.append("warnings=" + ht.get("Cards").toString() + "\n"); m_sHRFBuffer.append("speciality=" + ht.get("Specialty").toString() + "\n"); m_sHRFBuffer.append("specialityLabel=" + PlayerHelper.getNameForSpeciality(Integer.parseInt(ht.get("Specialty") .toString())) + "\n"); m_sHRFBuffer.append("gentleness=" + ht.get("Agreeability").toString() + "\n"); m_sHRFBuffer.append("gentlenessLabel=" + PlayerHelper.getNameForGentleness(Integer.parseInt(ht.get("Agreeability") .toString())) + "\n"); m_sHRFBuffer.append("honesty=" + ht.get("Honesty").toString() + "\n"); m_sHRFBuffer.append("honestyLabel=" + PlayerHelper.getNameForCharacter(Integer.parseInt(ht.get("Honesty") .toString())) + "\n"); m_sHRFBuffer.append("Aggressiveness=" + ht.get("Aggressiveness").toString() + "\n"); m_sHRFBuffer.append("AggressivenessLabel=" + PlayerHelper.getNameForAggressivness(Integer.parseInt(ht.get("Aggressiveness") .toString())) + "\n"); if (ht.get("TrainerSkill") != null) { m_sHRFBuffer.append("TrainerType=" + ht.get("TrainerType").toString() + "\n"); m_sHRFBuffer.append("TrainerSkill=" + ht.get("TrainerSkill").toString() + "\n"); } else { m_sHRFBuffer.append("TrainerType=" + "\n"); m_sHRFBuffer.append("TrainerSkill=" + "\n"); } if ((m_clTeam != null) && (m_clTeam.getPlayerByID(Integer.parseInt(ht.get("PlayerID").toString())) != null) && (m_clTeam.getPlayerByID(Integer.parseInt(ht.get("PlayerID").toString())) .getRating() >= 0)) { m_sHRFBuffer.append("rating=" + (int) (m_clTeam.getPlayerByID(Integer.parseInt(ht.get("PlayerID") .toString())) .getRating() * 2) + "\n"); } else { m_sHRFBuffer.append("rating=0" + "\n"); } //Bonus if ((ht.get("PlayerNumber") != null) || (!ht.get("PlayerNumber").equals(""))) { m_sHRFBuffer.append("PlayerNumber=" + ht.get("PlayerNumber") + "\n"); } m_sHRFBuffer.append("TransferListed=" + ht.get("TransferListed") + "\n"); m_sHRFBuffer.append("NationalTeamID=" + ht.get("NationalTeamID") + "\n"); m_sHRFBuffer.append("Caps=" + ht.get("Caps") + "\n"); m_sHRFBuffer.append("CapsU20=" + ht.get("CapsU20") + "\n"); } } /** * Create team related data (training, confidence, formation experience, etc.). */ protected final void createTeam() throws Exception { m_sHRFBuffer.append("[team]" + "\n"); m_sHRFBuffer.append("trLevel=" + m_htTraining.get("TrainingLevel") + "\n"); m_sHRFBuffer.append("staminaTrainingPart=" + m_htTraining.get("StaminaTrainingPart") + "\n"); m_sHRFBuffer.append("trTypeValue=" + m_htTraining.get("TrainingType") + "\n"); m_sHRFBuffer.append("trType=" + Team.getNameForTraining(Integer.parseInt(m_htTraining.get("TrainingType").toString())) + "\n"); if ((m_htTraining.get("Morale") != null) && (m_htTraining.get("SelfConfidence") != null)) { m_sHRFBuffer.append("stamningValue=" + m_htTraining.get("Morale") + "\n"); m_sHRFBuffer.append("stamning=" + Team.getNameForStimmung(Integer.parseInt(m_htTraining.get("Morale").toString())) + "\n"); m_sHRFBuffer.append("sjalvfortroendeValue=" + m_htTraining.get("SelfConfidence") + "\n"); m_sHRFBuffer.append("sjalvfortroende=" + Team.getNameForSelbstvertrauen(Integer.parseInt(m_htTraining.get("SelfConfidence").toString()))+ "\n"); } else { m_sHRFBuffer.append("playingMatch=true"); } m_sHRFBuffer.append("exper433=" + m_htTraining.get("Experience433") + "\n"); m_sHRFBuffer.append("exper451=" + m_htTraining.get("Experience451") + "\n"); m_sHRFBuffer.append("exper352=" + m_htTraining.get("Experience352") + "\n"); m_sHRFBuffer.append("exper532=" + m_htTraining.get("Experience532") + "\n"); m_sHRFBuffer.append("exper343=" + m_htTraining.get("Experience343") + "\n"); m_sHRFBuffer.append("exper541=" + m_htTraining.get("Experience541") + "\n"); if (m_htTraining.get("Experience442") != null) { m_sHRFBuffer.append("exper442=" + m_htTraining.get("Experience442") + "\n"); } if (m_htTraining.get("Experience523") != null) { m_sHRFBuffer.append("exper523=" + m_htTraining.get("Experience523") + "\n"); } if (m_htTraining.get("Experience550") != null) { m_sHRFBuffer.append("exper550=" + m_htTraining.get("Experience550") + "\n"); } if (m_htTraining.get("Experience253") != null) { m_sHRFBuffer.append("exper253=" + m_htTraining.get("Experience253") + "\n"); } } /** * Create the world data. */ protected final void createWorld() throws Exception { m_sHRFBuffer.append("[xtra]\n"); //schon in basics //m_sHRFBuffer.append ( "LeagueID=" + m_htWorld.get ( "LeagueID" ) + "\n" ); //m_sHRFBuffer.append ( "season=" + m_htWorld.get ( "Season" ) + "\n" ); //m_sHRFBuffer.append ( "matchround=" + m_htWorld.get ( "MatchRound" ) + "\n" ); //m_sHRFBuffer.append ( "CountryID=" + m_htWorld.get ( "CountryID" ) + "\n" ); //m_sHRFBuffer.append ( "ownerICQ=" + m_htWorld.get ( "ICQ" ) + "\n" ); m_sHRFBuffer.append("TrainingDate=" + m_htWorld.get("TrainingDate") + "\n"); m_sHRFBuffer.append("EconomyDate=" + m_htWorld.get("EconomyDate") + "\n"); m_sHRFBuffer.append("SeriesMatchDate=" + m_htWorld.get("SeriesMatchDate") + "\n"); m_sHRFBuffer.append("CurrencyName=" + m_htWorld.get("CurrencyName") + "\n"); m_sHRFBuffer.append("CurrencyRate=" + m_htWorld.get("CurrencyRate").toString().replace(',', '.') + "\n"); m_sHRFBuffer.append("LogoURL=" + m_htTeamdetails.get("LogoURL") + "\n"); m_sHRFBuffer.append("HasPromoted=" + m_htClub.get("HasPromoted") + "\n"); m_sHRFBuffer.append("TrainerID=" + m_htTraining.get("TrainerID") + "\n"); m_sHRFBuffer.append("TrainerName=" + m_htTraining.get("TrainerName") + "\n"); m_sHRFBuffer.append("ArrivalDate=" + m_htTraining.get("ArrivalDate") + "\n"); m_sHRFBuffer.append("LeagueLevelUnitID=" + m_htTeamdetails.get("LeagueLevelUnitID") + "\n"); } /** * Save the HRF file. */ protected final void writeHRF(String dateiname) { BufferedWriter out = null; final String text = m_sHRFBuffer.toString(); //utf-8 OutputStreamWriter outWrit = null; try { File f = new File(dateiname); if (f.exists()) { f.delete(); } f.createNewFile(); //write utf 8 outWrit = new OutputStreamWriter(new FileOutputStream(f), "UTF-8"); out = new BufferedWriter(outWrit); //write ansi //out = new BufferedWriter( new FileWriter( f ) ); if (text != null) { out.write(text); } } catch (Exception except) { HOLogger.instance().log(getClass(),except); } finally { if (out != null) { try { out.close(); } catch (Exception e) { } } } } }
true
true
public final String createHrf(LoginWaitDialog waitDialog) throws Exception { //init m_sHRFBuffer = new StringBuffer(); try { //Hashtable's füllen final MyConnector mc = MyConnector.instance(); waitDialog.setValue(5); m_htTeamdeatils = new xmlTeamDetailsParser().parseTeamdetailsFromString(mc.getTeamdetails(-1)); waitDialog.setValue(10); m_htClub = new XMLClubParser().parseClubFromString(mc.getVerein()); waitDialog.setValue(15); m_htLiga = new xmlLeagueDetailsParser().parseLeagueDetailsFromString(mc.getLeagueDetails(),m_htTeamdetails.get("TeamID").toString()); waitDialog.setValue(20); m_htWorld = new xmlWorldDetailsParser().parseWorldDetailsFromString(mc.getWorldDetails(),m_htTeamdetails.get("LeagueID").toString()); waitDialog.setValue(25); m_clLineUp = new XMLMatchLineupParser().parseMatchLineupFromString(mc.getMatchLineup(-1,-1).toString()); waitDialog.setValue(30); m_vSpieler = new xmlPlayersParser().parsePlayersFromString(mc.getPlayersAsp()); waitDialog.setValue(35); m_htEconomy = new xmlEconomyParser().parseEconomyFromString(mc.getEconomy()); waitDialog.setValue(40); m_htTraining = new XMLTrainingParser().parseTrainingFromString(mc.getTraining()); waitDialog.setValue(45); m_htArena = new XMLArenaParser().parseArenaFromString(mc.getArena()); //MatchOrder waitDialog.setValue(50); m_aMatches = new XMLMatchesParser().parseMatchesFromString(mc.getMatchesASP(Integer.parseInt(m_htTeamdetails.get("TeamID").toString()), false)); waitDialog.setValue(52); // Automatisch alle MatchLineups runterladen for (int i = 0; (m_aMatches != null) && (i < m_aMatches.length); i++) { if (m_aMatches[i].getMatchStatus() == MatchKurzInfo.UPCOMING) { waitDialog.setValue(54); m_htNextLineup = new xmlMatchOrderParser().parseMatchOrderFromString(mc.getMatchOrder(m_aMatches[i].getMatchID())); break; } } waitDialog.setValue(55); // Team ermitteln, für Ratings der Player wichtig if (m_clLineUp != null) { final Matchdetails md = new xmlMatchdetailsParser().parseMachtdetailsFromString(mc.getMatchdetails(m_clLineUp.getMatchID())); if (m_clLineUp.getHeimId() == Integer.parseInt(m_htTeamdetails.get("TeamID").toString())) { m_clTeam = (de.hattrickorganizer.model.matches.MatchLineupTeam) m_clLineUp.getHeim(); if (md != null) { m_iLastAttitude = md.getHomeEinstellung(); m_iLastTactic = md.getHomeTacticType(); } } else { m_clTeam = (de.hattrickorganizer.model.matches.MatchLineupTeam) m_clLineUp.getGast(); if (md != null) { m_iLastAttitude = md.getGuestEinstellung(); m_iLastTactic = md.getGuestTacticType(); } } m_clTeam.getTeamID(); } //Abschnitte erstellen waitDialog.setValue(60); //basics createBasics(); waitDialog.setValue(65); //Liga createLeague(); waitDialog.setValue(70); //Club createClub(); waitDialog.setValue(75); //team createTeam(); waitDialog.setValue(80); //lineup createLineUp(); waitDialog.setValue(85); //economy createEconemy(); waitDialog.setValue(90); //Arena createArena(); waitDialog.setValue(93); //players createPlayers(); waitDialog.setValue(96); //xtra Data createWorld(); waitDialog.setValue(99); //lineup from the last match createLastLineUp(); waitDialog.setValue(100); } catch (Exception e) { HOLogger.instance().log(getClass(),"convertxml2hrf: Exception: " + e); HOLogger.instance().log(getClass(),e); throw new Exception(e); } //dialog zum Saven anzeigen //speichern //writeHRF( dateiname ); return m_sHRFBuffer.toString(); }
public final String createHrf(LoginWaitDialog waitDialog) throws Exception { //init m_sHRFBuffer = new StringBuffer(); try { //Hashtable's füllen final MyConnector mc = MyConnector.instance(); waitDialog.setValue(5); m_htTeamdetails = new xmlTeamDetailsParser().parseTeamdetailsFromString(mc.getTeamdetails(-1)); waitDialog.setValue(10); m_htClub = new XMLClubParser().parseClubFromString(mc.getVerein()); waitDialog.setValue(15); m_htLiga = new xmlLeagueDetailsParser().parseLeagueDetailsFromString(mc.getLeagueDetails(),m_htTeamdetails.get("TeamID").toString()); waitDialog.setValue(20); m_htWorld = new xmlWorldDetailsParser().parseWorldDetailsFromString(mc.getWorldDetails(),m_htTeamdetails.get("LeagueID").toString()); waitDialog.setValue(25); m_clLineUp = new XMLMatchLineupParser().parseMatchLineupFromString(mc.getMatchLineup(-1,-1).toString()); waitDialog.setValue(30); m_vSpieler = new xmlPlayersParser().parsePlayersFromString(mc.getPlayersAsp()); waitDialog.setValue(35); m_htEconomy = new xmlEconomyParser().parseEconomyFromString(mc.getEconomy()); waitDialog.setValue(40); m_htTraining = new XMLTrainingParser().parseTrainingFromString(mc.getTraining()); waitDialog.setValue(45); m_htArena = new XMLArenaParser().parseArenaFromString(mc.getArena()); //MatchOrder waitDialog.setValue(50); m_aMatches = new XMLMatchesParser().parseMatchesFromString(mc.getMatchesASP(Integer.parseInt(m_htTeamdetails.get("TeamID").toString()), false)); waitDialog.setValue(52); // Automatisch alle MatchLineups runterladen for (int i = 0; (m_aMatches != null) && (i < m_aMatches.length); i++) { if (m_aMatches[i].getMatchStatus() == MatchKurzInfo.UPCOMING) { waitDialog.setValue(54); m_htNextLineup = new xmlMatchOrderParser().parseMatchOrderFromString(mc.getMatchOrder(m_aMatches[i].getMatchID())); break; } } waitDialog.setValue(55); // Team ermitteln, für Ratings der Player wichtig if (m_clLineUp != null) { final Matchdetails md = new xmlMatchdetailsParser().parseMachtdetailsFromString(mc.getMatchdetails(m_clLineUp.getMatchID())); if (m_clLineUp.getHeimId() == Integer.parseInt(m_htTeamdetails.get("TeamID").toString())) { m_clTeam = (de.hattrickorganizer.model.matches.MatchLineupTeam) m_clLineUp.getHeim(); if (md != null) { m_iLastAttitude = md.getHomeEinstellung(); m_iLastTactic = md.getHomeTacticType(); } } else { m_clTeam = (de.hattrickorganizer.model.matches.MatchLineupTeam) m_clLineUp.getGast(); if (md != null) { m_iLastAttitude = md.getGuestEinstellung(); m_iLastTactic = md.getGuestTacticType(); } } m_clTeam.getTeamID(); } //Abschnitte erstellen waitDialog.setValue(60); //basics createBasics(); waitDialog.setValue(65); //Liga createLeague(); waitDialog.setValue(70); //Club createClub(); waitDialog.setValue(75); //team createTeam(); waitDialog.setValue(80); //lineup createLineUp(); waitDialog.setValue(85); //economy createEconemy(); waitDialog.setValue(90); //Arena createArena(); waitDialog.setValue(93); //players createPlayers(); waitDialog.setValue(96); //xtra Data createWorld(); waitDialog.setValue(99); //lineup from the last match createLastLineUp(); waitDialog.setValue(100); } catch (Exception e) { HOLogger.instance().log(getClass(),"convertxml2hrf: Exception: " + e); HOLogger.instance().log(getClass(),e); throw new Exception(e); } //dialog zum Saven anzeigen //speichern //writeHRF( dateiname ); return m_sHRFBuffer.toString(); }
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasklist/internal/planner/TaskReportGenerator.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasklist/internal/planner/TaskReportGenerator.java index c0fab102e..82987d3c6 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasklist/internal/planner/TaskReportGenerator.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasklist/internal/planner/TaskReportGenerator.java @@ -1,94 +1,94 @@ /******************************************************************************* * Copyright (c) 2004 - 2005 University Of British Columbia and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * University Of British Columbia - initial API and implementation *******************************************************************************/ package org.eclipse.mylar.tasklist.internal.planner; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.mylar.core.util.ErrorLogger; import org.eclipse.mylar.tasklist.ITask; import org.eclipse.mylar.tasklist.internal.TaskCategory; import org.eclipse.mylar.tasklist.internal.TaskList; import org.eclipse.mylar.tasklist.ui.ITaskListElement; /** * @author Ken Sueda * @author Mik Kersten */ public class TaskReportGenerator implements IRunnableWithProgress { // NOTE: might want a map of tasks instead of a flattened list of tasks private List<ITaskCollector> collectors = new ArrayList<ITaskCollector>(); private List<ITask> tasks = new ArrayList<ITask>(); private TaskList tasklist = null; private boolean finished; public TaskReportGenerator(TaskList tlist) { tasklist = tlist; } public void addCollector(ITaskCollector collector) { collectors.add(collector); } public void collectTasks() { try { run(new NullProgressMonitor()); } catch (InvocationTargetException e) { // operation was canceled } catch (InterruptedException e) { ErrorLogger.log(e, "Could not collect tasks"); } } public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { List<ITask> roots = tasklist.getRootTasks(); - monitor.beginTask("Mylar Task Planner", 1 + tasklist.getCategories().size()); + monitor.beginTask("Mylar Task Planner", tasklist.getRoots().size() * (1+tasklist.getCategories().size())); // for(int i = 0; i < roots.size(); i++) { ITask task = (ITask) roots.get(i); for (ITaskCollector collector : collectors) { collector.consumeTask(task); } - monitor.worked(1); } for (TaskCategory cat : tasklist.getTaskCategories()) { List<? extends ITaskListElement> sub = cat.getChildren(); for (int j = 0; j < sub.size(); j++) { if (sub.get(j) instanceof ITask) { ITask element = (ITask) sub.get(j); for (ITaskCollector collector : collectors) { collector.consumeTask(element); + monitor.worked(1); } } } monitor.worked(1); } for (ITaskCollector collector : collectors) { tasks.addAll(collector.getTasks()); } finished = true; monitor.done(); } public List<ITask> getAllCollectedTasks() { return tasks; } public boolean isFinished() { return finished; } }
false
true
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { List<ITask> roots = tasklist.getRootTasks(); monitor.beginTask("Mylar Task Planner", 1 + tasklist.getCategories().size()); for(int i = 0; i < roots.size(); i++) { ITask task = (ITask) roots.get(i); for (ITaskCollector collector : collectors) { collector.consumeTask(task); } monitor.worked(1); } for (TaskCategory cat : tasklist.getTaskCategories()) { List<? extends ITaskListElement> sub = cat.getChildren(); for (int j = 0; j < sub.size(); j++) { if (sub.get(j) instanceof ITask) { ITask element = (ITask) sub.get(j); for (ITaskCollector collector : collectors) { collector.consumeTask(element); } } } monitor.worked(1); } for (ITaskCollector collector : collectors) { tasks.addAll(collector.getTasks()); } finished = true; monitor.done(); }
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { List<ITask> roots = tasklist.getRootTasks(); monitor.beginTask("Mylar Task Planner", tasklist.getRoots().size() * (1+tasklist.getCategories().size())); // for(int i = 0; i < roots.size(); i++) { ITask task = (ITask) roots.get(i); for (ITaskCollector collector : collectors) { collector.consumeTask(task); } } for (TaskCategory cat : tasklist.getTaskCategories()) { List<? extends ITaskListElement> sub = cat.getChildren(); for (int j = 0; j < sub.size(); j++) { if (sub.get(j) instanceof ITask) { ITask element = (ITask) sub.get(j); for (ITaskCollector collector : collectors) { collector.consumeTask(element); monitor.worked(1); } } } monitor.worked(1); } for (ITaskCollector collector : collectors) { tasks.addAll(collector.getTasks()); } finished = true; monitor.done(); }
diff --git a/src/test/functional/org/xmx0632/deliciousfruit/api/v1/FruitProductApiGetAllTest.java b/src/test/functional/org/xmx0632/deliciousfruit/api/v1/FruitProductApiGetAllTest.java index c212b23..294228f 100644 --- a/src/test/functional/org/xmx0632/deliciousfruit/api/v1/FruitProductApiGetAllTest.java +++ b/src/test/functional/org/xmx0632/deliciousfruit/api/v1/FruitProductApiGetAllTest.java @@ -1,75 +1,79 @@ package org.xmx0632.deliciousfruit.api.v1; import static org.junit.Assert.assertEquals; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.web.client.RestTemplate; import org.xmx0632.deliciousfruit.api.v1.bo.AllFruitProductRequest; import org.xmx0632.deliciousfruit.api.v1.bo.AllFruitProductResponse; import org.xmx0632.deliciousfruit.api.v1.bo.Result; import org.xmx0632.deliciousfruit.api.v1.bo.TerminalType; import org.xmx0632.deliciousfruit.functional.BaseControllerTestCase; public class FruitProductApiGetAllTest extends BaseControllerTestCase { private final RestTemplate restTemplate = new RestTemplate(); private static String url; @BeforeClass public static void initUrl() { url = baseUrl + "/fruitproduct/getAll"; } @Test public void testGetAllSuccess() throws Exception { HttpHeaders requestHeaders = createHttpHeader("user2", "password1"); AllFruitProductRequest allFruitProductRequest = new AllFruitProductRequest(); allFruitProductRequest.setTerminalType(TerminalType.IOS_RETINA.name()); HttpEntity<AllFruitProductRequest> entity = new HttpEntity<AllFruitProductRequest>( allFruitProductRequest, requestHeaders); AllFruitProductResponse response = restTemplate.postForObject(url, entity, AllFruitProductResponse.class); assertEquals(Result.SUCCESS, response.getResult().getValue()); - String expected = "[FruitProductBo [productId=110101, productName=红苹果, spec=好红苹果, place=新疆, min=1, max=10, unit=个, keyword=红, expirationDate=2013-06-30 00:00:00+0800, e6Price=10.00, marketPrice=20.00, picUrl=http://localhost/ios_retina/fruit_product/product_1.jpg, introduction=好吃, description=很红, descriptionPicUrl=http://localhost/ios_retina/fruit_product/product_desc_1.jpg, fruitCategoryId=C000001, promotion=, seconddiscount=0.00], FruitProductBo [productId=110103, productName=烟台苹果, spec=最好的苹果, place=烟台, min=1, max=5, unit=个, keyword=烟台, expirationDate=2015-07-30 00:00:00+0800, e6Price=666.00, marketPrice=888.00, picUrl=http://localhost/ios_retina/fruit_product/product_3.jpg, introduction=无敌好吃, description=最好, descriptionPicUrl=http://localhost/ios_retina/fruit_product/product_desc_3.jpg, fruitCategoryId=C000001, promotion=, seconddiscount=0.00], FruitProductBo [productId=120101, productName=新疆葡萄, spec=好葡萄, place=新疆, min=1, max=5, unit=串, keyword=甜, expirationDate=2014-07-30 00:00:00+0800, e6Price=20.00, marketPrice=30.00, picUrl=http://localhost/ios_retina/fruit_product/product_4.jpg, introduction=很甜, description=不错, descriptionPicUrl=http://localhost/ios_retina/fruit_product/product_desc_4.jpg, fruitCategoryId=S001201, promotion=, seconddiscount=0.00], FruitProductBo [productId=110601, productName=红苹果, spec=箱, place=新疆, min=1, max=10, unit=个, keyword=红, expirationDate=2013-06-30 00:00:00+0800, e6Price=10.00, marketPrice=20.00, picUrl=http://localhost/ios_retina/fruit_product/product_1.jpg, introduction=好吃, description=很红, descriptionPicUrl=http://localhost/ios_retina/fruit_product/product_desc_1.jpg, fruitCategoryId=, promotion=买30个送烟台苹果1个, seconddiscount=0.00]]"; + String expected = "[" + + "FruitProductBo [productId=110101, productName=红苹果, spec=好红苹果, place=新疆, min=1, max=10, unit=个, keyword=红, expirationDate=2013-06-30 00:00:00+0800, e6Price=10.00, marketPrice=20.00, picUrl=http://localhost/ios_retina/fruit_product/product_1.jpg, introduction=好吃, description=很红, descriptionPicUrl=http://localhost/ios_retina/fruit_product/product_desc_1.jpg, fruitCategoryId=C000001, promotion=, seconddiscount=0.00, quantity=0]," + + " FruitProductBo [productId=110103, productName=烟台苹果, spec=最好的苹果, place=烟台, min=1, max=5, unit=个, keyword=烟台, expirationDate=2015-07-30 00:00:00+0800, e6Price=666.00, marketPrice=888.00, picUrl=http://localhost/ios_retina/fruit_product/product_3.jpg, introduction=无敌好吃, description=最好, descriptionPicUrl=http://localhost/ios_retina/fruit_product/product_desc_3.jpg, fruitCategoryId=C000001, promotion=, seconddiscount=0.00, quantity=0]," + + " FruitProductBo [productId=120101, productName=新疆葡萄, spec=好葡萄, place=新疆, min=1, max=5, unit=串, keyword=甜, expirationDate=2014-07-30 00:00:00+0800, e6Price=20.00, marketPrice=30.00, picUrl=http://localhost/ios_retina/fruit_product/product_4.jpg, introduction=很甜, description=不错, descriptionPicUrl=http://localhost/ios_retina/fruit_product/product_desc_4.jpg, fruitCategoryId=S001201, promotion=, seconddiscount=0.00, quantity=0]," + + " FruitProductBo [productId=110601, productName=红苹果, spec=箱, place=新疆, min=1, max=10, unit=个, keyword=红, expirationDate=2013-06-30 00:00:00+0800, e6Price=10.00, marketPrice=20.00, picUrl=http://localhost/ios_retina/fruit_product/product_1.jpg, introduction=好吃, description=很红, descriptionPicUrl=http://localhost/ios_retina/fruit_product/product_desc_1.jpg, fruitCategoryId=, promotion=买30个送烟台苹果1个, seconddiscount=0.00, quantity=0]]"; assertEquals(expected.toString(), response.getFruitProducts() .toString()); formatHttpInfoPrint(HttpMethod.POST, url, requestHeaders, "获得所有水果产品, 成功", jsonMapper.toJson(allFruitProductRequest), jsonMapper.toJson(response)); } @Test public void testFailNotValidTerminalType() throws Exception { HttpHeaders requestHeaders = createHttpHeader("user2", "password"); AllFruitProductRequest allFruitProductRequest = new AllFruitProductRequest(); allFruitProductRequest.setTerminalType("ipad"); HttpEntity<AllFruitProductRequest> entity = new HttpEntity<AllFruitProductRequest>( allFruitProductRequest, requestHeaders); AllFruitProductResponse response = restTemplate.postForObject(url, entity, AllFruitProductResponse.class); assertEquals(Result.FAIL, response.getResult().getValue()); assertEquals(Result.MSG_ERR_NOT_VALID_TERMINAL_TYPE, response .getResult().getMsg()); formatHttpInfoPrint(HttpMethod.POST, url, requestHeaders, "获得所有水果产品, 失败. 原因: 无效的终端类型", jsonMapper.toJson(allFruitProductRequest), jsonMapper.toJson(response)); } }
true
true
public void testGetAllSuccess() throws Exception { HttpHeaders requestHeaders = createHttpHeader("user2", "password1"); AllFruitProductRequest allFruitProductRequest = new AllFruitProductRequest(); allFruitProductRequest.setTerminalType(TerminalType.IOS_RETINA.name()); HttpEntity<AllFruitProductRequest> entity = new HttpEntity<AllFruitProductRequest>( allFruitProductRequest, requestHeaders); AllFruitProductResponse response = restTemplate.postForObject(url, entity, AllFruitProductResponse.class); assertEquals(Result.SUCCESS, response.getResult().getValue()); String expected = "[FruitProductBo [productId=110101, productName=红苹果, spec=好红苹果, place=新疆, min=1, max=10, unit=个, keyword=红, expirationDate=2013-06-30 00:00:00+0800, e6Price=10.00, marketPrice=20.00, picUrl=http://localhost/ios_retina/fruit_product/product_1.jpg, introduction=好吃, description=很红, descriptionPicUrl=http://localhost/ios_retina/fruit_product/product_desc_1.jpg, fruitCategoryId=C000001, promotion=, seconddiscount=0.00], FruitProductBo [productId=110103, productName=烟台苹果, spec=最好的苹果, place=烟台, min=1, max=5, unit=个, keyword=烟台, expirationDate=2015-07-30 00:00:00+0800, e6Price=666.00, marketPrice=888.00, picUrl=http://localhost/ios_retina/fruit_product/product_3.jpg, introduction=无敌好吃, description=最好, descriptionPicUrl=http://localhost/ios_retina/fruit_product/product_desc_3.jpg, fruitCategoryId=C000001, promotion=, seconddiscount=0.00], FruitProductBo [productId=120101, productName=新疆葡萄, spec=好葡萄, place=新疆, min=1, max=5, unit=串, keyword=甜, expirationDate=2014-07-30 00:00:00+0800, e6Price=20.00, marketPrice=30.00, picUrl=http://localhost/ios_retina/fruit_product/product_4.jpg, introduction=很甜, description=不错, descriptionPicUrl=http://localhost/ios_retina/fruit_product/product_desc_4.jpg, fruitCategoryId=S001201, promotion=, seconddiscount=0.00], FruitProductBo [productId=110601, productName=红苹果, spec=箱, place=新疆, min=1, max=10, unit=个, keyword=红, expirationDate=2013-06-30 00:00:00+0800, e6Price=10.00, marketPrice=20.00, picUrl=http://localhost/ios_retina/fruit_product/product_1.jpg, introduction=好吃, description=很红, descriptionPicUrl=http://localhost/ios_retina/fruit_product/product_desc_1.jpg, fruitCategoryId=, promotion=买30个送烟台苹果1个, seconddiscount=0.00]]"; assertEquals(expected.toString(), response.getFruitProducts() .toString()); formatHttpInfoPrint(HttpMethod.POST, url, requestHeaders, "获得所有水果产品, 成功", jsonMapper.toJson(allFruitProductRequest), jsonMapper.toJson(response)); }
public void testGetAllSuccess() throws Exception { HttpHeaders requestHeaders = createHttpHeader("user2", "password1"); AllFruitProductRequest allFruitProductRequest = new AllFruitProductRequest(); allFruitProductRequest.setTerminalType(TerminalType.IOS_RETINA.name()); HttpEntity<AllFruitProductRequest> entity = new HttpEntity<AllFruitProductRequest>( allFruitProductRequest, requestHeaders); AllFruitProductResponse response = restTemplate.postForObject(url, entity, AllFruitProductResponse.class); assertEquals(Result.SUCCESS, response.getResult().getValue()); String expected = "[" + "FruitProductBo [productId=110101, productName=红苹果, spec=好红苹果, place=新疆, min=1, max=10, unit=个, keyword=红, expirationDate=2013-06-30 00:00:00+0800, e6Price=10.00, marketPrice=20.00, picUrl=http://localhost/ios_retina/fruit_product/product_1.jpg, introduction=好吃, description=很红, descriptionPicUrl=http://localhost/ios_retina/fruit_product/product_desc_1.jpg, fruitCategoryId=C000001, promotion=, seconddiscount=0.00, quantity=0]," + " FruitProductBo [productId=110103, productName=烟台苹果, spec=最好的苹果, place=烟台, min=1, max=5, unit=个, keyword=烟台, expirationDate=2015-07-30 00:00:00+0800, e6Price=666.00, marketPrice=888.00, picUrl=http://localhost/ios_retina/fruit_product/product_3.jpg, introduction=无敌好吃, description=最好, descriptionPicUrl=http://localhost/ios_retina/fruit_product/product_desc_3.jpg, fruitCategoryId=C000001, promotion=, seconddiscount=0.00, quantity=0]," + " FruitProductBo [productId=120101, productName=新疆葡萄, spec=好葡萄, place=新疆, min=1, max=5, unit=串, keyword=甜, expirationDate=2014-07-30 00:00:00+0800, e6Price=20.00, marketPrice=30.00, picUrl=http://localhost/ios_retina/fruit_product/product_4.jpg, introduction=很甜, description=不错, descriptionPicUrl=http://localhost/ios_retina/fruit_product/product_desc_4.jpg, fruitCategoryId=S001201, promotion=, seconddiscount=0.00, quantity=0]," + " FruitProductBo [productId=110601, productName=红苹果, spec=箱, place=新疆, min=1, max=10, unit=个, keyword=红, expirationDate=2013-06-30 00:00:00+0800, e6Price=10.00, marketPrice=20.00, picUrl=http://localhost/ios_retina/fruit_product/product_1.jpg, introduction=好吃, description=很红, descriptionPicUrl=http://localhost/ios_retina/fruit_product/product_desc_1.jpg, fruitCategoryId=, promotion=买30个送烟台苹果1个, seconddiscount=0.00, quantity=0]]"; assertEquals(expected.toString(), response.getFruitProducts() .toString()); formatHttpInfoPrint(HttpMethod.POST, url, requestHeaders, "获得所有水果产品, 成功", jsonMapper.toJson(allFruitProductRequest), jsonMapper.toJson(response)); }
diff --git a/src/net/rptools/maptool/client/ui/htmlframe/HTMLPaneFormView.java b/src/net/rptools/maptool/client/ui/htmlframe/HTMLPaneFormView.java index 84690aa8..859ea5ff 100644 --- a/src/net/rptools/maptool/client/ui/htmlframe/HTMLPaneFormView.java +++ b/src/net/rptools/maptool/client/ui/htmlframe/HTMLPaneFormView.java @@ -1,226 +1,227 @@ package net.rptools.maptool.client.ui.htmlframe; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import java.awt.*; import javax.swing.ComboBoxModel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.Element; import javax.swing.text.PlainDocument; import javax.swing.text.StyleConstants; import javax.swing.text.html.FormView; import javax.swing.text.html.HTML; import net.sf.json.JSONObject; import org.apache.log4j.Logger; public class HTMLPaneFormView extends FormView { private static final Logger LOGGER = Logger.getLogger(HTMLPaneFormView.class); private HTMLPane htmlPane; /** * Creates a new HTMLPaneFormView. * @param elem The element this is a view for. * @param pane The HTMLPane this element resides on. */ public HTMLPaneFormView(Element elem, HTMLPane pane) { super(elem); htmlPane = pane; } @Override protected Component createComponent() { Component c = null; AttributeSet attr = getElement().getAttributes(); HTML.Tag t = (HTML.Tag) attr.getAttribute(StyleConstants.NameAttribute); if (t == HTML.Tag.TEXTAREA) { JScrollPane sp = (JScrollPane)super.createComponent(); JTextArea area = (JTextArea)sp.getViewport().getView(); area.setLineWrap(true); area.setWrapStyleWord(true); c = new JScrollPane( area, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED ); } else { c = super.createComponent(); } return c; } @Override protected void submitData(String data) { // Find the form Element formElement = null; for (Element e = getElement(); e != null; e = e.getParentElement()) { if (e.getAttributes().getAttribute(StyleConstants.NameAttribute) == HTML.Tag.FORM) { formElement = e; break; } } if (formElement != null) { AttributeSet att = formElement.getAttributes(); String action = att.getAttribute(HTML.Attribute.ACTION).toString(); String method; if (att.getAttribute(HTML.Attribute.METHOD) != null) { method = att.getAttribute(HTML.Attribute.METHOD).toString(); } else { method = "get"; } action = action == null ? "" : action; method = method == null ? "" : method.toLowerCase(); if (method.equals("json")) { JSONObject jobj = new JSONObject(); String[] values = data.split("&"); for (String v : values) { String[] dataStr = v.split("="); if (dataStr.length == 1) { try { jobj.put(URLDecoder.decode(dataStr[0], "utf8"), ""); } catch (UnsupportedEncodingException e) { // Use the raw data. jobj.put(dataStr[0], ""); } } else if (dataStr.length > 2) { jobj.put(dataStr[0], dataStr[1]); } else { try { jobj.put(URLDecoder.decode(dataStr[0], "utf8"), URLDecoder.decode(dataStr[1], "utf8")); } catch (UnsupportedEncodingException e) { // Use the raw data. jobj.put(dataStr[0], dataStr[1]); } } } try { data = URLEncoder.encode(jobj.toString(), "utf8"); } catch (UnsupportedEncodingException e) { // Use the raw data. data = jobj.toString(); } } htmlPane.doSubmit(method, action, data); } } @Override protected void imageSubmit(String data) { Element formElement = null; for (Element e = getElement(); e != null; e = e.getParentElement()) { if (e.getAttributes().getAttribute(StyleConstants.NameAttribute) == HTML.Tag.FORM) { formElement = e; break; } } if (formElement != null) { String imageMapName = data.replaceFirst("\\..*", ""); Map<String, String> fdata = new HashMap<String, String>(); fdata.putAll(getDataFrom(formElement, imageMapName)); StringBuilder sb = new StringBuilder(); for (String s : fdata.keySet()) { if (sb.length() > 0) { sb.append("&"); } sb.append(s).append("=").append(fdata.get(s)); } sb.append("&").append(data); submitData(sb.toString()); } else { submitData(data); } } private Map<String, String> getDataFrom(Element ele, String selectedImageMap) { Map<String, String> vals = new HashMap<String, String>(); for (int i = 0; i < ele.getElementCount(); i++) { Element e = ele.getElement(i); AttributeSet as = e.getAttributes(); if (as.getAttribute(StyleConstants.ModelAttribute) != null || as.getAttribute(HTML.Attribute.TYPE) != null) { String type = (String)as.getAttribute(HTML.Attribute.TYPE); String name = (String)as.getAttribute(HTML.Attribute.NAME); Object model = as.getAttribute(StyleConstants.ModelAttribute); if (type == null && model instanceof PlainDocument) {// Text area has no HTML.Attribute.TYPE PlainDocument pd = (PlainDocument)model; try { vals.put(name, encode(pd.getText(0, pd.getLength()))); } catch (BadLocationException e1) { LOGGER.error(e1.getStackTrace()); } } else if (type == null && model instanceof ComboBoxModel) { vals.put(name, ((ComboBoxModel)model).getSelectedItem().toString()); } else if ("text".equals(type)) { PlainDocument pd = (PlainDocument)model; try { vals.put(name, encode(pd.getText(0, pd.getLength()))); } catch (BadLocationException e1) { LOGGER.error(e1.getStackTrace()); } } else if ("submit".equals(type)) { // Ignore } else if ("image".equals(type)) { if (name != null && name.equals(selectedImageMap)) { - vals.put(name + ".value" , encode((String)as.getAttribute(HTML.Attribute.VALUE))); + String val = (String)as.getAttribute(HTML.Attribute.VALUE); + vals.put(name + ".value" , encode(val == null ? "" : val)); } } else if ("radio".equals(type)) { if (as.getAttribute(HTML.Attribute.CHECKED) != null) { vals.put(name, encode(encode((String)as.getAttribute(HTML.Attribute.VALUE)))); } } else if ("checkbox".equals(type)) { if (as.getAttribute(HTML.Attribute.CHECKED) != null) { vals.put(name, encode(encode((String)as.getAttribute(HTML.Attribute.VALUE)))); } } else if ("password".equals(type)) { PlainDocument pd = (PlainDocument)model; try { vals.put(name, encode(pd.getText(0, pd.getLength()))); } catch (BadLocationException e1) { LOGGER.error(e1.getStackTrace()); } } else if ("hidden".equals(type)) { vals.put(name, encode(encode((String)as.getAttribute(HTML.Attribute.VALUE)))); } } vals.putAll(getDataFrom(e, selectedImageMap)); } return vals; } private String encode(String str) { try { return URLEncoder.encode(str, "utf-8"); } catch (UnsupportedEncodingException e) { LOGGER.error(e.getStackTrace()); return str; } } }
true
true
private Map<String, String> getDataFrom(Element ele, String selectedImageMap) { Map<String, String> vals = new HashMap<String, String>(); for (int i = 0; i < ele.getElementCount(); i++) { Element e = ele.getElement(i); AttributeSet as = e.getAttributes(); if (as.getAttribute(StyleConstants.ModelAttribute) != null || as.getAttribute(HTML.Attribute.TYPE) != null) { String type = (String)as.getAttribute(HTML.Attribute.TYPE); String name = (String)as.getAttribute(HTML.Attribute.NAME); Object model = as.getAttribute(StyleConstants.ModelAttribute); if (type == null && model instanceof PlainDocument) {// Text area has no HTML.Attribute.TYPE PlainDocument pd = (PlainDocument)model; try { vals.put(name, encode(pd.getText(0, pd.getLength()))); } catch (BadLocationException e1) { LOGGER.error(e1.getStackTrace()); } } else if (type == null && model instanceof ComboBoxModel) { vals.put(name, ((ComboBoxModel)model).getSelectedItem().toString()); } else if ("text".equals(type)) { PlainDocument pd = (PlainDocument)model; try { vals.put(name, encode(pd.getText(0, pd.getLength()))); } catch (BadLocationException e1) { LOGGER.error(e1.getStackTrace()); } } else if ("submit".equals(type)) { // Ignore } else if ("image".equals(type)) { if (name != null && name.equals(selectedImageMap)) { vals.put(name + ".value" , encode((String)as.getAttribute(HTML.Attribute.VALUE))); } } else if ("radio".equals(type)) { if (as.getAttribute(HTML.Attribute.CHECKED) != null) { vals.put(name, encode(encode((String)as.getAttribute(HTML.Attribute.VALUE)))); } } else if ("checkbox".equals(type)) { if (as.getAttribute(HTML.Attribute.CHECKED) != null) { vals.put(name, encode(encode((String)as.getAttribute(HTML.Attribute.VALUE)))); } } else if ("password".equals(type)) { PlainDocument pd = (PlainDocument)model; try { vals.put(name, encode(pd.getText(0, pd.getLength()))); } catch (BadLocationException e1) { LOGGER.error(e1.getStackTrace()); } } else if ("hidden".equals(type)) { vals.put(name, encode(encode((String)as.getAttribute(HTML.Attribute.VALUE)))); } } vals.putAll(getDataFrom(e, selectedImageMap)); } return vals; }
private Map<String, String> getDataFrom(Element ele, String selectedImageMap) { Map<String, String> vals = new HashMap<String, String>(); for (int i = 0; i < ele.getElementCount(); i++) { Element e = ele.getElement(i); AttributeSet as = e.getAttributes(); if (as.getAttribute(StyleConstants.ModelAttribute) != null || as.getAttribute(HTML.Attribute.TYPE) != null) { String type = (String)as.getAttribute(HTML.Attribute.TYPE); String name = (String)as.getAttribute(HTML.Attribute.NAME); Object model = as.getAttribute(StyleConstants.ModelAttribute); if (type == null && model instanceof PlainDocument) {// Text area has no HTML.Attribute.TYPE PlainDocument pd = (PlainDocument)model; try { vals.put(name, encode(pd.getText(0, pd.getLength()))); } catch (BadLocationException e1) { LOGGER.error(e1.getStackTrace()); } } else if (type == null && model instanceof ComboBoxModel) { vals.put(name, ((ComboBoxModel)model).getSelectedItem().toString()); } else if ("text".equals(type)) { PlainDocument pd = (PlainDocument)model; try { vals.put(name, encode(pd.getText(0, pd.getLength()))); } catch (BadLocationException e1) { LOGGER.error(e1.getStackTrace()); } } else if ("submit".equals(type)) { // Ignore } else if ("image".equals(type)) { if (name != null && name.equals(selectedImageMap)) { String val = (String)as.getAttribute(HTML.Attribute.VALUE); vals.put(name + ".value" , encode(val == null ? "" : val)); } } else if ("radio".equals(type)) { if (as.getAttribute(HTML.Attribute.CHECKED) != null) { vals.put(name, encode(encode((String)as.getAttribute(HTML.Attribute.VALUE)))); } } else if ("checkbox".equals(type)) { if (as.getAttribute(HTML.Attribute.CHECKED) != null) { vals.put(name, encode(encode((String)as.getAttribute(HTML.Attribute.VALUE)))); } } else if ("password".equals(type)) { PlainDocument pd = (PlainDocument)model; try { vals.put(name, encode(pd.getText(0, pd.getLength()))); } catch (BadLocationException e1) { LOGGER.error(e1.getStackTrace()); } } else if ("hidden".equals(type)) { vals.put(name, encode(encode((String)as.getAttribute(HTML.Attribute.VALUE)))); } } vals.putAll(getDataFrom(e, selectedImageMap)); } return vals; }
diff --git a/src/services/DevService.java b/src/services/DevService.java index f9689348..9b0eae3e 100644 --- a/src/services/DevService.java +++ b/src/services/DevService.java @@ -1,316 +1,316 @@ /******************************************************************************* * Copyright (c) 2013 <Project SWG> * * This File is part of NGECore2. * * 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/>. * * Using NGEngine to work with NGECore2 is making a combined work based on NGEngine. * Therefore all terms and conditions of the GNU Lesser General Public License cover the combination. ******************************************************************************/ package services; import java.nio.ByteOrder; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Vector; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import protocol.swg.ExpertiseRequestMessage; import resources.common.Console; import resources.common.FileUtilities; import resources.common.Opcodes; import resources.common.SpawnPoint; import resources.objects.building.BuildingObject; import resources.objects.creature.CreatureObject; import resources.objects.player.PlayerObject; import resources.objects.tangible.TangibleObject; import services.sui.SUIWindow; import services.sui.SUIService.ListBoxType; import services.sui.SUIWindow.SUICallback; import services.sui.SUIWindow.Trigger; import main.NGECore; import engine.clientdata.ClientFileManager; import engine.clientdata.visitors.DatatableVisitor; import engine.clients.Client; import engine.resources.objects.SWGObject; import engine.resources.scene.Planet; import engine.resources.scene.Point3D; import engine.resources.service.INetworkDispatch; import engine.resources.service.INetworkRemoteEvent; @SuppressWarnings("unused") public class DevService implements INetworkDispatch { private NGECore core; public DevService(NGECore core) { this.core = core; } public void sendCharacterBuilderSUI(CreatureObject creature, int childMenu) { Map<Long, String> suiOptions = new HashMap<Long, String>(); switch(childMenu) { case 0: // Root suiOptions.put((long) 1, "Character"); suiOptions.put((long) 2, "Items"); break; case 1: // Character suiOptions.put((long) 10, "Set combat level to 90"); suiOptions.put((long) 11, "Give 100,000 credits"); suiOptions.put((long) 12, "Reset expertise"); break; case 2: // Items suiOptions.put((long) 20, "(Light) Jedi Robe"); suiOptions.put((long) 21, "(Dark) Jedi Robe"); suiOptions.put((long) 22, "Composite Armor"); suiOptions.put((long) 23, "Weapons"); suiOptions.put((long) 24, "Misc Items"); break; case 3: // [Items] Weapons suiOptions.put((long) 30, "Jedi Weapons"); suiOptions.put((long) 31, "Melee Weapons"); suiOptions.put((long) 32, "Ranged Weapons"); break; case 4: // [Items] Misc Items suiOptions.put((long) 40, "Unity Ring"); break; } final SUIWindow window = core.suiService.createListBox(ListBoxType.LIST_BOX_OK_CANCEL, "Character Builder Terminal", "Select the desired option and click OK.", suiOptions, creature, null, 10); Vector<String> returnList = new Vector<String>(); returnList.add("List.lstList:SelectedRow"); window.addHandler(0, "", Trigger.TRIGGER_OK, returnList, new SUICallback() { public void process(SWGObject owner, int eventType, Vector<String> returnList) { int index = Integer.parseInt(returnList.get(0)); int childIndex = (int) window.getObjectIdByIndex(index); CreatureObject player = (CreatureObject) owner; SWGObject inventory = player.getSlottedObject("inventory"); Planet planet = player.getPlanet(); switch(childIndex) { // Root case 1: // Character sendCharacterBuilderSUI(player, 1); return; case 2: // Items sendCharacterBuilderSUI(player, 2); return; // Character case 10: // Set combat level to 90 core.playerService.grantLevel(player, 90); // Commented out until fixed //core.playerService.giveExperience(player, 999999999); return; case 11: // Give 100,000 credits player.setCashCredits(player.getCashCredits() + 100000); return; case 12: // Reset expertise // Seefo->Light: I commented out the below line because it gave us an error and didn't properly remove the skill, could you try the method SWGList.reverseGet that I added? //player.getSkills().get().stream().filter(s -> s.contains("expertise")).forEach(s -> core.skillService.removeSkill(creature, s)); // Using this for now for(int i = creature.getSkills().size() - 1; i >= 0; i-- ) { String skill = creature.getSkills().get(i); if(skill.contains("expertise")) core.skillService.removeSkill(player, skill); } return; // Items case 20: // (Light) Jedi Robe inventory.add(core.objectService.createObject("object/tangible/wearables/robe/shared_robe_jedi_light_s03.iff", planet)); return; case 21: // (Dark) Jedi Robe inventory.add(core.objectService.createObject("object/tangible/wearables/robe/shared_robe_jedi_dark_s03.iff", planet)); return; case 22: // Composite Armor SWGObject bicep_r = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_bicep_r.iff", planet); bicep_r.setIntAttribute("cat_armor_standard_protection.armor_eff_kinetic", 7000); bicep_r.setIntAttribute("cat_armor_standard_protection.armor_eff_energy", 5000); bicep_r.setIntAttribute("cat_armor_special_protection.special_protection_type_heat", 6000); bicep_r.setIntAttribute("cat_armor_special_protection.special_protection_type_cold", 6000); bicep_r.setIntAttribute("cat_armor_special_protection.special_protection_type_acid", 6000); bicep_r.setIntAttribute("cat_armor_special_protection.special_protection_type_electricity", 6000); SWGObject bicep_l = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_bicep_l.iff", planet); bicep_l.setIntAttribute("cat_armor_standard_protection.armor_eff_kinetic", 7000); bicep_l.setIntAttribute("cat_armor_standard_protection.armor_eff_energy", 5000); bicep_l.setIntAttribute("cat_armor_special_protection.special_protection_type_heat", 6000); bicep_l.setIntAttribute("cat_armor_special_protection.special_protection_type_cold", 6000); bicep_l.setIntAttribute("cat_armor_special_protection.special_protection_type_acid", 6000); bicep_l.setIntAttribute("cat_armor_special_protection.special_protection_type_electricity", 6000); SWGObject bracer_r = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_bracer_r.iff", planet); bracer_r.setIntAttribute("cat_armor_standard_protection.armor_eff_kinetic", 7000); bracer_r.setIntAttribute("cat_armor_standard_protection.armor_eff_energy", 5000); bracer_r.setIntAttribute("cat_armor_special_protection.special_protection_type_heat", 6000); bracer_r.setIntAttribute("cat_armor_special_protection.special_protection_type_cold", 6000); bracer_r.setIntAttribute("cat_armor_special_protection.special_protection_type_acid", 6000); bracer_r.setIntAttribute("cat_armor_special_protection.special_protection_type_electricity", 6000); SWGObject bracer_l = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_bracer_l.iff", planet); bracer_l.setIntAttribute("cat_armor_standard_protection.armor_eff_kinetic", 7000); bracer_l.setIntAttribute("cat_armor_standard_protection.armor_eff_energy", 5000); bracer_l.setIntAttribute("cat_armor_special_protection.special_protection_type_heat", 6000); bracer_l.setIntAttribute("cat_armor_special_protection.special_protection_type_cold", 6000); bracer_l.setIntAttribute("cat_armor_special_protection.special_protection_type_acid", 6000); bracer_l.setIntAttribute("cat_armor_special_protection.special_protection_type_electricity", 6000); SWGObject leggings = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_leggings.iff", planet); leggings.setIntAttribute("cat_armor_standard_protection.armor_eff_kinetic", 7000); leggings.setIntAttribute("cat_armor_standard_protection.armor_eff_energy", 5000); leggings.setIntAttribute("cat_armor_special_protection.special_protection_type_heat", 6000); leggings.setIntAttribute("cat_armor_special_protection.special_protection_type_cold", 6000); leggings.setIntAttribute("cat_armor_special_protection.special_protection_type_acid", 6000); leggings.setIntAttribute("cat_armor_special_protection.special_protection_type_electricity", 6000); SWGObject helmet = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_helmet.iff", planet); helmet.setIntAttribute("cat_armor_standard_protection.armor_eff_kinetic", 7000); helmet.setIntAttribute("cat_armor_standard_protection.armor_eff_energy", 5000); helmet.setIntAttribute("cat_armor_special_protection.special_protection_type_heat", 6000); helmet.setIntAttribute("cat_armor_special_protection.special_protection_type_cold", 6000); helmet.setIntAttribute("cat_armor_special_protection.special_protection_type_acid", 6000); helmet.setIntAttribute("cat_armor_special_protection.special_protection_type_electricity", 6000); SWGObject chest = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_chest_plate.iff", planet); chest.setIntAttribute("cat_armor_standard_protection.armor_eff_kinetic", 7000); chest.setIntAttribute("cat_armor_standard_protection.armor_eff_energy", 5000); chest.setIntAttribute("cat_armor_special_protection.special_protection_type_heat", 6000); chest.setIntAttribute("cat_armor_special_protection.special_protection_type_cold", 6000); chest.setIntAttribute("cat_armor_special_protection.special_protection_type_acid", 6000); chest.setIntAttribute("cat_armor_special_protection.special_protection_type_electricity", 6000); SWGObject boots = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_boots.iff", planet); SWGObject gloves = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_gloves.iff", planet); inventory.add(bicep_r); inventory.add(bicep_l); inventory.add(bracer_r); inventory.add(bracer_l); inventory.add(leggings); inventory.add(helmet); inventory.add(chest); inventory.add(boots); inventory.add(gloves); return; case 23: // Weapons sendCharacterBuilderSUI(player, 3); return; case 24: // Misc Items sendCharacterBuilderSUI(player, 4); return; // [Items] Weapons case 30: // Jedi Weapons TangibleObject lightsaber1 = (TangibleObject) core.objectService.createObject("object/weapon/melee/sword/crafted_saber/shared_sword_lightsaber_one_handed_gen5.iff", planet); lightsaber1.setIntAttribute("required_combat_level", 90); lightsaber1.setFloatAttribute("cat_wpn_damage.wpn_attack_speed", 1); lightsaber1.setStringAttribute("class_required", "Jedi"); lightsaber1.setStringAttribute("cat_wpn_damage.wpn_damage_type", "Energy"); lightsaber1.setStringAttribute("cat_wpn_damage.damage", "689-1379"); TangibleObject lightsaber2 = (TangibleObject) core.objectService.createObject("object/weapon/melee/2h_sword/crafted_saber/shared_sword_lightsaber_two_handed_gen5.iff", planet); lightsaber2.setIntAttribute("required_combat_level", 90); lightsaber2.setFloatAttribute("cat_wpn_damage.wpn_attack_speed", 1); lightsaber2.setStringAttribute("class_required", "Jedi"); lightsaber2.setStringAttribute("cat_wpn_damage.wpn_damage_type", "Energy"); lightsaber2.setStringAttribute("cat_wpn_damage.damage", "689-1379"); TangibleObject lightsaber3 = (TangibleObject) core.objectService.createObject("object/weapon/melee/polearm/crafted_saber/shared_sword_lightsaber_polearm_gen5.iff", planet); lightsaber3.setIntAttribute("required_combat_level", 90); lightsaber3.setFloatAttribute("cat_wpn_damage.wpn_attack_speed", 1); lightsaber3.setStringAttribute("class_required", "Jedi"); lightsaber3.setStringAttribute("cat_wpn_damage.wpn_damage_type", "Energy"); lightsaber3.setStringAttribute("cat_wpn_damage.damage", "689-1379"); Random random = new Random(); lightsaber1.setCustomizationVariable("/private/index_color_blade", (byte) random.nextInt(47)); lightsaber2.setCustomizationVariable("/private/index_color_blade", (byte) random.nextInt(47)); lightsaber3.setCustomizationVariable("/private/index_color_blade", (byte) random.nextInt(47)); inventory.add(lightsaber1); inventory.add(lightsaber2); inventory.add(lightsaber3); return; case 31: // Melee Weapons SWGObject sword1 = core.objectService.createObject("object/weapon/melee/sword/shared_sword_01.iff", planet); sword1.setIntAttribute("required_combat_level", 90); sword1.setFloatAttribute("cat_wpn_damage.wpn_attack_speed", 1); sword1.setStringAttribute("class_required", "None"); sword1.setStringAttribute("cat_wpn_damage.wpn_damage_type", "Energy"); sword1.setStringAttribute("cat_wpn_damage.damage", "1100-1200"); inventory.add(sword1); return; case 32: // Ranged Weapons SWGObject rifle1 = core.objectService.createObject("object/weapon/ranged/rifle/shared_rifle_e11.iff", planet); rifle1.setIntAttribute("required_combat_level", 90); - rifle1.setFloatAttribute("cat_wpn_damage.wpn_attack_speed", 1); + rifle1.setFloatAttribute("cat_wpn_damage.wpn_attack_speed", 0.8); rifle1.setStringAttribute("class_required", "None"); rifle1.setStringAttribute("cat_wpn_damage.wpn_damage_type", "Energy"); rifle1.setStringAttribute("cat_wpn_damage.damage", "800-1250"); inventory.add(rifle1); SWGObject pistol = core.objectService.createObject("object/weapon/ranged/pistol/shared_pistol_cdef.iff", planet); pistol.setIntAttribute("required_combat_level", 90); - pistol.setFloatAttribute("cat_wpn_damage.wpn_attack_speed", 1); + pistol.setFloatAttribute("cat_wpn_damage.wpn_attack_speed", 0.4); pistol.setStringAttribute("class_required", "None"); pistol.setStringAttribute("cat_wpn_damage.wpn_damage_type", "Energy"); pistol.setStringAttribute("cat_wpn_damage.damage", "400-559"); inventory.add(pistol); return; case 40: TangibleObject ring = (TangibleObject) core.objectService.createObject("object/tangible/wearables/ring/shared_ring_s01.iff", planet); ring.setCustomName("Unity Ring"); inventory.add(ring); } } }); core.suiService.openSUIWindow(window); } @Override public void insertOpcodes(Map<Integer, INetworkRemoteEvent> swgOpcodes, Map<Integer, INetworkRemoteEvent> objControllerOpcodes) { } @Override public void shutdown() { } }
false
true
public void sendCharacterBuilderSUI(CreatureObject creature, int childMenu) { Map<Long, String> suiOptions = new HashMap<Long, String>(); switch(childMenu) { case 0: // Root suiOptions.put((long) 1, "Character"); suiOptions.put((long) 2, "Items"); break; case 1: // Character suiOptions.put((long) 10, "Set combat level to 90"); suiOptions.put((long) 11, "Give 100,000 credits"); suiOptions.put((long) 12, "Reset expertise"); break; case 2: // Items suiOptions.put((long) 20, "(Light) Jedi Robe"); suiOptions.put((long) 21, "(Dark) Jedi Robe"); suiOptions.put((long) 22, "Composite Armor"); suiOptions.put((long) 23, "Weapons"); suiOptions.put((long) 24, "Misc Items"); break; case 3: // [Items] Weapons suiOptions.put((long) 30, "Jedi Weapons"); suiOptions.put((long) 31, "Melee Weapons"); suiOptions.put((long) 32, "Ranged Weapons"); break; case 4: // [Items] Misc Items suiOptions.put((long) 40, "Unity Ring"); break; } final SUIWindow window = core.suiService.createListBox(ListBoxType.LIST_BOX_OK_CANCEL, "Character Builder Terminal", "Select the desired option and click OK.", suiOptions, creature, null, 10); Vector<String> returnList = new Vector<String>(); returnList.add("List.lstList:SelectedRow"); window.addHandler(0, "", Trigger.TRIGGER_OK, returnList, new SUICallback() { public void process(SWGObject owner, int eventType, Vector<String> returnList) { int index = Integer.parseInt(returnList.get(0)); int childIndex = (int) window.getObjectIdByIndex(index); CreatureObject player = (CreatureObject) owner; SWGObject inventory = player.getSlottedObject("inventory"); Planet planet = player.getPlanet(); switch(childIndex) { // Root case 1: // Character sendCharacterBuilderSUI(player, 1); return; case 2: // Items sendCharacterBuilderSUI(player, 2); return; // Character case 10: // Set combat level to 90 core.playerService.grantLevel(player, 90); // Commented out until fixed //core.playerService.giveExperience(player, 999999999); return; case 11: // Give 100,000 credits player.setCashCredits(player.getCashCredits() + 100000); return; case 12: // Reset expertise // Seefo->Light: I commented out the below line because it gave us an error and didn't properly remove the skill, could you try the method SWGList.reverseGet that I added? //player.getSkills().get().stream().filter(s -> s.contains("expertise")).forEach(s -> core.skillService.removeSkill(creature, s)); // Using this for now for(int i = creature.getSkills().size() - 1; i >= 0; i-- ) { String skill = creature.getSkills().get(i); if(skill.contains("expertise")) core.skillService.removeSkill(player, skill); } return; // Items case 20: // (Light) Jedi Robe inventory.add(core.objectService.createObject("object/tangible/wearables/robe/shared_robe_jedi_light_s03.iff", planet)); return; case 21: // (Dark) Jedi Robe inventory.add(core.objectService.createObject("object/tangible/wearables/robe/shared_robe_jedi_dark_s03.iff", planet)); return; case 22: // Composite Armor SWGObject bicep_r = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_bicep_r.iff", planet); bicep_r.setIntAttribute("cat_armor_standard_protection.armor_eff_kinetic", 7000); bicep_r.setIntAttribute("cat_armor_standard_protection.armor_eff_energy", 5000); bicep_r.setIntAttribute("cat_armor_special_protection.special_protection_type_heat", 6000); bicep_r.setIntAttribute("cat_armor_special_protection.special_protection_type_cold", 6000); bicep_r.setIntAttribute("cat_armor_special_protection.special_protection_type_acid", 6000); bicep_r.setIntAttribute("cat_armor_special_protection.special_protection_type_electricity", 6000); SWGObject bicep_l = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_bicep_l.iff", planet); bicep_l.setIntAttribute("cat_armor_standard_protection.armor_eff_kinetic", 7000); bicep_l.setIntAttribute("cat_armor_standard_protection.armor_eff_energy", 5000); bicep_l.setIntAttribute("cat_armor_special_protection.special_protection_type_heat", 6000); bicep_l.setIntAttribute("cat_armor_special_protection.special_protection_type_cold", 6000); bicep_l.setIntAttribute("cat_armor_special_protection.special_protection_type_acid", 6000); bicep_l.setIntAttribute("cat_armor_special_protection.special_protection_type_electricity", 6000); SWGObject bracer_r = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_bracer_r.iff", planet); bracer_r.setIntAttribute("cat_armor_standard_protection.armor_eff_kinetic", 7000); bracer_r.setIntAttribute("cat_armor_standard_protection.armor_eff_energy", 5000); bracer_r.setIntAttribute("cat_armor_special_protection.special_protection_type_heat", 6000); bracer_r.setIntAttribute("cat_armor_special_protection.special_protection_type_cold", 6000); bracer_r.setIntAttribute("cat_armor_special_protection.special_protection_type_acid", 6000); bracer_r.setIntAttribute("cat_armor_special_protection.special_protection_type_electricity", 6000); SWGObject bracer_l = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_bracer_l.iff", planet); bracer_l.setIntAttribute("cat_armor_standard_protection.armor_eff_kinetic", 7000); bracer_l.setIntAttribute("cat_armor_standard_protection.armor_eff_energy", 5000); bracer_l.setIntAttribute("cat_armor_special_protection.special_protection_type_heat", 6000); bracer_l.setIntAttribute("cat_armor_special_protection.special_protection_type_cold", 6000); bracer_l.setIntAttribute("cat_armor_special_protection.special_protection_type_acid", 6000); bracer_l.setIntAttribute("cat_armor_special_protection.special_protection_type_electricity", 6000); SWGObject leggings = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_leggings.iff", planet); leggings.setIntAttribute("cat_armor_standard_protection.armor_eff_kinetic", 7000); leggings.setIntAttribute("cat_armor_standard_protection.armor_eff_energy", 5000); leggings.setIntAttribute("cat_armor_special_protection.special_protection_type_heat", 6000); leggings.setIntAttribute("cat_armor_special_protection.special_protection_type_cold", 6000); leggings.setIntAttribute("cat_armor_special_protection.special_protection_type_acid", 6000); leggings.setIntAttribute("cat_armor_special_protection.special_protection_type_electricity", 6000); SWGObject helmet = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_helmet.iff", planet); helmet.setIntAttribute("cat_armor_standard_protection.armor_eff_kinetic", 7000); helmet.setIntAttribute("cat_armor_standard_protection.armor_eff_energy", 5000); helmet.setIntAttribute("cat_armor_special_protection.special_protection_type_heat", 6000); helmet.setIntAttribute("cat_armor_special_protection.special_protection_type_cold", 6000); helmet.setIntAttribute("cat_armor_special_protection.special_protection_type_acid", 6000); helmet.setIntAttribute("cat_armor_special_protection.special_protection_type_electricity", 6000); SWGObject chest = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_chest_plate.iff", planet); chest.setIntAttribute("cat_armor_standard_protection.armor_eff_kinetic", 7000); chest.setIntAttribute("cat_armor_standard_protection.armor_eff_energy", 5000); chest.setIntAttribute("cat_armor_special_protection.special_protection_type_heat", 6000); chest.setIntAttribute("cat_armor_special_protection.special_protection_type_cold", 6000); chest.setIntAttribute("cat_armor_special_protection.special_protection_type_acid", 6000); chest.setIntAttribute("cat_armor_special_protection.special_protection_type_electricity", 6000); SWGObject boots = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_boots.iff", planet); SWGObject gloves = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_gloves.iff", planet); inventory.add(bicep_r); inventory.add(bicep_l); inventory.add(bracer_r); inventory.add(bracer_l); inventory.add(leggings); inventory.add(helmet); inventory.add(chest); inventory.add(boots); inventory.add(gloves); return; case 23: // Weapons sendCharacterBuilderSUI(player, 3); return; case 24: // Misc Items sendCharacterBuilderSUI(player, 4); return; // [Items] Weapons case 30: // Jedi Weapons TangibleObject lightsaber1 = (TangibleObject) core.objectService.createObject("object/weapon/melee/sword/crafted_saber/shared_sword_lightsaber_one_handed_gen5.iff", planet); lightsaber1.setIntAttribute("required_combat_level", 90); lightsaber1.setFloatAttribute("cat_wpn_damage.wpn_attack_speed", 1); lightsaber1.setStringAttribute("class_required", "Jedi"); lightsaber1.setStringAttribute("cat_wpn_damage.wpn_damage_type", "Energy"); lightsaber1.setStringAttribute("cat_wpn_damage.damage", "689-1379"); TangibleObject lightsaber2 = (TangibleObject) core.objectService.createObject("object/weapon/melee/2h_sword/crafted_saber/shared_sword_lightsaber_two_handed_gen5.iff", planet); lightsaber2.setIntAttribute("required_combat_level", 90); lightsaber2.setFloatAttribute("cat_wpn_damage.wpn_attack_speed", 1); lightsaber2.setStringAttribute("class_required", "Jedi"); lightsaber2.setStringAttribute("cat_wpn_damage.wpn_damage_type", "Energy"); lightsaber2.setStringAttribute("cat_wpn_damage.damage", "689-1379"); TangibleObject lightsaber3 = (TangibleObject) core.objectService.createObject("object/weapon/melee/polearm/crafted_saber/shared_sword_lightsaber_polearm_gen5.iff", planet); lightsaber3.setIntAttribute("required_combat_level", 90); lightsaber3.setFloatAttribute("cat_wpn_damage.wpn_attack_speed", 1); lightsaber3.setStringAttribute("class_required", "Jedi"); lightsaber3.setStringAttribute("cat_wpn_damage.wpn_damage_type", "Energy"); lightsaber3.setStringAttribute("cat_wpn_damage.damage", "689-1379"); Random random = new Random(); lightsaber1.setCustomizationVariable("/private/index_color_blade", (byte) random.nextInt(47)); lightsaber2.setCustomizationVariable("/private/index_color_blade", (byte) random.nextInt(47)); lightsaber3.setCustomizationVariable("/private/index_color_blade", (byte) random.nextInt(47)); inventory.add(lightsaber1); inventory.add(lightsaber2); inventory.add(lightsaber3); return; case 31: // Melee Weapons SWGObject sword1 = core.objectService.createObject("object/weapon/melee/sword/shared_sword_01.iff", planet); sword1.setIntAttribute("required_combat_level", 90); sword1.setFloatAttribute("cat_wpn_damage.wpn_attack_speed", 1); sword1.setStringAttribute("class_required", "None"); sword1.setStringAttribute("cat_wpn_damage.wpn_damage_type", "Energy"); sword1.setStringAttribute("cat_wpn_damage.damage", "1100-1200"); inventory.add(sword1); return; case 32: // Ranged Weapons SWGObject rifle1 = core.objectService.createObject("object/weapon/ranged/rifle/shared_rifle_e11.iff", planet); rifle1.setIntAttribute("required_combat_level", 90); rifle1.setFloatAttribute("cat_wpn_damage.wpn_attack_speed", 1); rifle1.setStringAttribute("class_required", "None"); rifle1.setStringAttribute("cat_wpn_damage.wpn_damage_type", "Energy"); rifle1.setStringAttribute("cat_wpn_damage.damage", "800-1250"); inventory.add(rifle1); SWGObject pistol = core.objectService.createObject("object/weapon/ranged/pistol/shared_pistol_cdef.iff", planet); pistol.setIntAttribute("required_combat_level", 90); pistol.setFloatAttribute("cat_wpn_damage.wpn_attack_speed", 1); pistol.setStringAttribute("class_required", "None"); pistol.setStringAttribute("cat_wpn_damage.wpn_damage_type", "Energy"); pistol.setStringAttribute("cat_wpn_damage.damage", "400-559"); inventory.add(pistol); return; case 40: TangibleObject ring = (TangibleObject) core.objectService.createObject("object/tangible/wearables/ring/shared_ring_s01.iff", planet); ring.setCustomName("Unity Ring"); inventory.add(ring); } } }); core.suiService.openSUIWindow(window); }
public void sendCharacterBuilderSUI(CreatureObject creature, int childMenu) { Map<Long, String> suiOptions = new HashMap<Long, String>(); switch(childMenu) { case 0: // Root suiOptions.put((long) 1, "Character"); suiOptions.put((long) 2, "Items"); break; case 1: // Character suiOptions.put((long) 10, "Set combat level to 90"); suiOptions.put((long) 11, "Give 100,000 credits"); suiOptions.put((long) 12, "Reset expertise"); break; case 2: // Items suiOptions.put((long) 20, "(Light) Jedi Robe"); suiOptions.put((long) 21, "(Dark) Jedi Robe"); suiOptions.put((long) 22, "Composite Armor"); suiOptions.put((long) 23, "Weapons"); suiOptions.put((long) 24, "Misc Items"); break; case 3: // [Items] Weapons suiOptions.put((long) 30, "Jedi Weapons"); suiOptions.put((long) 31, "Melee Weapons"); suiOptions.put((long) 32, "Ranged Weapons"); break; case 4: // [Items] Misc Items suiOptions.put((long) 40, "Unity Ring"); break; } final SUIWindow window = core.suiService.createListBox(ListBoxType.LIST_BOX_OK_CANCEL, "Character Builder Terminal", "Select the desired option and click OK.", suiOptions, creature, null, 10); Vector<String> returnList = new Vector<String>(); returnList.add("List.lstList:SelectedRow"); window.addHandler(0, "", Trigger.TRIGGER_OK, returnList, new SUICallback() { public void process(SWGObject owner, int eventType, Vector<String> returnList) { int index = Integer.parseInt(returnList.get(0)); int childIndex = (int) window.getObjectIdByIndex(index); CreatureObject player = (CreatureObject) owner; SWGObject inventory = player.getSlottedObject("inventory"); Planet planet = player.getPlanet(); switch(childIndex) { // Root case 1: // Character sendCharacterBuilderSUI(player, 1); return; case 2: // Items sendCharacterBuilderSUI(player, 2); return; // Character case 10: // Set combat level to 90 core.playerService.grantLevel(player, 90); // Commented out until fixed //core.playerService.giveExperience(player, 999999999); return; case 11: // Give 100,000 credits player.setCashCredits(player.getCashCredits() + 100000); return; case 12: // Reset expertise // Seefo->Light: I commented out the below line because it gave us an error and didn't properly remove the skill, could you try the method SWGList.reverseGet that I added? //player.getSkills().get().stream().filter(s -> s.contains("expertise")).forEach(s -> core.skillService.removeSkill(creature, s)); // Using this for now for(int i = creature.getSkills().size() - 1; i >= 0; i-- ) { String skill = creature.getSkills().get(i); if(skill.contains("expertise")) core.skillService.removeSkill(player, skill); } return; // Items case 20: // (Light) Jedi Robe inventory.add(core.objectService.createObject("object/tangible/wearables/robe/shared_robe_jedi_light_s03.iff", planet)); return; case 21: // (Dark) Jedi Robe inventory.add(core.objectService.createObject("object/tangible/wearables/robe/shared_robe_jedi_dark_s03.iff", planet)); return; case 22: // Composite Armor SWGObject bicep_r = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_bicep_r.iff", planet); bicep_r.setIntAttribute("cat_armor_standard_protection.armor_eff_kinetic", 7000); bicep_r.setIntAttribute("cat_armor_standard_protection.armor_eff_energy", 5000); bicep_r.setIntAttribute("cat_armor_special_protection.special_protection_type_heat", 6000); bicep_r.setIntAttribute("cat_armor_special_protection.special_protection_type_cold", 6000); bicep_r.setIntAttribute("cat_armor_special_protection.special_protection_type_acid", 6000); bicep_r.setIntAttribute("cat_armor_special_protection.special_protection_type_electricity", 6000); SWGObject bicep_l = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_bicep_l.iff", planet); bicep_l.setIntAttribute("cat_armor_standard_protection.armor_eff_kinetic", 7000); bicep_l.setIntAttribute("cat_armor_standard_protection.armor_eff_energy", 5000); bicep_l.setIntAttribute("cat_armor_special_protection.special_protection_type_heat", 6000); bicep_l.setIntAttribute("cat_armor_special_protection.special_protection_type_cold", 6000); bicep_l.setIntAttribute("cat_armor_special_protection.special_protection_type_acid", 6000); bicep_l.setIntAttribute("cat_armor_special_protection.special_protection_type_electricity", 6000); SWGObject bracer_r = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_bracer_r.iff", planet); bracer_r.setIntAttribute("cat_armor_standard_protection.armor_eff_kinetic", 7000); bracer_r.setIntAttribute("cat_armor_standard_protection.armor_eff_energy", 5000); bracer_r.setIntAttribute("cat_armor_special_protection.special_protection_type_heat", 6000); bracer_r.setIntAttribute("cat_armor_special_protection.special_protection_type_cold", 6000); bracer_r.setIntAttribute("cat_armor_special_protection.special_protection_type_acid", 6000); bracer_r.setIntAttribute("cat_armor_special_protection.special_protection_type_electricity", 6000); SWGObject bracer_l = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_bracer_l.iff", planet); bracer_l.setIntAttribute("cat_armor_standard_protection.armor_eff_kinetic", 7000); bracer_l.setIntAttribute("cat_armor_standard_protection.armor_eff_energy", 5000); bracer_l.setIntAttribute("cat_armor_special_protection.special_protection_type_heat", 6000); bracer_l.setIntAttribute("cat_armor_special_protection.special_protection_type_cold", 6000); bracer_l.setIntAttribute("cat_armor_special_protection.special_protection_type_acid", 6000); bracer_l.setIntAttribute("cat_armor_special_protection.special_protection_type_electricity", 6000); SWGObject leggings = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_leggings.iff", planet); leggings.setIntAttribute("cat_armor_standard_protection.armor_eff_kinetic", 7000); leggings.setIntAttribute("cat_armor_standard_protection.armor_eff_energy", 5000); leggings.setIntAttribute("cat_armor_special_protection.special_protection_type_heat", 6000); leggings.setIntAttribute("cat_armor_special_protection.special_protection_type_cold", 6000); leggings.setIntAttribute("cat_armor_special_protection.special_protection_type_acid", 6000); leggings.setIntAttribute("cat_armor_special_protection.special_protection_type_electricity", 6000); SWGObject helmet = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_helmet.iff", planet); helmet.setIntAttribute("cat_armor_standard_protection.armor_eff_kinetic", 7000); helmet.setIntAttribute("cat_armor_standard_protection.armor_eff_energy", 5000); helmet.setIntAttribute("cat_armor_special_protection.special_protection_type_heat", 6000); helmet.setIntAttribute("cat_armor_special_protection.special_protection_type_cold", 6000); helmet.setIntAttribute("cat_armor_special_protection.special_protection_type_acid", 6000); helmet.setIntAttribute("cat_armor_special_protection.special_protection_type_electricity", 6000); SWGObject chest = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_chest_plate.iff", planet); chest.setIntAttribute("cat_armor_standard_protection.armor_eff_kinetic", 7000); chest.setIntAttribute("cat_armor_standard_protection.armor_eff_energy", 5000); chest.setIntAttribute("cat_armor_special_protection.special_protection_type_heat", 6000); chest.setIntAttribute("cat_armor_special_protection.special_protection_type_cold", 6000); chest.setIntAttribute("cat_armor_special_protection.special_protection_type_acid", 6000); chest.setIntAttribute("cat_armor_special_protection.special_protection_type_electricity", 6000); SWGObject boots = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_boots.iff", planet); SWGObject gloves = core.objectService.createObject("object/tangible/wearables/armor/composite/shared_armor_composite_gloves.iff", planet); inventory.add(bicep_r); inventory.add(bicep_l); inventory.add(bracer_r); inventory.add(bracer_l); inventory.add(leggings); inventory.add(helmet); inventory.add(chest); inventory.add(boots); inventory.add(gloves); return; case 23: // Weapons sendCharacterBuilderSUI(player, 3); return; case 24: // Misc Items sendCharacterBuilderSUI(player, 4); return; // [Items] Weapons case 30: // Jedi Weapons TangibleObject lightsaber1 = (TangibleObject) core.objectService.createObject("object/weapon/melee/sword/crafted_saber/shared_sword_lightsaber_one_handed_gen5.iff", planet); lightsaber1.setIntAttribute("required_combat_level", 90); lightsaber1.setFloatAttribute("cat_wpn_damage.wpn_attack_speed", 1); lightsaber1.setStringAttribute("class_required", "Jedi"); lightsaber1.setStringAttribute("cat_wpn_damage.wpn_damage_type", "Energy"); lightsaber1.setStringAttribute("cat_wpn_damage.damage", "689-1379"); TangibleObject lightsaber2 = (TangibleObject) core.objectService.createObject("object/weapon/melee/2h_sword/crafted_saber/shared_sword_lightsaber_two_handed_gen5.iff", planet); lightsaber2.setIntAttribute("required_combat_level", 90); lightsaber2.setFloatAttribute("cat_wpn_damage.wpn_attack_speed", 1); lightsaber2.setStringAttribute("class_required", "Jedi"); lightsaber2.setStringAttribute("cat_wpn_damage.wpn_damage_type", "Energy"); lightsaber2.setStringAttribute("cat_wpn_damage.damage", "689-1379"); TangibleObject lightsaber3 = (TangibleObject) core.objectService.createObject("object/weapon/melee/polearm/crafted_saber/shared_sword_lightsaber_polearm_gen5.iff", planet); lightsaber3.setIntAttribute("required_combat_level", 90); lightsaber3.setFloatAttribute("cat_wpn_damage.wpn_attack_speed", 1); lightsaber3.setStringAttribute("class_required", "Jedi"); lightsaber3.setStringAttribute("cat_wpn_damage.wpn_damage_type", "Energy"); lightsaber3.setStringAttribute("cat_wpn_damage.damage", "689-1379"); Random random = new Random(); lightsaber1.setCustomizationVariable("/private/index_color_blade", (byte) random.nextInt(47)); lightsaber2.setCustomizationVariable("/private/index_color_blade", (byte) random.nextInt(47)); lightsaber3.setCustomizationVariable("/private/index_color_blade", (byte) random.nextInt(47)); inventory.add(lightsaber1); inventory.add(lightsaber2); inventory.add(lightsaber3); return; case 31: // Melee Weapons SWGObject sword1 = core.objectService.createObject("object/weapon/melee/sword/shared_sword_01.iff", planet); sword1.setIntAttribute("required_combat_level", 90); sword1.setFloatAttribute("cat_wpn_damage.wpn_attack_speed", 1); sword1.setStringAttribute("class_required", "None"); sword1.setStringAttribute("cat_wpn_damage.wpn_damage_type", "Energy"); sword1.setStringAttribute("cat_wpn_damage.damage", "1100-1200"); inventory.add(sword1); return; case 32: // Ranged Weapons SWGObject rifle1 = core.objectService.createObject("object/weapon/ranged/rifle/shared_rifle_e11.iff", planet); rifle1.setIntAttribute("required_combat_level", 90); rifle1.setFloatAttribute("cat_wpn_damage.wpn_attack_speed", 0.8); rifle1.setStringAttribute("class_required", "None"); rifle1.setStringAttribute("cat_wpn_damage.wpn_damage_type", "Energy"); rifle1.setStringAttribute("cat_wpn_damage.damage", "800-1250"); inventory.add(rifle1); SWGObject pistol = core.objectService.createObject("object/weapon/ranged/pistol/shared_pistol_cdef.iff", planet); pistol.setIntAttribute("required_combat_level", 90); pistol.setFloatAttribute("cat_wpn_damage.wpn_attack_speed", 0.4); pistol.setStringAttribute("class_required", "None"); pistol.setStringAttribute("cat_wpn_damage.wpn_damage_type", "Energy"); pistol.setStringAttribute("cat_wpn_damage.damage", "400-559"); inventory.add(pistol); return; case 40: TangibleObject ring = (TangibleObject) core.objectService.createObject("object/tangible/wearables/ring/shared_ring_s01.iff", planet); ring.setCustomName("Unity Ring"); inventory.add(ring); } } }); core.suiService.openSUIWindow(window); }
diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/JSONServlet.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/JSONServlet.java index 3a27a8401..e250fece0 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/JSONServlet.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/JSONServlet.java @@ -1,521 +1,521 @@ /* $This file is distributed under the terms of the license in /doc/license.txt$ */ package edu.cornell.mannlib.vitro.webapp.controller; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.rdf.model.Literal; import edu.cornell.mannlib.vitro.webapp.beans.DataProperty; import edu.cornell.mannlib.vitro.webapp.beans.Individual; import edu.cornell.mannlib.vitro.webapp.beans.VClass; import edu.cornell.mannlib.vitro.webapp.controller.TabEntitiesController.PageRecord; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.SelectListGenerator; import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch; import edu.cornell.mannlib.vitro.webapp.web.DisplayVocabulary; import edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual.IndividualTemplateModel; /** * This servlet is for servicing requests for JSON objects/data. * It could be generalized to get other types of data ex. XML, HTML etc * @author bdc34 * */ public class JSONServlet extends VitroHttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req, resp); VitroRequest vreq = new VitroRequest(req); if(vreq.getParameter("getEntitiesByVClass") != null ){ if( vreq.getParameter("resultKey") == null) { getEntitiesByVClass(req, resp); return; } else { getEntitiesByVClassContinuation( req, resp); return; } }else if( vreq.getParameter("getN3EditOptionList") != null ){ doN3EditOptionList(req,resp); return; }else if( vreq.getParameter("getLuceneIndividualsByVClass") != null ){ getLuceneIndividualsByVClass(req,resp); return; } } private void getLuceneIndividualsByVClass( HttpServletRequest req, HttpServletResponse resp ){ String errorMessage = null; JSONObject rObj = null; try{ VitroRequest vreq = new VitroRequest(req); VClass vclass=null; String vitroClassIdStr = vreq.getParameter("vclassId"); if ( vitroClassIdStr != null && !vitroClassIdStr.isEmpty()){ vclass = vreq.getWebappDaoFactory().getVClassDao().getVClassByURI(vitroClassIdStr); if (vclass == null) { log.debug("Couldn't retrieve vclass "); throw new Exception (errorMessage = "Class " + vitroClassIdStr + " not found"); } }else{ log.debug("parameter vclassId URI parameter expected "); throw new Exception("parameter vclassId URI parameter expected "); } rObj = getLuceneIndividualsByVClass(vclass.getURI(),req,resp,getServletContext()); }catch(Exception ex){ errorMessage = ex.toString(); log.error(ex,ex); } if( rObj == null ) rObj = new JSONObject(); try{ resp.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); if( errorMessage != null ){ rObj.put("errorMessage", errorMessage); resp.setStatus(500 /*HttpURLConnection.HTTP_SERVER_ERROR*/); }else{ rObj.put("errorMessage", ""); } Writer writer = resp.getWriter(); writer.write(rObj.toString()); }catch(JSONException jse){ log.error(jse,jse); } catch (IOException e) { log.error(e,e); } } protected static JSONObject getLuceneIndividualsByVClass(String vclassURI, HttpServletRequest req, HttpServletResponse resp, ServletContext context) throws Exception { VitroRequest vreq = new VitroRequest(req); VClass vclass=null; JSONObject rObj = new JSONObject(); DataProperty fNameDp = (new DataProperty()); fNameDp.setURI("http://xmlns.com/foaf/0.1/firstName"); DataProperty lNameDp = (new DataProperty()); lNameDp.setURI("http://xmlns.com/foaf/0.1/lastName"); DataProperty monikerDp = (new DataProperty()); monikerDp.setURI( VitroVocabulary.MONIKER); //this property is vivo specific - DataProperty perferredTitleDp = (new DataProperty()); - perferredTitleDp.setURI("http://vivoweb.org/ontology/core#preferredTitle"); + DataProperty preferredTitleDp = (new DataProperty()); + preferredTitleDp.setURI("http://vivoweb.org/ontology/core#preferredTitle"); if( log.isDebugEnabled() ){ Enumeration<String> e = vreq.getParameterNames(); while(e.hasMoreElements()){ String name = (String)e.nextElement(); log.debug("parameter: " + name); for( String value : vreq.getParameterValues(name) ){ log.debug("value for " + name + ": '" + value + "'"); } } } //need an unfiltered dao to get firstnames and lastnames WebappDaoFactory fullWdf = vreq.getFullWebappDaoFactory(); String vitroClassIdStr = vreq.getParameter("vclassId"); if ( vitroClassIdStr != null && !vitroClassIdStr.isEmpty()){ vclass = vreq.getWebappDaoFactory().getVClassDao().getVClassByURI(vitroClassIdStr); if (vclass == null) { log.debug("Couldn't retrieve vclass "); throw new Exception ("Class " + vitroClassIdStr + " not found"); } }else{ log.debug("parameter vclassId URI parameter expected "); throw new Exception("parameter vclassId URI parameter expected "); } rObj.put("vclass", new JSONObject().put("URI",vclass.getURI()) .put("name",vclass.getName())); if (vclass != null) { String alpha = EntityListController.getAlphaParamter(vreq); int page = EntityListController.getPageParameter(vreq); Map<String,Object> map = EntityListController.getResultsForVClass( vclass.getURI(), page, alpha, vreq.getPortal(), vreq.getWebappDaoFactory().getPortalDao().isSinglePortal(), vreq.getWebappDaoFactory().getIndividualDao(), context); rObj.put("totalCount", map.get("totalCount")); rObj.put("alpha", map.get("alpha")); List<Individual> inds = (List<Individual>)map.get("entities"); List<IndividualTemplateModel> indsTm = new ArrayList<IndividualTemplateModel>(); JSONArray jInds = new JSONArray(); for(Individual ind : inds ){ JSONObject jo = new JSONObject(); jo.put("URI", ind.getURI()); jo.put("label",ind.getRdfsLabel()); jo.put("name",ind.getName()); jo.put("thumbUrl", ind.getThumbUrl()); jo.put("imageUrl", ind.getImageUrl()); jo.put("profileUrl", UrlBuilder.getIndividualProfileUrl(ind, vreq.getWebappDaoFactory())); String moniker = getDataPropertyValue(ind, monikerDp, fullWdf); jo.put("moniker", moniker); jo.put("vclassName", getVClassName(ind,moniker,fullWdf)); - jo.put("perferredTitle", getDataPropertyValue(ind, perferredTitleDp, fullWdf)); + jo.put("preferredTitle", getDataPropertyValue(ind, preferredTitleDp, fullWdf)); jo.put("firstName", getDataPropertyValue(ind, fNameDp, fullWdf)); jo.put("lastName", getDataPropertyValue(ind, lNameDp, fullWdf)); jInds.put(jo); } rObj.put("individuals", jInds); JSONArray wpages = new JSONArray(); List<PageRecord> pages = (List<PageRecord>)map.get("pages"); for( PageRecord pr: pages ){ JSONObject p = new JSONObject(); p.put("text", pr.text); p.put("param", pr.param); p.put("index", pr.index); wpages.put( p ); } rObj.put("pages",wpages); JSONArray jletters = new JSONArray(); List<String> letters = Controllers.getLetters(); for( String s : letters){ JSONObject jo = new JSONObject(); jo.put("text", s); jo.put("param", "alpha=" + URLEncoder.encode(s, "UTF-8")); jletters.put( jo ); } rObj.put("letters", jletters); } return rObj; } private static String getVClassName(Individual ind, String moniker, WebappDaoFactory fullWdf) { /* so the moniker frequently has a vclass name in it. Try to return * the vclass name that is the same as the moniker so that the templates * can detect this. */ if( (moniker == null || moniker.isEmpty()) ){ if( ind.getVClass() != null && ind.getVClass().getName() != null ) return ind.getVClass().getName(); else return ""; } List<VClass> vcList = ind.getVClasses(); for( VClass vc : vcList){ if( vc != null && moniker.equals( vc.getName() )) return moniker; } // if we get here, then we didn't find a moniker that matched a vclass, // so just return any vclass.name if( ind.getVClass() != null && ind.getVClass().getName() != null ) return ind.getVClass().getName(); else return ""; } static String getDataPropertyValue(Individual ind, DataProperty dp, WebappDaoFactory wdf){ List<Literal> values = wdf.getDataPropertyStatementDao() .getDataPropertyValuesForIndividualByProperty(ind, dp); if( values == null || values.isEmpty() ) return ""; else{ if( values.get(0) != null ) return values.get(0).getLexicalForm(); else return ""; } } /** * Gets an option list for a given EditConfiguration and Field. * Requires following HTTP query parameters: * editKey * field */ private void doN3EditOptionList(HttpServletRequest req, HttpServletResponse resp) throws IOException { log.debug("in doN3EditOptionList()"); String field = req.getParameter("field"); if( field == null ){ log.debug("could not find query parameter 'field' for doN3EditOptionList"); throw new IllegalArgumentException(" getN3EditOptionList requires parameter 'field'"); } HttpSession sess = req.getSession(false); EditConfiguration editConfig = EditConfiguration.getConfigFromSession(sess, req); if( editConfig == null ) { log.debug("could not find query parameter 'editKey' for doN3EditOptionList"); throw new IllegalArgumentException(" getN3EditOptionList requires parameter 'editKey'"); } if( log.isDebugEnabled() ) log.debug(" attempting to get option list for field '" + field + "'"); // set ProhibitedFromSearch object so picklist doesn't show // individuals from classes that should be hidden from list views OntModel displayOntModel = (OntModel) getServletConfig().getServletContext() .getAttribute("displayOntModel"); if (displayOntModel != null) { ProhibitedFromSearch pfs = new ProhibitedFromSearch( DisplayVocabulary.PRIMARY_LUCENE_INDEX_URI, displayOntModel); editConfig.setProhibitedFromSearch(pfs); } Map<String,String> options = SelectListGenerator.getOptions(editConfig, field, (new VitroRequest(req)).getFullWebappDaoFactory()); resp.setContentType("application/json"); ServletOutputStream out = resp.getOutputStream(); out.println("["); for(String key : options.keySet()){ JSONArray jsonObj = new JSONArray(); jsonObj.put( options.get(key)); jsonObj.put( key); out.println(" " + jsonObj.toString() + ","); } out.println("]"); } private void getEntitiesByVClassContinuation(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { log.debug("in getEntitiesByVClassContinuation()"); VitroRequest vreq = new VitroRequest(req); String resKey = vreq.getParameter("resultKey"); if( resKey == null ) throw new ServletException("Could not get resultKey"); HttpSession session = vreq.getSession(); if( session == null ) throw new ServletException("there is no session to get the pervious results from"); List<Individual> entsInVClass = (List<Individual>) session.getAttribute(resKey); if( entsInVClass == null ) throw new ServletException("Could not find List<Individual> for resultKey " + resKey); List<Individual> entsToReturn = new ArrayList<Individual>(REPLY_SIZE); boolean more = false; int count = 0; int size = REPLY_SIZE; /* we have a large number of items to send back so we need to stash the list in the session scope */ if( entsInVClass.size() > REPLY_SIZE){ more = true; ListIterator<Individual> entsFromVclass = entsInVClass.listIterator(); while ( entsFromVclass.hasNext() && count <= REPLY_SIZE ){ entsToReturn.add( entsFromVclass.next()); entsFromVclass.remove(); count++; } if( log.isDebugEnabled() ) log.debug("getEntitiesByVClassContinuation(): Creating reply with continue token," + " sending in this reply: " + count +", remaing to send: " + entsInVClass.size() ); } else { //send out reply with no continuation entsToReturn = entsInVClass; count = entsToReturn.size(); session.removeAttribute(resKey); if( log.isDebugEnabled()) log.debug("getEntitiesByVClassContinuation(): sending " + count + " Ind without continue token"); } //put all the entities on the JSON array JSONArray ja = individualsToJson( entsToReturn ); //put the responseGroup number on the end of the JSON array if( more ){ try{ JSONObject obj = new JSONObject(); obj.put("resultGroup", "true"); obj.put("size", count); StringBuffer nextUrlStr = req.getRequestURL(); nextUrlStr.append("?") .append("getEntitiesByVClass").append( "=1&" ) .append("resultKey=").append( resKey ); obj.put("nextUrl", nextUrlStr.toString()); ja.put(obj); }catch(JSONException je ){ throw new ServletException(je.getMessage()); } } resp.setContentType("application/json"); ServletOutputStream out = resp.getOutputStream(); out.print( ja.toString() ); log.debug("done with getEntitiesByVClassContinuation()"); } /** * Gets a list of entities that are members of the indicated vClass. * * If the list is large then we will pass some token indicating that there is more * to come. The results are sent back in 250 entity blocks. To get all of the * entities for a VClass just keep requesting lists until there are not more * continue tokens. * * If there are more entities the last item on the returned array will be an object * with no id property. It will look like this: * * {"resultGroup":0, * "resultKey":"2WEK2306", * "nextUrl":"http://caruso.mannlib.cornell.edu:8080/vitro/dataservice?getEntitiesByVClass=1&resultKey=2WEK2306&resultGroup=1&vclassId=null", * "entsInVClass":1752, * "nextResultGroup":1, * "standardReplySize":256} * */ private void getEntitiesByVClass(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ log.debug("in getEntitiesByVClass()"); VitroRequest vreq = new VitroRequest(req); String vclassURI = vreq.getParameter("vclassURI"); WebappDaoFactory daos = (new VitroRequest(req)).getFullWebappDaoFactory(); resp.setCharacterEncoding("UTF-8"); // ServletOutputStream doesn't support UTF-8 PrintWriter out = resp.getWriter(); resp.getWriter(); if( vclassURI == null ){ log.debug("getEntitiesByVClass(): no value for 'vclassURI' found in the HTTP request"); out.print( (new JSONArray()).toString() ); return; } VClass vclass = daos.getVClassDao().getVClassByURI( vclassURI ); if( vclass == null ){ log.debug("getEntitiesByVClass(): could not find vclass for uri '"+ vclassURI + "'"); out.print( (new JSONArray()).toString() ); return; } List<Individual> entsInVClass = daos.getIndividualDao().getIndividualsByVClass( vclass ); if( entsInVClass == null ){ log.debug("getEntitiesByVClass(): null List<Individual> retruned by getIndividualsByVClass() for "+vclassURI); out.print( (new JSONArray().toString() )); return ; } int numberOfEntsInVClass = entsInVClass.size(); List<Individual> entsToReturn = new ArrayList<Individual>( REPLY_SIZE ); String requestHash = null; int count = 0; boolean more = false; /* we have a large number of items to send back so we need to stash the list in the session scope */ if( entsInVClass.size() > REPLY_SIZE){ more = true; HttpSession session = vreq.getSession(true); requestHash = Integer.toString((vclassURI + System.currentTimeMillis()).hashCode()); session.setAttribute(requestHash, entsInVClass ); ListIterator<Individual> entsFromVclass = entsInVClass.listIterator(); while ( entsFromVclass.hasNext() && count < REPLY_SIZE ){ entsToReturn.add( entsFromVclass.next()); entsFromVclass.remove(); count++; } if( log.isDebugEnabled() ){ log.debug("getEntitiesByVClass(): Creating reply with continue token, found " + numberOfEntsInVClass + " Individuals"); } }else{ if( log.isDebugEnabled() ) log.debug("getEntitiesByVClass(): sending " + numberOfEntsInVClass +" Individuals without continue token"); entsToReturn = entsInVClass; count = entsToReturn.size(); } //put all the entities on the JSON array JSONArray ja = individualsToJson( entsToReturn ); //put the responseGroup number on the end of the JSON array if( more ){ try{ JSONObject obj = new JSONObject(); obj.put("resultGroup", "true"); obj.put("size", count); obj.put("total", numberOfEntsInVClass); StringBuffer nextUrlStr = req.getRequestURL(); nextUrlStr.append("?") .append("getEntitiesByVClass").append( "=1&" ) .append("resultKey=").append( requestHash ); obj.put("nextUrl", nextUrlStr.toString()); ja.put(obj); }catch(JSONException je ){ throw new ServletException("unable to create continuation as JSON: " + je.getMessage()); } } resp.setContentType("application/json"); out.print( ja.toString() ); log.debug("done with getEntitiesByVClass()"); } private JSONArray individualsToJson(List<Individual> individuals) throws ServletException { JSONArray ja = new JSONArray(); Iterator it = individuals.iterator(); try{ while(it.hasNext()){ Individual ent = (Individual) it.next(); JSONObject entJ = new JSONObject(); entJ.put("name", ent.getName()); entJ.put("URI", ent.getURI()); ja.put( entJ ); } }catch(JSONException ex){ throw new ServletException("could not convert list of Individuals into JSON: " + ex); } return ja; } private static final int REPLY_SIZE = 256; private static final Log log = LogFactory.getLog(JSONServlet.class.getName()); }
false
true
protected static JSONObject getLuceneIndividualsByVClass(String vclassURI, HttpServletRequest req, HttpServletResponse resp, ServletContext context) throws Exception { VitroRequest vreq = new VitroRequest(req); VClass vclass=null; JSONObject rObj = new JSONObject(); DataProperty fNameDp = (new DataProperty()); fNameDp.setURI("http://xmlns.com/foaf/0.1/firstName"); DataProperty lNameDp = (new DataProperty()); lNameDp.setURI("http://xmlns.com/foaf/0.1/lastName"); DataProperty monikerDp = (new DataProperty()); monikerDp.setURI( VitroVocabulary.MONIKER); //this property is vivo specific DataProperty perferredTitleDp = (new DataProperty()); perferredTitleDp.setURI("http://vivoweb.org/ontology/core#preferredTitle"); if( log.isDebugEnabled() ){ Enumeration<String> e = vreq.getParameterNames(); while(e.hasMoreElements()){ String name = (String)e.nextElement(); log.debug("parameter: " + name); for( String value : vreq.getParameterValues(name) ){ log.debug("value for " + name + ": '" + value + "'"); } } } //need an unfiltered dao to get firstnames and lastnames WebappDaoFactory fullWdf = vreq.getFullWebappDaoFactory(); String vitroClassIdStr = vreq.getParameter("vclassId"); if ( vitroClassIdStr != null && !vitroClassIdStr.isEmpty()){ vclass = vreq.getWebappDaoFactory().getVClassDao().getVClassByURI(vitroClassIdStr); if (vclass == null) { log.debug("Couldn't retrieve vclass "); throw new Exception ("Class " + vitroClassIdStr + " not found"); } }else{ log.debug("parameter vclassId URI parameter expected "); throw new Exception("parameter vclassId URI parameter expected "); } rObj.put("vclass", new JSONObject().put("URI",vclass.getURI()) .put("name",vclass.getName())); if (vclass != null) { String alpha = EntityListController.getAlphaParamter(vreq); int page = EntityListController.getPageParameter(vreq); Map<String,Object> map = EntityListController.getResultsForVClass( vclass.getURI(), page, alpha, vreq.getPortal(), vreq.getWebappDaoFactory().getPortalDao().isSinglePortal(), vreq.getWebappDaoFactory().getIndividualDao(), context); rObj.put("totalCount", map.get("totalCount")); rObj.put("alpha", map.get("alpha")); List<Individual> inds = (List<Individual>)map.get("entities"); List<IndividualTemplateModel> indsTm = new ArrayList<IndividualTemplateModel>(); JSONArray jInds = new JSONArray(); for(Individual ind : inds ){ JSONObject jo = new JSONObject(); jo.put("URI", ind.getURI()); jo.put("label",ind.getRdfsLabel()); jo.put("name",ind.getName()); jo.put("thumbUrl", ind.getThumbUrl()); jo.put("imageUrl", ind.getImageUrl()); jo.put("profileUrl", UrlBuilder.getIndividualProfileUrl(ind, vreq.getWebappDaoFactory())); String moniker = getDataPropertyValue(ind, monikerDp, fullWdf); jo.put("moniker", moniker); jo.put("vclassName", getVClassName(ind,moniker,fullWdf)); jo.put("perferredTitle", getDataPropertyValue(ind, perferredTitleDp, fullWdf)); jo.put("firstName", getDataPropertyValue(ind, fNameDp, fullWdf)); jo.put("lastName", getDataPropertyValue(ind, lNameDp, fullWdf)); jInds.put(jo); } rObj.put("individuals", jInds); JSONArray wpages = new JSONArray(); List<PageRecord> pages = (List<PageRecord>)map.get("pages"); for( PageRecord pr: pages ){ JSONObject p = new JSONObject(); p.put("text", pr.text); p.put("param", pr.param); p.put("index", pr.index); wpages.put( p ); } rObj.put("pages",wpages); JSONArray jletters = new JSONArray(); List<String> letters = Controllers.getLetters(); for( String s : letters){ JSONObject jo = new JSONObject(); jo.put("text", s); jo.put("param", "alpha=" + URLEncoder.encode(s, "UTF-8")); jletters.put( jo ); } rObj.put("letters", jletters); } return rObj; }
protected static JSONObject getLuceneIndividualsByVClass(String vclassURI, HttpServletRequest req, HttpServletResponse resp, ServletContext context) throws Exception { VitroRequest vreq = new VitroRequest(req); VClass vclass=null; JSONObject rObj = new JSONObject(); DataProperty fNameDp = (new DataProperty()); fNameDp.setURI("http://xmlns.com/foaf/0.1/firstName"); DataProperty lNameDp = (new DataProperty()); lNameDp.setURI("http://xmlns.com/foaf/0.1/lastName"); DataProperty monikerDp = (new DataProperty()); monikerDp.setURI( VitroVocabulary.MONIKER); //this property is vivo specific DataProperty preferredTitleDp = (new DataProperty()); preferredTitleDp.setURI("http://vivoweb.org/ontology/core#preferredTitle"); if( log.isDebugEnabled() ){ Enumeration<String> e = vreq.getParameterNames(); while(e.hasMoreElements()){ String name = (String)e.nextElement(); log.debug("parameter: " + name); for( String value : vreq.getParameterValues(name) ){ log.debug("value for " + name + ": '" + value + "'"); } } } //need an unfiltered dao to get firstnames and lastnames WebappDaoFactory fullWdf = vreq.getFullWebappDaoFactory(); String vitroClassIdStr = vreq.getParameter("vclassId"); if ( vitroClassIdStr != null && !vitroClassIdStr.isEmpty()){ vclass = vreq.getWebappDaoFactory().getVClassDao().getVClassByURI(vitroClassIdStr); if (vclass == null) { log.debug("Couldn't retrieve vclass "); throw new Exception ("Class " + vitroClassIdStr + " not found"); } }else{ log.debug("parameter vclassId URI parameter expected "); throw new Exception("parameter vclassId URI parameter expected "); } rObj.put("vclass", new JSONObject().put("URI",vclass.getURI()) .put("name",vclass.getName())); if (vclass != null) { String alpha = EntityListController.getAlphaParamter(vreq); int page = EntityListController.getPageParameter(vreq); Map<String,Object> map = EntityListController.getResultsForVClass( vclass.getURI(), page, alpha, vreq.getPortal(), vreq.getWebappDaoFactory().getPortalDao().isSinglePortal(), vreq.getWebappDaoFactory().getIndividualDao(), context); rObj.put("totalCount", map.get("totalCount")); rObj.put("alpha", map.get("alpha")); List<Individual> inds = (List<Individual>)map.get("entities"); List<IndividualTemplateModel> indsTm = new ArrayList<IndividualTemplateModel>(); JSONArray jInds = new JSONArray(); for(Individual ind : inds ){ JSONObject jo = new JSONObject(); jo.put("URI", ind.getURI()); jo.put("label",ind.getRdfsLabel()); jo.put("name",ind.getName()); jo.put("thumbUrl", ind.getThumbUrl()); jo.put("imageUrl", ind.getImageUrl()); jo.put("profileUrl", UrlBuilder.getIndividualProfileUrl(ind, vreq.getWebappDaoFactory())); String moniker = getDataPropertyValue(ind, monikerDp, fullWdf); jo.put("moniker", moniker); jo.put("vclassName", getVClassName(ind,moniker,fullWdf)); jo.put("preferredTitle", getDataPropertyValue(ind, preferredTitleDp, fullWdf)); jo.put("firstName", getDataPropertyValue(ind, fNameDp, fullWdf)); jo.put("lastName", getDataPropertyValue(ind, lNameDp, fullWdf)); jInds.put(jo); } rObj.put("individuals", jInds); JSONArray wpages = new JSONArray(); List<PageRecord> pages = (List<PageRecord>)map.get("pages"); for( PageRecord pr: pages ){ JSONObject p = new JSONObject(); p.put("text", pr.text); p.put("param", pr.param); p.put("index", pr.index); wpages.put( p ); } rObj.put("pages",wpages); JSONArray jletters = new JSONArray(); List<String> letters = Controllers.getLetters(); for( String s : letters){ JSONObject jo = new JSONObject(); jo.put("text", s); jo.put("param", "alpha=" + URLEncoder.encode(s, "UTF-8")); jletters.put( jo ); } rObj.put("letters", jletters); } return rObj; }
diff --git a/proxy/src/main/java/org/fedoraproject/candlepin/auth/interceptor/AccessControlInterceptor.java b/proxy/src/main/java/org/fedoraproject/candlepin/auth/interceptor/AccessControlInterceptor.java index 400b84129..572ea6e5c 100644 --- a/proxy/src/main/java/org/fedoraproject/candlepin/auth/interceptor/AccessControlInterceptor.java +++ b/proxy/src/main/java/org/fedoraproject/candlepin/auth/interceptor/AccessControlInterceptor.java @@ -1,125 +1,125 @@ /** * Copyright (c) 2009 Red Hat, Inc. * * This software is licensed to you under the GNU General Public License, * version 2 (GPLv2). There is NO WARRANTY for this software, express or * implied, including the implied warranties of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 * along with this software; if not, see * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * Red Hat trademarks are not licensed under GPLv2. No permission is * granted to use or replicate Red Hat trademarks that are incorporated * in this software or its documentation. */ package org.fedoraproject.candlepin.auth.interceptor; import java.util.Arrays; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.fedoraproject.candlepin.auth.ConsumerPrincipal; import org.fedoraproject.candlepin.auth.Principal; import org.fedoraproject.candlepin.auth.Role; import org.fedoraproject.candlepin.auth.UserPrincipal; import org.fedoraproject.candlepin.exceptions.ForbiddenException; import org.fedoraproject.candlepin.model.AbstractHibernateCurator; import org.fedoraproject.candlepin.model.AccessControlEnforced; import com.google.inject.Inject; import com.google.inject.Provider; /** * AccessControlInterceptor */ public class AccessControlInterceptor implements MethodInterceptor { @Inject private Provider<Principal> principalProvider; @Override public Object invoke(MethodInvocation invocation) throws Throwable { String invokedMethodName = invocation.getMethod().getName(); if (invokedMethodName.startsWith("list")) { Object entity = ((AbstractHibernateCurator) invocation.getThis()).entityType(); if (!isAccessControlled(entity)) { return invocation.proceed(); } listFilter(invocation); } else { Object entity = invocation.getArguments()[0]; if (!isAccessControlled(entity)) { return invocation.proceed(); } crudAccessControl(entity); } return invocation.proceed(); } private boolean isAccessControlled(Object entity) { return Arrays.asList(entity.getClass().getInterfaces()) .contains(AccessControlEnforced.class); } private void listFilter(MethodInvocation invocation) { Principal currentUser = this.principalProvider.get(); Role role = currentUser.getRoles().get(0); if (Role.OWNER_ADMIN == role) { enableOwnerFilter(currentUser, invocation.getThis(), role); } else if (Role.CONSUMER == role) { enableConsumerFilter(currentUser, invocation.getThis(), role); } } private void crudAccessControl(Object entity) { Principal currentUser = this.principalProvider.get(); Role role = currentUser.getRoles().get(0); // Only available on entities that implement AccessControlEnforced interface - if (Role.CONSUMER == role) { + if (currentUser.getRoles().contains(Role.SUPER_ADMIN)) { + return; + } + else if (Role.CONSUMER == role) { ConsumerPrincipal consumer = (ConsumerPrincipal) currentUser; if (!((AccessControlEnforced) entity).shouldGrantAcessTo(consumer.consumer())) { throw new ForbiddenException("access denied."); } } else if (Role.OWNER_ADMIN == role) { if (!((AccessControlEnforced) entity) .shouldGrantAcessTo(currentUser.getOwner())) { throw new ForbiddenException("access denied."); } } - else if (Role.SUPER_ADMIN == role) { - return; - } else { throw new ForbiddenException("access denied."); } } @SuppressWarnings("unchecked") private void enableConsumerFilter(Principal currentUser, Object target, Role role) { AbstractHibernateCurator curator = (AbstractHibernateCurator) target; ConsumerPrincipal user = (ConsumerPrincipal) currentUser; String filterName = filterName(curator.entityType(), role); curator.enableFilter(filterName, "consumer_id", user.consumer().getId()); } @SuppressWarnings("unchecked") private void enableOwnerFilter(Principal currentUser, Object target, Role role) { AbstractHibernateCurator curator = (AbstractHibernateCurator) target; UserPrincipal user = (UserPrincipal) currentUser; String filterName = filterName(curator.entityType(), role); curator.enableFilter(filterName, "owner_id", user.getOwner().getId()); } private String filterName(Class<?> entity, Role role) { return entity.getSimpleName() + (role == Role.CONSUMER ? "_CONSUMER_FILTER" : "_OWNER_FILTER"); } }
false
true
private void crudAccessControl(Object entity) { Principal currentUser = this.principalProvider.get(); Role role = currentUser.getRoles().get(0); // Only available on entities that implement AccessControlEnforced interface if (Role.CONSUMER == role) { ConsumerPrincipal consumer = (ConsumerPrincipal) currentUser; if (!((AccessControlEnforced) entity).shouldGrantAcessTo(consumer.consumer())) { throw new ForbiddenException("access denied."); } } else if (Role.OWNER_ADMIN == role) { if (!((AccessControlEnforced) entity) .shouldGrantAcessTo(currentUser.getOwner())) { throw new ForbiddenException("access denied."); } } else if (Role.SUPER_ADMIN == role) { return; } else { throw new ForbiddenException("access denied."); } }
private void crudAccessControl(Object entity) { Principal currentUser = this.principalProvider.get(); Role role = currentUser.getRoles().get(0); // Only available on entities that implement AccessControlEnforced interface if (currentUser.getRoles().contains(Role.SUPER_ADMIN)) { return; } else if (Role.CONSUMER == role) { ConsumerPrincipal consumer = (ConsumerPrincipal) currentUser; if (!((AccessControlEnforced) entity).shouldGrantAcessTo(consumer.consumer())) { throw new ForbiddenException("access denied."); } } else if (Role.OWNER_ADMIN == role) { if (!((AccessControlEnforced) entity) .shouldGrantAcessTo(currentUser.getOwner())) { throw new ForbiddenException("access denied."); } } else { throw new ForbiddenException("access denied."); } }
diff --git a/edu/wisc/ssec/mcidasv/data/hydra/GranuleAggregation.java b/edu/wisc/ssec/mcidasv/data/hydra/GranuleAggregation.java index 3ee066983..7fa0474d1 100644 --- a/edu/wisc/ssec/mcidasv/data/hydra/GranuleAggregation.java +++ b/edu/wisc/ssec/mcidasv/data/hydra/GranuleAggregation.java @@ -1,436 +1,436 @@ /* * $Id$ * * This file is part of McIDAS-V * * Copyright 2007-2010 * Space Science and Engineering Center (SSEC) * University of Wisconsin - Madison * 1225 W. Dayton Street, Madison, WI 53706, USA * http://www.ssec.wisc.edu/mcidas * * All Rights Reserved * * McIDAS-V is built on Unidata's IDV and SSEC's VisAD libraries, and * some McIDAS-V source code is based on IDV and VisAD source code. * * McIDAS-V is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * McIDAS-V 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 Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with this program. If not, see http://www.gnu.org/licenses. */ package edu.wisc.ssec.mcidasv.data.hydra; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ucar.ma2.Array; import ucar.ma2.DataType; import ucar.ma2.Range; import ucar.ma2.StructureData; import ucar.ma2.StructureMembers; import ucar.nc2.Attribute; import ucar.nc2.Dimension; import ucar.nc2.NetcdfFile; import ucar.nc2.Structure; import ucar.nc2.Variable; /** * This file should be renamed - think about that Tommy. * This file needs to implement the same signatures NetCDFFile does, * but for aggregations of consecutive granules. * * @author tommyj * */ public class GranuleAggregation implements MultiDimensionReader { private static final Logger logger = LoggerFactory.getLogger(GranuleAggregation.class); // this structure holds the NcML readers that get passed in ArrayList<NetcdfFile> nclist = new ArrayList<NetcdfFile>(); // this holds the MultiDimensionReaders, here NetCDFFile ArrayList<NetCDFFile> ncdfal = null; // need an ArrayList for each variable hashmap structure ArrayList<HashMap<String, Variable>> varMapList = new ArrayList<HashMap<String, Variable>>(); ArrayList<HashMap<String, String[]>> varDimNamesList = new ArrayList<HashMap<String, String[]>>(); ArrayList<HashMap<String, int[]>> varDimLengthsList = new ArrayList<HashMap<String, int[]>>(); ArrayList<HashMap<String, Class>> varDataTypeList = new ArrayList<HashMap<String, Class>>(); // variable can have bulk array processor set by the application HashMap<String, RangeProcessor> varToRangeProcessor = new HashMap<String, RangeProcessor>(); private int granuleCount = -1; private int granuleLength = -1; private int inTrackIndex = -1; public GranuleAggregation(ArrayList<NetCDFFile> ncdfal, int granuleLength, int inTrackIndex) throws Exception { if (ncdfal == null) throw new Exception("No data: empty NPP aggregation object"); logger.trace("granule length: " + granuleLength); this.granuleLength = granuleLength; this.inTrackIndex = inTrackIndex; this.ncdfal = ncdfal; init(ncdfal); } public Class getArrayType(String array_name) { return varDataTypeList.get(0).get(array_name); } public String[] getDimensionNames(String array_name) { return varDimNamesList.get(0).get(array_name); } public int[] getDimensionLengths(String array_name) { logger.trace("GranuleAggregation.getDimensionLengths, requested: " + array_name); int[] lengths = varDimLengthsList.get(0).get(array_name); for (int i = 0; i < lengths.length; i++) { logger.trace("Length: " + lengths[i]); } return varDimLengthsList.get(0).get(array_name); } public float[] getFloatArray(String array_name, int[] start, int[] count, int[] stride) throws Exception { return (float[]) readArray(array_name, start, count, stride); } public int[] getIntArray(String array_name, int[] start, int[] count, int[] stride) throws Exception { return (int[]) readArray(array_name, start, count, stride); } public double[] getDoubleArray(String array_name, int[] start, int[] count, int[] stride) throws Exception { return (double[]) readArray(array_name, start, count, stride); } public short[] getShortArray(String array_name, int[] start, int[] count, int[] stride) throws Exception { return (short[]) readArray(array_name, start, count, stride); } public byte[] getByteArray(String array_name, int[] start, int[] count, int[] stride) throws Exception { return (byte[]) readArray(array_name, start, count, stride); } public Object getArray(String array_name, int[] start, int[] count, int[] stride) throws Exception { return readArray(array_name, start, count, stride); } public HDFArray getGlobalAttribute(String attr_name) throws Exception { throw new Exception("GranuleAggregation.getGlobalAttributes: Unimplemented"); } public HDFArray getArrayAttribute(String array_name, String attr_name) throws Exception { Variable var = varMapList.get(0).get(array_name); if (var == null) return null; Attribute attr = var.findAttribute(attr_name); if (attr == null) return null; Array attrVals = attr.getValues(); DataType dataType = attr.getDataType(); Object array = attrVals.copyTo1DJavaArray(); HDFArray harray = null; if (dataType.getPrimitiveClassType() == Float.TYPE) { harray = HDFArray.make((float[])array); } else if (dataType.getPrimitiveClassType() == Double.TYPE) { harray = HDFArray.make((double[])array); } else if (dataType == DataType.STRING) { harray = HDFArray.make((String[])array); } else if (dataType.getPrimitiveClassType() == Short.TYPE) { harray = HDFArray.make((short[])array); } else if (dataType.getPrimitiveClassType() == Integer.TYPE) { harray = HDFArray.make((int[])array); } return harray; } public void close() throws Exception { // close each NetCDF file for (NetcdfFile n : nclist) { n.close(); } } private void init(ArrayList<NetCDFFile> ncdfal) throws Exception { // make a NetCDFFile object from the NcML for each granule for (NetCDFFile n : ncdfal) { NetcdfFile ncfile = n.getNetCDFFile(); nclist.add(ncfile); } granuleCount = nclist.size(); for (int ncIdx = 0; ncIdx < nclist.size(); ncIdx++) { NetcdfFile ncfile = nclist.get(ncIdx); HashMap<String, Variable> varMap = new HashMap<String, Variable>(); HashMap<String, String[]> varDimNames = new HashMap<String, String[]>(); HashMap<String, int[]> varDimLengths = new HashMap<String, int[]>(); HashMap<String, Class> varDataType = new HashMap<String, Class>(); Iterator varIter = ncfile.getVariables().iterator(); while (varIter.hasNext()) { Variable var = (Variable) varIter.next(); if (var instanceof Structure) { analyzeStructure((Structure) var, varMap, varDimNames, varDimLengths, varDataType); continue; } int rank = var.getRank(); String varName = var.getName(); varMap.put(var.getName(), var); Iterator dimIter = var.getDimensions().iterator(); String[] dimNames = new String[rank]; int[] dimLengths = new int[rank]; int cnt = 0; while (dimIter.hasNext()) { Dimension dim = (Dimension) dimIter.next(); String dimName = dim.getName(); logger.trace("GranuleAggregation init, variable: " + varName + ", dimension name: " + dimName); if (dimName == null) dimName = "dim"+cnt; dimNames[cnt] = dimName; dimLengths[cnt] = dim.getLength(); cnt++; } // XXX TJJ - temp hack. How to know for certain the InTrack dimension? dimLengths[inTrackIndex] = dimLengths[inTrackIndex] * granuleCount; varDimNames.put(varName, dimNames); varDimLengths.put(varName, dimLengths); varDataType.put(varName, var.getDataType().getPrimitiveClassType()); } // add the new hashmaps to our enclosing lists varMapList.add(varMap); varDimNamesList.add(varDimNames); varDimLengthsList.add(varDimLengths); varDataTypeList.add(varDataType); } } void analyzeStructure(Structure var, HashMap<String, Variable> varMap, HashMap<String, String[]> varDimNames, HashMap<String, int[]> varDimLengths, HashMap<String, Class> varDataType) throws Exception { if ((var.getShape()).length == 0) { return; } String varName = var.getName(); String[] dimNames = new String[2]; int[] dimLengths = new int[2]; List vlist = var.getVariables(); int cnt = 0; dimLengths[0] = (var.getShape())[0]; dimNames[0] = "dim"+cnt; cnt++; StructureData sData = var.readStructure(0); List memList = sData.getMembers(); dimLengths[1] = memList.size(); dimNames[1] = "dim"+cnt; varDimNames.put(varName, dimNames); varDimLengths.put(varName, dimLengths); varMap.put(var.getName(), var); StructureMembers sMembers = sData.getStructureMembers(); Object obj = sData.getScalarObject(sMembers.getMember(0)); varDataType.put(varName, obj.getClass()); } private synchronized Object readArray(String array_name, int[] start, int[] count, int[] stride) throws Exception { // how many dimensions are we dealing with int dimensionCount = start.length; // which granules will we be dealing with? int loGranuleId = start[inTrackIndex] / granuleLength; int hiGranuleId = (start[inTrackIndex] + ((count[inTrackIndex] - 1) * stride[inTrackIndex])) / granuleLength; // next, we break out the offsets, counts, and strides for each granule int granuleSpan = hiGranuleId - loGranuleId + 1; logger.trace("readArray req, loGran: " + loGranuleId + ", hiGran: " + hiGranuleId + ", granule span: " + granuleSpan + ", dimCount: " + dimensionCount); for (int i = 0; i < dimensionCount; i++) { logger.trace("start[" + i + "]: " + start[i]); logger.trace("count[" + i + "]: " + count[i]); logger.trace("stride[" + i + "]: " + stride[i]); } int [][] startSet = new int [granuleSpan][dimensionCount]; int [][] countSet = new int [granuleSpan][dimensionCount]; int [][] strideSet = new int [granuleSpan][dimensionCount]; int countSubtotal = 0; // this part is a little tricky - set the values for each granule we need to access for this read int granuleNumber = loGranuleId; for (int i = 0; i < granuleSpan; i++) { granuleNumber++; for (int j = 0; j < dimensionCount; j++) { // for all indeces other than the inTrackIndex, the numbers match what was passed in if (j != inTrackIndex) { startSet[i][j] = start[j]; countSet[i][j] = count[j] * stride[j]; strideSet[i][j] = stride[j]; } else { // for the inTrackIndex, it's not so easy... // for first granule, start is what's passed in if (i == 0) { startSet[i][j] = start[j] % granuleLength; } else { startSet[i][j] = ((granuleLength * granuleNumber) - start[j]) % stride[j]; } // counts may be different for start, end, and middle granules if (i == 0) { // is this the first and only granule? if (granuleSpan == 1) { countSet[i][j] = count[j] * stride[j]; // or is this the first of multiple granules... } else { - if (((granuleLength * granuleNumber) - start[j]) < (count[j] * stride[j])) { - countSet[i][j] = ((granuleLength * granuleNumber) - start[j]) * stride[j]; + if (((granuleLength * granuleNumber) - start[j]) < (count[j] * stride[j])) { + countSet[i][j] = ((granuleLength * granuleNumber) - start[j]); } else { countSet[i][j] = count[j] * stride[j]; } countSubtotal += countSet[i][j]; } } else { // middle grandules if (i < (granuleSpan - 1)) { - countSet[i][j] = granuleLength * stride[j]; + countSet[i][j] = granuleLength; countSubtotal += countSet[i][j]; } else { // the end granule - countSet[i][j] = count[j] - countSubtotal; + countSet[i][j] = (count[j] * stride[j]) - countSubtotal; } } // luckily, stride never changes strideSet[i][j] = stride[j]; } } } int totalLength = 0; int rangeListCount = 0; ArrayList<Array> arrayList = new ArrayList<Array>(); for (int granuleIdx = 0; granuleIdx < granuleCount; granuleIdx++) { if ((granuleIdx >= loGranuleId) && (granuleIdx <= hiGranuleId)) { Variable var = varMapList.get(loGranuleId + (granuleIdx-loGranuleId)).get(array_name); if (var instanceof Structure) { // what to do here? } else { ArrayList<Range> rangeList = new ArrayList<Range>(); for (int dimensionIdx = 0; dimensionIdx < dimensionCount; dimensionIdx++) { logger.trace("Creating new Range: " + startSet[rangeListCount][dimensionIdx] + ", " + (startSet[rangeListCount][dimensionIdx] + countSet[rangeListCount][dimensionIdx] - 1) + ", " + strideSet[rangeListCount][dimensionIdx]); Range range = new Range( startSet[rangeListCount][dimensionIdx], startSet[rangeListCount][dimensionIdx] + countSet[rangeListCount][dimensionIdx] - 1, strideSet[rangeListCount][dimensionIdx] ); rangeList.add(dimensionIdx, range); } rangeListCount++; Array subarray = var.read(rangeList); //dataType = subarray.getElementType(); totalLength += subarray.getSize(); arrayList.add(subarray); } // put in an empty ArrayList placeholder to retain a slot for each granule } else { Array emptyArray = null; arrayList.add(emptyArray); } } // last, concatenate the individual NetCDF arrays pulled out //Object o = java.lang.reflect.Array.newInstance(getArrayType(array_name), totalLength); Class outType; Class arrayType = getArrayType(array_name); RangeProcessor rngProcessor = varToRangeProcessor.get(array_name); if (rngProcessor == null) { outType = getArrayType(array_name); } else { outType = java.lang.Float.TYPE; } Object o = java.lang.reflect.Array.newInstance(outType, totalLength); int destPos = 0; int granIdx = 0; for (Array a : arrayList) { if (a != null) { Object primArray = a.copyTo1DJavaArray(); primArray = processArray(array_name, arrayType, granIdx, primArray, rngProcessor); System.arraycopy(primArray, 0, o, destPos, (int) a.getSize()); destPos += a.getSize(); } granIdx++; } return o; } public HashMap getVarMap() { return varMapList.get(0); } public ArrayList<NetCDFFile> getReaders() { return this.ncdfal; } /* pass individual granule pieces just read from dataset through the RangeProcessor */ private Object processArray(String array_name, Class arrayType, int granIdx, Object values, RangeProcessor rngProcessor) { if (rngProcessor == null) { return values; } else { ((AggregationRangeProcessor)rngProcessor).setIndex(granIdx); Object outArray = null; if (arrayType == Short.TYPE) { outArray = rngProcessor.processRange((short[])values, null); } else if (arrayType == Byte.TYPE) { outArray = rngProcessor.processRange((byte[])values, null); } else if (arrayType == Float.TYPE) { outArray = rngProcessor.processRange((float[])values, null); } else if (arrayType == Double.TYPE) { outArray = rngProcessor.processRange((double[])values, null); } return outArray; } } /* Application can supply a RangeProcessor for an variable 'arrayName' */ public void addRangeProcessor(String arrayName, RangeProcessor rangeProcessor) { varToRangeProcessor.put(arrayName, rangeProcessor); } }
false
true
private synchronized Object readArray(String array_name, int[] start, int[] count, int[] stride) throws Exception { // how many dimensions are we dealing with int dimensionCount = start.length; // which granules will we be dealing with? int loGranuleId = start[inTrackIndex] / granuleLength; int hiGranuleId = (start[inTrackIndex] + ((count[inTrackIndex] - 1) * stride[inTrackIndex])) / granuleLength; // next, we break out the offsets, counts, and strides for each granule int granuleSpan = hiGranuleId - loGranuleId + 1; logger.trace("readArray req, loGran: " + loGranuleId + ", hiGran: " + hiGranuleId + ", granule span: " + granuleSpan + ", dimCount: " + dimensionCount); for (int i = 0; i < dimensionCount; i++) { logger.trace("start[" + i + "]: " + start[i]); logger.trace("count[" + i + "]: " + count[i]); logger.trace("stride[" + i + "]: " + stride[i]); } int [][] startSet = new int [granuleSpan][dimensionCount]; int [][] countSet = new int [granuleSpan][dimensionCount]; int [][] strideSet = new int [granuleSpan][dimensionCount]; int countSubtotal = 0; // this part is a little tricky - set the values for each granule we need to access for this read int granuleNumber = loGranuleId; for (int i = 0; i < granuleSpan; i++) { granuleNumber++; for (int j = 0; j < dimensionCount; j++) { // for all indeces other than the inTrackIndex, the numbers match what was passed in if (j != inTrackIndex) { startSet[i][j] = start[j]; countSet[i][j] = count[j] * stride[j]; strideSet[i][j] = stride[j]; } else { // for the inTrackIndex, it's not so easy... // for first granule, start is what's passed in if (i == 0) { startSet[i][j] = start[j] % granuleLength; } else { startSet[i][j] = ((granuleLength * granuleNumber) - start[j]) % stride[j]; } // counts may be different for start, end, and middle granules if (i == 0) { // is this the first and only granule? if (granuleSpan == 1) { countSet[i][j] = count[j] * stride[j]; // or is this the first of multiple granules... } else { if (((granuleLength * granuleNumber) - start[j]) < (count[j] * stride[j])) { countSet[i][j] = ((granuleLength * granuleNumber) - start[j]) * stride[j]; } else { countSet[i][j] = count[j] * stride[j]; } countSubtotal += countSet[i][j]; } } else { // middle grandules if (i < (granuleSpan - 1)) { countSet[i][j] = granuleLength * stride[j]; countSubtotal += countSet[i][j]; } else { // the end granule countSet[i][j] = count[j] - countSubtotal; } } // luckily, stride never changes strideSet[i][j] = stride[j]; } } } int totalLength = 0; int rangeListCount = 0; ArrayList<Array> arrayList = new ArrayList<Array>(); for (int granuleIdx = 0; granuleIdx < granuleCount; granuleIdx++) { if ((granuleIdx >= loGranuleId) && (granuleIdx <= hiGranuleId)) { Variable var = varMapList.get(loGranuleId + (granuleIdx-loGranuleId)).get(array_name); if (var instanceof Structure) { // what to do here? } else { ArrayList<Range> rangeList = new ArrayList<Range>(); for (int dimensionIdx = 0; dimensionIdx < dimensionCount; dimensionIdx++) { logger.trace("Creating new Range: " + startSet[rangeListCount][dimensionIdx] + ", " + (startSet[rangeListCount][dimensionIdx] + countSet[rangeListCount][dimensionIdx] - 1) + ", " + strideSet[rangeListCount][dimensionIdx]); Range range = new Range( startSet[rangeListCount][dimensionIdx], startSet[rangeListCount][dimensionIdx] + countSet[rangeListCount][dimensionIdx] - 1, strideSet[rangeListCount][dimensionIdx] ); rangeList.add(dimensionIdx, range); } rangeListCount++; Array subarray = var.read(rangeList); //dataType = subarray.getElementType(); totalLength += subarray.getSize(); arrayList.add(subarray); } // put in an empty ArrayList placeholder to retain a slot for each granule } else { Array emptyArray = null; arrayList.add(emptyArray); } } // last, concatenate the individual NetCDF arrays pulled out //Object o = java.lang.reflect.Array.newInstance(getArrayType(array_name), totalLength); Class outType; Class arrayType = getArrayType(array_name); RangeProcessor rngProcessor = varToRangeProcessor.get(array_name); if (rngProcessor == null) { outType = getArrayType(array_name); } else { outType = java.lang.Float.TYPE; } Object o = java.lang.reflect.Array.newInstance(outType, totalLength); int destPos = 0; int granIdx = 0; for (Array a : arrayList) { if (a != null) { Object primArray = a.copyTo1DJavaArray(); primArray = processArray(array_name, arrayType, granIdx, primArray, rngProcessor); System.arraycopy(primArray, 0, o, destPos, (int) a.getSize()); destPos += a.getSize(); } granIdx++; } return o; }
private synchronized Object readArray(String array_name, int[] start, int[] count, int[] stride) throws Exception { // how many dimensions are we dealing with int dimensionCount = start.length; // which granules will we be dealing with? int loGranuleId = start[inTrackIndex] / granuleLength; int hiGranuleId = (start[inTrackIndex] + ((count[inTrackIndex] - 1) * stride[inTrackIndex])) / granuleLength; // next, we break out the offsets, counts, and strides for each granule int granuleSpan = hiGranuleId - loGranuleId + 1; logger.trace("readArray req, loGran: " + loGranuleId + ", hiGran: " + hiGranuleId + ", granule span: " + granuleSpan + ", dimCount: " + dimensionCount); for (int i = 0; i < dimensionCount; i++) { logger.trace("start[" + i + "]: " + start[i]); logger.trace("count[" + i + "]: " + count[i]); logger.trace("stride[" + i + "]: " + stride[i]); } int [][] startSet = new int [granuleSpan][dimensionCount]; int [][] countSet = new int [granuleSpan][dimensionCount]; int [][] strideSet = new int [granuleSpan][dimensionCount]; int countSubtotal = 0; // this part is a little tricky - set the values for each granule we need to access for this read int granuleNumber = loGranuleId; for (int i = 0; i < granuleSpan; i++) { granuleNumber++; for (int j = 0; j < dimensionCount; j++) { // for all indeces other than the inTrackIndex, the numbers match what was passed in if (j != inTrackIndex) { startSet[i][j] = start[j]; countSet[i][j] = count[j] * stride[j]; strideSet[i][j] = stride[j]; } else { // for the inTrackIndex, it's not so easy... // for first granule, start is what's passed in if (i == 0) { startSet[i][j] = start[j] % granuleLength; } else { startSet[i][j] = ((granuleLength * granuleNumber) - start[j]) % stride[j]; } // counts may be different for start, end, and middle granules if (i == 0) { // is this the first and only granule? if (granuleSpan == 1) { countSet[i][j] = count[j] * stride[j]; // or is this the first of multiple granules... } else { if (((granuleLength * granuleNumber) - start[j]) < (count[j] * stride[j])) { countSet[i][j] = ((granuleLength * granuleNumber) - start[j]); } else { countSet[i][j] = count[j] * stride[j]; } countSubtotal += countSet[i][j]; } } else { // middle grandules if (i < (granuleSpan - 1)) { countSet[i][j] = granuleLength; countSubtotal += countSet[i][j]; } else { // the end granule countSet[i][j] = (count[j] * stride[j]) - countSubtotal; } } // luckily, stride never changes strideSet[i][j] = stride[j]; } } } int totalLength = 0; int rangeListCount = 0; ArrayList<Array> arrayList = new ArrayList<Array>(); for (int granuleIdx = 0; granuleIdx < granuleCount; granuleIdx++) { if ((granuleIdx >= loGranuleId) && (granuleIdx <= hiGranuleId)) { Variable var = varMapList.get(loGranuleId + (granuleIdx-loGranuleId)).get(array_name); if (var instanceof Structure) { // what to do here? } else { ArrayList<Range> rangeList = new ArrayList<Range>(); for (int dimensionIdx = 0; dimensionIdx < dimensionCount; dimensionIdx++) { logger.trace("Creating new Range: " + startSet[rangeListCount][dimensionIdx] + ", " + (startSet[rangeListCount][dimensionIdx] + countSet[rangeListCount][dimensionIdx] - 1) + ", " + strideSet[rangeListCount][dimensionIdx]); Range range = new Range( startSet[rangeListCount][dimensionIdx], startSet[rangeListCount][dimensionIdx] + countSet[rangeListCount][dimensionIdx] - 1, strideSet[rangeListCount][dimensionIdx] ); rangeList.add(dimensionIdx, range); } rangeListCount++; Array subarray = var.read(rangeList); //dataType = subarray.getElementType(); totalLength += subarray.getSize(); arrayList.add(subarray); } // put in an empty ArrayList placeholder to retain a slot for each granule } else { Array emptyArray = null; arrayList.add(emptyArray); } } // last, concatenate the individual NetCDF arrays pulled out //Object o = java.lang.reflect.Array.newInstance(getArrayType(array_name), totalLength); Class outType; Class arrayType = getArrayType(array_name); RangeProcessor rngProcessor = varToRangeProcessor.get(array_name); if (rngProcessor == null) { outType = getArrayType(array_name); } else { outType = java.lang.Float.TYPE; } Object o = java.lang.reflect.Array.newInstance(outType, totalLength); int destPos = 0; int granIdx = 0; for (Array a : arrayList) { if (a != null) { Object primArray = a.copyTo1DJavaArray(); primArray = processArray(array_name, arrayType, granIdx, primArray, rngProcessor); System.arraycopy(primArray, 0, o, destPos, (int) a.getSize()); destPos += a.getSize(); } granIdx++; } return o; }
diff --git a/src/commands/Attack.java b/src/commands/Attack.java index 9feedfd..6449bd0 100644 --- a/src/commands/Attack.java +++ b/src/commands/Attack.java @@ -1,110 +1,115 @@ package commands; import graphics.Animation; import actors.Actor; import actors.Player; public class Attack extends Command { final int base = 168; //this is the base hit chance value /** * Constructs a basic physical attack command * @param a * @param t */ public Attack(Actor a) { anim = new Animation("attack"); name = "Attack"; invoker = a; speedBonus = 25; } /** * Executes the attack */ @Override public void execute() { //make sure the animation is in relation to the target sprite - anim.setRelation(invoker.getTarget().getSprite()); + if (anim.getRelationType() == 2) + anim.setRelation(invoker.getSprite()); + else if (anim.getRelationType() == 1) + anim.setRelation(invoker.getTarget().getSprite()); + else + anim.setRelation(null); //reset damage damage = 0; hits = (1+(invoker.getAcc()/32))*1; if (!invoker.getTarget().getAlive()) return; /* * Calculate the chance of hitting * depending on the skill of the attacker, multiple hits * may land and do damage to the target */ int H = invoker.getAcc(); int E = invoker.getTarget().getEvd(); int chance = base + H - E; int hit = (int)(Math.random()*200); if (hit < chance) { /* Weapons not yet implemented if (invoker instanceof Player) db.isCritical((hit < ((Player)invoker).getWeapon().getCrit())); else db.isCritical(dunno yet); */ int amount = calculateDamage(false); for (int i = 0; i < hits; i++) damage += amount; } else hits = 0; invoker.getTarget().setHP(invoker.getTarget().getHP()-damage); //change display tag name = ""; if (hits > 1) name = hits + " hits"; } /** * Returns the name of the command */ @Override public String toString() { return name; } /** * Reset the name after the turn has been executed so it displays * properly in the menu */ @Override public void reset() { super.reset(); name = "Attack"; } /** * Calculates the damage an attack will do */ @Override protected int calculateDamage(boolean critical) { int D; D = (int)((Math.random()+1)*(invoker.getStr()/2))+1; //Black belts are special that their attack is their level*2 when unarmed if (invoker instanceof Player) if (((Player)invoker).getJobName().equals("Bl. BELT")) D = invoker.getLevel()*2; int A = invoker.getTarget().getDef(); return Math.max(1, D * (critical?2:1) - A); } }
true
true
public void execute() { //make sure the animation is in relation to the target sprite anim.setRelation(invoker.getTarget().getSprite()); //reset damage damage = 0; hits = (1+(invoker.getAcc()/32))*1; if (!invoker.getTarget().getAlive()) return; /* * Calculate the chance of hitting * depending on the skill of the attacker, multiple hits * may land and do damage to the target */ int H = invoker.getAcc(); int E = invoker.getTarget().getEvd(); int chance = base + H - E; int hit = (int)(Math.random()*200); if (hit < chance) { /* Weapons not yet implemented if (invoker instanceof Player) db.isCritical((hit < ((Player)invoker).getWeapon().getCrit())); else db.isCritical(dunno yet); */ int amount = calculateDamage(false); for (int i = 0; i < hits; i++) damage += amount; } else hits = 0; invoker.getTarget().setHP(invoker.getTarget().getHP()-damage); //change display tag name = ""; if (hits > 1) name = hits + " hits"; }
public void execute() { //make sure the animation is in relation to the target sprite if (anim.getRelationType() == 2) anim.setRelation(invoker.getSprite()); else if (anim.getRelationType() == 1) anim.setRelation(invoker.getTarget().getSprite()); else anim.setRelation(null); //reset damage damage = 0; hits = (1+(invoker.getAcc()/32))*1; if (!invoker.getTarget().getAlive()) return; /* * Calculate the chance of hitting * depending on the skill of the attacker, multiple hits * may land and do damage to the target */ int H = invoker.getAcc(); int E = invoker.getTarget().getEvd(); int chance = base + H - E; int hit = (int)(Math.random()*200); if (hit < chance) { /* Weapons not yet implemented if (invoker instanceof Player) db.isCritical((hit < ((Player)invoker).getWeapon().getCrit())); else db.isCritical(dunno yet); */ int amount = calculateDamage(false); for (int i = 0; i < hits; i++) damage += amount; } else hits = 0; invoker.getTarget().setHP(invoker.getTarget().getHP()-damage); //change display tag name = ""; if (hits > 1) name = hits + " hits"; }
diff --git a/src/org/fife/rsta/ac/js/resolver/JavaScriptCompletionResolver.java b/src/org/fife/rsta/ac/js/resolver/JavaScriptCompletionResolver.java index 7b2b88c..edf7322 100644 --- a/src/org/fife/rsta/ac/js/resolver/JavaScriptCompletionResolver.java +++ b/src/org/fife/rsta/ac/js/resolver/JavaScriptCompletionResolver.java @@ -1,484 +1,489 @@ package org.fife.rsta.ac.js.resolver; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import org.fife.rsta.ac.java.classreader.ClassFile; import org.fife.rsta.ac.js.JavaScriptHelper; import org.fife.rsta.ac.js.JavaScriptParser; import org.fife.rsta.ac.js.Logger; import org.fife.rsta.ac.js.SourceCompletionProvider; import org.fife.rsta.ac.js.ast.JavaScriptFunctionDeclaration; import org.fife.rsta.ac.js.ast.jsType.JavaScriptType; import org.fife.rsta.ac.js.ast.type.TypeDeclaration; import org.fife.rsta.ac.js.ast.type.TypeDeclarationFactory; import org.fife.rsta.ac.js.completion.JSCompletion; import org.fife.rsta.ac.js.completion.JSMethodData; import org.mozilla.javascript.CompilerEnvirons; import org.mozilla.javascript.Parser; import org.mozilla.javascript.Token; import org.mozilla.javascript.ast.AstNode; import org.mozilla.javascript.ast.AstRoot; import org.mozilla.javascript.ast.ExpressionStatement; import org.mozilla.javascript.ast.FunctionCall; import org.mozilla.javascript.ast.Name; import org.mozilla.javascript.ast.NodeVisitor; import org.mozilla.javascript.ast.PropertyGet; /** * Compiles the entered text using Rhino and tries to resolve the JavaScriptType * from the AstRoot e.g var a = ""; "" --> String JavaScriptType var b = * a.toString() a.toString --> String JavaScriptType * * etc.. * * Note, will resolve any type added to JavaScriptTypesFactory * */ public class JavaScriptCompletionResolver extends JavaScriptResolver { protected JavaScriptType lastJavaScriptType; protected String lastLookupName = null; /** * Standard ECMA JavaScript resolver * @param provider */ public JavaScriptCompletionResolver(SourceCompletionProvider provider) { super(provider); } /** * Compiles Text and resolves the type. * e.g * "Hello World".length; //resolve as a Number * * @param text to compile and resolve */ public JavaScriptType compileText(String text) throws IOException { CompilerEnvirons env = JavaScriptParser.createCompilerEnvironment(new JavaScriptParser.JSErrorReporter(), provider.getLanguageSupport()); String parseText = JavaScriptHelper.removeLastDotFromText(text); int charIndex = JavaScriptHelper.findIndexOfFirstOpeningBracket(parseText); env.setRecoverFromErrors(true); Parser parser = new Parser(env); StringReader r = new StringReader(parseText); AstRoot root = parser.parse(r, null, 0); CompilerNodeVisitor visitor = new CompilerNodeVisitor(charIndex == 0); root.visitAll(visitor); return lastJavaScriptType; } /** * Resolve node type to TypeDeclaration. Called instead of #compileText(String text) when document is already parsed * @param node AstNode to resolve * @return TypeDeclaration for node or null if not found. */ public TypeDeclaration resolveParamNode(String text) throws IOException { CompilerEnvirons env = JavaScriptParser.createCompilerEnvironment(new JavaScriptParser.JSErrorReporter(), provider.getLanguageSupport()); int charIndex = JavaScriptHelper.findIndexOfFirstOpeningBracket(text); env.setRecoverFromErrors(true); Parser parser = new Parser(env); StringReader r = new StringReader(text); AstRoot root = parser.parse(r, null, 0); CompilerNodeVisitor visitor = new CompilerNodeVisitor(charIndex == 0); root.visitAll(visitor); return lastJavaScriptType != null ? lastJavaScriptType.getType() : TypeDeclarationFactory.getDefaultTypeDeclaration(); } /** * Resolve node type to TypeDeclaration. Called instead of #compileText(String text) when document is already parsed * @param node AstNode to resolve * @return TypeDeclaration for node or null if not found. */ public TypeDeclaration resolveNode(AstNode node) { if(node == null) return TypeDeclarationFactory.getDefaultTypeDeclaration(); CompilerNodeVisitor visitor = new CompilerNodeVisitor(true); node.visit(visitor); return lastJavaScriptType != null ? lastJavaScriptType.getType() : TypeDeclarationFactory.getDefaultTypeDeclaration(); } /** * Resolve node type to TypeDeclaration * N.B called from <code>CompilerNodeVisitor.visit()</code> * * @param node AstNode to resolve * @return TypeDeclaration for node or null if not found. */ protected TypeDeclaration resolveNativeType(AstNode node) { return JavaScriptHelper.tokenToNativeTypeDeclaration(node, provider); } // TODO not sure how right this is, but is very tricky problem resolving // complex completions private class CompilerNodeVisitor implements NodeVisitor { private boolean ignoreParams; private HashSet paramNodes = new HashSet(); private CompilerNodeVisitor(boolean ignoreParams) { this.ignoreParams = ignoreParams; } public boolean visit(AstNode node) { Logger.log(JavaScriptHelper.convertNodeToSource(node)); Logger.log(node.shortName()); if(!validNode(node)) { //invalid node found, set last completion invalid and stop processing lastJavaScriptType = null; return false; } if (ignore(node, ignoreParams)) return true; JavaScriptType jsType = null; - TypeDeclaration dec = resolveNativeType(node); + TypeDeclaration dec = null; + //only resolve native type if last type is null + //otherwise it can be assumed that this is part of multi depth - e.g "".length.toString() + if(lastJavaScriptType == null) { + dec = resolveNativeType(node); + } if (dec != null) { // lookup JavaScript completions type jsType = provider.getJavaScriptTypesFactory().getCachedType( dec, provider.getJarManager(), provider, JavaScriptHelper.convertNodeToSource(node)); if (jsType != null) { lastJavaScriptType = jsType; // stop here return false; } } else if (lastJavaScriptType != null) { if (node.getType() == Token.NAME) { // lookup from source name jsType = lookupFromName(node, lastJavaScriptType); if (jsType == null) { // lookup name through the functions of // lastJavaScriptType jsType = lookupFunctionCompletion(node, lastJavaScriptType); } lastJavaScriptType = jsType; } } else if(node instanceof FunctionCall) { FunctionCall fn = (FunctionCall) node; String lookupText = createLookupString(fn); JavaScriptFunctionDeclaration funcDec = provider.getVariableResolver().findFunctionDeclaration(lookupText); if(funcDec != null) { jsType = provider.getJavaScriptTypesFactory().getCachedType( funcDec.getTypeDeclaration(), provider.getJarManager(), provider, JavaScriptHelper.convertNodeToSource(node)); if (jsType != null) { lastJavaScriptType = jsType; // stop here return false; } } } return true; } private boolean validNode(AstNode node) { switch(node.getType()) { case Token.NAME: return ((Name) node).getIdentifier() != null && ((Name) node).getIdentifier().length() > 0; } return true; } private String createLookupString(FunctionCall fn) { StringBuffer sb = new StringBuffer(); String name = ""; switch(fn.getTarget().getType()) { case Token.NAME : name = ((Name) fn.getTarget()).getIdentifier(); break; } sb.append(name); sb.append("("); for(Iterator i = fn.getArguments().iterator(); i.hasNext();) { i.next(); sb.append("p"); if(i.hasNext()) sb.append(","); } sb.append(")"); return sb.toString(); } /** * Test node to check whether to ignore resolving, this is for * parameters * * @param node node to test * @return true to ignore */ private boolean ignore(AstNode node, boolean ignoreParams) { switch (node.getType()) { // ignore errors e.g if statement - if(a. //no closing brace case Token.EXPR_VOID: case Token.EXPR_RESULT: return ((ExpressionStatement) node).getExpression() .getType() == Token.ERROR; case Token.ERROR: case Token.GETPROP: case Token.SCRIPT: return true; default: { if (isParameter(node)) { collectAllNodes(node); // everything within this node // is a parameter return ignoreParams; } break; } } if (JavaScriptHelper.isInfixOnly(node)) return true; return false; } /** * Get all nodes within AstNode and add to an ArrayList * * @param node */ private void collectAllNodes(AstNode node) { if (node.getType() == Token.CALL) { // collect all argument nodes FunctionCall call = (FunctionCall) node; for (Iterator args = call.getArguments().iterator(); args .hasNext();) { AstNode arg = (AstNode) args.next(); VisitorAll all = new VisitorAll(); arg.visit(all); paramNodes.addAll(all.getAllNodes()); } } } /** * Check the function that a name may belong to contains this actual * parameter * * @param node Node to check * @return true if the function contains the parameter */ private boolean isParameter(AstNode node) { if (paramNodes.contains(node)) return true; // get all params from this function too FunctionCall fc = JavaScriptHelper.findFunctionCallFromNode(node); if (fc != null && !(node == fc)) { collectAllNodes(fc); if (paramNodes.contains(node)) { return true; } } return false; } } /** * Lookup the name of the node within the last JavaScript type. e.g var a = * 1; var b = a.MAX_VALUE; looks up MAX_VALUE within NumberLiteral a where a * is resolve before as a JavaScript Number; * * @param node * @param lastJavaScriptType * @return */ protected JavaScriptType lookupFromName(AstNode node, JavaScriptType lastJavaScriptType) { JavaScriptType javaScriptType = null; if (lastJavaScriptType != null) { String lookupText = null; switch (node.getType()) { case Token.NAME: lookupText = ((Name) node).getIdentifier(); break; } if (lookupText == null) { // just try the source lookupText = node.toSource(); } javaScriptType = lookupJavaScriptType(lastJavaScriptType, lookupText); } return javaScriptType; } /** * Lookup the function name of the node within the last JavaScript type. e.g * var a = ""; var b = a.toString(); looks up toString() within * StringLiteral a where a is resolve before as a JavaScript String; * * @param node * @param lastJavaScriptType * @return */ protected JavaScriptType lookupFunctionCompletion(AstNode node, JavaScriptType lastJavaScriptType) { JavaScriptType javaScriptType = null; if (lastJavaScriptType != null) { String lookupText = JavaScriptHelper.getFunctionNameLookup(node, provider); javaScriptType = lookupJavaScriptType(lastJavaScriptType, lookupText); } // return last type return javaScriptType; } public String getLookupText(JSMethodData method, String name) { StringBuffer sb = new StringBuffer(name); sb.append('('); int count = method.getParameterCount(); for (int i = 0; i < count; i++) { sb.append("p"); if (i < count - 1) { sb.append(","); } } sb.append(')'); return sb.toString(); } public String getFunctionNameLookup(FunctionCall call, SourceCompletionProvider provider) { if (call != null) { StringBuffer sb = new StringBuffer(); if (call.getTarget() instanceof PropertyGet) { PropertyGet get = (PropertyGet) call.getTarget(); sb.append(get.getProperty().getIdentifier()); } sb.append("("); int count = call.getArguments().size(); for (int i = 0; i < count; i++) { sb.append("p"); if (i < count - 1) { sb.append(","); } } sb.append(")"); return sb.toString(); } return null; } private JavaScriptType lookupJavaScriptType( JavaScriptType lastJavaScriptType, String lookupText) { JavaScriptType javaScriptType = null; if (lookupText != null && !lookupText.equals(lastLookupName)) { // look up JSCompletion JSCompletion completion = lastJavaScriptType .getCompletion(lookupText, provider); if (completion != null) { String type = completion.getType(true); if (type != null) { TypeDeclaration newType = TypeDeclarationFactory.Instance() .getTypeDeclaration(type); if (newType != null) { javaScriptType = provider.getJavaScriptTypesFactory() .getCachedType(newType, provider.getJarManager(), provider, lookupText); } else { javaScriptType = createNewTypeDeclaration(provider, type, lookupText); } } } } lastLookupName = lookupText; return javaScriptType; } /** * Creates a new JavaScriptType based on the String type * @param provider SourceCompletionProvider * @param type type of JavaScript type to create e.g java.sql.Connection * @param text Text entered from the user to resolve the node. This will be null if resolveNode(AstNode node) is called * @return */ private JavaScriptType createNewTypeDeclaration( SourceCompletionProvider provider, String type, String text) { if (provider.getJavaScriptTypesFactory() != null) { ClassFile cf = provider.getJarManager().getClassEntry(type); TypeDeclaration newType = null; if (cf != null) { newType = provider.getJavaScriptTypesFactory() .createNewTypeDeclaration(cf, false); return provider.getJavaScriptTypesFactory() .getCachedType(newType, provider.getJarManager(), provider, text); } } return null; } /** * Visit all nodes in the AstNode tree and all to a single list */ private class VisitorAll implements NodeVisitor { private ArrayList all = new ArrayList(); public boolean visit(AstNode node) { all.add(node); return true; } public ArrayList getAllNodes() { return all; } } }
true
true
public boolean visit(AstNode node) { Logger.log(JavaScriptHelper.convertNodeToSource(node)); Logger.log(node.shortName()); if(!validNode(node)) { //invalid node found, set last completion invalid and stop processing lastJavaScriptType = null; return false; } if (ignore(node, ignoreParams)) return true; JavaScriptType jsType = null; TypeDeclaration dec = resolveNativeType(node); if (dec != null) { // lookup JavaScript completions type jsType = provider.getJavaScriptTypesFactory().getCachedType( dec, provider.getJarManager(), provider, JavaScriptHelper.convertNodeToSource(node)); if (jsType != null) { lastJavaScriptType = jsType; // stop here return false; } } else if (lastJavaScriptType != null) { if (node.getType() == Token.NAME) { // lookup from source name jsType = lookupFromName(node, lastJavaScriptType); if (jsType == null) { // lookup name through the functions of // lastJavaScriptType jsType = lookupFunctionCompletion(node, lastJavaScriptType); } lastJavaScriptType = jsType; } } else if(node instanceof FunctionCall) { FunctionCall fn = (FunctionCall) node; String lookupText = createLookupString(fn); JavaScriptFunctionDeclaration funcDec = provider.getVariableResolver().findFunctionDeclaration(lookupText); if(funcDec != null) { jsType = provider.getJavaScriptTypesFactory().getCachedType( funcDec.getTypeDeclaration(), provider.getJarManager(), provider, JavaScriptHelper.convertNodeToSource(node)); if (jsType != null) { lastJavaScriptType = jsType; // stop here return false; } } } return true; }
public boolean visit(AstNode node) { Logger.log(JavaScriptHelper.convertNodeToSource(node)); Logger.log(node.shortName()); if(!validNode(node)) { //invalid node found, set last completion invalid and stop processing lastJavaScriptType = null; return false; } if (ignore(node, ignoreParams)) return true; JavaScriptType jsType = null; TypeDeclaration dec = null; //only resolve native type if last type is null //otherwise it can be assumed that this is part of multi depth - e.g "".length.toString() if(lastJavaScriptType == null) { dec = resolveNativeType(node); } if (dec != null) { // lookup JavaScript completions type jsType = provider.getJavaScriptTypesFactory().getCachedType( dec, provider.getJarManager(), provider, JavaScriptHelper.convertNodeToSource(node)); if (jsType != null) { lastJavaScriptType = jsType; // stop here return false; } } else if (lastJavaScriptType != null) { if (node.getType() == Token.NAME) { // lookup from source name jsType = lookupFromName(node, lastJavaScriptType); if (jsType == null) { // lookup name through the functions of // lastJavaScriptType jsType = lookupFunctionCompletion(node, lastJavaScriptType); } lastJavaScriptType = jsType; } } else if(node instanceof FunctionCall) { FunctionCall fn = (FunctionCall) node; String lookupText = createLookupString(fn); JavaScriptFunctionDeclaration funcDec = provider.getVariableResolver().findFunctionDeclaration(lookupText); if(funcDec != null) { jsType = provider.getJavaScriptTypesFactory().getCachedType( funcDec.getTypeDeclaration(), provider.getJarManager(), provider, JavaScriptHelper.convertNodeToSource(node)); if (jsType != null) { lastJavaScriptType = jsType; // stop here return false; } } } return true; }
diff --git a/hale/eu.esdihumboldt.hale.core/src/eu/esdihumboldt/hale/core/io/project/model/Project.java b/hale/eu.esdihumboldt.hale.core/src/eu/esdihumboldt/hale/core/io/project/model/Project.java index 3ff1a93f2..7e73045d4 100644 --- a/hale/eu.esdihumboldt.hale.core/src/eu/esdihumboldt/hale/core/io/project/model/Project.java +++ b/hale/eu.esdihumboldt.hale.core/src/eu/esdihumboldt/hale/core/io/project/model/Project.java @@ -1,273 +1,274 @@ /* * HUMBOLDT: A Framework for Data Harmonisation and Service Integration. * EU Integrated Project #030962 01.10.2006 - 30.09.2010 * * For more information on the project, please refer to the this web site: * http://www.esdi-humboldt.eu * * LICENSE: For information on the license under which this program is * available, please refer to http:/www.esdi-humboldt.eu/license.html#core * (c) the HUMBOLDT Consortium, 2007 to 2011. */ package eu.esdihumboldt.hale.core.io.project.model; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.exolab.castor.mapping.Mapping; import org.exolab.castor.mapping.MappingException; import org.exolab.castor.xml.MarshalException; import org.exolab.castor.xml.Marshaller; import org.exolab.castor.xml.Unmarshaller; import org.exolab.castor.xml.ValidationException; import org.exolab.castor.xml.XMLContext; import org.osgi.framework.Version; import org.xml.sax.InputSource; /** * Represents a project. * @author Simon Templer */ public class Project { /** * Load a project from an input stream. * @param in the input stream * @return the project * * @throws MappingException if the mapping could not be loaded * @throws MarshalException if the project could not be read * @throws ValidationException if the input stream did not provide valid XML */ public static Project load(InputStream in) throws MappingException, MarshalException, ValidationException { Mapping mapping = new Mapping(Project.class.getClassLoader()); mapping.loadMapping(new InputSource( Project.class.getResourceAsStream("Project.xml"))); XMLContext context = new XMLContext(); context.addMapping(mapping); Unmarshaller unmarshaller = context.createUnmarshaller(); try { return (Project) unmarshaller.unmarshal(new InputSource(in)); } finally { try { in.close(); } catch (IOException e) { // ignore } } } /** * Save a project to an output stream. * @param project the project to save * @param out the output stream * @throws MappingException if the mapping could not be loaded * @throws ValidationException if the mapping is no valid XML * @throws MarshalException if the project could not be marshaled * @throws IOException if the output could not be written */ public static void save(Project project, OutputStream out) throws MappingException, MarshalException, ValidationException, IOException { Mapping mapping = new Mapping(Project.class.getClassLoader()); mapping.loadMapping(new InputSource( Project.class.getResourceAsStream("Project.xml"))); XMLContext context = new XMLContext(); context.setProperty("org.exolab.castor.indent", true); // enable indentation for marshaling as project files should be very small context.addMapping(mapping); Marshaller marshaller = context.createMarshaller(); - Writer writer = new BufferedWriter(new OutputStreamWriter(out)); +// marshaller.setEncoding("UTF-8"); XXX not possible using the XMLContext but UTF-8 seems to be default, see http://jira.codehaus.org/browse/CASTOR-2846 + Writer writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8")); try { marshaller.setWriter(writer); marshaller.marshal(project); } finally { try { writer.close(); } catch (IOException e) { // ignore } } } /** * The project name */ private String name; /** * The project author */ private String author; /** * The HALE version */ private Version haleVersion; /** * The date the project was created */ private Date created; /** * The date the project was modified */ private Date modified; /** * A project description */ private String description; /** * The configuration the project was saved with */ private IOConfiguration saveConfiguration; /** * I/O configurations */ private final List<IOConfiguration> configurations = new ArrayList<IOConfiguration>(); /** * Project properties */ private final Map<String, String> properties = new HashMap<String, String>(); /** * File names and classes of additional project files */ private final Map<String, Class<? extends ProjectFile>> files = new HashMap<String, Class<? extends ProjectFile>>(); /** * @return the configurations */ public List<IOConfiguration> getConfigurations() { return configurations; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the author */ public String getAuthor() { return author; } /** * @param author the author to set */ public void setAuthor(String author) { this.author = author; } /** * @return the haleVersion */ public Version getHaleVersion() { return haleVersion; } /** * @param haleVersion the haleVersion to set */ public void setHaleVersion(Version haleVersion) { this.haleVersion = haleVersion; } /** * @return the created */ public Date getCreated() { return created; } /** * @param created the created to set */ public void setCreated(Date created) { this.created = created; } /** * @return the modified */ public Date getModified() { return modified; } /** * @param modified the modified to set */ public void setModified(Date modified) { this.modified = modified; } /** * @return the properties */ public Map<String, String> getProperties() { return properties; } /** * @return the files */ public Map<String, Class<? extends ProjectFile>> getFiles() { return files; } /** * @return the saveConfiguration */ public IOConfiguration getSaveConfiguration() { return saveConfiguration; } /** * @param saveConfiguration the saveConfiguration to set */ public void setSaveConfiguration(IOConfiguration saveConfiguration) { this.saveConfiguration = saveConfiguration; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } }
true
true
public static void save(Project project, OutputStream out) throws MappingException, MarshalException, ValidationException, IOException { Mapping mapping = new Mapping(Project.class.getClassLoader()); mapping.loadMapping(new InputSource( Project.class.getResourceAsStream("Project.xml"))); XMLContext context = new XMLContext(); context.setProperty("org.exolab.castor.indent", true); // enable indentation for marshaling as project files should be very small context.addMapping(mapping); Marshaller marshaller = context.createMarshaller(); Writer writer = new BufferedWriter(new OutputStreamWriter(out)); try { marshaller.setWriter(writer); marshaller.marshal(project); } finally { try { writer.close(); } catch (IOException e) { // ignore } } }
public static void save(Project project, OutputStream out) throws MappingException, MarshalException, ValidationException, IOException { Mapping mapping = new Mapping(Project.class.getClassLoader()); mapping.loadMapping(new InputSource( Project.class.getResourceAsStream("Project.xml"))); XMLContext context = new XMLContext(); context.setProperty("org.exolab.castor.indent", true); // enable indentation for marshaling as project files should be very small context.addMapping(mapping); Marshaller marshaller = context.createMarshaller(); // marshaller.setEncoding("UTF-8"); XXX not possible using the XMLContext but UTF-8 seems to be default, see http://jira.codehaus.org/browse/CASTOR-2846 Writer writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8")); try { marshaller.setWriter(writer); marshaller.marshal(project); } finally { try { writer.close(); } catch (IOException e) { // ignore } } }
diff --git a/src/main/java/de/cismet/tools/gui/downloadmanager/DownloadManagerOptionsPanel.java b/src/main/java/de/cismet/tools/gui/downloadmanager/DownloadManagerOptionsPanel.java index 9e135e1..b24562b 100644 --- a/src/main/java/de/cismet/tools/gui/downloadmanager/DownloadManagerOptionsPanel.java +++ b/src/main/java/de/cismet/tools/gui/downloadmanager/DownloadManagerOptionsPanel.java @@ -1,440 +1,441 @@ /*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ /* * DownloadManagerOptionsPanel.java * * Created on 09.08.2011, 15:10:48 */ package de.cismet.tools.gui.downloadmanager; import org.apache.log4j.Logger; import org.jdom.Element; import org.openide.util.NbBundle; import org.openide.util.lookup.ServiceProvider; import java.io.File; import javax.swing.JFileChooser; import de.cismet.lookupoptions.AbstractOptionsPanel; import de.cismet.lookupoptions.OptionsPanelController; import de.cismet.tools.BrowserLauncher; import de.cismet.tools.configuration.NoWriteError; /** * DOCUMENT ME! * * @author jweintraut * @version $Revision$, $Date$ */ @ServiceProvider(service = OptionsPanelController.class) public class DownloadManagerOptionsPanel extends AbstractOptionsPanel implements OptionsPanelController { //~ Static fields/initializers --------------------------------------------- private static final Logger LOG = Logger.getLogger(DownloadManagerOptionsPanel.class); private static final String OPTION_NAME = NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.OPTION_NAME"); //~ Instance fields -------------------------------------------------------- private File downloadDestination; private boolean downloadDestinationChanged = false; private String jobname = ""; private boolean askForJobtitle = true; private boolean openAutomatically = true; private boolean closeAutomatically = true; private int parallelDownloads = 2; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnChangeDownloadDestination; private javax.swing.JCheckBox chkAskForJobname; private javax.swing.JFileChooser fileChooser; private javax.swing.Box.Filler filler1; private javax.swing.Box.Filler filler2; private org.jdesktop.swingx.JXHyperlink jhlDownloadDestination; private javax.swing.JLabel lblCloseAutomatically; private javax.swing.JLabel lblDestinationDirectory; private javax.swing.JLabel lblJobname; private javax.swing.JLabel lblOpenAutomatically; private javax.swing.JLabel lblParallelDownloads; private javax.swing.JPanel pnlCloseAutomatically; private javax.swing.JPanel pnlOpenAutomatically; private javax.swing.JRadioButton rdoCloseAutomatically; private javax.swing.JRadioButton rdoDontCloseAutomatically; private javax.swing.JRadioButton rdoDontOpenAutomatically; private javax.swing.JRadioButton rdoOpenAutomatically; private javax.swing.ButtonGroup rgrCloseAutomatically; private javax.swing.ButtonGroup rgrOpenAutomatically; private javax.swing.JSpinner spnParallelDownloads; private javax.swing.JTextField txtJobname; // End of variables declaration//GEN-END:variables //~ Constructors ----------------------------------------------------------- /** * Creates new form DownloadManagerOptionsPanel. */ public DownloadManagerOptionsPanel() { super(OPTION_NAME, DownloadManagerOptionsCategory.class); initComponents(); } //~ Methods ---------------------------------------------------------------- /** * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The * content of this method is always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; rgrOpenAutomatically = new javax.swing.ButtonGroup(); fileChooser = new javax.swing.JFileChooser(); rgrCloseAutomatically = new javax.swing.ButtonGroup(); lblDestinationDirectory = new javax.swing.JLabel(); jhlDownloadDestination = new org.jdesktop.swingx.JXHyperlink(); btnChangeDownloadDestination = new javax.swing.JButton(); lblJobname = new javax.swing.JLabel(); txtJobname = new javax.swing.JTextField(); chkAskForJobname = new javax.swing.JCheckBox(); lblOpenAutomatically = new javax.swing.JLabel(); filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 32767)); filler2 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 32767)); pnlOpenAutomatically = new javax.swing.JPanel(); rdoDontOpenAutomatically = new javax.swing.JRadioButton(); rdoOpenAutomatically = new javax.swing.JRadioButton(); lblCloseAutomatically = new javax.swing.JLabel(); lblParallelDownloads = new javax.swing.JLabel(); spnParallelDownloads = new javax.swing.JSpinner(); pnlCloseAutomatically = new javax.swing.JPanel(); rdoDontCloseAutomatically = new javax.swing.JRadioButton(); rdoCloseAutomatically = new javax.swing.JRadioButton(); fileChooser.setDialogTitle(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.fileChooser.dialogTitle")); // NOI18N fileChooser.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY); setLayout(new java.awt.GridBagLayout()); lblDestinationDirectory.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.lblDestinationDirectory.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; - gridBagConstraints.insets = new java.awt.Insets(8, 3, 8, 10); + gridBagConstraints.insets = new java.awt.Insets(8, 5, 3, 10); add(lblDestinationDirectory, gridBagConstraints); jhlDownloadDestination.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.jhlDownloadDestination.text")); // NOI18N jhlDownloadDestination.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { jhlDownloadDestinationActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; - gridBagConstraints.insets = new java.awt.Insets(8, 4, 8, 3); + gridBagConstraints.insets = new java.awt.Insets(8, 3, 3, 5); add(jhlDownloadDestination, gridBagConstraints); btnChangeDownloadDestination.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.btnChangeDownloadDestination.text")); // NOI18N btnChangeDownloadDestination.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnChangeDownloadDestinationActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; + gridBagConstraints.insets = new java.awt.Insets(8, 0, 3, 5); add(btnChangeDownloadDestination, gridBagConstraints); lblJobname.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.lblJobname.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; - gridBagConstraints.insets = new java.awt.Insets(8, 3, 8, 10); + gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 10); add(lblJobname, gridBagConstraints); txtJobname.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.txtJobname.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; - gridBagConstraints.insets = new java.awt.Insets(8, 4, 3, 3); + gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 5); add(txtJobname, gridBagConstraints); chkAskForJobname.setSelected(true); chkAskForJobname.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.chkAskForJobname.text")); // NOI18N chkAskForJobname.setFocusPainted(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_START; gridBagConstraints.weightx = 1.0; - gridBagConstraints.insets = new java.awt.Insets(3, 0, 8, 3); + gridBagConstraints.insets = new java.awt.Insets(0, 5, 3, 5); add(chkAskForJobname, gridBagConstraints); lblOpenAutomatically.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.lblOpenAutomatically.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; - gridBagConstraints.insets = new java.awt.Insets(8, 3, 8, 10); + gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 10); add(lblOpenAutomatically, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.gridheight = 7; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.weighty = 1.0; add(filler1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(filler2, gridBagConstraints); pnlOpenAutomatically.setLayout(new java.awt.GridBagLayout()); rgrOpenAutomatically.add(rdoDontOpenAutomatically); rdoDontOpenAutomatically.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.rdoDontOpenAutomatically.text")); // NOI18N rdoDontOpenAutomatically.setFocusPainted(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0); pnlOpenAutomatically.add(rdoDontOpenAutomatically, gridBagConstraints); rgrOpenAutomatically.add(rdoOpenAutomatically); rdoOpenAutomatically.setSelected(true); rdoOpenAutomatically.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.rdoOpenAutomatically.text")); // NOI18N rdoOpenAutomatically.setFocusPainted(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); pnlOpenAutomatically.add(rdoOpenAutomatically, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; - gridBagConstraints.insets = new java.awt.Insets(8, 0, 8, 3); + gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 5); add(pnlOpenAutomatically, gridBagConstraints); lblCloseAutomatically.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.lblCloseAutomatically.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; - gridBagConstraints.insets = new java.awt.Insets(8, 3, 8, 10); + gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 10); add(lblCloseAutomatically, gridBagConstraints); lblParallelDownloads.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.lblParallelDownloads.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; - gridBagConstraints.insets = new java.awt.Insets(8, 3, 8, 10); + gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 10); add(lblParallelDownloads, gridBagConstraints); spnParallelDownloads.setModel(new javax.swing.SpinnerNumberModel(2, 1, 50, 1)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; - gridBagConstraints.insets = new java.awt.Insets(8, 4, 3, 3); + gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 5); add(spnParallelDownloads, gridBagConstraints); pnlCloseAutomatically.setLayout(new java.awt.GridBagLayout()); rgrCloseAutomatically.add(rdoDontCloseAutomatically); rdoDontCloseAutomatically.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.rdoDontCloseAutomatically.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0); pnlCloseAutomatically.add(rdoDontCloseAutomatically, gridBagConstraints); rgrCloseAutomatically.add(rdoCloseAutomatically); rdoCloseAutomatically.setSelected(true); rdoCloseAutomatically.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.rdoCloseAutomatically.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); pnlCloseAutomatically.add(rdoCloseAutomatically, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; - gridBagConstraints.insets = new java.awt.Insets(8, 0, 8, 3); + gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 5); add(pnlCloseAutomatically, gridBagConstraints); } // </editor-fold>//GEN-END:initComponents /** * An event handler. * * @param evt The event. */ private void btnChangeDownloadDestinationActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnChangeDownloadDestinationActionPerformed final int returnValue = fileChooser.showOpenDialog(this); if (returnValue == JFileChooser.APPROVE_OPTION) { downloadDestination = fileChooser.getSelectedFile(); downloadDestinationChanged = true; jhlDownloadDestination.setText(downloadDestination.getAbsolutePath()); } } //GEN-LAST:event_btnChangeDownloadDestinationActionPerformed /** * An event handler. * * @param evt The event. */ private void jhlDownloadDestinationActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_jhlDownloadDestinationActionPerformed BrowserLauncher.openURLorFile(jhlDownloadDestination.getText()); } //GEN-LAST:event_jhlDownloadDestinationActionPerformed @Override public void update() { downloadDestination = DownloadManager.instance().getDestinationDirectory(); downloadDestinationChanged = false; jobname = DownloadManagerDialog.getJobname(); askForJobtitle = DownloadManagerDialog.isAskForJobname(); openAutomatically = DownloadManagerDialog.isOpenAutomatically(); closeAutomatically = DownloadManagerDialog.isCloseAutomatically(); parallelDownloads = DownloadManager.instance().getParallelDownloads(); jhlDownloadDestination.setText(downloadDestination.getAbsolutePath()); txtJobname.setText(jobname); chkAskForJobname.setSelected(askForJobtitle); rdoOpenAutomatically.setSelected(openAutomatically); rdoCloseAutomatically.setSelected(closeAutomatically); rdoDontOpenAutomatically.setSelected(!openAutomatically); spnParallelDownloads.setValue(parallelDownloads); } @Override public void applyChanges() { downloadDestinationChanged = false; jobname = txtJobname.getText(); askForJobtitle = chkAskForJobname.isSelected(); openAutomatically = rdoOpenAutomatically.isSelected(); closeAutomatically = rdoCloseAutomatically.isSelected(); parallelDownloads = (Integer)spnParallelDownloads.getValue(); DownloadManager.instance().setDestinationDirectory(downloadDestination); DownloadManagerDialog.setJobname(jobname); DownloadManagerDialog.setAskForJobname(askForJobtitle); DownloadManagerDialog.setOpenAutomatically(openAutomatically); DownloadManagerDialog.setCloseAutomatically(closeAutomatically); DownloadManager.instance().setParallelDownloads(parallelDownloads); } @Override public boolean isChanged() { boolean result = false; if (jobname != null) { result = downloadDestinationChanged || (!jobname.equals(txtJobname.getText())) || (!askForJobtitle == chkAskForJobname.isSelected()) || (!openAutomatically == rdoOpenAutomatically.isSelected()) || (!closeAutomatically == rdoCloseAutomatically.isSelected()) || (parallelDownloads != ((Integer)spnParallelDownloads.getValue()).intValue()); } return result; } @Override public String getTooltip() { return ""; } @Override public Element getConfiguration() throws NoWriteError { return DownloadManager.instance().getConfiguration(); } @Override public void configure(final Element parent) { DownloadManager.instance().configure(parent); } @Override public void masterConfigure(final Element parent) { DownloadManager.instance().masterConfigure(parent); } }
false
true
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; rgrOpenAutomatically = new javax.swing.ButtonGroup(); fileChooser = new javax.swing.JFileChooser(); rgrCloseAutomatically = new javax.swing.ButtonGroup(); lblDestinationDirectory = new javax.swing.JLabel(); jhlDownloadDestination = new org.jdesktop.swingx.JXHyperlink(); btnChangeDownloadDestination = new javax.swing.JButton(); lblJobname = new javax.swing.JLabel(); txtJobname = new javax.swing.JTextField(); chkAskForJobname = new javax.swing.JCheckBox(); lblOpenAutomatically = new javax.swing.JLabel(); filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 32767)); filler2 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 32767)); pnlOpenAutomatically = new javax.swing.JPanel(); rdoDontOpenAutomatically = new javax.swing.JRadioButton(); rdoOpenAutomatically = new javax.swing.JRadioButton(); lblCloseAutomatically = new javax.swing.JLabel(); lblParallelDownloads = new javax.swing.JLabel(); spnParallelDownloads = new javax.swing.JSpinner(); pnlCloseAutomatically = new javax.swing.JPanel(); rdoDontCloseAutomatically = new javax.swing.JRadioButton(); rdoCloseAutomatically = new javax.swing.JRadioButton(); fileChooser.setDialogTitle(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.fileChooser.dialogTitle")); // NOI18N fileChooser.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY); setLayout(new java.awt.GridBagLayout()); lblDestinationDirectory.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.lblDestinationDirectory.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(8, 3, 8, 10); add(lblDestinationDirectory, gridBagConstraints); jhlDownloadDestination.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.jhlDownloadDestination.text")); // NOI18N jhlDownloadDestination.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { jhlDownloadDestinationActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(8, 4, 8, 3); add(jhlDownloadDestination, gridBagConstraints); btnChangeDownloadDestination.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.btnChangeDownloadDestination.text")); // NOI18N btnChangeDownloadDestination.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnChangeDownloadDestinationActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; add(btnChangeDownloadDestination, gridBagConstraints); lblJobname.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.lblJobname.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(8, 3, 8, 10); add(lblJobname, gridBagConstraints); txtJobname.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.txtJobname.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(8, 4, 3, 3); add(txtJobname, gridBagConstraints); chkAskForJobname.setSelected(true); chkAskForJobname.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.chkAskForJobname.text")); // NOI18N chkAskForJobname.setFocusPainted(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(3, 0, 8, 3); add(chkAskForJobname, gridBagConstraints); lblOpenAutomatically.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.lblOpenAutomatically.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(8, 3, 8, 10); add(lblOpenAutomatically, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.gridheight = 7; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.weighty = 1.0; add(filler1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(filler2, gridBagConstraints); pnlOpenAutomatically.setLayout(new java.awt.GridBagLayout()); rgrOpenAutomatically.add(rdoDontOpenAutomatically); rdoDontOpenAutomatically.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.rdoDontOpenAutomatically.text")); // NOI18N rdoDontOpenAutomatically.setFocusPainted(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0); pnlOpenAutomatically.add(rdoDontOpenAutomatically, gridBagConstraints); rgrOpenAutomatically.add(rdoOpenAutomatically); rdoOpenAutomatically.setSelected(true); rdoOpenAutomatically.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.rdoOpenAutomatically.text")); // NOI18N rdoOpenAutomatically.setFocusPainted(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); pnlOpenAutomatically.add(rdoOpenAutomatically, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(8, 0, 8, 3); add(pnlOpenAutomatically, gridBagConstraints); lblCloseAutomatically.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.lblCloseAutomatically.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(8, 3, 8, 10); add(lblCloseAutomatically, gridBagConstraints); lblParallelDownloads.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.lblParallelDownloads.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.insets = new java.awt.Insets(8, 3, 8, 10); add(lblParallelDownloads, gridBagConstraints); spnParallelDownloads.setModel(new javax.swing.SpinnerNumberModel(2, 1, 50, 1)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(8, 4, 3, 3); add(spnParallelDownloads, gridBagConstraints); pnlCloseAutomatically.setLayout(new java.awt.GridBagLayout()); rgrCloseAutomatically.add(rdoDontCloseAutomatically); rdoDontCloseAutomatically.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.rdoDontCloseAutomatically.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0); pnlCloseAutomatically.add(rdoDontCloseAutomatically, gridBagConstraints); rgrCloseAutomatically.add(rdoCloseAutomatically); rdoCloseAutomatically.setSelected(true); rdoCloseAutomatically.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.rdoCloseAutomatically.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); pnlCloseAutomatically.add(rdoCloseAutomatically, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(8, 0, 8, 3); add(pnlCloseAutomatically, gridBagConstraints); } // </editor-fold>//GEN-END:initComponents
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; rgrOpenAutomatically = new javax.swing.ButtonGroup(); fileChooser = new javax.swing.JFileChooser(); rgrCloseAutomatically = new javax.swing.ButtonGroup(); lblDestinationDirectory = new javax.swing.JLabel(); jhlDownloadDestination = new org.jdesktop.swingx.JXHyperlink(); btnChangeDownloadDestination = new javax.swing.JButton(); lblJobname = new javax.swing.JLabel(); txtJobname = new javax.swing.JTextField(); chkAskForJobname = new javax.swing.JCheckBox(); lblOpenAutomatically = new javax.swing.JLabel(); filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 32767)); filler2 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 32767)); pnlOpenAutomatically = new javax.swing.JPanel(); rdoDontOpenAutomatically = new javax.swing.JRadioButton(); rdoOpenAutomatically = new javax.swing.JRadioButton(); lblCloseAutomatically = new javax.swing.JLabel(); lblParallelDownloads = new javax.swing.JLabel(); spnParallelDownloads = new javax.swing.JSpinner(); pnlCloseAutomatically = new javax.swing.JPanel(); rdoDontCloseAutomatically = new javax.swing.JRadioButton(); rdoCloseAutomatically = new javax.swing.JRadioButton(); fileChooser.setDialogTitle(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.fileChooser.dialogTitle")); // NOI18N fileChooser.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY); setLayout(new java.awt.GridBagLayout()); lblDestinationDirectory.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.lblDestinationDirectory.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(8, 5, 3, 10); add(lblDestinationDirectory, gridBagConstraints); jhlDownloadDestination.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.jhlDownloadDestination.text")); // NOI18N jhlDownloadDestination.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { jhlDownloadDestinationActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(8, 3, 3, 5); add(jhlDownloadDestination, gridBagConstraints); btnChangeDownloadDestination.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.btnChangeDownloadDestination.text")); // NOI18N btnChangeDownloadDestination.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnChangeDownloadDestinationActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(8, 0, 3, 5); add(btnChangeDownloadDestination, gridBagConstraints); lblJobname.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.lblJobname.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 10); add(lblJobname, gridBagConstraints); txtJobname.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.txtJobname.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 5); add(txtJobname, gridBagConstraints); chkAskForJobname.setSelected(true); chkAskForJobname.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.chkAskForJobname.text")); // NOI18N chkAskForJobname.setFocusPainted(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 3, 5); add(chkAskForJobname, gridBagConstraints); lblOpenAutomatically.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.lblOpenAutomatically.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 10); add(lblOpenAutomatically, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.gridheight = 7; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.weighty = 1.0; add(filler1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(filler2, gridBagConstraints); pnlOpenAutomatically.setLayout(new java.awt.GridBagLayout()); rgrOpenAutomatically.add(rdoDontOpenAutomatically); rdoDontOpenAutomatically.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.rdoDontOpenAutomatically.text")); // NOI18N rdoDontOpenAutomatically.setFocusPainted(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0); pnlOpenAutomatically.add(rdoDontOpenAutomatically, gridBagConstraints); rgrOpenAutomatically.add(rdoOpenAutomatically); rdoOpenAutomatically.setSelected(true); rdoOpenAutomatically.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.rdoOpenAutomatically.text")); // NOI18N rdoOpenAutomatically.setFocusPainted(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); pnlOpenAutomatically.add(rdoOpenAutomatically, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 5); add(pnlOpenAutomatically, gridBagConstraints); lblCloseAutomatically.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.lblCloseAutomatically.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 10); add(lblCloseAutomatically, gridBagConstraints); lblParallelDownloads.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.lblParallelDownloads.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 10); add(lblParallelDownloads, gridBagConstraints); spnParallelDownloads.setModel(new javax.swing.SpinnerNumberModel(2, 1, 50, 1)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 5); add(spnParallelDownloads, gridBagConstraints); pnlCloseAutomatically.setLayout(new java.awt.GridBagLayout()); rgrCloseAutomatically.add(rdoDontCloseAutomatically); rdoDontCloseAutomatically.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.rdoDontCloseAutomatically.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0); pnlCloseAutomatically.add(rdoDontCloseAutomatically, gridBagConstraints); rgrCloseAutomatically.add(rdoCloseAutomatically); rdoCloseAutomatically.setSelected(true); rdoCloseAutomatically.setText(org.openide.util.NbBundle.getMessage( DownloadManagerOptionsPanel.class, "DownloadManagerOptionsPanel.rdoCloseAutomatically.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); pnlCloseAutomatically.add(rdoCloseAutomatically, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 5); add(pnlCloseAutomatically, gridBagConstraints); } // </editor-fold>//GEN-END:initComponents
diff --git a/src/org/dita/dost/writer/KeyrefPaser.java b/src/org/dita/dost/writer/KeyrefPaser.java index 87b96f8cb..1c200552e 100644 --- a/src/org/dita/dost/writer/KeyrefPaser.java +++ b/src/org/dita/dost/writer/KeyrefPaser.java @@ -1,777 +1,777 @@ /* * This file is part of the DITA Open Toolkit project hosted on * Sourceforge.net. See the accompanying license.txt file for * applicable licenses. */ /* * (c) Copyright IBM Corp. 2010 All Rights Reserved. */ package org.dita.dost.writer; import static org.dita.dost.util.Constants.*; import static javax.xml.XMLConstants.*; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Stack; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import org.dita.dost.exception.DITAOTException; import org.dita.dost.log.DITAOTLogger; import org.dita.dost.log.MessageUtils; import org.dita.dost.module.Content; import org.dita.dost.util.DitaClass; import org.dita.dost.util.FileUtils; import org.dita.dost.util.MergeUtils; import org.dita.dost.util.StringUtils; import org.dita.dost.util.XMLUtils; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl; import org.xml.sax.helpers.AttributesImpl; /** * Filter for processing key reference elements in DITA files. * Instances are reusable but not thread-safe. */ public final class KeyrefPaser extends XMLFilterImpl { /** * Set of attributes which should not be copied from * key definition to key reference which is {@code <topicref>}. */ private static final Set<String> no_copy; static { final Set<String> nc = new HashSet<String>(); nc.add(ATTRIBUTE_NAME_ID); nc.add(ATTRIBUTE_NAME_CLASS); nc.add(ATTRIBUTE_NAME_XTRC); nc.add(ATTRIBUTE_NAME_XTRF); nc.add(ATTRIBUTE_NAME_HREF); nc.add(ATTRIBUTE_NAME_KEYS); nc.add(ATTRIBUTE_NAME_TOC); nc.add(ATTRIBUTE_NAME_PROCESSING_ROLE); no_copy = Collections.unmodifiableSet(nc); } /** * Set of attributes which should not be copied from * key definition to key reference which is not {@code <topicref>}. */ private static final Set<String> no_copy_topic; static { final Set<String> nct = new HashSet<String>(); nct.addAll(no_copy); nct.add("query"); nct.add("search"); nct.add(ATTRIBUTE_NAME_TOC); nct.add(ATTRIBUTE_NAME_PRINT); nct.add(ATTRIBUTE_NAME_COPY_TO); nct.add(ATTRIBUTE_NAME_CHUNK); nct.add(ATTRIBUTE_NAME_NAVTITLE); no_copy_topic = Collections.unmodifiableSet(nct); } /** List of key reference element definitions. */ private final static List<KeyrefInfo> keyrefInfos; static { final List<KeyrefInfo> ki = new ArrayList<KeyrefInfo>(); ki.add(new KeyrefInfo(TOPIC_AUTHOR, ATTRIBUTE_NAME_HREF, false)); ki.add(new KeyrefInfo(TOPIC_DATA, ATTRIBUTE_NAME_HREF, false)); ki.add(new KeyrefInfo(TOPIC_DATA_ABOUT, ATTRIBUTE_NAME_HREF, false)); ki.add(new KeyrefInfo(TOPIC_IMAGE, ATTRIBUTE_NAME_HREF, true)); ki.add(new KeyrefInfo(TOPIC_LINK, ATTRIBUTE_NAME_HREF, false)); ki.add(new KeyrefInfo(TOPIC_LQ, ATTRIBUTE_NAME_HREF, false)); ki.add(new KeyrefInfo(MAP_NAVREF, "mapref", true)); ki.add(new KeyrefInfo(TOPIC_PUBLISHER, ATTRIBUTE_NAME_HREF, false)); ki.add(new KeyrefInfo(TOPIC_SOURCE, ATTRIBUTE_NAME_HREF, false)); ki.add(new KeyrefInfo(MAP_TOPICREF, ATTRIBUTE_NAME_HREF, false)); ki.add(new KeyrefInfo(TOPIC_XREF, ATTRIBUTE_NAME_HREF, false)); ki.add(new KeyrefInfo(TOPIC_CITE, null, false)); ki.add(new KeyrefInfo(TOPIC_DT, null, false)); ki.add(new KeyrefInfo(TOPIC_KEYWORD, null, false)); ki.add(new KeyrefInfo(TOPIC_TERM, null, false)); ki.add(new KeyrefInfo(TOPIC_PH, null, false)); ki.add(new KeyrefInfo(TOPIC_INDEXTERM, null, false)); ki.add(new KeyrefInfo(TOPIC_INDEX_BASE, null, false)); ki.add(new KeyrefInfo(TOPIC_INDEXTERMREF, null, false)); keyrefInfos = Collections.unmodifiableList(ki); } private final XMLReader parser; private final TransformerFactory tf; private DITAOTLogger logger; private Hashtable<String, String> definitionMap; private String tempDir; /** * It is stack used to store the place of current element * relative to the key reference element. Because keyref can be nested. */ private final Stack<Integer> keyrefLevalStack; /** * It is used to store the place of current element * relative to the key reference element. If it is out of range of key * reference element it is zero, otherwise it is positive number. * It is also used to indicate whether current element is descendant of the * key reference element. */ private int keyrefLeval; /** Relative path of the filename to the temporary directory. */ private String filepath; private String extName; /** * It is used to store the target of the keys * In the from the map <keys, target>. */ private Map<String, String> keyMap; /** * It is used to indicate whether the keyref is valid. * The descendant element should know whether keyref is valid because keyrefs can be nested. */ private final Stack<Boolean> validKeyref; /** * Flag indicating whether the key reference element is empty, * if it is empty, it should pull matching content from the key definition. */ private boolean empty; /** Stack of element names of the element containing keyref attribute. */ private final Stack<String> elemName; /** Current element keyref info, {@code null} if not keyref type element. */ private KeyrefInfo currentElement; private boolean hasChecked; /** Flag stack to indicate whether key reference element has sub-elements. */ private final Stack<Boolean> hasSubElem; /** Current key definition. */ private Document doc; /** File name with relative path to the temporary directory of input file. */ private String fileName; /** * Constructor. */ public KeyrefPaser() { keyrefLeval = 0; keyrefLevalStack = new Stack<Integer>(); validKeyref = new Stack<Boolean>(); empty = true; keyMap = new HashMap<String, String>(); elemName = new Stack<String>(); hasSubElem = new Stack<Boolean>(); try { parser = StringUtils.getXMLReader(); parser.setFeature(FEATURE_NAMESPACE_PREFIX, true); parser.setFeature(FEATURE_NAMESPACE, true); setParent(parser); tf = TransformerFactory.newInstance(); } catch (final Exception e) { throw new RuntimeException("Failed to initialize XML parser: " + e.getMessage(), e); } } /** * Set logger * * @param logger output logger */ public void setLogger(final DITAOTLogger logger) { this.logger = logger; } /** * Get extension name. * @return extension name */ public String getExtName() { return extName; } /** * Set extension name. * @param extName extension name */ public void setExtName(final String extName) { this.extName = extName; } /** * Set key definition map. * * @param content value {@code Hashtable<String, String>} */ @SuppressWarnings("unchecked") public void setContent(final Content content) { definitionMap = (Hashtable<String, String>) content.getValue(); if (definitionMap == null) { throw new IllegalArgumentException("Content value must be non-null Hashtable<String, String>"); } } /** * Set temp dir. * @param tempDir temp dir */ public void setTempDir(final String tempDir) { this.tempDir = tempDir; } /** * Set key map. * @param map key map */ public void setKeyMap(final Map<String, String> map) { this.keyMap = map; } /** * Process key references. * * @param filename file to process * @throws DITAOTException if key reference resolution failed */ public void write(final String filename) throws DITAOTException { final File inputFile = new File(tempDir, filename); filepath = inputFile.getAbsolutePath(); final File outputFile = new File(tempDir, filename + ATTRIBUTE_NAME_KEYREF); this.fileName = filename; OutputStream output = null; try { output = new BufferedOutputStream(new FileOutputStream(outputFile)); final Transformer t = tf.newTransformer(); final Source src = new SAXSource(this, new InputSource(inputFile.toURI().toString())); final Result dst = new StreamResult(output); t.transform(src, dst); } catch (final Exception e) { throw new DITAOTException("Failed to process key references: " + e.getMessage(), e); } finally { if (output != null) { try { output.close(); } catch (final Exception ex) { logger.logError("Failed to close output stream: " + ex.getMessage(), ex); } } } if (!inputFile.delete()) { final Properties prop = new Properties(); prop.put("%1", inputFile.getPath()); prop.put("%2", outputFile.getPath()); logger.logError(MessageUtils.getMessage("DOTJ009E", prop).toString()); } if (!outputFile.renameTo(inputFile)) { final Properties prop = new Properties(); prop.put("%1", inputFile.getPath()); prop.put("%2", outputFile.getPath()); logger.logError(MessageUtils.getMessage("DOTJ009E", prop).toString()); } } // XML filter methods ------------------------------------------------------ @Override public void characters(final char[] ch, final int start, final int length) throws SAXException { if (keyrefLeval != 0 && new String(ch,start,length).trim().length() == 0) { if (!hasChecked) { empty = true; } } else { hasChecked = true; empty = false; } getContentHandler().characters(ch, start, length); } @Override public void endElement(final String uri, final String localName, final String name) throws SAXException { if (keyrefLeval != 0 && empty && !elemName.peek().equals(MAP_TOPICREF.localName)) { // If current element is in the scope of key reference element // and the element is empty if (!validKeyref.isEmpty() && validKeyref.peek()) { // Key reference is valid, // need to pull matching content from the key definition final Element elem = doc.getDocumentElement(); NodeList nodeList = null; // If current element name doesn't equal the key reference element // just grab the content from the matching element of key definition if(!name.equals(elemName.peek())){ nodeList = elem.getElementsByTagName(name); if(nodeList.getLength() > 0){ final Node node = nodeList.item(0); final NodeList nList = node.getChildNodes(); int index = 0; while(index < nList.getLength()){ final Node n = nList.item(index++); if(n.getNodeType() == Node.TEXT_NODE){ final char[] ch = n.getNodeValue().toCharArray(); getContentHandler().characters(ch, 0, ch.length); break; } } } }else{ // Current element name equals the key reference element // grab keyword or term from key definition nodeList = elem.getElementsByTagName(TOPIC_KEYWORD.localName); if(nodeList.getLength() == 0 ){ nodeList = elem.getElementsByTagName(TOPIC_TERM.localName); } if(!hasSubElem.peek()){ if(nodeList.getLength() > 0){ if(currentElement != null && !currentElement.isRefType){ // only one keyword or term is used. nodeToString((Element)nodeList.item(0), false); } else if(currentElement != null){ // If the key reference element carries href attribute // all keyword or term are used. if(TOPIC_LINK.matches(currentElement.type)){ final AttributesImpl atts = new AttributesImpl(); XMLUtils.addOrSetAttribute(atts, ATTRIBUTE_NAME_CLASS, TOPIC_LINKTEXT.toString()); getContentHandler().startElement(NULL_NS_URI, TOPIC_LINKTEXT.localName, TOPIC_LINKTEXT.localName, atts); } if (!currentElement.isEmpty) { for(int index =0; index<nodeList.getLength(); index++){ final Node node = nodeList.item(index); if(node.getNodeType() == Node.ELEMENT_NODE){ nodeToString((Element)node, true); } } } if(TOPIC_LINK.matches(currentElement.type)){ getContentHandler().endElement(NULL_NS_URI, TOPIC_LINKTEXT.localName, TOPIC_LINKTEXT.localName); } } }else{ if(currentElement != null && TOPIC_LINK.matches(currentElement.type)){ // If the key reference element is link or its specification, // should pull in the linktext final NodeList linktext = elem.getElementsByTagName(TOPIC_LINKTEXT.localName); if(linktext.getLength()>0){ nodeToString((Element)linktext.item(0), true); }else if (!StringUtils.isEmptyString(elem.getAttribute(ATTRIBUTE_NAME_NAVTITLE))){ final AttributesImpl atts = new AttributesImpl(); XMLUtils.addOrSetAttribute(atts, ATTRIBUTE_NAME_CLASS, TOPIC_LINKTEXT.toString()); getContentHandler().startElement(NULL_NS_URI, TOPIC_LINKTEXT.localName, TOPIC_LINKTEXT.localName, atts); if (elem.getAttribute(ATTRIBUTE_NAME_NAVTITLE) != null) { final char[] ch = elem.getAttribute(ATTRIBUTE_NAME_NAVTITLE).toCharArray(); getContentHandler().characters(ch, 0, ch.length); } getContentHandler().endElement(NULL_NS_URI, TOPIC_LINKTEXT.localName, TOPIC_LINKTEXT.localName); } }else if(currentElement != null && currentElement.isRefType){ final NodeList linktext = elem.getElementsByTagName(TOPIC_LINKTEXT.localName); if(linktext.getLength()>0){ nodeToString((Element)linktext.item(0), false); }else{ if (elem.getAttribute(ATTRIBUTE_NAME_NAVTITLE) != null) { final char[] ch = elem.getAttribute(ATTRIBUTE_NAME_NAVTITLE).toCharArray(); getContentHandler().characters(ch, 0, ch.length); } } } } } } } } if (keyrefLeval != 0){ keyrefLeval--; empty = false; } if (keyrefLeval == 0 && !keyrefLevalStack.empty()) { // To the end of key reference, pop the stacks. keyrefLeval = keyrefLevalStack.pop(); validKeyref.pop(); elemName.pop(); hasSubElem.pop(); } getContentHandler().endElement(uri, localName, name); } @Override public void startElement(final String uri, final String localName, final String name, final Attributes atts) throws SAXException { currentElement = null; final String cls = atts.getValue(ATTRIBUTE_NAME_CLASS); for (final KeyrefInfo k: keyrefInfos) { if (k.type.matches(cls)) { currentElement = k; } } final AttributesImpl resAtts = new AttributesImpl(atts); hasChecked = false; empty = true; boolean valid = false; if (atts.getIndex(ATTRIBUTE_NAME_KEYREF) == -1) { // If the keyrefLeval doesn't equal 0, it means that current element is under the key reference element if(keyrefLeval != 0){ keyrefLeval ++; hasSubElem.pop(); hasSubElem.push(true); } } else { // If there is @keyref, use the key definition to do // combination. // HashSet to store the attributes copied from key // definition to key reference. elemName.push(name); //hasKeyref = true; if (keyrefLeval != 0) { keyrefLevalStack.push(keyrefLeval); hasSubElem.pop(); hasSubElem.push(true); } hasSubElem.push(false); keyrefLeval = 0; keyrefLeval++; //keyref.push(atts.getValue(ATTRIBUTE_NAME_KEYREF)); //the @keyref could be in the following forms: // 1.keyName 2.keyName/elementId /*String definition = ((Hashtable<String, String>) content .getValue()).get(atts .getValue(ATTRIBUTE_NAME_KEYREF));*/ final String keyrefValue=atts.getValue(ATTRIBUTE_NAME_KEYREF); final int slashIndex=keyrefValue.indexOf(SLASH); String keyName= keyrefValue; String tail= ""; if (slashIndex != -1) { keyName = keyrefValue.substring(0, slashIndex); tail = keyrefValue.substring(slashIndex); } final String definition = definitionMap.get(keyName); // If definition is not null if(definition!=null){ doc = keyDefToDoc(definition); final Element elem = doc.getDocumentElement(); final NamedNodeMap namedNodeMap = elem.getAttributes(); // first resolve the keyref attribute if (currentElement != null && currentElement.isRefType) { String target = keyMap.get(keyName); if (target != null && target.length() != 0) { String target_output = target; // if the scope equals local, the target should be verified that // it exists. final String scopeValue=elem.getAttribute(ATTRIBUTE_NAME_SCOPE); if (TOPIC_IMAGE.matches(currentElement.type)) { valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); target_output = FileUtils.getRelativePathFromMap(fileName, target_output); target_output = normalizeHrefValue(target_output, tail); XMLUtils.addOrSetAttribute(resAtts, currentElement.refAttr, target_output); } else if ("".equals(scopeValue) || ATTR_SCOPE_VALUE_LOCAL.equals(scopeValue)){ if (!(MAPGROUP_D_MAPREF.matches(cls) && FileUtils.isDITAMapFile(target.toLowerCase()))){ target = FileUtils.replaceExtName(target,extName); } final File topicFile = new File(FileUtils.resolveFile(tempDir, target)); if (topicFile.exists()) { final String topicId = this.getFirstTopicId(topicFile); target_output = FileUtils.getRelativePathFromMap(filepath, new File(tempDir, target).getAbsolutePath()); valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); target_output = normalizeHrefValue(target_output, tail, topicId); XMLUtils.addOrSetAttribute(resAtts, currentElement.refAttr, target_output); } else { // referenced file does not exist, emits a message. // Should only emit this if in a debug mode; comment out for now /*Properties prop = new Properties(); prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); javaLogger .logInfo(MessageUtils.getMessage("DOTJ047I", prop) .toString());*/ } } // scope equals peer or external else { valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); target_output = normalizeHrefValue(target_output, tail); XMLUtils.addOrSetAttribute(resAtts, ATTRIBUTE_NAME_HREF, target_output); } - } else if(target.length() == 0){ + } else if(target == null || target.length() == 0){ // Key definition does not carry an href or href equals "". valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); }else{ // key does not exist. final Properties prop = new Properties(); prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); logger.logInfo(MessageUtils.getMessage("DOTJ047I", prop).toString()); } } else if (currentElement != null && !currentElement.isRefType) { final String target = keyMap.get(keyName); if (target != null) { valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); } else { // key does not exist // Do not log error, key should not need a link //final Properties prop = new Properties(); //prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); //logger.logInfo(MessageUtils.getMessage("DOTJ047I", prop).toString()); } } // copy attributes in key definition to key reference // Set no_copy and no_copy_topic define some attributes should not be copied. if (valid) { if (currentElement != null && MAP_TOPICREF.matches(currentElement.type)) { // @keyref in topicref for (int index = 0; index < namedNodeMap.getLength(); index++) { final Node node = namedNodeMap.item(index); if (node.getNodeType() == Node.ATTRIBUTE_NODE && !no_copy.contains(node.getNodeName())) { XMLUtils.removeAttribute(resAtts, node.getNodeName()); XMLUtils.addOrSetAttribute(resAtts, node); } } } else { // @keyref not in topicref // different elements have different attributes if (currentElement != null && currentElement.isRefType) { // current element with href attribute for (int index = 0; index < namedNodeMap.getLength(); index++) { final Node node = namedNodeMap.item(index); if (node.getNodeType() == Node.ATTRIBUTE_NODE && !no_copy_topic.contains(node.getNodeName())) { XMLUtils.removeAttribute(resAtts, node.getNodeName()); XMLUtils.addOrSetAttribute(resAtts, node); } } } else if (currentElement != null && !currentElement.isRefType) { // current element without href attribute // so attributes about href should not be copied. for (int index = 0; index < namedNodeMap.getLength(); index++) { final Node node = namedNodeMap.item(index); if (node.getNodeType() == Node.ATTRIBUTE_NODE && !no_copy_topic.contains(node.getNodeName()) && !(node.getNodeName().equals(ATTRIBUTE_NAME_SCOPE) || node.getNodeName().equals(ATTRIBUTE_NAME_FORMAT) || node.getNodeName().equals(ATTRIBUTE_NAME_TYPE))) { XMLUtils.removeAttribute(resAtts, node.getNodeName()); XMLUtils.addOrSetAttribute(resAtts, node); } } } } } else { // keyref is not valid, don't copy any attribute. } }else{ // key does not exist final Properties prop = new Properties(); prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); logger.logInfo(MessageUtils.getMessage("DOTJ047I", prop).toString());; } validKeyref.push(valid); } getContentHandler().startElement(uri, localName, name, resAtts); } // Private methods --------------------------------------------------------- /** * Read key definition * * @param key key definition XML string * @return parsed key definition document */ private Document keyDefToDoc(final String key) { final InputSource inputSource = new InputSource(new StringReader(key)); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document document = null; try { final DocumentBuilder documentBuilder = factory.newDocumentBuilder(); document = documentBuilder.parse(inputSource); } catch (final Exception e) { logger.logError("Failed to parse key definition: " + e.getMessage(), e); } return document; } /** * Serialize DOM node into a string. * * @param elem element to serialize * @param flag {@code true} to serialize elements, {@code false} to only serialize text nodes. * @return */ private void nodeToString(final Element elem, final boolean flag) throws SAXException{ // use flag to indicate that whether there is need to copy the element name if(flag){ final AttributesImpl atts = new AttributesImpl(); final NamedNodeMap namedNodeMap = elem.getAttributes(); for(int i=0; i<namedNodeMap.getLength(); i++){ final Attr a = (Attr) namedNodeMap.item(i); if(a.getNodeName().equals(ATTRIBUTE_NAME_CLASS)) { XMLUtils.addOrSetAttribute(atts, ATTRIBUTE_NAME_CLASS, changeclassValue(a.getNodeValue())); } else { XMLUtils.addOrSetAttribute(atts, a); } } getContentHandler().startElement(NULL_NS_URI, elem.getNodeName(), elem.getNodeName(), atts); } final NodeList nodeList = elem.getChildNodes(); for(int i=0; i<nodeList.getLength(); i++){ final Node node = nodeList.item(i); if(node.getNodeType() == Node.ELEMENT_NODE){ final Element e = (Element) node; //special process for tm tag. if(TOPIC_TM.matches(e)){ nodeToString(e, true); }else{ // If the type of current node is ELEMENT_NODE, process current node. nodeToString(e, flag); } // If the type of current node is ELEMENT_NODE, process current node. //stringBuffer.append(nodeToString((Element)node, flag)); } else if(node.getNodeType() == Node.TEXT_NODE){ final char[] ch = node.getNodeValue().toCharArray(); getContentHandler().characters(ch, 0, ch.length); } } if(flag) { getContentHandler().endElement(NULL_NS_URI, elem.getNodeName(), elem.getNodeName()); } } /** * Change map type to topic type. */ private String changeclassValue(final String classValue){ return classValue.replaceAll("map/", "topic/"); } /** * change elementId into topicId if there is no topicId in key definition. */ private static String normalizeHrefValue(final String keyName, final String tail) { final int sharpIndex=keyName.indexOf(SHARP); if(sharpIndex == -1){ return keyName + tail.replaceAll(SLASH, SHARP); } return keyName + tail; } /** * Get first topic id */ private String getFirstTopicId(final File topicFile) { final String path = topicFile.getParent(); final String name = topicFile.getName(); final String topicId = MergeUtils.getFirstTopicId(name, path, false); return topicId; } /** * Insert topic id into href */ private static String normalizeHrefValue(final String fileName, final String tail, final String topicId) { final int sharpIndex=fileName.indexOf(SHARP); //Insert first topic id only when topicid is not set in keydef //and keyref has elementid if(sharpIndex == -1 && !"".equals(tail)){ return fileName + SHARP + topicId + tail; } return fileName + tail; } // Inner classes ----------------------------------------------------------- private static final class KeyrefInfo { /** DITA class. */ final DitaClass type; /** Reference attribute name. */ final String refAttr; /** Element is reference type. */ final boolean isRefType; /** Element is empty. */ final boolean isEmpty; /** * Construct a new key reference info object. * * @param type element type * @param refAttr hyperlink attribute name * @param isEmpty flag if element is empty */ KeyrefInfo(final DitaClass type, final String refAttr, final boolean isEmpty) { this.type = type; this.refAttr = refAttr; this.isEmpty = isEmpty; this.isRefType = refAttr != null; } } }
true
true
public void startElement(final String uri, final String localName, final String name, final Attributes atts) throws SAXException { currentElement = null; final String cls = atts.getValue(ATTRIBUTE_NAME_CLASS); for (final KeyrefInfo k: keyrefInfos) { if (k.type.matches(cls)) { currentElement = k; } } final AttributesImpl resAtts = new AttributesImpl(atts); hasChecked = false; empty = true; boolean valid = false; if (atts.getIndex(ATTRIBUTE_NAME_KEYREF) == -1) { // If the keyrefLeval doesn't equal 0, it means that current element is under the key reference element if(keyrefLeval != 0){ keyrefLeval ++; hasSubElem.pop(); hasSubElem.push(true); } } else { // If there is @keyref, use the key definition to do // combination. // HashSet to store the attributes copied from key // definition to key reference. elemName.push(name); //hasKeyref = true; if (keyrefLeval != 0) { keyrefLevalStack.push(keyrefLeval); hasSubElem.pop(); hasSubElem.push(true); } hasSubElem.push(false); keyrefLeval = 0; keyrefLeval++; //keyref.push(atts.getValue(ATTRIBUTE_NAME_KEYREF)); //the @keyref could be in the following forms: // 1.keyName 2.keyName/elementId /*String definition = ((Hashtable<String, String>) content .getValue()).get(atts .getValue(ATTRIBUTE_NAME_KEYREF));*/ final String keyrefValue=atts.getValue(ATTRIBUTE_NAME_KEYREF); final int slashIndex=keyrefValue.indexOf(SLASH); String keyName= keyrefValue; String tail= ""; if (slashIndex != -1) { keyName = keyrefValue.substring(0, slashIndex); tail = keyrefValue.substring(slashIndex); } final String definition = definitionMap.get(keyName); // If definition is not null if(definition!=null){ doc = keyDefToDoc(definition); final Element elem = doc.getDocumentElement(); final NamedNodeMap namedNodeMap = elem.getAttributes(); // first resolve the keyref attribute if (currentElement != null && currentElement.isRefType) { String target = keyMap.get(keyName); if (target != null && target.length() != 0) { String target_output = target; // if the scope equals local, the target should be verified that // it exists. final String scopeValue=elem.getAttribute(ATTRIBUTE_NAME_SCOPE); if (TOPIC_IMAGE.matches(currentElement.type)) { valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); target_output = FileUtils.getRelativePathFromMap(fileName, target_output); target_output = normalizeHrefValue(target_output, tail); XMLUtils.addOrSetAttribute(resAtts, currentElement.refAttr, target_output); } else if ("".equals(scopeValue) || ATTR_SCOPE_VALUE_LOCAL.equals(scopeValue)){ if (!(MAPGROUP_D_MAPREF.matches(cls) && FileUtils.isDITAMapFile(target.toLowerCase()))){ target = FileUtils.replaceExtName(target,extName); } final File topicFile = new File(FileUtils.resolveFile(tempDir, target)); if (topicFile.exists()) { final String topicId = this.getFirstTopicId(topicFile); target_output = FileUtils.getRelativePathFromMap(filepath, new File(tempDir, target).getAbsolutePath()); valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); target_output = normalizeHrefValue(target_output, tail, topicId); XMLUtils.addOrSetAttribute(resAtts, currentElement.refAttr, target_output); } else { // referenced file does not exist, emits a message. // Should only emit this if in a debug mode; comment out for now /*Properties prop = new Properties(); prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); javaLogger .logInfo(MessageUtils.getMessage("DOTJ047I", prop) .toString());*/ } } // scope equals peer or external else { valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); target_output = normalizeHrefValue(target_output, tail); XMLUtils.addOrSetAttribute(resAtts, ATTRIBUTE_NAME_HREF, target_output); } } else if(target.length() == 0){ // Key definition does not carry an href or href equals "". valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); }else{ // key does not exist. final Properties prop = new Properties(); prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); logger.logInfo(MessageUtils.getMessage("DOTJ047I", prop).toString()); } } else if (currentElement != null && !currentElement.isRefType) { final String target = keyMap.get(keyName); if (target != null) { valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); } else { // key does not exist // Do not log error, key should not need a link //final Properties prop = new Properties(); //prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); //logger.logInfo(MessageUtils.getMessage("DOTJ047I", prop).toString()); } } // copy attributes in key definition to key reference // Set no_copy and no_copy_topic define some attributes should not be copied. if (valid) { if (currentElement != null && MAP_TOPICREF.matches(currentElement.type)) { // @keyref in topicref for (int index = 0; index < namedNodeMap.getLength(); index++) { final Node node = namedNodeMap.item(index); if (node.getNodeType() == Node.ATTRIBUTE_NODE && !no_copy.contains(node.getNodeName())) { XMLUtils.removeAttribute(resAtts, node.getNodeName()); XMLUtils.addOrSetAttribute(resAtts, node); } } } else { // @keyref not in topicref // different elements have different attributes if (currentElement != null && currentElement.isRefType) { // current element with href attribute for (int index = 0; index < namedNodeMap.getLength(); index++) { final Node node = namedNodeMap.item(index); if (node.getNodeType() == Node.ATTRIBUTE_NODE && !no_copy_topic.contains(node.getNodeName())) { XMLUtils.removeAttribute(resAtts, node.getNodeName()); XMLUtils.addOrSetAttribute(resAtts, node); } } } else if (currentElement != null && !currentElement.isRefType) { // current element without href attribute // so attributes about href should not be copied. for (int index = 0; index < namedNodeMap.getLength(); index++) { final Node node = namedNodeMap.item(index); if (node.getNodeType() == Node.ATTRIBUTE_NODE && !no_copy_topic.contains(node.getNodeName()) && !(node.getNodeName().equals(ATTRIBUTE_NAME_SCOPE) || node.getNodeName().equals(ATTRIBUTE_NAME_FORMAT) || node.getNodeName().equals(ATTRIBUTE_NAME_TYPE))) { XMLUtils.removeAttribute(resAtts, node.getNodeName()); XMLUtils.addOrSetAttribute(resAtts, node); } } } } } else { // keyref is not valid, don't copy any attribute. } }else{ // key does not exist final Properties prop = new Properties(); prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); logger.logInfo(MessageUtils.getMessage("DOTJ047I", prop).toString());; } validKeyref.push(valid); } getContentHandler().startElement(uri, localName, name, resAtts); }
public void startElement(final String uri, final String localName, final String name, final Attributes atts) throws SAXException { currentElement = null; final String cls = atts.getValue(ATTRIBUTE_NAME_CLASS); for (final KeyrefInfo k: keyrefInfos) { if (k.type.matches(cls)) { currentElement = k; } } final AttributesImpl resAtts = new AttributesImpl(atts); hasChecked = false; empty = true; boolean valid = false; if (atts.getIndex(ATTRIBUTE_NAME_KEYREF) == -1) { // If the keyrefLeval doesn't equal 0, it means that current element is under the key reference element if(keyrefLeval != 0){ keyrefLeval ++; hasSubElem.pop(); hasSubElem.push(true); } } else { // If there is @keyref, use the key definition to do // combination. // HashSet to store the attributes copied from key // definition to key reference. elemName.push(name); //hasKeyref = true; if (keyrefLeval != 0) { keyrefLevalStack.push(keyrefLeval); hasSubElem.pop(); hasSubElem.push(true); } hasSubElem.push(false); keyrefLeval = 0; keyrefLeval++; //keyref.push(atts.getValue(ATTRIBUTE_NAME_KEYREF)); //the @keyref could be in the following forms: // 1.keyName 2.keyName/elementId /*String definition = ((Hashtable<String, String>) content .getValue()).get(atts .getValue(ATTRIBUTE_NAME_KEYREF));*/ final String keyrefValue=atts.getValue(ATTRIBUTE_NAME_KEYREF); final int slashIndex=keyrefValue.indexOf(SLASH); String keyName= keyrefValue; String tail= ""; if (slashIndex != -1) { keyName = keyrefValue.substring(0, slashIndex); tail = keyrefValue.substring(slashIndex); } final String definition = definitionMap.get(keyName); // If definition is not null if(definition!=null){ doc = keyDefToDoc(definition); final Element elem = doc.getDocumentElement(); final NamedNodeMap namedNodeMap = elem.getAttributes(); // first resolve the keyref attribute if (currentElement != null && currentElement.isRefType) { String target = keyMap.get(keyName); if (target != null && target.length() != 0) { String target_output = target; // if the scope equals local, the target should be verified that // it exists. final String scopeValue=elem.getAttribute(ATTRIBUTE_NAME_SCOPE); if (TOPIC_IMAGE.matches(currentElement.type)) { valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); target_output = FileUtils.getRelativePathFromMap(fileName, target_output); target_output = normalizeHrefValue(target_output, tail); XMLUtils.addOrSetAttribute(resAtts, currentElement.refAttr, target_output); } else if ("".equals(scopeValue) || ATTR_SCOPE_VALUE_LOCAL.equals(scopeValue)){ if (!(MAPGROUP_D_MAPREF.matches(cls) && FileUtils.isDITAMapFile(target.toLowerCase()))){ target = FileUtils.replaceExtName(target,extName); } final File topicFile = new File(FileUtils.resolveFile(tempDir, target)); if (topicFile.exists()) { final String topicId = this.getFirstTopicId(topicFile); target_output = FileUtils.getRelativePathFromMap(filepath, new File(tempDir, target).getAbsolutePath()); valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); target_output = normalizeHrefValue(target_output, tail, topicId); XMLUtils.addOrSetAttribute(resAtts, currentElement.refAttr, target_output); } else { // referenced file does not exist, emits a message. // Should only emit this if in a debug mode; comment out for now /*Properties prop = new Properties(); prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); javaLogger .logInfo(MessageUtils.getMessage("DOTJ047I", prop) .toString());*/ } } // scope equals peer or external else { valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); target_output = normalizeHrefValue(target_output, tail); XMLUtils.addOrSetAttribute(resAtts, ATTRIBUTE_NAME_HREF, target_output); } } else if(target == null || target.length() == 0){ // Key definition does not carry an href or href equals "". valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); }else{ // key does not exist. final Properties prop = new Properties(); prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); logger.logInfo(MessageUtils.getMessage("DOTJ047I", prop).toString()); } } else if (currentElement != null && !currentElement.isRefType) { final String target = keyMap.get(keyName); if (target != null) { valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); } else { // key does not exist // Do not log error, key should not need a link //final Properties prop = new Properties(); //prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); //logger.logInfo(MessageUtils.getMessage("DOTJ047I", prop).toString()); } } // copy attributes in key definition to key reference // Set no_copy and no_copy_topic define some attributes should not be copied. if (valid) { if (currentElement != null && MAP_TOPICREF.matches(currentElement.type)) { // @keyref in topicref for (int index = 0; index < namedNodeMap.getLength(); index++) { final Node node = namedNodeMap.item(index); if (node.getNodeType() == Node.ATTRIBUTE_NODE && !no_copy.contains(node.getNodeName())) { XMLUtils.removeAttribute(resAtts, node.getNodeName()); XMLUtils.addOrSetAttribute(resAtts, node); } } } else { // @keyref not in topicref // different elements have different attributes if (currentElement != null && currentElement.isRefType) { // current element with href attribute for (int index = 0; index < namedNodeMap.getLength(); index++) { final Node node = namedNodeMap.item(index); if (node.getNodeType() == Node.ATTRIBUTE_NODE && !no_copy_topic.contains(node.getNodeName())) { XMLUtils.removeAttribute(resAtts, node.getNodeName()); XMLUtils.addOrSetAttribute(resAtts, node); } } } else if (currentElement != null && !currentElement.isRefType) { // current element without href attribute // so attributes about href should not be copied. for (int index = 0; index < namedNodeMap.getLength(); index++) { final Node node = namedNodeMap.item(index); if (node.getNodeType() == Node.ATTRIBUTE_NODE && !no_copy_topic.contains(node.getNodeName()) && !(node.getNodeName().equals(ATTRIBUTE_NAME_SCOPE) || node.getNodeName().equals(ATTRIBUTE_NAME_FORMAT) || node.getNodeName().equals(ATTRIBUTE_NAME_TYPE))) { XMLUtils.removeAttribute(resAtts, node.getNodeName()); XMLUtils.addOrSetAttribute(resAtts, node); } } } } } else { // keyref is not valid, don't copy any attribute. } }else{ // key does not exist final Properties prop = new Properties(); prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); logger.logInfo(MessageUtils.getMessage("DOTJ047I", prop).toString());; } validKeyref.push(valid); } getContentHandler().startElement(uri, localName, name, resAtts); }
diff --git a/Coliseum/src/org/SkyCraft/Coliseum/ColiseumCommandExecutor.java b/Coliseum/src/org/SkyCraft/Coliseum/ColiseumCommandExecutor.java index 02940bb..e436e50 100644 --- a/Coliseum/src/org/SkyCraft/Coliseum/ColiseumCommandExecutor.java +++ b/Coliseum/src/org/SkyCraft/Coliseum/ColiseumCommandExecutor.java @@ -1,355 +1,355 @@ package org.SkyCraft.Coliseum; import java.util.logging.Logger; import org.SkyCraft.Coliseum.Arena.Arena; import org.SkyCraft.Coliseum.Arena.PVPArena; import org.SkyCraft.Coliseum.Arena.Combatant.Combatant; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.command.RemoteConsoleCommandSender; import org.bukkit.entity.Player; public class ColiseumCommandExecutor implements CommandExecutor { private ColiseumPlugin plugin; private Logger log; private ConfigHandler config; ColiseumCommandExecutor(ColiseumPlugin plugin, Logger log, ConfigHandler config) { this.plugin = plugin; this.log = log; this.config = config; } public boolean onCommand(CommandSender sender, Command cmd, String aliasUsed, String[] args) { if(sender instanceof ConsoleCommandSender || sender instanceof RemoteConsoleCommandSender) { sender.sendMessage("[Coliseum] Coliseum can only be used in-game."); return true; } else { if(args.length == 0) { sender.sendMessage(ChatColor.GRAY + "[Coliseum] You need to add arguments to do anything useful."); return true; } String argument = args[0]; //TODO add you are not editing messages. if(argument.equalsIgnoreCase("create") && args.length >= 3) {//TODO editor permissions if(args[1].equalsIgnoreCase("pvp")) { StringBuilder sb = new StringBuilder(); for(int i = 2; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } PVPArena a = new PVPArena(sb.toString(), plugin); plugin.getArenaSet().add(a); config.createArena(sb.toString(), "pvp"); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Created a new PVP arena called " + sb.toString() + "."); for(Arena a2 : plugin.getArenaSet()) { if(a2.isPlayerEditing((Player) sender)) { a2.removeEditor((Player) sender); sender.sendMessage(ChatColor.GRAY + "You are no longer editing " + a.getName() + "."); break; } } a.setPlayerEditing((Player) sender); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Now editing " + sb.toString() + "."); return true; } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] Not a recognized arena type."); return true; } } else if(argument.equalsIgnoreCase("edit")) {//TODO editor permissions if(args.length >=2) { StringBuilder sb = new StringBuilder(); for(int i = 1; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } for(Arena a : plugin.getArenaSet()) { if(a.isThisArena(sb.toString())) { for(Arena a2 : plugin.getArenaSet()) { if(a2.isPlayerEditing((Player) sender)) { a2.removeEditor((Player) sender); sender.sendMessage(ChatColor.GRAY + "[Coliseum] You are no longer editing " + sb.toString() + "."); break; } } if(!a.isEnabled()) { a.setPlayerEditing((Player) sender); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Now editing " + sb.toString() + "."); return true; } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] The arena you chose was enabled; you could not be placed in editing mode."); return true; } } } sender.sendMessage(ChatColor.GRAY + "[Coliseum] No arena was found by that name."); return true; } else { for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { a.removeEditor((Player) sender); sender.sendMessage(ChatColor.GRAY + "[Coliseum] You are no longer editing " + a.getName() + "."); return true; } } sender.sendMessage(ChatColor.GRAY + "[Coliseum] You need to supply an arena to begin editing or you were not editing anything to be removed from."); return true; } } else if(argument.equalsIgnoreCase("posone") || argument.equalsIgnoreCase("po") || argument.equalsIgnoreCase("p1")) {//TODO editor permissions for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { a.getRegion().setPos1(((Player) sender).getTargetBlock(null, 10)); config.setArenaPos(1, a.getName(), a.getRegion().getPos1()); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Position one set."); return true; }//TODO Check if block is null (looking too far away), do later in interest of getting this done. } } else if(argument.equalsIgnoreCase("wposone") || argument.equalsIgnoreCase("wpo") || argument.equalsIgnoreCase("wp1")) {//TODO editor permissions for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { a.getWaitingRegion().setPos1(((Player) sender).getTargetBlock(null, 10)); config.setArenaPos(3, a.getName(), a.getWaitingRegion().getPos1()); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Waiting region position one set."); return true; }//TODO Check if block is null (looking too far away), do later in interest of getting this done. } } else if(argument.equalsIgnoreCase("postwo") || argument.equalsIgnoreCase("pt") || argument.equalsIgnoreCase("p2")) {//TODO editor permissions for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { a.getRegion().setPos2(((Player) sender).getTargetBlock(null, 10)); config.setArenaPos(2, a.getName(), a.getRegion().getPos2()); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Position two set."); return true; }//TODO Check if block is null (looking too far away), do later in interest of getting this done. } } else if(argument.equalsIgnoreCase("wpostwo") || argument.equalsIgnoreCase("wpt") || argument.equalsIgnoreCase("wp2")) {//TODO editor permissions for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { a.getWaitingRegion().setPos2(((Player) sender).getTargetBlock(null, 10)); config.setArenaPos(4, a.getName(), a.getWaitingRegion().getPos2()); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Waiting region position two set."); return true; }//TODO Check if block is null (looking too far away), do later in interest of getting this done. } } else if(argument.equalsIgnoreCase("spawn") && args.length >= 2) {//TODO editor permissions for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { StringBuilder sb = new StringBuilder(); for(int i = 1; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } if(sb.toString().equalsIgnoreCase("waiting") || sb.toString().equalsIgnoreCase("wait") || sb.toString().equalsIgnoreCase("w")) { if(a.getWaitingRegion().setSpawn(((Player) sender).getTargetBlock(null, 10).getLocation())) { config.setSpawn(a.getName(), "WaitingAreaSpawn", a.getWaitingRegion().getSpawn()); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Waiting area spawn set."); } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] Waiting spawn was not created, place spawn inside region."); } return true; } else { if(a.getTeams().containsKey(sb.toString().toLowerCase())) {//TODO if containsKey is case sensitive need new way to match arena names if(a.getRegion().addTeamSpawn(sb.toString().toLowerCase(), ((Player) sender).getTargetBlock(null, 10).getLocation())) { - config.setSpawn(a.getName(), sb.toString(), a.getRegion().getTeamSpawn(sb.toString())); - sender.sendMessage(ChatColor.GRAY + "[Coliseum] Team " + sb.toString() + " spawn was created."); + config.setSpawn(a.getName(), sb.toString().toLowerCase(), a.getRegion().getTeamSpawn(sb.toString().toLowerCase())); + sender.sendMessage(ChatColor.GRAY + "[Coliseum] Team " + sb.toString().toLowerCase() + " spawn was created."); return true; } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] Spawn was not created, place spawn inside region."); return true; } } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] No team with that name was found, no spawn was set."); return true; } } } } } else if(argument.equalsIgnoreCase("addteam") && args.length >= 2) { StringBuilder sb = new StringBuilder(); for(int i = 1; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { a.addTeamName(sb.toString().toLowerCase()); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Team " + sb.toString().toLowerCase() + " added."); return true; } } } else if(argument.equalsIgnoreCase("remteam") && args.length >= 2) { StringBuilder sb = new StringBuilder(); for(int i = 1; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { if(a.removeTeamName(sb.toString().toLowerCase())) { sender.sendMessage(ChatColor.GRAY + "[Coliseum] Team " + sb.toString().toLowerCase() + " removed"); config.removeTeam(a.getName(), sb.toString()); return true; } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] No team " + sb.toString().toLowerCase() + " was found"); return true; } } } } else if(argument.equalsIgnoreCase("enable") && args.length >= 2) {//TODO Admin (and/or editor) [multiple permissions? admin can boot, editor can't?] StringBuilder sb = new StringBuilder(); for(int i = 1; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } for(Arena a: plugin.getArenaSet()) { if(a.isThisArena(sb.toString())) { if(a.enable()) { config.setArenaEnabledState(a.getName(), true); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Arena was successfully enabled!"); return true; } sender.sendMessage(ChatColor.GRAY + "[Coliseum] This arena was not ready to be enabled for some reason."); return true; } } sender.sendMessage(ChatColor.GRAY + "[Coliseum] No arena was found by that name."); return true; } else if(argument.equalsIgnoreCase("join") && !plugin.isPlayerJoined(((Player) sender).getName()) && args.length >= 2) {//TODO player permissions for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { sender.sendMessage(ChatColor.GRAY + "[Coliseum] You're still editing something. Quit editing and try to join again."); return true; } } StringBuilder sb = new StringBuilder(); for(int i = 1; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } for(Arena a : plugin.getArenaSet()) { if(a.isThisArena(sb.toString())) { if(a.isEnabled()) { a.addPlayer(((Player) sender)); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Welcome to " + a.getName() + "!"); return true; } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] Arena was not enabled."); return true; } } sender.sendMessage(ChatColor.GRAY + "[Coliseum] No arena was found by that name."); return true; } } else if(argument.equalsIgnoreCase("leave") && plugin.isPlayerJoined(((Player) sender).getName())) {//TODO player permissions for(Arena a : plugin.getArenaSet()) { if(a.hasThisPlayer(((Player) sender))) { a.removePlayer(((Player) sender)); sender.sendMessage(ChatColor.GRAY + "Arena left."); return true; } sender.sendMessage(ChatColor.GRAY + "[Coliseum] You're not in an arena."); return true; } } else if(argument.equalsIgnoreCase("team") && args.length >= 2) { StringBuilder sb = new StringBuilder(); for(int i = 1; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } for(Arena a : plugin.getArenaSet()) { if(a.hasThisPlayer((Player) sender)) { if(a.getTeams().containsKey(sb.toString().toLowerCase())) { a.getCombatant((Player) sender).joinTeam(sb.toString()); sender.sendMessage(ChatColor.GRAY + "[Colisemm] Your team is now set to " + sb.toString() + "."); return true; } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] No team was found by that name."); return true; } } } } else if(argument.equalsIgnoreCase("ready")) {//TODO fix me for(Arena a : plugin.getArenaSet()) { if(a.hasThisPlayer((Player) sender)) { Combatant c = a.getCombatant((Player) sender); if(c.setReadiness(!c.isReady())) { sender.sendMessage(ChatColor.GRAY + "[Coliseum] You are now " + (c.isReady() ? "ready." : "not ready.")); return true; } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] You could not be readied for some reason. Ensure you are entirely set up."); return true; } } } sender.sendMessage(ChatColor.GRAY + "[Coliseum] You are not in an arena."); } else if(argument.equalsIgnoreCase("start")) {//TODO FIX ME for(Arena a : plugin.getArenaSet()) { a.start(); } } //TODO implement other commands (disable, kick, forcestart, forcend, createteam, removeteam) //TODO implement a "help" message. return true; } } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String aliasUsed, String[] args) { if(sender instanceof ConsoleCommandSender || sender instanceof RemoteConsoleCommandSender) { sender.sendMessage("[Coliseum] Coliseum can only be used in-game."); return true; } else { if(args.length == 0) { sender.sendMessage(ChatColor.GRAY + "[Coliseum] You need to add arguments to do anything useful."); return true; } String argument = args[0]; //TODO add you are not editing messages. if(argument.equalsIgnoreCase("create") && args.length >= 3) {//TODO editor permissions if(args[1].equalsIgnoreCase("pvp")) { StringBuilder sb = new StringBuilder(); for(int i = 2; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } PVPArena a = new PVPArena(sb.toString(), plugin); plugin.getArenaSet().add(a); config.createArena(sb.toString(), "pvp"); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Created a new PVP arena called " + sb.toString() + "."); for(Arena a2 : plugin.getArenaSet()) { if(a2.isPlayerEditing((Player) sender)) { a2.removeEditor((Player) sender); sender.sendMessage(ChatColor.GRAY + "You are no longer editing " + a.getName() + "."); break; } } a.setPlayerEditing((Player) sender); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Now editing " + sb.toString() + "."); return true; } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] Not a recognized arena type."); return true; } } else if(argument.equalsIgnoreCase("edit")) {//TODO editor permissions if(args.length >=2) { StringBuilder sb = new StringBuilder(); for(int i = 1; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } for(Arena a : plugin.getArenaSet()) { if(a.isThisArena(sb.toString())) { for(Arena a2 : plugin.getArenaSet()) { if(a2.isPlayerEditing((Player) sender)) { a2.removeEditor((Player) sender); sender.sendMessage(ChatColor.GRAY + "[Coliseum] You are no longer editing " + sb.toString() + "."); break; } } if(!a.isEnabled()) { a.setPlayerEditing((Player) sender); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Now editing " + sb.toString() + "."); return true; } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] The arena you chose was enabled; you could not be placed in editing mode."); return true; } } } sender.sendMessage(ChatColor.GRAY + "[Coliseum] No arena was found by that name."); return true; } else { for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { a.removeEditor((Player) sender); sender.sendMessage(ChatColor.GRAY + "[Coliseum] You are no longer editing " + a.getName() + "."); return true; } } sender.sendMessage(ChatColor.GRAY + "[Coliseum] You need to supply an arena to begin editing or you were not editing anything to be removed from."); return true; } } else if(argument.equalsIgnoreCase("posone") || argument.equalsIgnoreCase("po") || argument.equalsIgnoreCase("p1")) {//TODO editor permissions for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { a.getRegion().setPos1(((Player) sender).getTargetBlock(null, 10)); config.setArenaPos(1, a.getName(), a.getRegion().getPos1()); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Position one set."); return true; }//TODO Check if block is null (looking too far away), do later in interest of getting this done. } } else if(argument.equalsIgnoreCase("wposone") || argument.equalsIgnoreCase("wpo") || argument.equalsIgnoreCase("wp1")) {//TODO editor permissions for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { a.getWaitingRegion().setPos1(((Player) sender).getTargetBlock(null, 10)); config.setArenaPos(3, a.getName(), a.getWaitingRegion().getPos1()); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Waiting region position one set."); return true; }//TODO Check if block is null (looking too far away), do later in interest of getting this done. } } else if(argument.equalsIgnoreCase("postwo") || argument.equalsIgnoreCase("pt") || argument.equalsIgnoreCase("p2")) {//TODO editor permissions for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { a.getRegion().setPos2(((Player) sender).getTargetBlock(null, 10)); config.setArenaPos(2, a.getName(), a.getRegion().getPos2()); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Position two set."); return true; }//TODO Check if block is null (looking too far away), do later in interest of getting this done. } } else if(argument.equalsIgnoreCase("wpostwo") || argument.equalsIgnoreCase("wpt") || argument.equalsIgnoreCase("wp2")) {//TODO editor permissions for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { a.getWaitingRegion().setPos2(((Player) sender).getTargetBlock(null, 10)); config.setArenaPos(4, a.getName(), a.getWaitingRegion().getPos2()); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Waiting region position two set."); return true; }//TODO Check if block is null (looking too far away), do later in interest of getting this done. } } else if(argument.equalsIgnoreCase("spawn") && args.length >= 2) {//TODO editor permissions for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { StringBuilder sb = new StringBuilder(); for(int i = 1; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } if(sb.toString().equalsIgnoreCase("waiting") || sb.toString().equalsIgnoreCase("wait") || sb.toString().equalsIgnoreCase("w")) { if(a.getWaitingRegion().setSpawn(((Player) sender).getTargetBlock(null, 10).getLocation())) { config.setSpawn(a.getName(), "WaitingAreaSpawn", a.getWaitingRegion().getSpawn()); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Waiting area spawn set."); } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] Waiting spawn was not created, place spawn inside region."); } return true; } else { if(a.getTeams().containsKey(sb.toString().toLowerCase())) {//TODO if containsKey is case sensitive need new way to match arena names if(a.getRegion().addTeamSpawn(sb.toString().toLowerCase(), ((Player) sender).getTargetBlock(null, 10).getLocation())) { config.setSpawn(a.getName(), sb.toString(), a.getRegion().getTeamSpawn(sb.toString())); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Team " + sb.toString() + " spawn was created."); return true; } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] Spawn was not created, place spawn inside region."); return true; } } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] No team with that name was found, no spawn was set."); return true; } } } } } else if(argument.equalsIgnoreCase("addteam") && args.length >= 2) { StringBuilder sb = new StringBuilder(); for(int i = 1; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { a.addTeamName(sb.toString().toLowerCase()); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Team " + sb.toString().toLowerCase() + " added."); return true; } } } else if(argument.equalsIgnoreCase("remteam") && args.length >= 2) { StringBuilder sb = new StringBuilder(); for(int i = 1; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { if(a.removeTeamName(sb.toString().toLowerCase())) { sender.sendMessage(ChatColor.GRAY + "[Coliseum] Team " + sb.toString().toLowerCase() + " removed"); config.removeTeam(a.getName(), sb.toString()); return true; } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] No team " + sb.toString().toLowerCase() + " was found"); return true; } } } } else if(argument.equalsIgnoreCase("enable") && args.length >= 2) {//TODO Admin (and/or editor) [multiple permissions? admin can boot, editor can't?] StringBuilder sb = new StringBuilder(); for(int i = 1; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } for(Arena a: plugin.getArenaSet()) { if(a.isThisArena(sb.toString())) { if(a.enable()) { config.setArenaEnabledState(a.getName(), true); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Arena was successfully enabled!"); return true; } sender.sendMessage(ChatColor.GRAY + "[Coliseum] This arena was not ready to be enabled for some reason."); return true; } } sender.sendMessage(ChatColor.GRAY + "[Coliseum] No arena was found by that name."); return true; } else if(argument.equalsIgnoreCase("join") && !plugin.isPlayerJoined(((Player) sender).getName()) && args.length >= 2) {//TODO player permissions for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { sender.sendMessage(ChatColor.GRAY + "[Coliseum] You're still editing something. Quit editing and try to join again."); return true; } } StringBuilder sb = new StringBuilder(); for(int i = 1; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } for(Arena a : plugin.getArenaSet()) { if(a.isThisArena(sb.toString())) { if(a.isEnabled()) { a.addPlayer(((Player) sender)); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Welcome to " + a.getName() + "!"); return true; } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] Arena was not enabled."); return true; } } sender.sendMessage(ChatColor.GRAY + "[Coliseum] No arena was found by that name."); return true; } } else if(argument.equalsIgnoreCase("leave") && plugin.isPlayerJoined(((Player) sender).getName())) {//TODO player permissions for(Arena a : plugin.getArenaSet()) { if(a.hasThisPlayer(((Player) sender))) { a.removePlayer(((Player) sender)); sender.sendMessage(ChatColor.GRAY + "Arena left."); return true; } sender.sendMessage(ChatColor.GRAY + "[Coliseum] You're not in an arena."); return true; } } else if(argument.equalsIgnoreCase("team") && args.length >= 2) { StringBuilder sb = new StringBuilder(); for(int i = 1; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } for(Arena a : plugin.getArenaSet()) { if(a.hasThisPlayer((Player) sender)) { if(a.getTeams().containsKey(sb.toString().toLowerCase())) { a.getCombatant((Player) sender).joinTeam(sb.toString()); sender.sendMessage(ChatColor.GRAY + "[Colisemm] Your team is now set to " + sb.toString() + "."); return true; } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] No team was found by that name."); return true; } } } } else if(argument.equalsIgnoreCase("ready")) {//TODO fix me for(Arena a : plugin.getArenaSet()) { if(a.hasThisPlayer((Player) sender)) { Combatant c = a.getCombatant((Player) sender); if(c.setReadiness(!c.isReady())) { sender.sendMessage(ChatColor.GRAY + "[Coliseum] You are now " + (c.isReady() ? "ready." : "not ready.")); return true; } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] You could not be readied for some reason. Ensure you are entirely set up."); return true; } } } sender.sendMessage(ChatColor.GRAY + "[Coliseum] You are not in an arena."); } else if(argument.equalsIgnoreCase("start")) {//TODO FIX ME for(Arena a : plugin.getArenaSet()) { a.start(); } } //TODO implement other commands (disable, kick, forcestart, forcend, createteam, removeteam) //TODO implement a "help" message. return true; } }
public boolean onCommand(CommandSender sender, Command cmd, String aliasUsed, String[] args) { if(sender instanceof ConsoleCommandSender || sender instanceof RemoteConsoleCommandSender) { sender.sendMessage("[Coliseum] Coliseum can only be used in-game."); return true; } else { if(args.length == 0) { sender.sendMessage(ChatColor.GRAY + "[Coliseum] You need to add arguments to do anything useful."); return true; } String argument = args[0]; //TODO add you are not editing messages. if(argument.equalsIgnoreCase("create") && args.length >= 3) {//TODO editor permissions if(args[1].equalsIgnoreCase("pvp")) { StringBuilder sb = new StringBuilder(); for(int i = 2; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } PVPArena a = new PVPArena(sb.toString(), plugin); plugin.getArenaSet().add(a); config.createArena(sb.toString(), "pvp"); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Created a new PVP arena called " + sb.toString() + "."); for(Arena a2 : plugin.getArenaSet()) { if(a2.isPlayerEditing((Player) sender)) { a2.removeEditor((Player) sender); sender.sendMessage(ChatColor.GRAY + "You are no longer editing " + a.getName() + "."); break; } } a.setPlayerEditing((Player) sender); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Now editing " + sb.toString() + "."); return true; } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] Not a recognized arena type."); return true; } } else if(argument.equalsIgnoreCase("edit")) {//TODO editor permissions if(args.length >=2) { StringBuilder sb = new StringBuilder(); for(int i = 1; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } for(Arena a : plugin.getArenaSet()) { if(a.isThisArena(sb.toString())) { for(Arena a2 : plugin.getArenaSet()) { if(a2.isPlayerEditing((Player) sender)) { a2.removeEditor((Player) sender); sender.sendMessage(ChatColor.GRAY + "[Coliseum] You are no longer editing " + sb.toString() + "."); break; } } if(!a.isEnabled()) { a.setPlayerEditing((Player) sender); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Now editing " + sb.toString() + "."); return true; } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] The arena you chose was enabled; you could not be placed in editing mode."); return true; } } } sender.sendMessage(ChatColor.GRAY + "[Coliseum] No arena was found by that name."); return true; } else { for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { a.removeEditor((Player) sender); sender.sendMessage(ChatColor.GRAY + "[Coliseum] You are no longer editing " + a.getName() + "."); return true; } } sender.sendMessage(ChatColor.GRAY + "[Coliseum] You need to supply an arena to begin editing or you were not editing anything to be removed from."); return true; } } else if(argument.equalsIgnoreCase("posone") || argument.equalsIgnoreCase("po") || argument.equalsIgnoreCase("p1")) {//TODO editor permissions for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { a.getRegion().setPos1(((Player) sender).getTargetBlock(null, 10)); config.setArenaPos(1, a.getName(), a.getRegion().getPos1()); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Position one set."); return true; }//TODO Check if block is null (looking too far away), do later in interest of getting this done. } } else if(argument.equalsIgnoreCase("wposone") || argument.equalsIgnoreCase("wpo") || argument.equalsIgnoreCase("wp1")) {//TODO editor permissions for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { a.getWaitingRegion().setPos1(((Player) sender).getTargetBlock(null, 10)); config.setArenaPos(3, a.getName(), a.getWaitingRegion().getPos1()); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Waiting region position one set."); return true; }//TODO Check if block is null (looking too far away), do later in interest of getting this done. } } else if(argument.equalsIgnoreCase("postwo") || argument.equalsIgnoreCase("pt") || argument.equalsIgnoreCase("p2")) {//TODO editor permissions for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { a.getRegion().setPos2(((Player) sender).getTargetBlock(null, 10)); config.setArenaPos(2, a.getName(), a.getRegion().getPos2()); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Position two set."); return true; }//TODO Check if block is null (looking too far away), do later in interest of getting this done. } } else if(argument.equalsIgnoreCase("wpostwo") || argument.equalsIgnoreCase("wpt") || argument.equalsIgnoreCase("wp2")) {//TODO editor permissions for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { a.getWaitingRegion().setPos2(((Player) sender).getTargetBlock(null, 10)); config.setArenaPos(4, a.getName(), a.getWaitingRegion().getPos2()); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Waiting region position two set."); return true; }//TODO Check if block is null (looking too far away), do later in interest of getting this done. } } else if(argument.equalsIgnoreCase("spawn") && args.length >= 2) {//TODO editor permissions for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { StringBuilder sb = new StringBuilder(); for(int i = 1; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } if(sb.toString().equalsIgnoreCase("waiting") || sb.toString().equalsIgnoreCase("wait") || sb.toString().equalsIgnoreCase("w")) { if(a.getWaitingRegion().setSpawn(((Player) sender).getTargetBlock(null, 10).getLocation())) { config.setSpawn(a.getName(), "WaitingAreaSpawn", a.getWaitingRegion().getSpawn()); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Waiting area spawn set."); } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] Waiting spawn was not created, place spawn inside region."); } return true; } else { if(a.getTeams().containsKey(sb.toString().toLowerCase())) {//TODO if containsKey is case sensitive need new way to match arena names if(a.getRegion().addTeamSpawn(sb.toString().toLowerCase(), ((Player) sender).getTargetBlock(null, 10).getLocation())) { config.setSpawn(a.getName(), sb.toString().toLowerCase(), a.getRegion().getTeamSpawn(sb.toString().toLowerCase())); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Team " + sb.toString().toLowerCase() + " spawn was created."); return true; } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] Spawn was not created, place spawn inside region."); return true; } } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] No team with that name was found, no spawn was set."); return true; } } } } } else if(argument.equalsIgnoreCase("addteam") && args.length >= 2) { StringBuilder sb = new StringBuilder(); for(int i = 1; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { a.addTeamName(sb.toString().toLowerCase()); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Team " + sb.toString().toLowerCase() + " added."); return true; } } } else if(argument.equalsIgnoreCase("remteam") && args.length >= 2) { StringBuilder sb = new StringBuilder(); for(int i = 1; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { if(a.removeTeamName(sb.toString().toLowerCase())) { sender.sendMessage(ChatColor.GRAY + "[Coliseum] Team " + sb.toString().toLowerCase() + " removed"); config.removeTeam(a.getName(), sb.toString()); return true; } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] No team " + sb.toString().toLowerCase() + " was found"); return true; } } } } else if(argument.equalsIgnoreCase("enable") && args.length >= 2) {//TODO Admin (and/or editor) [multiple permissions? admin can boot, editor can't?] StringBuilder sb = new StringBuilder(); for(int i = 1; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } for(Arena a: plugin.getArenaSet()) { if(a.isThisArena(sb.toString())) { if(a.enable()) { config.setArenaEnabledState(a.getName(), true); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Arena was successfully enabled!"); return true; } sender.sendMessage(ChatColor.GRAY + "[Coliseum] This arena was not ready to be enabled for some reason."); return true; } } sender.sendMessage(ChatColor.GRAY + "[Coliseum] No arena was found by that name."); return true; } else if(argument.equalsIgnoreCase("join") && !plugin.isPlayerJoined(((Player) sender).getName()) && args.length >= 2) {//TODO player permissions for(Arena a : plugin.getArenaSet()) { if(a.isPlayerEditing((Player) sender)) { sender.sendMessage(ChatColor.GRAY + "[Coliseum] You're still editing something. Quit editing and try to join again."); return true; } } StringBuilder sb = new StringBuilder(); for(int i = 1; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } for(Arena a : plugin.getArenaSet()) { if(a.isThisArena(sb.toString())) { if(a.isEnabled()) { a.addPlayer(((Player) sender)); sender.sendMessage(ChatColor.GRAY + "[Coliseum] Welcome to " + a.getName() + "!"); return true; } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] Arena was not enabled."); return true; } } sender.sendMessage(ChatColor.GRAY + "[Coliseum] No arena was found by that name."); return true; } } else if(argument.equalsIgnoreCase("leave") && plugin.isPlayerJoined(((Player) sender).getName())) {//TODO player permissions for(Arena a : plugin.getArenaSet()) { if(a.hasThisPlayer(((Player) sender))) { a.removePlayer(((Player) sender)); sender.sendMessage(ChatColor.GRAY + "Arena left."); return true; } sender.sendMessage(ChatColor.GRAY + "[Coliseum] You're not in an arena."); return true; } } else if(argument.equalsIgnoreCase("team") && args.length >= 2) { StringBuilder sb = new StringBuilder(); for(int i = 1; i <= (args.length - 1); i++) { if(i + 1 == args.length) { sb.append(args[i]); break; } sb.append(args[i] + " "); } for(Arena a : plugin.getArenaSet()) { if(a.hasThisPlayer((Player) sender)) { if(a.getTeams().containsKey(sb.toString().toLowerCase())) { a.getCombatant((Player) sender).joinTeam(sb.toString()); sender.sendMessage(ChatColor.GRAY + "[Colisemm] Your team is now set to " + sb.toString() + "."); return true; } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] No team was found by that name."); return true; } } } } else if(argument.equalsIgnoreCase("ready")) {//TODO fix me for(Arena a : plugin.getArenaSet()) { if(a.hasThisPlayer((Player) sender)) { Combatant c = a.getCombatant((Player) sender); if(c.setReadiness(!c.isReady())) { sender.sendMessage(ChatColor.GRAY + "[Coliseum] You are now " + (c.isReady() ? "ready." : "not ready.")); return true; } else { sender.sendMessage(ChatColor.GRAY + "[Coliseum] You could not be readied for some reason. Ensure you are entirely set up."); return true; } } } sender.sendMessage(ChatColor.GRAY + "[Coliseum] You are not in an arena."); } else if(argument.equalsIgnoreCase("start")) {//TODO FIX ME for(Arena a : plugin.getArenaSet()) { a.start(); } } //TODO implement other commands (disable, kick, forcestart, forcend, createteam, removeteam) //TODO implement a "help" message. return true; } }
diff --git a/src/com/anysoftkeyboard/keyboards/views/AnyKeyboardBaseView.java b/src/com/anysoftkeyboard/keyboards/views/AnyKeyboardBaseView.java index c1631d2a..d4eae93e 100644 --- a/src/com/anysoftkeyboard/keyboards/views/AnyKeyboardBaseView.java +++ b/src/com/anysoftkeyboard/keyboards/views/AnyKeyboardBaseView.java @@ -1,2768 +1,2768 @@ /* * Copyright (C) 2011 AnySoftKeyboard * * 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.anysoftkeyboard.keyboards.views; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.res.ColorStateList; import android.content.res.Configuration; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.FontMetrics; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.text.Layout.Alignment; import android.text.StaticLayout; import android.text.TextPaint; import android.text.TextUtils; import android.util.AttributeSet; import android.util.FloatMath; import android.util.Log; import android.util.TypedValue; import android.view.GestureDetector; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.ImageView; import android.widget.PopupWindow; import android.widget.TextView; import com.anysoftkeyboard.AnyKeyboardContextProvider; import com.anysoftkeyboard.Configuration.AnimationsLevel; import com.anysoftkeyboard.api.KeyCodes; import com.anysoftkeyboard.devicespecific.AskOnGestureListener; import com.anysoftkeyboard.devicespecific.WMotionEvent; import com.anysoftkeyboard.keyboards.AnyKeyboard; import com.anysoftkeyboard.keyboards.AnyKeyboard.AnyKey; import com.anysoftkeyboard.keyboards.AnyPopupKeyboard; import com.anysoftkeyboard.keyboards.Keyboard; import com.anysoftkeyboard.keyboards.Keyboard.Key; import com.anysoftkeyboard.keyboards.KeyboardDimens; import com.anysoftkeyboard.theme.KeyboardTheme; import com.anysoftkeyboard.theme.KeyboardThemeFactory; import com.anysoftkeyboard.utils.IMEUtil.GCUtils; import com.anysoftkeyboard.utils.IMEUtil.GCUtils.MemRelatedOperation; import com.menny.android.anysoftkeyboard.AnyApplication; import com.menny.android.anysoftkeyboard.R; public class AnyKeyboardBaseView extends View implements PointerTracker.UIProxy, OnSharedPreferenceChangeListener { static final String TAG = "ASKKbdViewBase"; public static final int NOT_A_TOUCH_COORDINATE = -1; // Timing constants private final int mKeyRepeatInterval; // Miscellaneous constants public static final int NOT_A_KEY = -1; private static final int[] LONG_PRESSABLE_STATE_SET = { android.R.attr.state_long_pressable }; // private static final int NUMBER_HINT_VERTICAL_ADJUSTMENT_PIXEL = -1; private static final int[] DRAWABLE_STATE_MODIFIER_NORMAL = new int[] {}; private static final int[] DRAWABLE_STATE_MODIFIER_PRESSED = new int[] { android.R.attr.state_pressed }; private static final int[] DRAWABLE_STATE_MODIFIER_LOCKED = new int[] { android.R.attr.state_checked }; private static final int[] DRAWABLE_STATE_ACTION_NORMAL = new int[] {}; private static final int[] DRAWABLE_STATE_ACTION_DONE = new int[] { R.attr.action_done }; private static final int[] DRAWABLE_STATE_ACTION_SEARCH = new int[] { R.attr.action_search }; private static final int[] DRAWABLE_STATE_ACTION_GO = new int[] { R.attr.action_go }; // XML attribute private float mKeyTextSize; private FontMetrics mTextFM; private ColorStateList mKeyTextColor; private Typeface mKeyTextStyle = Typeface.DEFAULT; private float mLabelTextSize; private FontMetrics mLabelFM; private float mKeyboardNameTextSize; private FontMetrics mKeyboardNameFM; private ColorStateList mKeyboardNameTextColor; private float mHintTextSize; private ColorStateList mHintTextColor; private FontMetrics mHintTextFM; private int mHintLabelAlign; private int mHintLabelVAlign; private String mHintOverflowLabel = null; private int mSymbolColorScheme = 0; private int mShadowColor; private int mShadowRadius; private int mShadowOffsetX; private int mShadowOffsetY; private Drawable mKeyBackground; /* keys icons */ private Drawable mShiftIcon; private Drawable mControlIcon; private Drawable mActionKeyIcon; private Drawable mDeleteKeyIcon; private Drawable mSpaceKeyIcon; private Drawable mTabKeyIcon; private Drawable mCancelKeyIcon; private Drawable mGlobeKeyIcon; private Drawable mMicKeyIcon; private Drawable mSettingsKeyIcon; private Drawable mArrowRightKeyIcon; private Drawable mArrowLeftKeyIcon; private Drawable mArrowUpKeyIcon; private Drawable mArrowDownKeyIcon; private Drawable mMoveHomeKeyIcon; private Drawable mMoveEndKeyIcon; private float mBackgroundDimAmount; private float mKeyHysteresisDistance; private float mVerticalCorrection; private int mPreviewOffset; // private int mPreviewHeight; // private final int mPopupLayout = R.layout.keyboard_popup; // Main keyboard private AnyKeyboard mKeyboard; private String mKeyboardName; private Key[] mKeys; // Key preview popup private ViewGroup mPreviewLayut; private TextView mPreviewText; private ImageView mPreviewIcon; private PopupWindow mPreviewPopup; private boolean mStaticLocationPopupWindow = false; private int mPreviewKeyTextSize; private int mPreviewLabelTextSize; private int mPreviewPaddingWidth = -1; private int mPreviewPaddingHeight = -1; // private int mPreviewTextSizeLarge; private int[] mOffsetInWindow; private int mOldPreviewKeyIndex = NOT_A_KEY; private boolean mShowPreview = true; private final boolean mShowTouchPoints = false; private int mPopupPreviewOffsetX; private int mPopupPreviewOffsetY; private int mWindowY; private int mPopupPreviewDisplayedY; private final int mDelayBeforePreview; private final int mDelayAfterPreview; // Popup mini keyboard protected PopupWindow mMiniKeyboardPopup; protected AnyKeyboardBaseView mMiniKeyboard = null;; private boolean mMiniKeyboardVisible = false; private View mMiniKeyboardParent; // private final WeakHashMap<Key, AnyKeyboardBaseView> mMiniKeyboardCache = // new WeakHashMap<Key, AnyKeyboardBaseView>(); private int mMiniKeyboardOriginX; private int mMiniKeyboardOriginY; private long mMiniKeyboardPopupTime; private int[] mWindowOffset; private final float mMiniKeyboardSlideAllowance; private int mMiniKeyboardTrackerId; protected AnimationsLevel mAnimationLevel = AnyApplication.getConfig() .getAnimationsLevel(); /** Listener for {@link OnKeyboardActionListener}. */ OnKeyboardActionListener mKeyboardActionListener; private final ArrayList<PointerTracker> mPointerTrackers = new ArrayList<PointerTracker>(); // TODO: Let the PointerTracker class manage this pointer queue final PointerQueue mPointerQueue = new PointerQueue(); private final boolean mHasDistinctMultitouch; private int mOldPointerCount = 1; protected KeyDetector mKeyDetector = new ProximityKeyDetector(); // Swipe gesture detector private GestureDetector mGestureDetector; private final SwipeTracker mSwipeTracker = new SwipeTracker(); int mSwipeVelocityThreshold; int mSwipeXDistanceThreshold; int mSwipeYDistanceThreshold; int mSwipeSpaceXDistanceThreshold; int mScrollXDistanceThreshold; int mScrollYDistanceThreshold; final boolean mDisambiguateSwipe; // private boolean mInScrollGesture = false; // Drawing /** Whether the keyboard bitmap needs to be redrawn before it's blitted. **/ private boolean mDrawPending; /** The dirty region in the keyboard bitmap */ private final Rect mDirtyRect = new Rect(); /** The keyboard bitmap for faster updates */ private Bitmap mBuffer; /** * Notes if the keyboard just changed, so that we could possibly reallocate * the mBuffer. */ protected boolean mKeyboardChanged; private Key mInvalidatedKey; /** The canvas for the above mutable keyboard bitmap */ // private Canvas mCanvas; private final Paint mPaint; private final Rect mKeyBackgroundPadding; private final Rect mClipRegion = new Rect(0, 0, 0, 0); /* * NOTE: this field EXISTS ONLY AFTER THE CTOR IS FINISHED! */ private AnyKeyboardContextProvider mAskContext; private final UIHandler mHandler = new UIHandler(); private Drawable mPreviewKeyBackground; private int mPreviewKeyTextColor; private final KeyboardDimensFromTheme mKeyboardDimens = new KeyboardDimensFromTheme(); class UIHandler extends Handler { private static final int MSG_POPUP_PREVIEW = 1; private static final int MSG_DISMISS_PREVIEW = 2; private static final int MSG_REPEAT_KEY = 3; private static final int MSG_LONGPRESS_KEY = 4; private boolean mInKeyRepeat; @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_POPUP_PREVIEW: showKey(msg.arg1, (PointerTracker) msg.obj); break; case MSG_DISMISS_PREVIEW: mPreviewPopup.dismiss(); break; case MSG_REPEAT_KEY: { final PointerTracker tracker = (PointerTracker) msg.obj; tracker.repeatKey(msg.arg1); startKeyRepeatTimer(mKeyRepeatInterval, msg.arg1, tracker); break; } case MSG_LONGPRESS_KEY: { final PointerTracker tracker = (PointerTracker) msg.obj; openPopupIfRequired(msg.arg1, tracker); break; } } } public void popupPreview(long delay, int keyIndex, PointerTracker tracker) { removeMessages(MSG_POPUP_PREVIEW); if (mPreviewPopup.isShowing() && mPreviewLayut.getVisibility() == VISIBLE) { // Show right away, if it's already visible and finger is moving // around showKey(keyIndex, tracker); } else { sendMessageDelayed( obtainMessage(MSG_POPUP_PREVIEW, keyIndex, 0, tracker), delay); } } public void cancelPopupPreview() { removeMessages(MSG_POPUP_PREVIEW); } public void dismissPreview(long delay) { if (mPreviewPopup.isShowing()) { sendMessageDelayed(obtainMessage(MSG_DISMISS_PREVIEW), delay); } } public void cancelDismissPreview() { removeMessages(MSG_DISMISS_PREVIEW); } public void startKeyRepeatTimer(long delay, int keyIndex, PointerTracker tracker) { mInKeyRepeat = true; sendMessageDelayed( obtainMessage(MSG_REPEAT_KEY, keyIndex, 0, tracker), delay); } public void cancelKeyRepeatTimer() { mInKeyRepeat = false; removeMessages(MSG_REPEAT_KEY); } public boolean isInKeyRepeat() { return mInKeyRepeat; } public void startLongPressTimer(long delay, int keyIndex, PointerTracker tracker) { removeMessages(MSG_LONGPRESS_KEY); sendMessageDelayed( obtainMessage(MSG_LONGPRESS_KEY, keyIndex, 0, tracker), delay); } public void cancelLongPressTimer() { removeMessages(MSG_LONGPRESS_KEY); } public void cancelKeyTimers() { cancelKeyRepeatTimer(); cancelLongPressTimer(); } public void cancelAllMessages() { cancelKeyTimers(); cancelPopupPreview(); cancelDismissPreview(); } } static class PointerQueue { private LinkedList<PointerTracker> mQueue = new LinkedList<PointerTracker>(); public void add(PointerTracker tracker) { mQueue.add(tracker); } public int lastIndexOf(PointerTracker tracker) { LinkedList<PointerTracker> queue = mQueue; for (int index = queue.size() - 1; index >= 0; index--) { PointerTracker t = queue.get(index); if (t == tracker) return index; } return -1; } public void releaseAllPointersOlderThan(PointerTracker tracker, long eventTime) { LinkedList<PointerTracker> queue = mQueue; int oldestPos = 0; for (PointerTracker t = queue.get(oldestPos); t != tracker; t = queue .get(oldestPos)) { if (t.isModifier()) { oldestPos++; } else { t.onUpEvent(t.getLastX(), t.getLastY(), eventTime); t.setAlreadyProcessed(); queue.remove(oldestPos); } } } public void releaseAllPointersExcept(PointerTracker tracker, long eventTime) { for (PointerTracker t : mQueue) { if (t == tracker) continue; t.onUpEvent(t.getLastX(), t.getLastY(), eventTime); t.setAlreadyProcessed(); } mQueue.clear(); if (tracker != null) mQueue.add(tracker); } public void remove(PointerTracker tracker) { mQueue.remove(tracker); } public boolean isInSlidingKeyInput() { for (final PointerTracker tracker : mQueue) { if (tracker.isInSlidingKeyInput()) return true; } return false; } public void cancelAllTrackers() { final long time = System.currentTimeMillis(); for (PointerTracker t : mQueue) { t.onCancelEvent(NOT_A_TOUCH_COORDINATE, NOT_A_TOUCH_COORDINATE, time); } mQueue.clear(); } } public AnyKeyboardBaseView(Context context, AttributeSet attrs) { this(context, attrs, R.style.PlainLightAnySoftKeyboard); } public AnyKeyboardBaseView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); LayoutInflater inflate = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // int previewLayout = 0; mPreviewKeyTextSize = -1; mPreviewLabelTextSize = -1; mPreviewKeyBackground = null; mPreviewKeyTextColor = 0xFFF; final int[] padding = new int[] { 0, 0, 0, 0 }; KeyboardTheme theme = KeyboardThemeFactory .getCurrentKeyboardTheme(context.getApplicationContext()); final int keyboardThemeStyleResId = getKeyboardStyleResId(theme); Log.d(TAG, "Will use keyboard theme " + theme.getName() + " id " + theme.getId() + " res " + keyboardThemeStyleResId); HashSet<Integer> doneStylesIndexes = new HashSet<Integer>(); TypedArray a = theme.getPackageContext().obtainStyledAttributes(null, R.styleable.AnySoftKeyboardTheme, 0, keyboardThemeStyleResId); final int n = a.getIndexCount(); for (int i = 0; i < n; i++) { final int attr = a.getIndex(i); if (setValueFromTheme(a, padding, attr)) doneStylesIndexes.add(attr); } a.recycle(); // taking icons int iconSetStyleRes = theme.getIconsThemeResId(); HashSet<Integer> doneIconsStylesIndexes = new HashSet<Integer>(); Log.d(TAG, "Will use keyboard icons theme " + theme.getName() + " id " + theme.getId() + " res " + iconSetStyleRes); if (iconSetStyleRes != 0) { a = theme.getPackageContext().obtainStyledAttributes(null, R.styleable.AnySoftKeyboardThemeKeyIcons, 0, iconSetStyleRes); final int iconsCount = a.getIndexCount(); for (int i = 0; i < iconsCount; i++) { final int attr = a.getIndex(i); if (setKeyIconValueFromTheme(a, attr)) doneIconsStylesIndexes.add(attr); } a.recycle(); } // filling what's missing KeyboardTheme fallbackTheme = KeyboardThemeFactory .getFallbackTheme(context.getApplicationContext()); final int keyboardFallbackThemeStyleResId = getKeyboardStyleResId(fallbackTheme); Log.d(TAG, "Will use keyboard fallback theme " + fallbackTheme.getName() + " id " + fallbackTheme.getId() + " res " + keyboardFallbackThemeStyleResId); a = fallbackTheme.getPackageContext().obtainStyledAttributes(null, R.styleable.AnySoftKeyboardTheme, 0, keyboardFallbackThemeStyleResId); final int fallbackCount = a.getIndexCount(); for (int i = 0; i < fallbackCount; i++) { final int attr = a.getIndex(i); if (doneStylesIndexes.contains(attr)) continue; if (AnyApplication.DEBUG) Log.d(TAG, "Falling back theme res ID " + attr); setValueFromTheme(a, padding, attr); } a.recycle(); // taking missing icons int fallbackIconSetStyleId = fallbackTheme.getIconsThemeResId(); Log.d(TAG, "Will use keyboard fallback icons theme " + fallbackTheme.getName() + " id " + fallbackTheme.getId() + " res " + fallbackIconSetStyleId); a = fallbackTheme.getPackageContext().obtainStyledAttributes(null, R.styleable.AnySoftKeyboardThemeKeyIcons, 0, fallbackIconSetStyleId); final int fallbackIconsCount = a.getIndexCount(); for (int i = 0; i < fallbackIconsCount; i++) { final int attr = a.getIndex(i); if (doneIconsStylesIndexes.contains(attr)) continue; if (AnyApplication.DEBUG) Log.d(TAG, "Falling back icon res ID " + attr); setKeyIconValueFromTheme(a, attr); } a.recycle(); // settings. // don't forget that there are TWO paddings, the theme's and the // background image's padding! Drawable keyboardBabground = super.getBackground(); if (keyboardBabground != null) { Rect backgroundPadding = new Rect(); keyboardBabground.getPadding(backgroundPadding); padding[0] += backgroundPadding.left; padding[1] += backgroundPadding.top; padding[2] += backgroundPadding.right; padding[3] += backgroundPadding.bottom; } super.setPadding(padding[0], padding[1], padding[2], padding[3]); final Resources res = getResources(); mKeyboardDimens.setKeyboardMaxWidth(res.getDisplayMetrics().widthPixels - padding[0] - padding[2]); mPreviewPopup = new PopupWindow(context); if (mPreviewKeyTextSize > 0) { if (mPreviewLabelTextSize <= 0) mPreviewLabelTextSize = mPreviewKeyTextSize; mPreviewLayut = (ViewGroup) inflate.inflate(R.layout.key_preview, null); mPreviewText = (TextView) mPreviewLayut .findViewById(R.id.key_preview_text); mPreviewText.setTextColor(mPreviewKeyTextColor); mPreviewText.setTypeface(mKeyTextStyle); mPreviewIcon = (ImageView) mPreviewLayut .findViewById(R.id.key_preview_icon); mPreviewPopup.setBackgroundDrawable(mPreviewKeyBackground); mPreviewPopup.setContentView(mPreviewLayut); mShowPreview = true; } else { mPreviewLayut = null; mPreviewText = null; mShowPreview = false; } mPreviewPopup.setTouchable(false); mPreviewPopup .setAnimationStyle((mAnimationLevel == AnimationsLevel.None) ? 0 : R.style.KeyPreviewAnimation); mDelayBeforePreview = 0; mDelayAfterPreview = 10; mMiniKeyboardParent = this; mMiniKeyboardPopup = new PopupWindow(context); mMiniKeyboardPopup.setBackgroundDrawable(null); mMiniKeyboardPopup .setAnimationStyle((mAnimationLevel == AnimationsLevel.None) ? 0 : R.style.MiniKeyboardAnimation); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setTextSize(mKeyTextSize); mPaint.setTextAlign(Align.CENTER); mPaint.setAlpha(255); mKeyBackgroundPadding = new Rect(0, 0, 0, 0); mKeyBackground.getPadding(mKeyBackgroundPadding); if (AnyApplication.DEBUG) Log.d(TAG, "mKeyBackgroundPadding(L,R,T,B) " + mKeyBackgroundPadding.left + "," + mKeyBackgroundPadding.right + "," + mKeyBackgroundPadding.top + "," + mKeyBackgroundPadding.bottom); reloadSwipeThresholdsSettings(res); mDisambiguateSwipe = res.getBoolean(R.bool.config_swipeDisambiguation); mMiniKeyboardSlideAllowance = res .getDimension(R.dimen.mini_keyboard_slide_allowance); AskOnGestureListener listener = new AskGestureEventsListener(this, mSwipeTracker); mGestureDetector = AnyApplication.getDeviceSpecific() .createGestureDetector(getContext(), listener); mGestureDetector.setIsLongpressEnabled(false); // MultiTouchSupportLevel multiTouchSupportLevel = // AnyApplication.getDeviceSpecific().getMultiTouchSupportLevel(getContext()); mHasDistinctMultitouch = true;/* * (multiTouchSupportLevel == * MultiTouchSupportLevel.Basic) * ||(multiTouchSupportLevel == * MultiTouchSupportLevel.Distinct); */ mKeyRepeatInterval = 50; AnyApplication.getConfig().addChangedListener(this); } public void setAnySoftKeyboardContext(AnyKeyboardContextProvider askContext) { mAskContext = askContext; } public boolean setValueFromTheme(TypedArray a, final int[] padding, final int attr) { try { switch (attr) { case R.styleable.AnySoftKeyboardTheme_android_background: Drawable keyboardBackground = a.getDrawable(attr); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_android_background " + (keyboardBackground != null)); super.setBackgroundDrawable(keyboardBackground); break; case R.styleable.AnySoftKeyboardTheme_android_paddingLeft: padding[0] = a.getDimensionPixelSize(attr, 0); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_android_paddingLeft " + padding[0]); break; case R.styleable.AnySoftKeyboardTheme_android_paddingTop: padding[1] = a.getDimensionPixelSize(attr, 0); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_android_paddingTop " + padding[1]); break; case R.styleable.AnySoftKeyboardTheme_android_paddingRight: padding[2] = a.getDimensionPixelSize(attr, 0); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_android_paddingRight " + padding[2]); break; case R.styleable.AnySoftKeyboardTheme_android_paddingBottom: padding[3] = a.getDimensionPixelSize(attr, 0); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_android_paddingBottom " + padding[3]); break; case R.styleable.AnySoftKeyboardTheme_keyBackground: mKeyBackground = a.getDrawable(attr); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_keyBackground " + (mKeyBackground != null)); break; case R.styleable.AnySoftKeyboardTheme_keyHysteresisDistance: mKeyHysteresisDistance = a.getDimensionPixelOffset(attr, 0); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_keyHysteresisDistance " + mKeyHysteresisDistance); break; case R.styleable.AnySoftKeyboardTheme_verticalCorrection: mVerticalCorrection = a.getDimensionPixelOffset(attr, 0); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_verticalCorrection " + mVerticalCorrection); break; case R.styleable.AnySoftKeyboardTheme_keyPreviewBackground: mPreviewKeyBackground = a.getDrawable(attr); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_keyPreviewBackground " + (mPreviewKeyBackground != null)); break; case R.styleable.AnySoftKeyboardTheme_keyPreviewTextColor: mPreviewKeyTextColor = a.getColor(attr, 0xFFF); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_keyPreviewTextColor " + mPreviewKeyTextColor); break; case R.styleable.AnySoftKeyboardTheme_keyPreviewTextSize: mPreviewKeyTextSize = a.getDimensionPixelSize(attr, 0); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_keyPreviewTextSize " + mPreviewKeyTextSize); break; case R.styleable.AnySoftKeyboardTheme_keyPreviewLabelTextSize: mPreviewLabelTextSize = a.getDimensionPixelSize(attr, 0); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_keyPreviewLabelTextSize " + mPreviewLabelTextSize); break; case R.styleable.AnySoftKeyboardTheme_keyPreviewOffset: mPreviewOffset = a.getDimensionPixelOffset(attr, 0); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_keyPreviewOffset " + mPreviewOffset); break; case R.styleable.AnySoftKeyboardTheme_keyTextSize: mKeyTextSize = a.getDimensionPixelSize(attr, 18); // you might ask yourself "why did Menny sqrt root the factor?" // I'll tell you; the factor is mostly for the height, not the // font size, // but I also factorize the font size because I want the text to // be a little like // the key size. // the whole factor maybe too much, so I ease that a bit. if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) mKeyTextSize = mKeyTextSize * FloatMath.sqrt(AnyApplication.getConfig() .getKeysHeightFactorInLandscape()); else mKeyTextSize = mKeyTextSize * FloatMath.sqrt(AnyApplication.getConfig() .getKeysHeightFactorInPortrait()); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_keyTextSize " + mKeyTextSize); break; case R.styleable.AnySoftKeyboardTheme_keyTextColor: mKeyTextColor = a.getColorStateList(attr); if (mKeyTextColor == null) { if (AnyApplication.DEBUG) Log.d(TAG, "Creating an empty ColorStateList for mKeyTextColor"); mKeyTextColor = new ColorStateList(new int[][] { { 0 } }, new int[] { a.getColor(attr, 0xFF000000) }); } if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_keyTextColor " + mKeyTextColor); break; case R.styleable.AnySoftKeyboardTheme_labelTextSize: mLabelTextSize = a.getDimensionPixelSize(attr, 14); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) mLabelTextSize = mLabelTextSize * AnyApplication.getConfig() .getKeysHeightFactorInLandscape(); else mLabelTextSize = mLabelTextSize * AnyApplication.getConfig() .getKeysHeightFactorInPortrait(); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_labelTextSize " + mLabelTextSize); break; case R.styleable.AnySoftKeyboardTheme_keyboardNameTextSize: mKeyboardNameTextSize = a.getDimensionPixelSize(attr, 10); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) mKeyboardNameTextSize = mKeyboardNameTextSize * AnyApplication.getConfig() .getKeysHeightFactorInLandscape(); else mKeyboardNameTextSize = mKeyboardNameTextSize * AnyApplication.getConfig() .getKeysHeightFactorInPortrait(); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_keyboardNameTextSize " + mKeyboardNameTextSize); break; case R.styleable.AnySoftKeyboardTheme_keyboardNameTextColor: mKeyboardNameTextColor = a.getColorStateList(attr); if (mKeyboardNameTextColor == null) { if (AnyApplication.DEBUG) Log.d(TAG, "Creating an empty ColorStateList for mKeyboardNameTextColor"); mKeyboardNameTextColor = new ColorStateList(new int[][] { { 0 } }, new int[] { a.getColor(attr, 0xFFAAAAAA) }); } if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_keyboardNameTextColor " + mKeyboardNameTextColor); break; case R.styleable.AnySoftKeyboardTheme_shadowColor: mShadowColor = a.getColor(attr, 0); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_shadowColor " + mShadowColor); break; case R.styleable.AnySoftKeyboardTheme_shadowRadius: mShadowRadius = a.getDimensionPixelOffset(attr, 0); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_shadowRadius " + mShadowRadius); break; case R.styleable.AnySoftKeyboardTheme_shadowOffsetX: mShadowOffsetX = a.getDimensionPixelOffset(attr, 0); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_shadowOffsetX " + mShadowOffsetX); break; case R.styleable.AnySoftKeyboardTheme_shadowOffsetY: mShadowOffsetY = a.getDimensionPixelOffset(attr, 0); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_shadowOffsetY " + mShadowOffsetY); break; case R.styleable.AnySoftKeyboardTheme_backgroundDimAmount: mBackgroundDimAmount = a.getFloat(attr, 0.5f); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_backgroundDimAmount " + mBackgroundDimAmount); break; case R.styleable.AnySoftKeyboardTheme_keyTextStyle: int textStyle = a.getInt(attr, 0); switch (textStyle) { case 0: mKeyTextStyle = Typeface.DEFAULT; break; case 1: mKeyTextStyle = Typeface.DEFAULT_BOLD; break; case 2: mKeyTextStyle = Typeface.defaultFromStyle(Typeface.ITALIC); break; default: mKeyTextStyle = Typeface.defaultFromStyle(textStyle); break; } if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_keyTextStyle " + mKeyTextStyle); break; case R.styleable.AnySoftKeyboardTheme_symbolColorScheme: mSymbolColorScheme = a.getInt(attr, 0); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_symbolColorScheme " + mSymbolColorScheme); break; case R.styleable.AnySoftKeyboardTheme_keyHorizontalGap: float themeHorizotalKeyGap = a.getDimensionPixelOffset(attr, 0); mKeyboardDimens.setHorizontalKeyGap(themeHorizotalKeyGap); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_keyHorizontalGap " + themeHorizotalKeyGap); break; case R.styleable.AnySoftKeyboardTheme_keyVerticalGap: float themeVerticalRowGap = a.getDimensionPixelOffset(attr, 0); mKeyboardDimens.setVerticalRowGap(themeVerticalRowGap); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_keyVerticalGap " + themeVerticalRowGap); break; case R.styleable.AnySoftKeyboardTheme_keyNormalHeight: float themeNormalKeyHeight = a.getDimensionPixelOffset(attr, 0); mKeyboardDimens.setNormalKeyHeight(themeNormalKeyHeight); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_keyNormalHeight " + themeNormalKeyHeight); break; case R.styleable.AnySoftKeyboardTheme_keyLargeHeight: float themeLargeKeyHeight = a.getDimensionPixelOffset(attr, 0); mKeyboardDimens.setLargeKeyHeight(themeLargeKeyHeight); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_keyLargeHeight " + themeLargeKeyHeight); break; case R.styleable.AnySoftKeyboardTheme_keySmallHeight: float themeSmallKeyHeight = a.getDimensionPixelOffset(attr, 0); mKeyboardDimens.setSmallKeyHeight(themeSmallKeyHeight); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_keySmallHeight " + themeSmallKeyHeight); break; case R.styleable.AnySoftKeyboardTheme_hintTextSize: mHintTextSize = a.getDimensionPixelSize(attr, 0); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_hintTextSize " + mHintTextSize); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) mHintTextSize = mHintTextSize * AnyApplication.getConfig() .getKeysHeightFactorInLandscape(); else mHintTextSize = mHintTextSize * AnyApplication.getConfig() .getKeysHeightFactorInPortrait(); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_hintTextSize with factor " + mHintTextSize); break; case R.styleable.AnySoftKeyboardTheme_hintTextColor: mHintTextColor = a.getColorStateList(attr); if (mHintTextColor == null) { if (AnyApplication.DEBUG) Log.d(TAG, "Creating an empty ColorStateList for mHintTextColor"); mHintTextColor = new ColorStateList(new int[][] { { 0 } }, new int[] { a.getColor(attr, 0xFF000000) }); } if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_hintTextColor " + mHintTextColor); break; case R.styleable.AnySoftKeyboardTheme_hintLabelVAlign: mHintLabelVAlign = a.getInt(attr, Gravity.BOTTOM); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_hintLabelVAlign " + mHintLabelVAlign); break; case R.styleable.AnySoftKeyboardTheme_hintLabelAlign: mHintLabelAlign = a.getInt(attr, Gravity.RIGHT); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_hintLabelAlign " + mHintLabelAlign); break; case R.styleable.AnySoftKeyboardTheme_hintOverflowLabel: mHintOverflowLabel = a.getString(attr); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardTheme_hintOverflowLabel " + mHintOverflowLabel); break; } return true; } catch (Exception e) { // on API changes, so the incompatible themes wont crash me.. e.printStackTrace(); return false; } } public boolean setKeyIconValueFromTheme(TypedArray a, final int attr) { try { switch (attr) { case R.styleable.AnySoftKeyboardThemeKeyIcons_iconKeyShift: mShiftIcon = a.getDrawable(attr); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardThemeKeyIcons_iconKeyShift " + (mShiftIcon != null)); break; case R.styleable.AnySoftKeyboardThemeKeyIcons_iconKeyControl: mControlIcon = a.getDrawable(attr); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardThemeKeyIcons_iconKeyControl " + (mControlIcon != null)); break; case R.styleable.AnySoftKeyboardThemeKeyIcons_iconKeyAction: mActionKeyIcon = a.getDrawable(attr); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardThemeKeyIcons_iconKeyAction " + (mActionKeyIcon != null)); break; case R.styleable.AnySoftKeyboardThemeKeyIcons_iconKeyBackspace: mDeleteKeyIcon = a.getDrawable(attr); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardThemeKeyIcons_iconKeyBackspace " + (mDeleteKeyIcon != null)); break; case R.styleable.AnySoftKeyboardThemeKeyIcons_iconKeyCancel: mCancelKeyIcon = a.getDrawable(attr); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardThemeKeyIcons_iconKeyCancel " + (mCancelKeyIcon != null)); break; case R.styleable.AnySoftKeyboardThemeKeyIcons_iconKeyGlobe: mGlobeKeyIcon = a.getDrawable(attr); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardThemeKeyIcons_iconKeyGlobe " + (mGlobeKeyIcon != null)); break; case R.styleable.AnySoftKeyboardThemeKeyIcons_iconKeySpace: mSpaceKeyIcon = a.getDrawable(attr); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardThemeKeyIcons_iconKeySpace " + (mSpaceKeyIcon != null)); break; case R.styleable.AnySoftKeyboardThemeKeyIcons_iconKeyTab: mTabKeyIcon = a.getDrawable(attr); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardThemeKeyIcons_iconKeyTab " + (mTabKeyIcon != null)); break; case R.styleable.AnySoftKeyboardThemeKeyIcons_iconKeyArrowDown: mArrowDownKeyIcon = a.getDrawable(attr); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardThemeKeyIcons_iconKeyArrowDown " + (mArrowDownKeyIcon != null)); break; case R.styleable.AnySoftKeyboardThemeKeyIcons_iconKeyArrowLeft: mArrowLeftKeyIcon = a.getDrawable(attr); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardThemeKeyIcons_iconKeyArrowLeft " + (mArrowLeftKeyIcon != null)); break; case R.styleable.AnySoftKeyboardThemeKeyIcons_iconKeyArrowRight: mArrowRightKeyIcon = a.getDrawable(attr); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardThemeKeyIcons_iconKeyArrowRight " + (mArrowRightKeyIcon != null)); break; case R.styleable.AnySoftKeyboardThemeKeyIcons_iconKeyArrowUp: mArrowUpKeyIcon = a.getDrawable(attr); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardThemeKeyIcons_iconKeyArrowUp " + (mArrowUpKeyIcon != null)); break; case R.styleable.AnySoftKeyboardThemeKeyIcons_iconKeyInputMoveHome: mMoveHomeKeyIcon = a.getDrawable(attr); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardThemeKeyIcons_iconKeyInputMoveHome " + (mMoveHomeKeyIcon != null)); break; case R.styleable.AnySoftKeyboardThemeKeyIcons_iconKeyInputMoveEnd: mMoveEndKeyIcon = a.getDrawable(attr); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardThemeKeyIcons_iconKeyInputMoveEnd " + (mMoveEndKeyIcon != null)); break; case R.styleable.AnySoftKeyboardThemeKeyIcons_iconKeyMic: mMicKeyIcon = a.getDrawable(attr); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardThemeKeyIcons_iconKeyMic " + (mMicKeyIcon != null)); break; case R.styleable.AnySoftKeyboardThemeKeyIcons_iconKeySettings: mSettingsKeyIcon = a.getDrawable(attr); if (AnyApplication.DEBUG) Log.d(TAG, "AnySoftKeyboardThemeKeyIcons_iconKeySettings " + (mSettingsKeyIcon != null)); break; } return true; } catch (Exception e) { e.printStackTrace(); return false; } } protected int getKeyboardStyleResId(KeyboardTheme theme) { return theme.getPopupThemeResId(); } /* * public int getKeyboardMaxWidth() { return mMaxKeyboardWidth; } public int * getThemeVerticalRowGap() { return mThemeVerticalRowGap; } public int * getThemeHorizontalKeyGap() { return mThemeHorizotalKeyGap; } */ private void reloadSwipeThresholdsSettings(final Resources res) { final float density = res.getDisplayMetrics().density; mSwipeVelocityThreshold = (int) (AnyApplication.getConfig() .getSwipeVelocityThreshold() * density); mSwipeXDistanceThreshold = (int) (AnyApplication.getConfig() .getSwipeDistanceThreshold() * density); Keyboard kbd = getKeyboard(); if (kbd != null) { mSwipeYDistanceThreshold = (int) (mSwipeXDistanceThreshold * (((float) kbd .getHeight()) / ((float) getWidth()))); } else { mSwipeYDistanceThreshold = 0; } if (mSwipeYDistanceThreshold == 0) mSwipeYDistanceThreshold = mSwipeXDistanceThreshold; mSwipeSpaceXDistanceThreshold = mSwipeXDistanceThreshold / 2; mSwipeYDistanceThreshold = mSwipeYDistanceThreshold / 2; mScrollXDistanceThreshold = mSwipeXDistanceThreshold / 8; mScrollYDistanceThreshold = mSwipeYDistanceThreshold / 8; if (AnyApplication.DEBUG) { Log.d(TAG, String.format( "Swipe thresholds: Velocity %d, X-Distance %d, Y-Distance %d", mSwipeVelocityThreshold, mSwipeXDistanceThreshold, mSwipeYDistanceThreshold)); } } public void setOnKeyboardActionListener(OnKeyboardActionListener listener) { mKeyboardActionListener = listener; for (PointerTracker tracker : mPointerTrackers) { tracker.setOnKeyboardActionListener(listener); } } /** * Returns the {@link OnKeyboardActionListener} object. * * @return the listener attached to this keyboard */ protected OnKeyboardActionListener getOnKeyboardActionListener() { return mKeyboardActionListener; } /** * Attaches a keyboard to this view. The keyboard can be switched at any * time and the view will re-layout itself to accommodate the keyboard. * * @see Keyboard * @see #getKeyboard() * @param keyboard * the keyboard to display in this view */ public void setKeyboard(AnyKeyboard keyboard) { setKeyboard(keyboard, mVerticalCorrection); } public void setKeyboard(AnyKeyboard keyboard, float verticalCorrection) { if (mKeyboard != null) { dismissKeyPreview(); } // Remove any pending messages, except dismissing preview mHandler.cancelKeyTimers(); mHandler.cancelPopupPreview(); mKeyboard = keyboard; mKeyboardName = keyboard != null? keyboard.getKeyboardName() : null; // ImeLogger.onSetKeyboard(keyboard); mKeys = mKeyDetector.setKeyboard(keyboard); mKeyDetector.setCorrection(-getPaddingLeft(), -getPaddingTop() + verticalCorrection); // mKeyboardVerticalGap = // (int)getResources().getDimension(R.dimen.key_bottom_gap); for (PointerTracker tracker : mPointerTrackers) { tracker.setKeyboard(mKeys, mKeyHysteresisDistance); } // setting the icon/text setSpecialKeysIconsAndLabels(); requestLayout(); // Hint to reallocate the buffer if the size changed mKeyboardChanged = true; invalidateAllKeys(); computeProximityThreshold(keyboard); // mMiniKeyboardCache.clear(); super.invalidate(); } /** * Returns the current keyboard being displayed by this view. * * @return the currently attached keyboard * @see #setKeyboard(Keyboard) */ public AnyKeyboard getKeyboard() { return mKeyboard; } /** * Return whether the device has distinct multi-touch panel. * * @return true if the device has distinct multi-touch panel. */ public boolean hasDistinctMultitouch() { return mHasDistinctMultitouch; } /** * Sets the state of the shift key of the keyboard, if any. * * @param shifted * whether or not to enable the state of the shift key * @return true if the shift key state changed, false if there was no change */ public boolean setShifted(boolean shifted) { if (mKeyboard != null) { if (mKeyboard.setShifted(shifted)) { // The whole keyboard probably needs to be redrawn invalidateAllKeys(); return true; } } return false; } /** * Returns the state of the shift key of the keyboard, if any. * * @return true if the shift is in a pressed state, false otherwise. If * there is no shift key on the keyboard or there is no keyboard * attached, it returns false. */ public boolean isShifted() { if (isPopupShowing()) return mMiniKeyboard.isShifted(); if (mKeyboard != null) return mKeyboard.isShifted(); return false; } /** * Sets the state of the control key of the keyboard, if any. * * @param control * whether or not to enable the state of the control key * @return true if the control key state changed, false if there was no * change */ public boolean setControl(boolean control) { if (mKeyboard != null) { if (mKeyboard.setControl(control)) { // The whole keyboard probably needs to be redrawn invalidateAllKeys(); return true; } } return false; } /** * Returns the state of the control key of the keyboard, if any. * * @return true if the control is in a pressed state, false otherwise. If * there is no control key on the keyboard or there is no keyboard * attached, it returns false. */ public boolean isControl() { if (mKeyboard != null) { return mKeyboard.isControl(); } return false; } /** * Enables or disables the key feedback popup. This is a popup that shows a * magnified version of the depressed key. By default the preview is * enabled. * * @param previewEnabled * whether or not to enable the key feedback popup * @see #isPreviewEnabled() */ protected void setPreviewEnabled(boolean previewEnabled) { mShowPreview = mPreviewText != null && previewEnabled; } // /** // * Returns the enabled state of the key feedback popup. // * @return whether or not the key feedback popup is enabled // * @see #setPreviewEnabled(boolean) // */ // public boolean isPreviewEnabled() { // return mShowPreview; // } public int getSymbolColorScheme() { return mSymbolColorScheme; } public void setPopupParent(View v) { mMiniKeyboardParent = v; } public void setPopupOffset(int x, int y) { mPopupPreviewOffsetX = x; mPopupPreviewOffsetY = y; mPreviewPopup.dismiss(); } /** * When enabled, calls to {@link OnKeyboardActionListener#onKey} will * include key codes for adjacent keys. When disabled, only the primary key * code will be reported. * * @param enabled * whether or not the proximity correction is enabled */ public void setProximityCorrectionEnabled(boolean enabled) { mKeyDetector.setProximityCorrectionEnabled(enabled); } /** * Returns true if proximity correction is enabled. */ public boolean isProximityCorrectionEnabled() { return mKeyDetector.isProximityCorrectionEnabled(); } private CharSequence adjustCase(AnyKey key) { // if (mKeyboard.isShifted() && label != null && label.length() < 3 // && Character.isLowerCase(label.charAt(0))) { // label = label.toString().toUpperCase(); // } CharSequence label = key.label; // if (mKeyboard.isShifted() && // (!TextUtils.isEmpty(label)) && // Character.isLowerCase(label.charAt(0))) { // label = label.toString().toUpperCase(); // } if (mKeyboard.isShifted()) { if (!TextUtils.isEmpty(key.shiftedKeyLabel)) label = key.shiftedKeyLabel; else if (!TextUtils.isEmpty(label) && Character.isLowerCase(label.charAt(0))) label = label.toString().toUpperCase(); } return label; } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // Round up a little if (mKeyboard == null) { setMeasuredDimension(getPaddingLeft() + getPaddingRight(), getPaddingTop() + getPaddingBottom()); } else { int width = mKeyboard.getMinWidth() + getPaddingLeft() + getPaddingRight(); if (MeasureSpec.getSize(widthMeasureSpec) < width + 10) { width = MeasureSpec.getSize(widthMeasureSpec); } setMeasuredDimension(width, mKeyboard.getHeight() + getPaddingTop() + getPaddingBottom()); } } /** * Compute the average distance between adjacent keys (horizontally and * vertically) and square it to get the proximity threshold. We use a square * here and in computing the touch distance from a key's center to avoid * taking a square root. * * @param keyboard */ private void computeProximityThreshold(Keyboard keyboard) { if (keyboard == null) return; final Key[] keys = mKeys; if (keys == null) return; int length = keys.length; int dimensionSum = 0; for (int i = 0; i < length; i++) { Key key = keys[i]; dimensionSum += Math.min(key.width, key.height/* * + * mKeyboardVerticalGap */) + key.gap; } if (dimensionSum < 0 || length == 0) return; mKeyDetector .setProximityThreshold((int) (dimensionSum * 1.4f / length)); } @Override public void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); // Release the buffer, if any and it will be reallocated on the next // draw mBuffer = null; } @Override public void onDraw(final Canvas canvas) { super.onDraw(canvas); // mCanvas = canvas; if (mDrawPending || mBuffer == null || mKeyboardChanged) { GCUtils.getInstance().peformOperationWithMemRetry(TAG, new MemRelatedOperation() { public void operation() { onBufferDraw(canvas); } }, true); } // maybe there is no buffer, since drawing was not done. if (mBuffer != null) canvas.drawBitmap(mBuffer, 0, 0, null); } private void onBufferDraw(Canvas canvas) { if (mKeyboardChanged) { invalidateAllKeys(); mKeyboardChanged = false; } canvas.getClipBounds(mDirtyRect); if (mKeyboard == null) return; - final boolean drawKeyboardNameText = (mKeyboardNameTextSize > 1) + final boolean drawKeyboardNameText = (mKeyboardNameTextSize > 1f) && AnyApplication.getConfig().getShowKeyboardNameText(); final boolean drawHintText = (mHintTextSize > 1) && AnyApplication.getConfig().getShowHintTextOnKeys(); if (AnyApplication.DEBUG && !drawHintText) { Log.d(TAG, "drawHintText is false. mHintTextSize: " + mHintTextSize + ", getShowHintTextOnKeys: " + AnyApplication.getConfig().getShowHintTextOnKeys()); } // TODO: calls to AnyApplication.getConfig().getXXXXX() functions are // not yet implemented, // but need to when allowing preferences to override theme settings of // these values // right now just using what should be the default values for these // unimplemented preferences final boolean useCustomKeyTextColor = false; // TODO: final boolean useCustomKeyTextColor = // AnyApplication.getConfig().getUseCustomTextColorOnKeys(); final ColorStateList keyTextColor = useCustomKeyTextColor ? new ColorStateList( new int[][] { { 0 } }, new int[] { 0xFF6666FF }) : mKeyTextColor; // TODO: ? AnyApplication.getConfig().getCustomKeyTextColorOnKeys() : // mKeyTextColor; final boolean useCustomHintColor = drawHintText && false; // TODO: final boolean useCustomHintColor = drawHintText && // AnyApplication.getConfig().getUseCustomHintColorOnKeys(); final ColorStateList hintColor = useCustomHintColor ? new ColorStateList( new int[][] { { 0 } }, new int[] { 0xFFFF6666 }) : mHintTextColor; // TODO: ? AnyApplication.getConfig().getCustomHintColorOnKeys() : // mHintTextColor; // allow preferences to override theme settings for hint text position final boolean useCustomHintAlign = drawHintText && AnyApplication.getConfig().getUseCustomHintAlign(); final int hintAlign = useCustomHintAlign ? AnyApplication.getConfig() .getCustomHintAlign() : mHintLabelAlign; final int hintVAlign = useCustomHintAlign ? AnyApplication.getConfig() .getCustomHintVAlign() : mHintLabelVAlign; final Paint paint = mPaint; final Drawable keyBackground = mKeyBackground; final Rect clipRegion = mClipRegion; final int kbdPaddingLeft = getPaddingLeft(); final int kbdPaddingTop = getPaddingTop(); final Key[] keys = mKeys; final Key invalidKey = mInvalidatedKey; boolean drawSingleKey = false; if (invalidKey != null && canvas.getClipBounds(clipRegion)) { // TODO we should use Rect.inset and Rect.contains here. // Is clipRegion completely contained within the invalidated key? if (invalidKey.x + kbdPaddingLeft - 1 <= clipRegion.left && invalidKey.y + kbdPaddingTop - 1 <= clipRegion.top && invalidKey.x + invalidKey.width + kbdPaddingLeft + 1 >= clipRegion.right && invalidKey.y + invalidKey.height + kbdPaddingTop + 1 >= clipRegion.bottom) { drawSingleKey = true; } } // canvas.drawColor(0x00000000, PorterDuff.Mode.CLEAR); final int keyCount = keys.length; for (int i = 0; i < keyCount; i++) { final AnyKey key = (AnyKey) keys[i]; final boolean keyIsSpace = isSpaceKey(key); if (drawSingleKey && (invalidKey != key)) { continue; } if (!mDirtyRect.intersects(key.x + kbdPaddingLeft, key.y + kbdPaddingTop, key.x + key.width + kbdPaddingLeft, key.y + key.height + kbdPaddingTop)) { continue; } int[] drawableState = key.getCurrentDrawableState(); if (keyIsSpace) paint.setColor(mKeyboardNameTextColor.getColorForState(drawableState, 0xFF000000)); else paint.setColor(keyTextColor.getColorForState(drawableState, 0xFF000000)); keyBackground.setState(drawableState); // Switch the character to uppercase if shift is pressed CharSequence label = key.label == null ? null : adjustCase(key) .toString(); final Rect bounds = keyBackground.getBounds(); if ((key.width != bounds.right) || (key.height != bounds.bottom)) { keyBackground.setBounds(0, 0, key.width, key.height); } canvas.translate(key.x + kbdPaddingLeft, key.y + kbdPaddingTop); keyBackground.draw(canvas); if (TextUtils.isEmpty(label)) { Drawable iconToDraw = getIconToDrawForKey(key, false); if (iconToDraw != null/* && shouldDrawIcon */) { // Special handing for the upper-right number hint icons final int drawableWidth; final int drawableHeight; final int drawableX; final int drawableY; drawableWidth = iconToDraw.getIntrinsicWidth(); drawableHeight = iconToDraw.getIntrinsicHeight(); drawableX = (key.width + mKeyBackgroundPadding.left - mKeyBackgroundPadding.right - drawableWidth) / 2; drawableY = (key.height + mKeyBackgroundPadding.top - mKeyBackgroundPadding.bottom - drawableHeight) / 2; canvas.translate(drawableX, drawableY); iconToDraw.setBounds(0, 0, drawableWidth, drawableHeight); iconToDraw.draw(canvas); canvas.translate(-drawableX, -drawableY); if (keyIsSpace && drawKeyboardNameText) { //now a little hack, I'll set the label now, so it get drawn. label = mKeyboardName; } } else { // ho... no icon. // I'll try to guess the text label = guessLabelForKey(key); if (TextUtils.isEmpty(label)) { Log.w(TAG, "That's unfortunate, for key " + key.codes[0] + " at (" + key.x + ", " + key.y + ") there is no icon nor label. Action ID is " + mKeyboardActionType); } } } if (label != null) { // For characters, use large font. For labels like "Done", use // small font. final FontMetrics fm; if (keyIsSpace) { paint.setTextSize(mKeyboardNameTextSize); - paint.setTypeface(Typeface.DEFAULT); + paint.setTypeface(Typeface.DEFAULT_BOLD); if (mKeyboardNameFM == null) mKeyboardNameFM = paint.getFontMetrics(); fm = mKeyboardNameFM; } else if (label.length() > 1 && key.codes.length < 2) { paint.setTextSize(mLabelTextSize); paint.setTypeface(Typeface.DEFAULT_BOLD); if (mLabelFM == null) mLabelFM = paint.getFontMetrics(); fm = mLabelFM; } else { paint.setTextSize(mKeyTextSize); paint.setTypeface(mKeyTextStyle); if (mTextFM == null) mTextFM = paint.getFontMetrics(); fm = mTextFM; } final float labelHeight = -fm.top; // Draw a drop shadow for the text paint.setShadowLayer(mShadowRadius, mShadowOffsetX, mShadowOffsetY, mShadowColor); // (+)This is the trick to get RTL/LTR text correct // no matter what: StaticLayout // this should be in the top left corner of the key float textWidth = paint.measureText(label, 0, label.length()); //I'm going to try something if the key is too small for the text: //1) divide the text size by 1.5 //2) if still too large, divide by 2.5 //3) show no text if (textWidth > key.width) { if (AnyApplication.DEBUG) Log.d(TAG, "Label '"+label+"' is too large for the key. Reducing by 1.5."); paint.setTextSize(mKeyTextSize/1.5f); textWidth = paint.measureText(label, 0, label.length()); if (textWidth > key.width) { if (AnyApplication.DEBUG) Log.d(TAG, "Label '"+label+"' is too large for the key. Reducing by 2.5."); paint.setTextSize(mKeyTextSize/2.5f); textWidth = paint.measureText(label, 0, label.length()); if (textWidth > key.width) { if (AnyApplication.DEBUG) Log.d(TAG, "Label '"+label+"' is too large for the key. Showing no text."); paint.setTextSize(0f); textWidth = paint.measureText(label, 0, label.length()); } } } // the center of the drawable space, which is value used // previously for vertically // positioning the key label final float centerY = mKeyBackgroundPadding.top - + (key.height - mKeyBackgroundPadding.top - mKeyBackgroundPadding.bottom) - / 2; + + ((key.height - mKeyBackgroundPadding.top - mKeyBackgroundPadding.bottom) + / (keyIsSpace? 3 : 2));//the label on the space is a bit higher // the X coordinate for the center of the main label text is // unaffected by the hints final float centerX = mKeyBackgroundPadding.left + (key.width - mKeyBackgroundPadding.left - mKeyBackgroundPadding.right) / 2; final float textX = centerX; final float textY; // Some devices (mostly pre-Honeycomb, have issues with RTL text // drawing. // Of course, there is no issue with a single character :) // so, we'll use the RTL secured drawing (via StaticLayout) for // labels. if (label.length() > 1 && !AnyApplication.getConfig() .workaround_alwaysUseDrawText()) { // calculate Y coordinate of top of text based on center // location textY = centerY - ((labelHeight - paint.descent()) / 2); canvas.translate(textX, textY); if (AnyApplication.DEBUG) Log.d(TAG, "Using RTL fix for key draw '" + label + "'"); // RTL fix. But it costs, let do it when in need (more than // 1 character) StaticLayout labelText = new StaticLayout(label, new TextPaint(paint), (int) textWidth, Alignment.ALIGN_NORMAL, 0.0f, 0.0f, false); labelText.draw(canvas); } else { // to get Y coordinate of baseline from center of text, // first add half the height (to get to // bottom of text), then subtract the part below the // baseline. Note that fm.top is negative. textY = centerY + ((labelHeight - paint.descent()) / 2); canvas.translate(textX, textY); canvas.drawText(label, 0, label.length(), 0, 0, paint); } canvas.translate(-textX, -textY); // (-) // Turn off drop shadow paint.setShadowLayer(0, 0, 0, 0); } if (drawHintText) { if ((key.popupCharacters != null && key.popupCharacters .length() > 0) || (key.popupResId != 0) || (key.longPressCode != 0)) { Paint.Align oldAlign = paint.getTextAlign(); String hintText = null; if (key.hintLabel != null && key.hintLabel.length() > 0) { hintText = key.hintLabel.toString(); // it is the responsibility of the keyboard layout // designer to ensure that they do // not put too many characters in the hint label... } else if (key.longPressCode != 0) { if (Character.isLetterOrDigit(key.longPressCode)) hintText = Character .toString((char) key.longPressCode); } else if (key.popupCharacters != null) { final String hintString = key.popupCharacters .toString(); final int hintLength = hintString.length(); if (hintLength <= 3) hintText = hintString; } // if hintText is still null, it means it didn't fit one of // the above // cases, so we should provide the hint using the default if (hintText == null) { if (mHintOverflowLabel != null) hintText = mHintOverflowLabel.toString(); else { // theme does not provide a defaultHintLabel // use ˙˙˙ if hints are above, ... if hints are // below // (to avoid being too close to main label/icon) if (hintVAlign == Gravity.TOP) hintText = "˙˙˙"; else hintText = "..."; } } if (mKeyboard.isShifted()) hintText = hintText.toUpperCase(); // now draw hint paint.setTypeface(Typeface.DEFAULT); paint.setColor(hintColor.getColorForState(drawableState, 0xFF000000)); paint.setTextSize(mHintTextSize); // get the hint text font metrics so that we know the size // of the hint when // we try to position the main label (to try to make sure // they don't overlap) if (mHintTextFM == null) { mHintTextFM = paint.getFontMetrics(); } final float hintX; final float hintY; // the (float) 0.5 value is added or subtracted to just give // a little more room // in case the theme designer didn't account for the hint // label location if (hintAlign == Gravity.LEFT) { // left paint.setTextAlign(Paint.Align.LEFT); hintX = mKeyBackgroundPadding.left + (float) 0.5; } else if (hintAlign == Gravity.CENTER) { // center paint.setTextAlign(Paint.Align.CENTER); hintX = mKeyBackgroundPadding.left + (key.width - mKeyBackgroundPadding.left - mKeyBackgroundPadding.right) / 2; } else { // right paint.setTextAlign(Paint.Align.RIGHT); hintX = key.width - mKeyBackgroundPadding.right - (float) 0.5; } if (hintVAlign == Gravity.TOP) { // above hintY = mKeyBackgroundPadding.top - mHintTextFM.top + (float) 0.5; } else { // below hintY = key.height - mKeyBackgroundPadding.bottom - mHintTextFM.bottom - (float) 0.5; } canvas.drawText(hintText, hintX, hintY, paint); paint.setTextAlign(oldAlign); } } canvas.translate(-key.x - kbdPaddingLeft, -key.y - kbdPaddingTop); } mInvalidatedKey = null; // Overlay a dark rectangle to dim the keyboard if (mMiniKeyboard != null && mMiniKeyboardVisible) { paint.setColor((int) (mBackgroundDimAmount * 0xFF) << 24); canvas.drawRect(0, 0, getWidth(), getHeight(), paint); } if (AnyApplication.DEBUG) { if (mShowTouchPoints) { for (PointerTracker tracker : mPointerTrackers) { int startX = tracker.getStartX(); int startY = tracker.getStartY(); int lastX = tracker.getLastX(); int lastY = tracker.getLastY(); paint.setAlpha(128); paint.setColor(0xFFFF0000); canvas.drawCircle(startX, startY, 3, paint); canvas.drawLine(startX, startY, lastX, lastY, paint); paint.setColor(0xFF0000FF); canvas.drawCircle(lastX, lastY, 3, paint); paint.setColor(0xFF00FF00); canvas.drawCircle((startX + lastX) / 2, (startY + lastY) / 2, 2, paint); } } } mDrawPending = false; mDirtyRect.setEmpty(); } private static boolean isSpaceKey(final AnyKey key) { return key.codes.length > 0 && key.codes[0] == KeyCodes.SPACE; } int mKeyboardActionType = EditorInfo.IME_ACTION_UNSPECIFIED; public void setKeyboardActionType(final int imeOptions) { if (AnyApplication.DEBUG) Log.d(TAG, "setKeyboardActionType imeOptions:" + imeOptions + " action:" + (imeOptions & EditorInfo.IME_MASK_ACTION)); if ((imeOptions & EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0)// this is // usually a // multi-line // edittext // box mKeyboardActionType = EditorInfo.IME_ACTION_UNSPECIFIED; else mKeyboardActionType = (imeOptions & EditorInfo.IME_MASK_ACTION); // setting the icon/text setSpecialKeysIconsAndLabels(); } public void setSpecialKeysIconsAndLabels() { List<Key> keys = (mKeyboard != null) ? mKeyboard.getKeys() : null; if (keys != null) { for (Key key : keys) { if (key.codes != null && key.codes.length > 0 && key.codes[0] == KeyCodes.ENTER) { key.icon = null; key.iconPreview = null; key.label = null; ((AnyKey) key).shiftedKeyLabel = null; Drawable icon = getIconToDrawForKey(key, false); if (icon != null) { key.icon = icon; key.iconPreview = icon; } else { CharSequence label = guessLabelForKey((AnyKey) key); key.label = label; ((AnyKey) key).shiftedKeyLabel = label; } // making sure something is shown if (key.icon == null && TextUtils.isEmpty(key.label)) { Log.i(TAG, "Wow. Unknown ACTION ID " + mKeyboardActionType + ". Will default to ENTER icon."); // I saw devices (Galaxy Tab 10") which say the action // type is 255... // D/ASKKbdViewBase( 3594): setKeyboardActionType // imeOptions:33554687 action:255 // which means it is not a known ACTION mActionKeyIcon.setState(DRAWABLE_STATE_ACTION_NORMAL); key.icon = mActionKeyIcon; key.iconPreview = mActionKeyIcon; } } } } } private CharSequence guessLabelForKey(AnyKey key) { switch (key.codes[0]) { case KeyCodes.ENTER: if (AnyApplication.DEBUG) Log.d(TAG, "Action key action ID is: " + mKeyboardActionType); switch (mKeyboardActionType) { case EditorInfo.IME_ACTION_DONE: return getContext().getText(R.string.label_done_key); case EditorInfo.IME_ACTION_GO: return getContext().getText(R.string.label_go_key); case EditorInfo.IME_ACTION_NEXT: return getContext().getText(R.string.label_next_key); case 0x00000007:// API 11: EditorInfo.IME_ACTION_PREVIOUS: return getContext().getText(R.string.label_previous_key); case EditorInfo.IME_ACTION_SEARCH: return getContext().getText(R.string.label_search_key); case EditorInfo.IME_ACTION_SEND: return getContext().getText(R.string.label_send_key); default: return ""; } case KeyCodes.MODE_ALPHABET: return getContext().getText(R.string.change_lang_regular); case KeyCodes.TAB: return getContext().getText(R.string.label_tab_key); case KeyCodes.MOVE_HOME: return getContext().getText(R.string.label_home_key); case KeyCodes.MOVE_END: return getContext().getText(R.string.label_end_key); default: return null; } } private Drawable getIconToDrawForKey(Key key, boolean feedback) { if (feedback && key.iconPreview != null) return key.iconPreview; if (key.icon != null) return key.icon; switch (key.codes[0]) { case KeyCodes.ENTER: if (AnyApplication.DEBUG) Log.d(TAG, "Action key action ID is: " + mKeyboardActionType); Drawable actionKeyDrawable = null; switch (mKeyboardActionType) { case EditorInfo.IME_ACTION_DONE: mActionKeyIcon.setState(DRAWABLE_STATE_ACTION_DONE); actionKeyDrawable = mActionKeyIcon; break; case EditorInfo.IME_ACTION_GO: mActionKeyIcon.setState(DRAWABLE_STATE_ACTION_GO); actionKeyDrawable = mActionKeyIcon; break; case EditorInfo.IME_ACTION_SEARCH: mActionKeyIcon.setState(DRAWABLE_STATE_ACTION_SEARCH); actionKeyDrawable = mActionKeyIcon; break; case EditorInfo.IME_ACTION_NONE: case EditorInfo.IME_ACTION_UNSPECIFIED: mActionKeyIcon.setState(DRAWABLE_STATE_ACTION_NORMAL); actionKeyDrawable = mActionKeyIcon; break; } return actionKeyDrawable; case KeyCodes.DELETE: return mDeleteKeyIcon; case KeyCodes.SPACE: return mSpaceKeyIcon; case KeyCodes.SHIFT: if (mKeyboard.isShiftLocked()) mShiftIcon.setState(DRAWABLE_STATE_MODIFIER_LOCKED); else if (mKeyboard.isShifted()) mShiftIcon.setState(DRAWABLE_STATE_MODIFIER_PRESSED); else mShiftIcon.setState(DRAWABLE_STATE_MODIFIER_NORMAL); return mShiftIcon; case KeyCodes.CANCEL: return mCancelKeyIcon; case KeyCodes.MODE_ALPHABET: if (key.label == null) return mGlobeKeyIcon; else return null; case KeyCodes.CTRL: /* * if (mKeyboard.isControlLocked()) * mControlIcon.setState(DRAWABLE_STATE_MODIFIER_LOCKED); else */if (mKeyboard.isControl()) mControlIcon.setState(DRAWABLE_STATE_MODIFIER_PRESSED); else mControlIcon.setState(DRAWABLE_STATE_MODIFIER_NORMAL); return mControlIcon; case KeyCodes.TAB: return mTabKeyIcon; case KeyCodes.ARROW_DOWN: return mArrowDownKeyIcon; case KeyCodes.ARROW_LEFT: return mArrowLeftKeyIcon; case KeyCodes.ARROW_RIGHT: return mArrowRightKeyIcon; case KeyCodes.ARROW_UP: return mArrowUpKeyIcon; case KeyCodes.MOVE_HOME: return mMoveHomeKeyIcon; case KeyCodes.MOVE_END: return mMoveEndKeyIcon; case KeyCodes.VOICE_INPUT: return mMicKeyIcon; case KeyCodes.SETTINGS: return mSettingsKeyIcon; default: return null; } } void dismissKeyPreview() { for (PointerTracker tracker : mPointerTrackers) tracker.updateKey(NOT_A_KEY); showPreview(NOT_A_KEY, null); } public void showPreview(int keyIndex, PointerTracker tracker) { int oldKeyIndex = mOldPreviewKeyIndex; mOldPreviewKeyIndex = keyIndex; final boolean isLanguageSwitchEnabled = false; // We should re-draw popup preview when 1) we need to hide the preview, // 2) we will show // the space key preview and 3) pointer moves off the space key to other // letter key, we // should hide the preview of the previous key. final boolean hidePreviewOrShowSpaceKeyPreview = (tracker == null)/* * || * tracker * . * isSpaceKey * ( * keyIndex * ) || * tracker * . * isSpaceKey * ( * oldKeyIndex * ) */; // If key changed and preview is on or the key is space (language switch // is enabled) if (oldKeyIndex != keyIndex && (mShowPreview || (hidePreviewOrShowSpaceKeyPreview && isLanguageSwitchEnabled))) { if (keyIndex == NOT_A_KEY) { mHandler.cancelPopupPreview(); mHandler.dismissPreview(mDelayAfterPreview); } else if (tracker != null) { mHandler.popupPreview(mDelayBeforePreview, keyIndex, tracker); } } } private void showKey(final int keyIndex, PointerTracker tracker) { Key key = tracker.getKey(keyIndex); if (key == null || !mShowPreview) return; int popupWidth = 0; int popupHeight = 0; // Should not draw hint icon in key preview CharSequence label = tracker.getPreviewText(key, mKeyboard.isShifted()); if (TextUtils.isEmpty(label)) { Drawable iconToDraw = getIconToDrawForKey(key, true); // mPreviewText.setCompoundDrawables(null, null, null, // key.iconPreview != null ? key.iconPreview : key.icon); mPreviewIcon.setImageDrawable(iconToDraw); if (key.codes.length > 0 && key.codes[0] == KeyCodes.SPACE) { // in the spacebar we'll also add the current gesture, with alpha [0...128,255]. //if any //TODO: the above //mPreviewText.setTextColor(color+alpha) mPreviewText.setText(null); } else { mPreviewText.setText(null); } mPreviewIcon.measure( MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); popupWidth = Math.max(mPreviewIcon.getMeasuredWidth(), key.width); popupHeight = Math .max(mPreviewIcon.getMeasuredHeight(), key.height); } else { // mPreviewText.setCompoundDrawables(null, null, null, null); mPreviewIcon.setImageDrawable(null); setKeyPreviewText(key, label); popupWidth = Math.max(mPreviewText.getMeasuredWidth(), key.width); popupHeight = Math .max(mPreviewText.getMeasuredHeight(), key.height); } if (mPreviewPaddingHeight < 0) { mPreviewPaddingWidth = mPreviewLayut.getPaddingLeft() + mPreviewLayut.getPaddingRight(); mPreviewPaddingHeight = mPreviewLayut.getPaddingTop() + mPreviewLayut.getPaddingBottom(); if (mPreviewKeyBackground != null) { Rect padding = new Rect(); mPreviewKeyBackground.getPadding(padding); mPreviewPaddingWidth += (padding.left + padding.right); mPreviewPaddingHeight += (padding.top + padding.bottom); } } popupWidth += mPreviewPaddingWidth; popupHeight += mPreviewPaddingHeight; // and checking that the width and height are big enough for the // background. if (mPreviewKeyBackground != null) { popupWidth = Math.max(mPreviewKeyBackground.getMinimumWidth(), popupWidth); popupHeight = Math.max(mPreviewKeyBackground.getMinimumHeight(), popupHeight); } final boolean showPopupAboveKey = AnyApplication.getConfig() .showKeyPreviewAboveKey(); int popupPreviewX = showPopupAboveKey ? key.x - ((popupWidth - key.width) / 2) : (getWidth() - popupWidth) / 2; int popupPreviewY = (showPopupAboveKey ? key.y : 0) - popupHeight - mPreviewOffset; mHandler.cancelDismissPreview(); if (mOffsetInWindow == null) { mOffsetInWindow = new int[] { 0, 0 }; getLocationInWindow(mOffsetInWindow); if (AnyApplication.DEBUG) Log.d(TAG, "mOffsetInWindow " + mOffsetInWindow[0] + ", " + mOffsetInWindow[1]); mOffsetInWindow[0] += mPopupPreviewOffsetX; // Offset may be zero mOffsetInWindow[1] += mPopupPreviewOffsetY; // Offset may be zero int[] windowLocation = new int[2]; getLocationOnScreen(windowLocation); mWindowY = windowLocation[1]; } popupPreviewX += mOffsetInWindow[0]; popupPreviewY += mOffsetInWindow[1]; // If the popup cannot be shown above the key, put it on the side if (popupPreviewY + mWindowY < 0) { // If the key you're pressing is on the left side of the keyboard, // show the popup on // the right, offset by enough to see at least one key to the // left/right. if (key.x + key.width <= getWidth() / 2) { popupPreviewX += (int) (key.width * 2.5); } else { popupPreviewX -= (int) (key.width * 2.5); } popupPreviewY += popupHeight; } if (mPreviewPopup.isShowing()) { if (mStaticLocationPopupWindow) { // started at SPACE, so I stick with the position. This is used // for // showing gesture info } else { mPreviewPopup.update(popupPreviewX, popupPreviewY, popupWidth, popupHeight); } } else { mPreviewPopup.setWidth(popupWidth); mPreviewPopup.setHeight(popupHeight); // if started at SPACE, so I stick with the position. This is used // for // showing gesture info mStaticLocationPopupWindow = key.codes.length > 0 && key.codes[0] == KeyCodes.SPACE; try { // https://github.com/AnySoftKeyboard/AnySoftKeyboard/issues/6 // I don't understand why this should happen, and only with MIUI // ROMs. // anyhow, it easy to hide :) mPreviewPopup.showAtLocation(mMiniKeyboardParent, Gravity.NO_GRAVITY, popupPreviewX, popupPreviewY); } catch (RuntimeException e) { // nothing to do here. I think. } } // mPreviewPopup.getContentView().invalidate(); // Record popup preview position to display mini-keyboard later at the // same positon mPopupPreviewDisplayedY = popupPreviewY + (showPopupAboveKey ? 0 : key.y);// the popup keyboard should // be // placed at the right // position. // So I'm fixing mPreviewLayut.setVisibility(VISIBLE); // Set the preview background state if (mPreviewKeyBackground != null) { mPreviewKeyBackground .setState(key.popupResId != 0 ? LONG_PRESSABLE_STATE_SET : EMPTY_STATE_SET); } // LayoutParams lp = mPreviewLayut.getLayoutParams(); // lp.width = popupWidth; } private void setKeyPreviewText(Key key, CharSequence label) { mPreviewText.setText(label); if (label.length() > 1 && key.codes.length < 2) { mPreviewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mPreviewLabelTextSize); } else { mPreviewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mPreviewKeyTextSize); } mPreviewText.measure( MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); } /** * Requests a redraw of the entire keyboard. Calling {@link #invalidate} is * not sufficient because the keyboard renders the keys to an off-screen * buffer and an invalidate() only draws the cached buffer. * * @see #invalidateKey(Key) */ public void invalidateAllKeys() { mDirtyRect.union(0, 0, getWidth(), getHeight()); mDrawPending = true; invalidate(); } /** * Invalidates a key so that it will be redrawn on the next repaint. Use * this method if only one key is changing it's content. Any changes that * affect the position or size of the key may not be honored. * * @param key * key in the attached {@link Keyboard}. * @see #invalidateAllKeys */ public void invalidateKey(Key key) { if (key == null) return; mInvalidatedKey = key; // TODO we should clean up this and record key's region to use in // onBufferDraw. mDirtyRect.union(key.x + getPaddingLeft(), key.y + getPaddingTop(), key.x + key.width + getPaddingLeft(), key.y + key.height + getPaddingTop()); // doOnBufferDrawWithMemProtection(mCanvas); invalidate(key.x + getPaddingLeft(), key.y + getPaddingTop(), key.x + key.width + getPaddingLeft(), key.y + key.height + getPaddingTop()); } private boolean openPopupIfRequired(int keyIndex, PointerTracker tracker) { /* * this is a uselss code.. // Check if we have a popup layout specified * first. if (mPopupLayout == 0) { return false; } */ Key popupKey = tracker.getKey(keyIndex); if (popupKey == null) return false; boolean result = onLongPress(getContext(), popupKey, false, true); if (result) { dismissKeyPreview(); mMiniKeyboardTrackerId = tracker.mPointerId; // Mark this tracker "already processed" and remove it from the // pointer queue tracker.setAlreadyProcessed(); mPointerQueue.remove(tracker); } return result; } private void setupMiniKeyboardContainer(Context packageContext, CharSequence popupCharacters, int popupKeyboardId, boolean isSticky) { final AnyPopupKeyboard keyboard; if (popupCharacters != null) { keyboard = new AnyPopupKeyboard(mAskContext, popupCharacters, mMiniKeyboard.getThemedKeyboardDimens()); } else { keyboard = new AnyPopupKeyboard(mAskContext, packageContext, popupKeyboardId, mMiniKeyboard.getThemedKeyboardDimens()); } keyboard.setIsOneKeyEventPopup(!isSticky); if (isSticky) mMiniKeyboard.setKeyboard(keyboard, mVerticalCorrection); else mMiniKeyboard.setKeyboard(keyboard); mMiniKeyboard.measure( MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.AT_MOST)); } public KeyboardDimens getThemedKeyboardDimens() { return mKeyboardDimens; } /* * private static boolean isOneRowKeys(List<Key> keys) { if (keys.size() == * 0) return false; final int edgeFlags = keys.get(0).edgeFlags; // HACK: * The first key of mini keyboard which was inflated from xml and has * multiple rows, // does not have both top and bottom edge flags on at the * same time. On the other hand, // the first key of mini keyboard that was * created with popupCharacters must have both top // and bottom edge flags * on. // When you want to use one row mini-keyboard from xml file, make * sure that the row has // both top and bottom edge flags set. return * (edgeFlags & Keyboard.EDGE_TOP) != 0 && (edgeFlags & * Keyboard.EDGE_BOTTOM) != 0; } */ /** * Called when a key is long pressed. By default this will open any popup * keyboard associated with this key through the attributes popupLayout and * popupCharacters. * * @param popupKey * the key that was long pressed * @return true if the long press is handled, false otherwise. Subclasses * should call the method on the base class if the subclass doesn't * wish to handle the call. */ protected boolean onLongPress(Context packageContext, Key popupKey, boolean isSticky, boolean requireSlideInto) { if (popupKey.popupResId == 0) return false; if (mMiniKeyboard == null) { createMiniKeyboard(); } setupMiniKeyboardContainer(packageContext, popupKey.popupCharacters, popupKey.popupResId, isSticky); mMiniKeyboardVisible = true; if (mWindowOffset == null) { mWindowOffset = new int[2]; getLocationInWindow(mWindowOffset); } int popupX = popupKey.x + mWindowOffset[0]; popupX -= mMiniKeyboard.getPaddingLeft(); int popupY = popupKey.y + mWindowOffset[1]; popupY += getPaddingTop(); popupY -= mMiniKeyboard.getMeasuredHeight(); popupY -= mMiniKeyboard.getPaddingBottom(); final int x = popupX; final int y = mShowPreview && mOldPreviewKeyIndex != NOT_A_KEY && isOneRowKeys(mMiniKeyboard.getKeyboard().getKeys()) ? mPopupPreviewDisplayedY : popupY; int adjustedX = x; if (x < 0) { adjustedX = 0; } else if (x > (getMeasuredWidth() - mMiniKeyboard.getMeasuredWidth())) { adjustedX = getMeasuredWidth() - mMiniKeyboard.getMeasuredWidth(); } mMiniKeyboardOriginX = adjustedX + mMiniKeyboard.getPaddingLeft() - mWindowOffset[0]; mMiniKeyboardOriginY = y + mMiniKeyboard.getPaddingTop() - mWindowOffset[1]; mMiniKeyboard.setPopupOffset(adjustedX, y); // NOTE:I'm checking the main keyboard shift state directly! // Not anything else. mMiniKeyboard.setShifted(mKeyboard != null ? mKeyboard.isShifted() : false); // Mini keyboard needs no pop-up key preview displayed. mMiniKeyboard.setPreviewEnabled(false); // animation switching required? mMiniKeyboardPopup.setContentView(mMiniKeyboard); mMiniKeyboardPopup.setWidth(mMiniKeyboard.getMeasuredWidth()); mMiniKeyboardPopup.setHeight(mMiniKeyboard.getMeasuredHeight()); mMiniKeyboardPopup.showAtLocation(this, Gravity.NO_GRAVITY, adjustedX, y); if (requireSlideInto) { // Inject down event on the key to mini keyboard. long eventTime = SystemClock.uptimeMillis(); mMiniKeyboardPopupTime = eventTime; MotionEvent downEvent = generateMiniKeyboardMotionEvent( MotionEvent.ACTION_DOWN, popupKey.x + popupKey.width / 2, popupKey.y + popupKey.height / 2, eventTime); mMiniKeyboard.onTouchEvent(downEvent); downEvent.recycle(); } invalidateAllKeys(); return true; } public void createMiniKeyboard() { LayoutInflater inflater = (LayoutInflater) getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); mMiniKeyboard = (AnyKeyboardBaseView) inflater.inflate( R.layout.popup_keyboard_layout, null); mMiniKeyboard.setPopupParent(this); mMiniKeyboard .setOnKeyboardActionListener(new OnKeyboardActionListener() { private final AnyKeyboardBaseView mParent = mMiniKeyboard; private AnyPopupKeyboard getMyKeyboard() { return (AnyPopupKeyboard) mParent.getKeyboard(); } public void onKey(int primaryCode, Key key, int multiTapIndex, int[] nearByKeyCodes, boolean fromUI) { mKeyboardActionListener.onKey(primaryCode, key, multiTapIndex, nearByKeyCodes, fromUI); if (getMyKeyboard().isOneKeyEventPopup()) dismissPopupKeyboard(); } public void onMultiTapStarted() { mKeyboardActionListener.onMultiTapStarted(); } public void onMultiTapEndeded() { mKeyboardActionListener.onMultiTapEndeded(); } public void onText(CharSequence text) { mKeyboardActionListener.onText(text); if (getMyKeyboard().isOneKeyEventPopup()) dismissPopupKeyboard(); } public void onCancel() { mKeyboardActionListener.onCancel(); dismissPopupKeyboard(); } public void onSwipeLeft(boolean onSpacebar) { } public void onSwipeRight(boolean onSpacebar) { } public void onSwipeUp(boolean onSpacebar) { } public void onSwipeDown(boolean onSpacebar) { } public void onPinch() { } public void onSeparate() { } public void onPress(int primaryCode) { mKeyboardActionListener.onPress(primaryCode); } public void onRelease(int primaryCode) { mKeyboardActionListener.onRelease(primaryCode); } }); // Override default ProximityKeyDetector. mMiniKeyboard.mKeyDetector = new MiniKeyboardKeyDetector( mMiniKeyboardSlideAllowance); // Remove gesture detector on mini-keyboard mMiniKeyboard.mGestureDetector = null; } private static boolean isOneRowKeys(List<Key> keys) { if (keys.size() == 0) return false; final int edgeFlags = keys.get(0).edgeFlags; // HACK: The first key of mini keyboard which was inflated from xml and // has multiple rows, // does not have both top and bottom edge flags on at the same time. On // the other hand, // the first key of mini keyboard that was created with popupCharacters // must have both top // and bottom edge flags on. // When you want to use one row mini-keyboard from xml file, make sure // that the row has // both top and bottom edge flags set. return (edgeFlags & Keyboard.EDGE_TOP) != 0 && (edgeFlags & Keyboard.EDGE_BOTTOM) != 0; } // private static boolean hasMultiplePopupChars(Key key) { // if (key.popupCharacters != null && key.popupCharacters.length() > 1) { // return true; // } // return false; // } // private boolean shouldDrawIconFully(Key key) { // return isNumberAtEdgeOfPopupChars(key) /*|| isLatinF1Key(key) // || LatinKeyboard.hasPuncOrSmileysPopup(key)*/; // } // // private boolean shouldDrawLabelAndIcon(Key key) { // return isNumberAtEdgeOfPopupChars(key) /*|| isNonMicLatinF1Key(key) // || AnyKeyboard.hasPuncOrSmileysPopup(key)*/; // } // private boolean isLatinF1Key(Key key) { // return (mKeyboard instanceof AnyKeyboard) && // ((AnyKeyboard)mKeyboard).isF1Key(key); // } // private boolean isNonMicLatinF1Key(Key key) { // return isLatinF1Key(key) && key.label != null; // } // private static boolean isNumberAtEdgeOfPopupChars(Key key) { // return isNumberAtLeftmostPopupChar(key) || // isNumberAtRightmostPopupChar(key); // } // /* package */ static boolean isNumberAtLeftmostPopupChar(Key key) { // if (key.popupCharacters != null && key.popupCharacters.length() > 0 // && isAsciiDigit(key.popupCharacters.charAt(0))) { // return true; // } // return false; // } // /* package */ static boolean isNumberAtRightmostPopupChar(Key key) { // if (key.popupCharacters != null && key.popupCharacters.length() > 0 // && isAsciiDigit(key.popupCharacters.charAt(key.popupCharacters.length() - // 1))) { // return true; // } // return false; // } // // private static boolean isAsciiDigit(char c) { // return (c < 0x80) && Character.isDigit(c); // } private MotionEvent generateMiniKeyboardMotionEvent(int action, int x, int y, long eventTime) { return MotionEvent.obtain(mMiniKeyboardPopupTime, eventTime, action, x - mMiniKeyboardOriginX, y - mMiniKeyboardOriginY, 0); } private PointerTracker getPointerTracker(final int id) { final ArrayList<PointerTracker> pointers = mPointerTrackers; final Key[] keys = mKeys; final OnKeyboardActionListener listener = mKeyboardActionListener; // Create pointer trackers until we can get 'id+1'-th tracker, if // needed. for (int i = pointers.size(); i <= id; i++) { final PointerTracker tracker = new PointerTracker(i, mHandler, mKeyDetector, this, getResources()); if (keys != null) tracker.setKeyboard(keys, mKeyHysteresisDistance); if (listener != null) tracker.setOnKeyboardActionListener(listener); pointers.add(tracker); } return pointers.get(id); } public boolean isInSlidingKeyInput() { if (mMiniKeyboard != null && mMiniKeyboardVisible) { return mMiniKeyboard.isInSlidingKeyInput(); } else { return mPointerQueue.isInSlidingKeyInput(); } } public int getPointerCount() { return mOldPointerCount; } @Override public boolean onTouchEvent(MotionEvent nativeMotionEvent) { WMotionEvent me = AnyApplication.getDeviceSpecific() .createMotionEventWrapper(nativeMotionEvent); final int action = me.getActionMasked(); final int pointerCount = me.getPointerCount(); final int oldPointerCount = mOldPointerCount; mOldPointerCount = pointerCount; // TODO: cleanup this code into a multi-touch to single-touch event // converter class? // If the device does not have distinct multi-touch support panel, // ignore all multi-touch // events except a transition from/to single-touch. if (!mHasDistinctMultitouch && pointerCount > 1 && oldPointerCount > 1) { return true; } // Track the last few movements to look for spurious swipes. mSwipeTracker.addMovement(me.getNativeMotionEvent()); // Gesture detector must be enabled only when mini-keyboard is not // on the screen. if (!mMiniKeyboardVisible && mGestureDetector != null && (mGestureDetector.onTouchEvent(me.getNativeMotionEvent()) /* * || * mInScrollGesture */)) { if (AnyApplication.DEBUG) Log.d(TAG, "Gesture detected!"); // mHandler.cancelAllMessages(); mHandler.cancelKeyTimers(); dismissKeyPreview(); return true; } final long eventTime = me.getEventTime(); final int index = me.getActionIndex(); final int id = me.getPointerId(index); final int x = (int) me.getX(index); final int y = (int) me.getY(index); // Needs to be called after the gesture detector gets a turn, as it // may have // displayed the mini keyboard if (mMiniKeyboard != null && mMiniKeyboardVisible) { final int miniKeyboardPointerIndex = me .findPointerIndex(mMiniKeyboardTrackerId); if (miniKeyboardPointerIndex >= 0 && miniKeyboardPointerIndex < pointerCount) { final int miniKeyboardX = (int) me .getX(miniKeyboardPointerIndex); final int miniKeyboardY = (int) me .getY(miniKeyboardPointerIndex); MotionEvent translated = generateMiniKeyboardMotionEvent( action, miniKeyboardX, miniKeyboardY, eventTime); mMiniKeyboard.onTouchEvent(translated); translated.recycle(); } return true; } if (mHandler.isInKeyRepeat()) { // It will keep being in the key repeating mode while the key is // being pressed. if (action == MotionEvent.ACTION_MOVE) { return true; } final PointerTracker tracker = getPointerTracker(id); // Key repeating timer will be canceled if 2 or more keys are in // action, and current // event (UP or DOWN) is non-modifier key. if (pointerCount > 1 && !tracker.isModifier()) { mHandler.cancelKeyRepeatTimer(); } // Up event will pass through. } // TODO: cleanup this code into a multi-touch to single-touch event // converter class? // Translate mutli-touch event to single-touch events on the device // that has no distinct // multi-touch panel. if (!mHasDistinctMultitouch) { // Use only main (id=0) pointer tracker. PointerTracker tracker = getPointerTracker(0); if (pointerCount == 1 && oldPointerCount == 2) { // Multi-touch to single touch transition. // Send a down event for the latest pointer. tracker.onDownEvent(x, y, eventTime); } else if (pointerCount == 2 && oldPointerCount == 1) { // Single-touch to multi-touch transition. // Send an up event for the last pointer. tracker.onUpEvent(tracker.getLastX(), tracker.getLastY(), eventTime); } else if (pointerCount == 1 && oldPointerCount == 1) { tracker.onTouchEvent(action, x, y, eventTime); } else { Log.w(TAG, "Unknown touch panel behavior: pointer count is " + pointerCount + " (old " + oldPointerCount + ")"); } return true; } if (action == MotionEvent.ACTION_MOVE) { for (int i = 0; i < pointerCount; i++) { PointerTracker tracker = getPointerTracker(me.getPointerId(i)); tracker.onMoveEvent((int) me.getX(i), (int) me.getY(i), eventTime); } } else { PointerTracker tracker = getPointerTracker(id); sendOnXEvent(action, eventTime, x, y, tracker); } return true; } protected boolean isFirstDownEventInsideSpaceBar() { return false; } private void sendOnXEvent(final int action, final long eventTime, final int x, final int y, PointerTracker tracker) { switch (action) { case MotionEvent.ACTION_DOWN: case 0x00000005:// MotionEvent.ACTION_POINTER_DOWN: onDownEvent(tracker, x, y, eventTime); break; case MotionEvent.ACTION_UP: case 0x00000006:// MotionEvent.ACTION_POINTER_UP: onUpEvent(tracker, x, y, eventTime); break; case MotionEvent.ACTION_CANCEL: onCancelEvent(tracker, x, y, eventTime); break; } } protected void onDownEvent(PointerTracker tracker, int x, int y, long eventTime) { if (tracker.isOnModifierKey(x, y)) { // Before processing a down event of modifier key, all pointers // already being tracked // should be released. mPointerQueue.releaseAllPointersExcept(tracker, eventTime); } tracker.onDownEvent(x, y, eventTime); mPointerQueue.add(tracker); } private void onUpEvent(PointerTracker tracker, int x, int y, long eventTime) { if (tracker.isModifier()) { // Before processing an up event of modifier key, all pointers // already being tracked // should be released. mPointerQueue.releaseAllPointersExcept(tracker, eventTime); } else { int index = mPointerQueue.lastIndexOf(tracker); if (index >= 0) { mPointerQueue.releaseAllPointersOlderThan(tracker, eventTime); } else { Log.w(TAG, "onUpEvent: corresponding down event not found for pointer " + tracker.mPointerId); return; } } tracker.onUpEvent(x, y, eventTime); mPointerQueue.remove(tracker); } private void onCancelEvent(PointerTracker tracker, int x, int y, long eventTime) { tracker.onCancelEvent(x, y, eventTime); mPointerQueue.remove(tracker); } /* * protected void swipeRight(boolean onSpacebar) { * mKeyboardActionListener.onSwipeRight(onSpacebar); } protected void * swipeLeft(boolean onSpacebar) { * mKeyboardActionListener.onSwipeLeft(onSpacebar); } protected void * swipeUp(boolean onSpacebar) { * mKeyboardActionListener.onSwipeUp(onSpacebar); } protected void * swipeDown(boolean onSpacebar) { * mKeyboardActionListener.onSwipeDown(onSpacebar); } */ /* * protected void scrollGestureStarted(float dX, float dY) { * mInScrollGesture = true; } protected void scrollGestureEnded() { * mInScrollGesture = false; } */ protected Key findKeyByKeyCode(int keyCode) { if (getKeyboard() == null) { return null; } for (Key key : getKeyboard().getKeys()) { if (key.codes[0] == keyCode) return key; } return null; } public boolean closing() { mPreviewPopup.dismiss(); mHandler.cancelAllMessages(); if (!dismissPopupKeyboard()) { // mBuffer = null; // mCanvas = null; // mMiniKeyboardCache.clear(); return true; } else { return false; } } @Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); AnyApplication.getConfig().removeChangedListener(this); closing(); } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Resources res = getResources(); if (key.equals(res .getString(R.string.settings_key_swipe_distance_threshold)) || key.equals(res .getString(R.string.settings_key_swipe_velocity_threshold))) { reloadSwipeThresholdsSettings(res); } else if (key.equals(res .getString(R.string.settings_key_long_press_timeout)) || key.equals(res .getString(R.string.settings_key_multitap_timeout))) { closing(); mPointerTrackers.clear(); } mAnimationLevel = AnyApplication.getConfig().getAnimationsLevel(); mPreviewPopup .setAnimationStyle((mAnimationLevel == AnimationsLevel.None) ? 0 : R.style.KeyPreviewAnimation); mMiniKeyboardPopup .setAnimationStyle((mAnimationLevel == AnimationsLevel.None) ? 0 : R.style.MiniKeyboardAnimation); } protected boolean isPopupShowing() { return mMiniKeyboardPopup != null && mMiniKeyboardVisible; } protected boolean dismissPopupKeyboard() { if (isPopupShowing()) { mMiniKeyboardPopup.dismiss(); mMiniKeyboardVisible = false; mMiniKeyboardOriginX = 0; mMiniKeyboardOriginY = 0; invalidateAllKeys(); return true; } else return false; } public boolean handleBack() { if (mMiniKeyboardPopup.isShowing()) { dismissPopupKeyboard(); return true; } return false; } // helper classes to translate the hint positioning integer values from the // theme or settings into the Paint.Align and boolean values used in // onBufferDraw() }
false
true
private void onBufferDraw(Canvas canvas) { if (mKeyboardChanged) { invalidateAllKeys(); mKeyboardChanged = false; } canvas.getClipBounds(mDirtyRect); if (mKeyboard == null) return; final boolean drawKeyboardNameText = (mKeyboardNameTextSize > 1) && AnyApplication.getConfig().getShowKeyboardNameText(); final boolean drawHintText = (mHintTextSize > 1) && AnyApplication.getConfig().getShowHintTextOnKeys(); if (AnyApplication.DEBUG && !drawHintText) { Log.d(TAG, "drawHintText is false. mHintTextSize: " + mHintTextSize + ", getShowHintTextOnKeys: " + AnyApplication.getConfig().getShowHintTextOnKeys()); } // TODO: calls to AnyApplication.getConfig().getXXXXX() functions are // not yet implemented, // but need to when allowing preferences to override theme settings of // these values // right now just using what should be the default values for these // unimplemented preferences final boolean useCustomKeyTextColor = false; // TODO: final boolean useCustomKeyTextColor = // AnyApplication.getConfig().getUseCustomTextColorOnKeys(); final ColorStateList keyTextColor = useCustomKeyTextColor ? new ColorStateList( new int[][] { { 0 } }, new int[] { 0xFF6666FF }) : mKeyTextColor; // TODO: ? AnyApplication.getConfig().getCustomKeyTextColorOnKeys() : // mKeyTextColor; final boolean useCustomHintColor = drawHintText && false; // TODO: final boolean useCustomHintColor = drawHintText && // AnyApplication.getConfig().getUseCustomHintColorOnKeys(); final ColorStateList hintColor = useCustomHintColor ? new ColorStateList( new int[][] { { 0 } }, new int[] { 0xFFFF6666 }) : mHintTextColor; // TODO: ? AnyApplication.getConfig().getCustomHintColorOnKeys() : // mHintTextColor; // allow preferences to override theme settings for hint text position final boolean useCustomHintAlign = drawHintText && AnyApplication.getConfig().getUseCustomHintAlign(); final int hintAlign = useCustomHintAlign ? AnyApplication.getConfig() .getCustomHintAlign() : mHintLabelAlign; final int hintVAlign = useCustomHintAlign ? AnyApplication.getConfig() .getCustomHintVAlign() : mHintLabelVAlign; final Paint paint = mPaint; final Drawable keyBackground = mKeyBackground; final Rect clipRegion = mClipRegion; final int kbdPaddingLeft = getPaddingLeft(); final int kbdPaddingTop = getPaddingTop(); final Key[] keys = mKeys; final Key invalidKey = mInvalidatedKey; boolean drawSingleKey = false; if (invalidKey != null && canvas.getClipBounds(clipRegion)) { // TODO we should use Rect.inset and Rect.contains here. // Is clipRegion completely contained within the invalidated key? if (invalidKey.x + kbdPaddingLeft - 1 <= clipRegion.left && invalidKey.y + kbdPaddingTop - 1 <= clipRegion.top && invalidKey.x + invalidKey.width + kbdPaddingLeft + 1 >= clipRegion.right && invalidKey.y + invalidKey.height + kbdPaddingTop + 1 >= clipRegion.bottom) { drawSingleKey = true; } } // canvas.drawColor(0x00000000, PorterDuff.Mode.CLEAR); final int keyCount = keys.length; for (int i = 0; i < keyCount; i++) { final AnyKey key = (AnyKey) keys[i]; final boolean keyIsSpace = isSpaceKey(key); if (drawSingleKey && (invalidKey != key)) { continue; } if (!mDirtyRect.intersects(key.x + kbdPaddingLeft, key.y + kbdPaddingTop, key.x + key.width + kbdPaddingLeft, key.y + key.height + kbdPaddingTop)) { continue; } int[] drawableState = key.getCurrentDrawableState(); if (keyIsSpace) paint.setColor(mKeyboardNameTextColor.getColorForState(drawableState, 0xFF000000)); else paint.setColor(keyTextColor.getColorForState(drawableState, 0xFF000000)); keyBackground.setState(drawableState); // Switch the character to uppercase if shift is pressed CharSequence label = key.label == null ? null : adjustCase(key) .toString(); final Rect bounds = keyBackground.getBounds(); if ((key.width != bounds.right) || (key.height != bounds.bottom)) { keyBackground.setBounds(0, 0, key.width, key.height); } canvas.translate(key.x + kbdPaddingLeft, key.y + kbdPaddingTop); keyBackground.draw(canvas); if (TextUtils.isEmpty(label)) { Drawable iconToDraw = getIconToDrawForKey(key, false); if (iconToDraw != null/* && shouldDrawIcon */) { // Special handing for the upper-right number hint icons final int drawableWidth; final int drawableHeight; final int drawableX; final int drawableY; drawableWidth = iconToDraw.getIntrinsicWidth(); drawableHeight = iconToDraw.getIntrinsicHeight(); drawableX = (key.width + mKeyBackgroundPadding.left - mKeyBackgroundPadding.right - drawableWidth) / 2; drawableY = (key.height + mKeyBackgroundPadding.top - mKeyBackgroundPadding.bottom - drawableHeight) / 2; canvas.translate(drawableX, drawableY); iconToDraw.setBounds(0, 0, drawableWidth, drawableHeight); iconToDraw.draw(canvas); canvas.translate(-drawableX, -drawableY); if (keyIsSpace && drawKeyboardNameText) { //now a little hack, I'll set the label now, so it get drawn. label = mKeyboardName; } } else { // ho... no icon. // I'll try to guess the text label = guessLabelForKey(key); if (TextUtils.isEmpty(label)) { Log.w(TAG, "That's unfortunate, for key " + key.codes[0] + " at (" + key.x + ", " + key.y + ") there is no icon nor label. Action ID is " + mKeyboardActionType); } } } if (label != null) { // For characters, use large font. For labels like "Done", use // small font. final FontMetrics fm; if (keyIsSpace) { paint.setTextSize(mKeyboardNameTextSize); paint.setTypeface(Typeface.DEFAULT); if (mKeyboardNameFM == null) mKeyboardNameFM = paint.getFontMetrics(); fm = mKeyboardNameFM; } else if (label.length() > 1 && key.codes.length < 2) { paint.setTextSize(mLabelTextSize); paint.setTypeface(Typeface.DEFAULT_BOLD); if (mLabelFM == null) mLabelFM = paint.getFontMetrics(); fm = mLabelFM; } else { paint.setTextSize(mKeyTextSize); paint.setTypeface(mKeyTextStyle); if (mTextFM == null) mTextFM = paint.getFontMetrics(); fm = mTextFM; } final float labelHeight = -fm.top; // Draw a drop shadow for the text paint.setShadowLayer(mShadowRadius, mShadowOffsetX, mShadowOffsetY, mShadowColor); // (+)This is the trick to get RTL/LTR text correct // no matter what: StaticLayout // this should be in the top left corner of the key float textWidth = paint.measureText(label, 0, label.length()); //I'm going to try something if the key is too small for the text: //1) divide the text size by 1.5 //2) if still too large, divide by 2.5 //3) show no text if (textWidth > key.width) { if (AnyApplication.DEBUG) Log.d(TAG, "Label '"+label+"' is too large for the key. Reducing by 1.5."); paint.setTextSize(mKeyTextSize/1.5f); textWidth = paint.measureText(label, 0, label.length()); if (textWidth > key.width) { if (AnyApplication.DEBUG) Log.d(TAG, "Label '"+label+"' is too large for the key. Reducing by 2.5."); paint.setTextSize(mKeyTextSize/2.5f); textWidth = paint.measureText(label, 0, label.length()); if (textWidth > key.width) { if (AnyApplication.DEBUG) Log.d(TAG, "Label '"+label+"' is too large for the key. Showing no text."); paint.setTextSize(0f); textWidth = paint.measureText(label, 0, label.length()); } } } // the center of the drawable space, which is value used // previously for vertically // positioning the key label final float centerY = mKeyBackgroundPadding.top + (key.height - mKeyBackgroundPadding.top - mKeyBackgroundPadding.bottom) / 2; // the X coordinate for the center of the main label text is // unaffected by the hints final float centerX = mKeyBackgroundPadding.left + (key.width - mKeyBackgroundPadding.left - mKeyBackgroundPadding.right) / 2; final float textX = centerX; final float textY; // Some devices (mostly pre-Honeycomb, have issues with RTL text // drawing. // Of course, there is no issue with a single character :) // so, we'll use the RTL secured drawing (via StaticLayout) for // labels. if (label.length() > 1 && !AnyApplication.getConfig() .workaround_alwaysUseDrawText()) { // calculate Y coordinate of top of text based on center // location textY = centerY - ((labelHeight - paint.descent()) / 2); canvas.translate(textX, textY); if (AnyApplication.DEBUG) Log.d(TAG, "Using RTL fix for key draw '" + label + "'"); // RTL fix. But it costs, let do it when in need (more than // 1 character) StaticLayout labelText = new StaticLayout(label, new TextPaint(paint), (int) textWidth, Alignment.ALIGN_NORMAL, 0.0f, 0.0f, false); labelText.draw(canvas); } else { // to get Y coordinate of baseline from center of text, // first add half the height (to get to // bottom of text), then subtract the part below the // baseline. Note that fm.top is negative. textY = centerY + ((labelHeight - paint.descent()) / 2); canvas.translate(textX, textY); canvas.drawText(label, 0, label.length(), 0, 0, paint); } canvas.translate(-textX, -textY); // (-) // Turn off drop shadow paint.setShadowLayer(0, 0, 0, 0); } if (drawHintText) { if ((key.popupCharacters != null && key.popupCharacters .length() > 0) || (key.popupResId != 0) || (key.longPressCode != 0)) { Paint.Align oldAlign = paint.getTextAlign(); String hintText = null; if (key.hintLabel != null && key.hintLabel.length() > 0) { hintText = key.hintLabel.toString(); // it is the responsibility of the keyboard layout // designer to ensure that they do // not put too many characters in the hint label... } else if (key.longPressCode != 0) { if (Character.isLetterOrDigit(key.longPressCode)) hintText = Character .toString((char) key.longPressCode); } else if (key.popupCharacters != null) { final String hintString = key.popupCharacters .toString(); final int hintLength = hintString.length(); if (hintLength <= 3) hintText = hintString; } // if hintText is still null, it means it didn't fit one of // the above // cases, so we should provide the hint using the default if (hintText == null) { if (mHintOverflowLabel != null) hintText = mHintOverflowLabel.toString(); else { // theme does not provide a defaultHintLabel // use ˙˙˙ if hints are above, ... if hints are // below // (to avoid being too close to main label/icon) if (hintVAlign == Gravity.TOP) hintText = "˙˙˙"; else hintText = "..."; } } if (mKeyboard.isShifted()) hintText = hintText.toUpperCase(); // now draw hint paint.setTypeface(Typeface.DEFAULT); paint.setColor(hintColor.getColorForState(drawableState, 0xFF000000)); paint.setTextSize(mHintTextSize); // get the hint text font metrics so that we know the size // of the hint when // we try to position the main label (to try to make sure // they don't overlap) if (mHintTextFM == null) { mHintTextFM = paint.getFontMetrics(); } final float hintX; final float hintY; // the (float) 0.5 value is added or subtracted to just give // a little more room // in case the theme designer didn't account for the hint // label location if (hintAlign == Gravity.LEFT) { // left paint.setTextAlign(Paint.Align.LEFT); hintX = mKeyBackgroundPadding.left + (float) 0.5; } else if (hintAlign == Gravity.CENTER) { // center paint.setTextAlign(Paint.Align.CENTER); hintX = mKeyBackgroundPadding.left + (key.width - mKeyBackgroundPadding.left - mKeyBackgroundPadding.right) / 2; } else { // right paint.setTextAlign(Paint.Align.RIGHT); hintX = key.width - mKeyBackgroundPadding.right - (float) 0.5; } if (hintVAlign == Gravity.TOP) { // above hintY = mKeyBackgroundPadding.top - mHintTextFM.top + (float) 0.5; } else { // below hintY = key.height - mKeyBackgroundPadding.bottom - mHintTextFM.bottom - (float) 0.5; } canvas.drawText(hintText, hintX, hintY, paint); paint.setTextAlign(oldAlign); } } canvas.translate(-key.x - kbdPaddingLeft, -key.y - kbdPaddingTop); } mInvalidatedKey = null; // Overlay a dark rectangle to dim the keyboard if (mMiniKeyboard != null && mMiniKeyboardVisible) { paint.setColor((int) (mBackgroundDimAmount * 0xFF) << 24); canvas.drawRect(0, 0, getWidth(), getHeight(), paint); } if (AnyApplication.DEBUG) { if (mShowTouchPoints) { for (PointerTracker tracker : mPointerTrackers) { int startX = tracker.getStartX(); int startY = tracker.getStartY(); int lastX = tracker.getLastX(); int lastY = tracker.getLastY(); paint.setAlpha(128); paint.setColor(0xFFFF0000); canvas.drawCircle(startX, startY, 3, paint); canvas.drawLine(startX, startY, lastX, lastY, paint); paint.setColor(0xFF0000FF); canvas.drawCircle(lastX, lastY, 3, paint); paint.setColor(0xFF00FF00); canvas.drawCircle((startX + lastX) / 2, (startY + lastY) / 2, 2, paint); } } } mDrawPending = false; mDirtyRect.setEmpty(); }
private void onBufferDraw(Canvas canvas) { if (mKeyboardChanged) { invalidateAllKeys(); mKeyboardChanged = false; } canvas.getClipBounds(mDirtyRect); if (mKeyboard == null) return; final boolean drawKeyboardNameText = (mKeyboardNameTextSize > 1f) && AnyApplication.getConfig().getShowKeyboardNameText(); final boolean drawHintText = (mHintTextSize > 1) && AnyApplication.getConfig().getShowHintTextOnKeys(); if (AnyApplication.DEBUG && !drawHintText) { Log.d(TAG, "drawHintText is false. mHintTextSize: " + mHintTextSize + ", getShowHintTextOnKeys: " + AnyApplication.getConfig().getShowHintTextOnKeys()); } // TODO: calls to AnyApplication.getConfig().getXXXXX() functions are // not yet implemented, // but need to when allowing preferences to override theme settings of // these values // right now just using what should be the default values for these // unimplemented preferences final boolean useCustomKeyTextColor = false; // TODO: final boolean useCustomKeyTextColor = // AnyApplication.getConfig().getUseCustomTextColorOnKeys(); final ColorStateList keyTextColor = useCustomKeyTextColor ? new ColorStateList( new int[][] { { 0 } }, new int[] { 0xFF6666FF }) : mKeyTextColor; // TODO: ? AnyApplication.getConfig().getCustomKeyTextColorOnKeys() : // mKeyTextColor; final boolean useCustomHintColor = drawHintText && false; // TODO: final boolean useCustomHintColor = drawHintText && // AnyApplication.getConfig().getUseCustomHintColorOnKeys(); final ColorStateList hintColor = useCustomHintColor ? new ColorStateList( new int[][] { { 0 } }, new int[] { 0xFFFF6666 }) : mHintTextColor; // TODO: ? AnyApplication.getConfig().getCustomHintColorOnKeys() : // mHintTextColor; // allow preferences to override theme settings for hint text position final boolean useCustomHintAlign = drawHintText && AnyApplication.getConfig().getUseCustomHintAlign(); final int hintAlign = useCustomHintAlign ? AnyApplication.getConfig() .getCustomHintAlign() : mHintLabelAlign; final int hintVAlign = useCustomHintAlign ? AnyApplication.getConfig() .getCustomHintVAlign() : mHintLabelVAlign; final Paint paint = mPaint; final Drawable keyBackground = mKeyBackground; final Rect clipRegion = mClipRegion; final int kbdPaddingLeft = getPaddingLeft(); final int kbdPaddingTop = getPaddingTop(); final Key[] keys = mKeys; final Key invalidKey = mInvalidatedKey; boolean drawSingleKey = false; if (invalidKey != null && canvas.getClipBounds(clipRegion)) { // TODO we should use Rect.inset and Rect.contains here. // Is clipRegion completely contained within the invalidated key? if (invalidKey.x + kbdPaddingLeft - 1 <= clipRegion.left && invalidKey.y + kbdPaddingTop - 1 <= clipRegion.top && invalidKey.x + invalidKey.width + kbdPaddingLeft + 1 >= clipRegion.right && invalidKey.y + invalidKey.height + kbdPaddingTop + 1 >= clipRegion.bottom) { drawSingleKey = true; } } // canvas.drawColor(0x00000000, PorterDuff.Mode.CLEAR); final int keyCount = keys.length; for (int i = 0; i < keyCount; i++) { final AnyKey key = (AnyKey) keys[i]; final boolean keyIsSpace = isSpaceKey(key); if (drawSingleKey && (invalidKey != key)) { continue; } if (!mDirtyRect.intersects(key.x + kbdPaddingLeft, key.y + kbdPaddingTop, key.x + key.width + kbdPaddingLeft, key.y + key.height + kbdPaddingTop)) { continue; } int[] drawableState = key.getCurrentDrawableState(); if (keyIsSpace) paint.setColor(mKeyboardNameTextColor.getColorForState(drawableState, 0xFF000000)); else paint.setColor(keyTextColor.getColorForState(drawableState, 0xFF000000)); keyBackground.setState(drawableState); // Switch the character to uppercase if shift is pressed CharSequence label = key.label == null ? null : adjustCase(key) .toString(); final Rect bounds = keyBackground.getBounds(); if ((key.width != bounds.right) || (key.height != bounds.bottom)) { keyBackground.setBounds(0, 0, key.width, key.height); } canvas.translate(key.x + kbdPaddingLeft, key.y + kbdPaddingTop); keyBackground.draw(canvas); if (TextUtils.isEmpty(label)) { Drawable iconToDraw = getIconToDrawForKey(key, false); if (iconToDraw != null/* && shouldDrawIcon */) { // Special handing for the upper-right number hint icons final int drawableWidth; final int drawableHeight; final int drawableX; final int drawableY; drawableWidth = iconToDraw.getIntrinsicWidth(); drawableHeight = iconToDraw.getIntrinsicHeight(); drawableX = (key.width + mKeyBackgroundPadding.left - mKeyBackgroundPadding.right - drawableWidth) / 2; drawableY = (key.height + mKeyBackgroundPadding.top - mKeyBackgroundPadding.bottom - drawableHeight) / 2; canvas.translate(drawableX, drawableY); iconToDraw.setBounds(0, 0, drawableWidth, drawableHeight); iconToDraw.draw(canvas); canvas.translate(-drawableX, -drawableY); if (keyIsSpace && drawKeyboardNameText) { //now a little hack, I'll set the label now, so it get drawn. label = mKeyboardName; } } else { // ho... no icon. // I'll try to guess the text label = guessLabelForKey(key); if (TextUtils.isEmpty(label)) { Log.w(TAG, "That's unfortunate, for key " + key.codes[0] + " at (" + key.x + ", " + key.y + ") there is no icon nor label. Action ID is " + mKeyboardActionType); } } } if (label != null) { // For characters, use large font. For labels like "Done", use // small font. final FontMetrics fm; if (keyIsSpace) { paint.setTextSize(mKeyboardNameTextSize); paint.setTypeface(Typeface.DEFAULT_BOLD); if (mKeyboardNameFM == null) mKeyboardNameFM = paint.getFontMetrics(); fm = mKeyboardNameFM; } else if (label.length() > 1 && key.codes.length < 2) { paint.setTextSize(mLabelTextSize); paint.setTypeface(Typeface.DEFAULT_BOLD); if (mLabelFM == null) mLabelFM = paint.getFontMetrics(); fm = mLabelFM; } else { paint.setTextSize(mKeyTextSize); paint.setTypeface(mKeyTextStyle); if (mTextFM == null) mTextFM = paint.getFontMetrics(); fm = mTextFM; } final float labelHeight = -fm.top; // Draw a drop shadow for the text paint.setShadowLayer(mShadowRadius, mShadowOffsetX, mShadowOffsetY, mShadowColor); // (+)This is the trick to get RTL/LTR text correct // no matter what: StaticLayout // this should be in the top left corner of the key float textWidth = paint.measureText(label, 0, label.length()); //I'm going to try something if the key is too small for the text: //1) divide the text size by 1.5 //2) if still too large, divide by 2.5 //3) show no text if (textWidth > key.width) { if (AnyApplication.DEBUG) Log.d(TAG, "Label '"+label+"' is too large for the key. Reducing by 1.5."); paint.setTextSize(mKeyTextSize/1.5f); textWidth = paint.measureText(label, 0, label.length()); if (textWidth > key.width) { if (AnyApplication.DEBUG) Log.d(TAG, "Label '"+label+"' is too large for the key. Reducing by 2.5."); paint.setTextSize(mKeyTextSize/2.5f); textWidth = paint.measureText(label, 0, label.length()); if (textWidth > key.width) { if (AnyApplication.DEBUG) Log.d(TAG, "Label '"+label+"' is too large for the key. Showing no text."); paint.setTextSize(0f); textWidth = paint.measureText(label, 0, label.length()); } } } // the center of the drawable space, which is value used // previously for vertically // positioning the key label final float centerY = mKeyBackgroundPadding.top + ((key.height - mKeyBackgroundPadding.top - mKeyBackgroundPadding.bottom) / (keyIsSpace? 3 : 2));//the label on the space is a bit higher // the X coordinate for the center of the main label text is // unaffected by the hints final float centerX = mKeyBackgroundPadding.left + (key.width - mKeyBackgroundPadding.left - mKeyBackgroundPadding.right) / 2; final float textX = centerX; final float textY; // Some devices (mostly pre-Honeycomb, have issues with RTL text // drawing. // Of course, there is no issue with a single character :) // so, we'll use the RTL secured drawing (via StaticLayout) for // labels. if (label.length() > 1 && !AnyApplication.getConfig() .workaround_alwaysUseDrawText()) { // calculate Y coordinate of top of text based on center // location textY = centerY - ((labelHeight - paint.descent()) / 2); canvas.translate(textX, textY); if (AnyApplication.DEBUG) Log.d(TAG, "Using RTL fix for key draw '" + label + "'"); // RTL fix. But it costs, let do it when in need (more than // 1 character) StaticLayout labelText = new StaticLayout(label, new TextPaint(paint), (int) textWidth, Alignment.ALIGN_NORMAL, 0.0f, 0.0f, false); labelText.draw(canvas); } else { // to get Y coordinate of baseline from center of text, // first add half the height (to get to // bottom of text), then subtract the part below the // baseline. Note that fm.top is negative. textY = centerY + ((labelHeight - paint.descent()) / 2); canvas.translate(textX, textY); canvas.drawText(label, 0, label.length(), 0, 0, paint); } canvas.translate(-textX, -textY); // (-) // Turn off drop shadow paint.setShadowLayer(0, 0, 0, 0); } if (drawHintText) { if ((key.popupCharacters != null && key.popupCharacters .length() > 0) || (key.popupResId != 0) || (key.longPressCode != 0)) { Paint.Align oldAlign = paint.getTextAlign(); String hintText = null; if (key.hintLabel != null && key.hintLabel.length() > 0) { hintText = key.hintLabel.toString(); // it is the responsibility of the keyboard layout // designer to ensure that they do // not put too many characters in the hint label... } else if (key.longPressCode != 0) { if (Character.isLetterOrDigit(key.longPressCode)) hintText = Character .toString((char) key.longPressCode); } else if (key.popupCharacters != null) { final String hintString = key.popupCharacters .toString(); final int hintLength = hintString.length(); if (hintLength <= 3) hintText = hintString; } // if hintText is still null, it means it didn't fit one of // the above // cases, so we should provide the hint using the default if (hintText == null) { if (mHintOverflowLabel != null) hintText = mHintOverflowLabel.toString(); else { // theme does not provide a defaultHintLabel // use ˙˙˙ if hints are above, ... if hints are // below // (to avoid being too close to main label/icon) if (hintVAlign == Gravity.TOP) hintText = "˙˙˙"; else hintText = "..."; } } if (mKeyboard.isShifted()) hintText = hintText.toUpperCase(); // now draw hint paint.setTypeface(Typeface.DEFAULT); paint.setColor(hintColor.getColorForState(drawableState, 0xFF000000)); paint.setTextSize(mHintTextSize); // get the hint text font metrics so that we know the size // of the hint when // we try to position the main label (to try to make sure // they don't overlap) if (mHintTextFM == null) { mHintTextFM = paint.getFontMetrics(); } final float hintX; final float hintY; // the (float) 0.5 value is added or subtracted to just give // a little more room // in case the theme designer didn't account for the hint // label location if (hintAlign == Gravity.LEFT) { // left paint.setTextAlign(Paint.Align.LEFT); hintX = mKeyBackgroundPadding.left + (float) 0.5; } else if (hintAlign == Gravity.CENTER) { // center paint.setTextAlign(Paint.Align.CENTER); hintX = mKeyBackgroundPadding.left + (key.width - mKeyBackgroundPadding.left - mKeyBackgroundPadding.right) / 2; } else { // right paint.setTextAlign(Paint.Align.RIGHT); hintX = key.width - mKeyBackgroundPadding.right - (float) 0.5; } if (hintVAlign == Gravity.TOP) { // above hintY = mKeyBackgroundPadding.top - mHintTextFM.top + (float) 0.5; } else { // below hintY = key.height - mKeyBackgroundPadding.bottom - mHintTextFM.bottom - (float) 0.5; } canvas.drawText(hintText, hintX, hintY, paint); paint.setTextAlign(oldAlign); } } canvas.translate(-key.x - kbdPaddingLeft, -key.y - kbdPaddingTop); } mInvalidatedKey = null; // Overlay a dark rectangle to dim the keyboard if (mMiniKeyboard != null && mMiniKeyboardVisible) { paint.setColor((int) (mBackgroundDimAmount * 0xFF) << 24); canvas.drawRect(0, 0, getWidth(), getHeight(), paint); } if (AnyApplication.DEBUG) { if (mShowTouchPoints) { for (PointerTracker tracker : mPointerTrackers) { int startX = tracker.getStartX(); int startY = tracker.getStartY(); int lastX = tracker.getLastX(); int lastY = tracker.getLastY(); paint.setAlpha(128); paint.setColor(0xFFFF0000); canvas.drawCircle(startX, startY, 3, paint); canvas.drawLine(startX, startY, lastX, lastY, paint); paint.setColor(0xFF0000FF); canvas.drawCircle(lastX, lastY, 3, paint); paint.setColor(0xFF00FF00); canvas.drawCircle((startX + lastX) / 2, (startY + lastY) / 2, 2, paint); } } } mDrawPending = false; mDirtyRect.setEmpty(); }
diff --git a/weaver/src/org/aspectj/weaver/bcel/BcelShadow.java b/weaver/src/org/aspectj/weaver/bcel/BcelShadow.java index f0b0742d8..6059e7d9f 100644 --- a/weaver/src/org/aspectj/weaver/bcel/BcelShadow.java +++ b/weaver/src/org/aspectj/weaver/bcel/BcelShadow.java @@ -1,1899 +1,1903 @@ /* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * 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: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.File; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.bcel.Constants; import org.apache.bcel.classfile.Field; import org.apache.bcel.generic.ACONST_NULL; import org.apache.bcel.generic.ArrayType; import org.apache.bcel.generic.BranchInstruction; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.DUP; import org.apache.bcel.generic.DUP_X1; import org.apache.bcel.generic.FieldInstruction; import org.apache.bcel.generic.INVOKESPECIAL; import org.apache.bcel.generic.INVOKESTATIC; import org.apache.bcel.generic.Instruction; import org.apache.bcel.generic.InstructionFactory; import org.apache.bcel.generic.InstructionHandle; import org.apache.bcel.generic.InstructionList; import org.apache.bcel.generic.InstructionTargeter; import org.apache.bcel.generic.InvokeInstruction; import org.apache.bcel.generic.NEW; import org.apache.bcel.generic.ObjectType; import org.apache.bcel.generic.ReturnInstruction; import org.apache.bcel.generic.SWAP; import org.apache.bcel.generic.TargetLostException; import org.apache.bcel.generic.Type; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.SourceLocation; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.BCException; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Var; /* * Some fun implementation stuff: * * * expressionKind advice is non-execution advice * * may have a target. * * if the body is extracted, it will be extracted into * a static method. The first argument to the static * method is the target * * advice may expose a this object, but that's the advice's * consideration, not ours. This object will NOT be cached in another * local, but will always come from frame zero. * * * non-expressionKind advice is execution advice * * may have a this. * * target is same as this, and is exposed that way to advice * (i.e., target will not be cached, will always come from frame zero) * * if the body is extracted, it will be extracted into a method * with same static/dynamic modifier as enclosing method. If non-static, * target of callback call will be this. * * * because of these two facts, the setup of the actual arguments (including * possible target) callback method is the same for both kinds of advice: * push the targetVar, if it exists (it will not exist for advice on static * things), then push all the argVars. * * Protected things: * * * the above is sufficient for non-expressionKind advice for protected things, * since the target will always be this. * * * For expressionKind things, we have to modify the signature of the callback * method slightly. For non-static expressionKind things, we modify * the first argument of the callback method NOT to be the type specified * by the method/field signature (the owner), but rather we type it to * the currentlyEnclosing type. We are guaranteed this will be fine, * since the verifier verifies that the target is a subtype of the currently * enclosingType. * * Worries: * * * ConstructorCalls will be weirder than all of these, since they * supposedly don't have a target (according to AspectJ), but they clearly * do have a target of sorts, just one that needs to be pushed on the stack, * dupped, and not touched otherwise until the constructor runs. * */ public class BcelShadow extends Shadow { private ShadowRange range; private final BcelWorld world; private final LazyMethodGen enclosingMethod; private boolean fallsThrough; //XXX not used anymore // ---- initialization /** * This generates an unassociated shadow, rooted in a particular method but not rooted * to any particular point in the code. It should be given to a rooted ShadowRange * in the {@link ShadowRange#associateWithShadow(BcelShadow)} method. */ public BcelShadow( BcelWorld world, Kind kind, Member signature, LazyMethodGen enclosingMethod, BcelShadow enclosingShadow) { super(kind, signature, enclosingShadow); this.world = world; this.enclosingMethod = enclosingMethod; fallsThrough = kind.argsOnStack(); } // ---- copies all state, including Shadow's mungers... public BcelShadow copyInto(LazyMethodGen recipient, BcelShadow enclosing) { BcelShadow s = new BcelShadow(world, getKind(), getSignature(), recipient, enclosing); List src = mungers; List dest = s.mungers; for (Iterator i = src.iterator(); i.hasNext(); ) { dest.add(i.next()); } return s; } // ---- overridden behaviour public World getIWorld() { return world; } private void deleteNewAndDup() { final ConstantPoolGen cpg = getEnclosingClass().getConstantPoolGen(); int depth = 1; InstructionHandle ih = range.getStart(); while (true) { Instruction inst = ih.getInstruction(); if (inst instanceof INVOKESPECIAL && ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) { depth++; } else if (inst instanceof NEW) { depth--; if (depth == 0) break; } ih = ih.getPrev(); } // now IH points to the NEW. We're followed by the DUP, and that is followed // by the actual instruciton we care about. InstructionHandle newHandle = ih; InstructionHandle endHandle = newHandle.getNext(); InstructionHandle nextHandle; if (endHandle.getInstruction() instanceof DUP) { nextHandle = endHandle.getNext(); retargetFrom(newHandle, nextHandle); retargetFrom(endHandle, nextHandle); } else if (endHandle.getInstruction() instanceof DUP_X1) { InstructionHandle dupHandle = endHandle; endHandle = endHandle.getNext(); nextHandle = endHandle.getNext(); if (endHandle.getInstruction() instanceof SWAP) {} else { // XXX see next XXX comment throw new RuntimeException("Unhandled kind of new " + endHandle); } retargetFrom(newHandle, nextHandle); retargetFrom(dupHandle, nextHandle); retargetFrom(endHandle, nextHandle); } else { endHandle = newHandle; nextHandle = endHandle.getNext(); retargetFrom(newHandle, nextHandle); // add a POP here... we found a NEW w/o a dup or anything else, so // we must be in statement context. getRange().insert(getFactory().POP, Range.OutsideAfter); } // assert (dupHandle.getInstruction() instanceof DUP); try { range.getBody().delete(newHandle, endHandle); } catch (TargetLostException e) { throw new BCException("shouldn't happen"); } } private void retargetFrom(InstructionHandle old, InstructionHandle fresh) { InstructionTargeter[] sources = old.getTargeters(); if (sources != null) { for (int i = sources.length - 1; i >= 0; i--) { sources[i].updateTarget(old, fresh); } } } protected void prepareForMungers() { // if we're a constructor call, we need to remove the new:dup or the new:dup_x1:swap, // and store all our // arguments on the frame. // ??? This is a bit of a hack (for the Java langauge). We do this because // we sometime add code "outsideBefore" when dealing with weaving join points. We only // do this for exposing state that is on the stack. It turns out to just work for // everything except for constructor calls and exception handlers. If we were to clean // this up, every ShadowRange would have three instructionHandle points, the start of // the arg-setup code, the start of the running code, and the end of the running code. if (getKind() == ConstructorCall) { deleteNewAndDup(); initializeArgVars(); } else if (getKind() == ExceptionHandler) { ShadowRange range = getRange(); InstructionList body = range.getBody(); InstructionHandle start = range.getStart(); InstructionHandle freshIh = body.insert(start, getFactory().NOP); InstructionTargeter[] targeters = start.getTargeters(); for (int i = 0; i < targeters.length; i++) { InstructionTargeter t = targeters[i]; if (t instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) t; er.updateTarget(start, freshIh, body); } } } // now we ask each munger to request our state for (Iterator iter = mungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); munger.specializeOn(this); } // If we are an expression kind, we require our target/arguments on the stack // before we do our actual thing. However, they may have been removed // from the stack as the shadowMungers have requested state. // if any of our shadowMungers requested either the arguments or target, // the munger will have added code // to pop the target/arguments into temporary variables, represented by // targetVar and argVars. In such a case, we must make sure to re-push the // values. // If we are nonExpressionKind, we don't expect arguments on the stack // so this is moot. If our argVars happen to be null, then we know that // no ShadowMunger has squirrelled away our arguments, so they're still // on the stack. InstructionFactory fact = getFactory(); if (getKind().argsOnStack() && argVars != null) { range.insert( BcelRenderer.renderExprs(fact, world, argVars), Range.InsideBefore); if (targetVar != null) { range.insert( BcelRenderer.renderExpr(fact, world, targetVar), Range.InsideBefore); } if (getKind() == ConstructorCall) { range.insert((Instruction) fact.createDup(1), Range.InsideBefore); range.insert( fact.createNew( (ObjectType) BcelWorld.makeBcelType( getSignature().getDeclaringType())), Range.InsideBefore); } } } // ---- getters public ShadowRange getRange() { return range; } public void setRange(ShadowRange range) { this.range = range; } public int getSourceLine() { if (range == null) { if (getEnclosingMethod().hasBody()) { return Utility.getSourceLine(getEnclosingMethod().getBody().getStart()); } else { return 0; } } int ret = Utility.getSourceLine(range.getStart()); if (ret < 0) return 0; return ret; } // overrides public TypeX getEnclosingType() { return getEnclosingClass().getType(); } public LazyClassGen getEnclosingClass() { return enclosingMethod.getEnclosingClass(); } public BcelWorld getWorld() { return world; } // ---- factory methods public static BcelShadow makeConstructorExecution( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle justBeforeStart) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, ConstructorExecution, world.makeMethodSignature(enclosingMethod), enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, justBeforeStart.getNext()), Range.genEnd(body)); return s; } public static BcelShadow makeStaticInitialization( BcelWorld world, LazyMethodGen enclosingMethod) { InstructionList body = enclosingMethod.getBody(); // move the start past ajc$preClinit InstructionHandle clinitStart = body.getStart(); if (clinitStart.getInstruction() instanceof InvokeInstruction) { InvokeInstruction ii = (InvokeInstruction)clinitStart.getInstruction(); if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen()).equals(NameMangler.AJC_PRE_CLINIT_NAME)) { clinitStart = clinitStart.getNext(); } } InstructionHandle clinitEnd = body.getEnd(); //XXX should move the end before the postClinit, but the return is then tricky... // if (clinitEnd.getInstruction() instanceof InvokeInstruction) { // InvokeInstruction ii = (InvokeInstruction)clinitEnd.getInstruction(); // if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen()).equals(NameMangler.AJC_POST_CLINIT_NAME)) { // clinitEnd = clinitEnd.getPrev(); // } // } BcelShadow s = new BcelShadow( world, StaticInitialization, world.makeMethodSignature(enclosingMethod), enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, clinitStart), Range.genEnd(body, clinitEnd)); return s; } /** Make the shadow for an exception handler. Currently makes an empty shadow that * only allows before advice to be woven into it. */ public static BcelShadow makeExceptionHandler( BcelWorld world, ExceptionRange exceptionRange, LazyMethodGen enclosingMethod, InstructionHandle startOfHandler, BcelShadow enclosingShadow) { InstructionList body = enclosingMethod.getBody(); TypeX catchType = exceptionRange.getCatchType(); TypeX inType = enclosingMethod.getEnclosingClass().getType(); BcelShadow s = new BcelShadow( world, ExceptionHandler, Member.makeExceptionHandlerSignature(inType, catchType), enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); InstructionHandle start = Range.genStart(body, startOfHandler); InstructionHandle end = Range.genEnd(body, start); r.associateWithTargets(start, end); exceptionRange.updateTarget(startOfHandler, start, body); return s; } /** create an init join point associated w/ an interface in the body of a constructor */ public static BcelShadow makeIfaceInitialization( BcelWorld world, LazyMethodGen constructor, BcelShadow ifaceCExecShadow, Member interfaceConstructorSignature) { InstructionList body = constructor.getBody(); TypeX inType = constructor.getEnclosingClass().getType(); BcelShadow s = new BcelShadow( world, Initialization, interfaceConstructorSignature, constructor, null); s.fallsThrough = true; ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); InstructionHandle start = Range.genStart(body, ifaceCExecShadow.getRange().getStart()); InstructionHandle end = Range.genEnd(body, ifaceCExecShadow.getRange().getEnd()); r.associateWithTargets(start, end); return s; } public static BcelShadow makeIfaceConstructorExecution( BcelWorld world, LazyMethodGen constructor, InstructionHandle next, Member interfaceConstructorSignature) { final InstructionFactory fact = constructor.getEnclosingClass().getFactory(); InstructionList body = constructor.getBody(); TypeX inType = constructor.getEnclosingClass().getType(); BcelShadow s = new BcelShadow( world, ConstructorExecution, interfaceConstructorSignature, constructor, null); s.fallsThrough = true; ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); // ??? this may or may not work InstructionHandle start = Range.genStart(body, next); //InstructionHandle end = Range.genEnd(body, body.append(start, fact.NOP)); InstructionHandle end = Range.genStart(body, next); //body.append(start, fact.NOP); r.associateWithTargets(start, end); return s; } /** Create an initialization join point associated with a constructor, but not * with any body of code yet. If this is actually matched, it's range will be set * when we inline self constructors. * * @param constructor The constructor starting this initialization. */ public static BcelShadow makeUnfinishedInitialization( BcelWorld world, LazyMethodGen constructor) { return new BcelShadow( world, Initialization, world.makeMethodSignature(constructor), constructor, null); } public static BcelShadow makeUnfinishedPreinitialization( BcelWorld world, LazyMethodGen constructor) { BcelShadow ret = new BcelShadow( world, PreInitialization, world.makeMethodSignature(constructor), constructor, null); ret.fallsThrough = true; return ret; } public static BcelShadow makeMethodExecution( BcelWorld world, LazyMethodGen enclosingMethod) { return makeShadowForMethod(world, enclosingMethod, MethodExecution, world.makeMethodSignature(enclosingMethod)); } public static BcelShadow makeShadowForMethod(BcelWorld world, LazyMethodGen enclosingMethod, Shadow.Kind kind, Member sig) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, kind, sig, enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body), Range.genEnd(body)); return s; } public static BcelShadow makeAdviceExecution( BcelWorld world, LazyMethodGen enclosingMethod) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, AdviceExecution, world.makeMethodSignature(enclosingMethod, Member.ADVICE), enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body), Range.genEnd(body)); return s; } // constructor call shadows are <em>initially</em> just around the // call to the constructor. If ANY advice gets put on it, we move // the NEW instruction inside the join point, which involves putting // all the arguments in temps. public static BcelShadow makeConstructorCall( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); Member sig = world.makeMethodSignature( enclosingMethod.getEnclosingClass(), (InvokeInstruction) callHandle.getInstruction()); BcelShadow s = new BcelShadow( world, ConstructorCall, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, callHandle), Range.genEnd(body, callHandle)); retargetAllBranches(callHandle, r.getStart()); return s; } public static BcelShadow makeMethodCall( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, MethodCall, world.makeMethodSignature( enclosingMethod.getEnclosingClass(), (InvokeInstruction) callHandle.getInstruction()), enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, callHandle), Range.genEnd(body, callHandle)); retargetAllBranches(callHandle, r.getStart()); return s; } public static BcelShadow makeShadowForMethodCall( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle, BcelShadow enclosingShadow, Kind kind, ResolvedMember sig) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, kind, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, callHandle), Range.genEnd(body, callHandle)); retargetAllBranches(callHandle, r.getStart()); return s; } public static BcelShadow makeFieldGet( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle getHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, FieldGet, world.makeFieldSignature( enclosingMethod.getEnclosingClass(), (FieldInstruction) getHandle.getInstruction()), enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, getHandle), Range.genEnd(body, getHandle)); retargetAllBranches(getHandle, r.getStart()); return s; } public static BcelShadow makeFieldSet( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle setHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, FieldSet, world.makeFieldSignature( enclosingMethod.getEnclosingClass(), (FieldInstruction) setHandle.getInstruction()), enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, setHandle), Range.genEnd(body, setHandle)); retargetAllBranches(setHandle, r.getStart()); return s; } public static void retargetAllBranches(InstructionHandle from, InstructionHandle to) { InstructionTargeter[] sources = from.getTargeters(); if (sources != null) { for (int i = sources.length - 1; i >= 0; i--) { InstructionTargeter source = sources[i]; if (source instanceof BranchInstruction) { source.updateTarget(from, to); } } } } // ---- type access methods private ObjectType getTargetBcelType() { return (ObjectType) world.makeBcelType(getTargetType()); } private Type getArgBcelType(int arg) { return world.makeBcelType(getArgType(arg)); } // ---- kinding /** * If the end of my range has no real instructions following then * my context needs a return at the end. */ public boolean terminatesWithReturn() { return getRange().getRealNext() == null; } /** * Is arg0 occupied with the value of this */ public boolean arg0HoldsThis() { if (getKind().isEnclosingKind()) { return !getSignature().isStatic(); } else if (enclosingShadow == null) { //XXX this is mostly right // this doesn't do the right thing for calls in the pre part of introduced constructors. return !enclosingMethod.isStatic(); } else { return ((BcelShadow)enclosingShadow).arg0HoldsThis(); } } // ---- argument getting methods private BcelVar thisVar = null; private BcelVar targetVar = null; private BcelVar[] argVars = null; public Var getThisVar() { if (!hasThis()) { throw new IllegalStateException("no this"); } initializeThisVar(); return thisVar; } public Var getTargetVar() { if (!hasTarget()) { throw new IllegalStateException("no target"); } initializeTargetVar(); return targetVar; } public Var getArgVar(int i) { initializeArgVars(); return argVars[i]; } // reflective thisJoinPoint support private BcelVar thisJoinPointVar = null; private BcelVar thisJoinPointStaticPartVar = null; private BcelVar thisEnclosingJoinPointStaticPartVar = null; public final Var getThisJoinPointVar() { return getThisJoinPointBcelVar(); } public final Var getThisJoinPointStaticPartVar() { return getThisJoinPointStaticPartBcelVar(); } public final Var getThisEnclosingJoinPointStaticPartVar() { return getThisEnclosingJoinPointStaticPartBcelVar(); } public BcelVar getThisJoinPointBcelVar() { if (thisJoinPointVar == null) { thisJoinPointVar = genTempVar(TypeX.forName("org.aspectj.lang.JoinPoint")); InstructionFactory fact = getFactory(); InstructionList il = new InstructionList(); BcelVar staticPart = getThisJoinPointStaticPartBcelVar(); staticPart.appendLoad(il, fact); if (hasThis()) { ((BcelVar)getThisVar()).appendLoad(il, fact); } else { il.append(new ACONST_NULL()); } if (hasTarget()) { ((BcelVar)getTargetVar()).appendLoad(il, fact); } else { il.append(new ACONST_NULL()); } il.append(makeArgsObjectArray()); il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT, new ArrayType(Type.OBJECT, 1)}, Constants.INVOKESTATIC)); il.append(thisJoinPointVar.createStore(fact)); range.insert(il, Range.OutsideBefore); } return thisJoinPointVar; } public BcelVar getThisJoinPointStaticPartBcelVar() { if (thisJoinPointStaticPartVar == null) { Field field = getEnclosingClass().getTjpField(this); thisJoinPointStaticPartVar = new BcelFieldRef( world.resolve(TypeX.forName("org.aspectj.lang.JoinPoint$StaticPart")), getEnclosingClass().getClassName(), field.getName()); } return thisJoinPointStaticPartVar; } public BcelVar getThisEnclosingJoinPointStaticPartBcelVar() { if (enclosingShadow == null) { // the enclosing of an execution is itself return getThisJoinPointStaticPartBcelVar(); } else { return ((BcelShadow)enclosingShadow).getThisJoinPointStaticPartBcelVar(); } } public Member getEnclosingCodeSignature() { if (enclosingShadow == null) { return getSignature(); } else { return enclosingShadow.getSignature(); } } private InstructionList makeArgsObjectArray() { InstructionFactory fact = getFactory(); BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY); final InstructionList il = new InstructionList(); int alen = getArgCount() ; il.append(Utility.createConstant(fact, alen)); il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1)); arrayVar.appendStore(il, fact); int stateIndex = 0; for (int i = 0, len = getArgCount(); i<len; i++) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, (BcelVar)getArgVar(i)); stateIndex++; } arrayVar.appendLoad(il, fact); return il; } // ---- initializing var tables /* initializing this is doesn't do anything, because this * is protected from side-effects, so we don't need to copy its location */ private void initializeThisVar() { if (thisVar != null) return; thisVar = new BcelVar(getThisType().resolve(world), 0); thisVar.setPositionInAroundState(0); } public void initializeTargetVar() { InstructionFactory fact = getFactory(); if (targetVar != null) return; if (getKind().isTargetSameAsThis()) { if (hasThis()) initializeThisVar(); targetVar = thisVar; } else { initializeArgVars(); // gotta pop off the args before we find the target TypeX type = getTargetType(); targetVar = genTempVar(type, "ajc$target"); range.insert(targetVar.createStore(fact), Range.OutsideBefore); targetVar.setPositionInAroundState(hasThis() ? 1 : 0); } } public void initializeArgVars() { if (argVars != null) return; InstructionFactory fact = getFactory(); int len = getArgCount(); argVars = new BcelVar[len]; int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0); if (getKind().argsOnStack()) { // we move backwards because we're popping off the stack for (int i = len - 1; i >= 0; i--) { TypeX type = getArgType(i); BcelVar tmp = genTempVar(type, "ajc$arg" + i); range.insert(tmp.createStore(getFactory()), Range.OutsideBefore); int position = i; position += positionOffset; tmp.setPositionInAroundState(position); argVars[i] = tmp; } } else { int index = 0; if (arg0HoldsThis()) index++; for (int i = 0; i < len; i++) { TypeX type = getArgType(i); BcelVar tmp = genTempVar(type, "ajc$arg" + i); range.insert(tmp.createCopyFrom(fact, index), Range.OutsideBefore); argVars[i] = tmp; int position = i; position += positionOffset; // System.out.println("set position: " + tmp + ", " + position + " in " + this); // System.out.println(" hasThis: " + hasThis() + ", hasTarget: " + hasTarget()); tmp.setPositionInAroundState(position); index += type.getSize(); } } } public void initializeForAroundClosure() { initializeArgVars(); if (hasTarget()) initializeTargetVar(); if (hasThis()) initializeThisVar(); // System.out.println("initialized: " + this + " thisVar = " + thisVar); } // ---- weave methods void weaveBefore(BcelAdvice munger) { range.insert( munger.getAdviceInstructions(this, null, range.getRealStart()), Range.InsideBefore); } public void weaveAfter(BcelAdvice munger) { weaveAfterThrowing(munger, TypeX.THROWABLE); weaveAfterReturning(munger); } /** * We guarantee that the return value is on the top of the stack when * munger.getAdviceInstructions() will be run * (Unless we have a void return type in which case there's nothing) */ public void weaveAfterReturning(BcelAdvice munger) { InstructionFactory fact = getFactory(); List returns = new ArrayList(); Instruction ret = null; for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) { if (ih.getInstruction() instanceof ReturnInstruction) { returns.add(ih); ret = ih.getInstruction().copy(); } } InstructionList retList; InstructionHandle afterAdvice; if (ret != null) { retList = new InstructionList(ret); afterAdvice = retList.getStart(); } else /* if (munger.hasDynamicTests()) */ { retList = new InstructionList(fact.NOP); afterAdvice = retList.getStart(); // } else { // retList = new InstructionList(); // afterAdvice = null; } InstructionList advice = new InstructionList(); BcelVar tempVar = null; if (munger.hasExtraParameter()) { TypeX tempVarType = getReturnType(); if (tempVarType.equals(ResolvedTypeX.VOID)) { tempVar = genTempVar(TypeX.OBJECT); advice.append(getFactory().ACONST_NULL); tempVar.appendStore(advice, getFactory()); } else { tempVar = genTempVar(tempVarType); advice.append(getFactory().createDup(tempVarType.getSize())); tempVar.appendStore(advice, getFactory()); } } advice.append(munger.getAdviceInstructions(this, tempVar, afterAdvice)); if (ret != null) { InstructionHandle gotoTarget = advice.getStart(); for (Iterator i = returns.iterator(); i.hasNext(); ) { InstructionHandle ih = (InstructionHandle) i.next(); Utility.replaceInstruction(ih, fact.createBranchInstruction(Constants.GOTO, gotoTarget), enclosingMethod); } range.append(advice); range.append(retList); } else { range.append(advice); range.append(retList); } } public void weaveAfterThrowing(BcelAdvice munger, TypeX catchType) { // a good optimization would be not to generate anything here // if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even // a shadow, inside me). if (getRange().getStart().getNext() == getRange().getEnd()) return; InstructionFactory fact = getFactory(); InstructionList handler = new InstructionList(); BcelVar exceptionVar = genTempVar(catchType); exceptionVar.appendStore(handler, fact); InstructionList endHandler = new InstructionList( exceptionVar.createLoad(fact)); handler.append(munger.getAdviceInstructions(this, exceptionVar, endHandler.getStart())); handler.append(endHandler); handler.append(fact.ATHROW); InstructionHandle handlerStart = handler.getStart(); if (isFallsThrough()) { InstructionHandle jumpTarget = handler.append(fact.NOP); handler.insert(fact.createBranchInstruction(Constants.GOTO, jumpTarget)); } InstructionHandle protectedEnd = handler.getStart(); range.insert(handler, Range.InsideAfter); enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(), handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType), //???Type.THROWABLE, // high priority if our args are on the stack getKind().hasHighPriorityExceptions()); } //??? this shares a lot of code with the above weaveAfterThrowing //??? would be nice to abstract that to say things only once public void weaveSoftener(BcelAdvice munger, TypeX catchType) { // a good optimization would be not to generate anything here // if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even // a shadow, inside me). if (getRange().getStart().getNext() == getRange().getEnd()) return; InstructionFactory fact = getFactory(); InstructionList handler = new InstructionList(); BcelVar exceptionVar = genTempVar(catchType); exceptionVar.appendStore(handler, fact); handler.append(fact.createNew(NameMangler.SOFT_EXCEPTION_TYPE)); handler.append(fact.createDup(1)); handler.append(exceptionVar.createLoad(fact)); handler.append(fact.createInvoke(NameMangler.SOFT_EXCEPTION_TYPE, "<init>", Type.VOID, new Type[] { Type.THROWABLE }, Constants.INVOKESPECIAL)); //??? special handler.append(fact.ATHROW); InstructionHandle handlerStart = handler.getStart(); if (isFallsThrough()) { InstructionHandle jumpTarget = range.getEnd();//handler.append(fact.NOP); handler.insert(fact.createBranchInstruction(Constants.GOTO, jumpTarget)); } InstructionHandle protectedEnd = handler.getStart(); range.insert(handler, Range.InsideAfter); enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(), handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType), // high priority if our args are on the stack getKind().hasHighPriorityExceptions()); } public void weavePerObjectEntry(final BcelAdvice munger, final BcelVar onVar) { final InstructionFactory fact = getFactory(); InstructionList entryInstructions = new InstructionList(); InstructionList entrySuccessInstructions = new InstructionList(); onVar.appendLoad(entrySuccessInstructions, fact); entrySuccessInstructions.append( Utility.createInvoke(fact, world, AjcMemberMaker.perObjectBind(munger.getConcreteAspect()))); InstructionList testInstructions = munger.getTestInstructions(this, entrySuccessInstructions.getStart(), range.getRealStart(), entrySuccessInstructions.getStart()); entryInstructions.append(testInstructions); entryInstructions.append(entrySuccessInstructions); range.insert(entryInstructions, Range.InsideBefore); } public void weaveCflowEntry(final BcelAdvice munger, final Member cflowStackField) { final boolean isPer = munger.getKind() == AdviceKind.PerCflowBelowEntry || munger.getKind() == AdviceKind.PerCflowEntry; final Type objectArrayType = new ArrayType(Type.OBJECT, 1); final InstructionFactory fact = getFactory(); final BcelVar testResult = genTempVar(ResolvedTypeX.BOOLEAN); InstructionList entryInstructions = new InstructionList(); { InstructionList entrySuccessInstructions = new InstructionList(); if (munger.hasDynamicTests()) { entryInstructions.append(Utility.createConstant(fact, 0)); testResult.appendStore(entryInstructions, fact); entrySuccessInstructions.append(Utility.createConstant(fact, 1)); testResult.appendStore(entrySuccessInstructions, fact); } if (isPer) { entrySuccessInstructions.append( fact.createInvoke(munger.getConcreteAspect().getName(), NameMangler.PERCFLOW_PUSH_METHOD, Type.VOID, new Type[] { }, Constants.INVOKESTATIC)); } else { BcelVar[] cflowStateVars = munger.getExposedStateAsBcelVars(); BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY); int alen = cflowStateVars.length; entrySuccessInstructions.append(Utility.createConstant(fact, alen)); entrySuccessInstructions.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1)); arrayVar.appendStore(entrySuccessInstructions, fact); for (int i = 0; i < alen; i++) { arrayVar.appendConvertableArrayStore(entrySuccessInstructions, fact, i, cflowStateVars[i]); } entrySuccessInstructions.append( Utility.createGet(fact, cflowStackField)); arrayVar.appendLoad(entrySuccessInstructions, fact); entrySuccessInstructions.append( fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "push", Type.VOID, new Type[] { objectArrayType }, Constants.INVOKEVIRTUAL)); } InstructionList testInstructions = munger.getTestInstructions(this, entrySuccessInstructions.getStart(), range.getRealStart(), entrySuccessInstructions.getStart()); entryInstructions.append(testInstructions); entryInstructions.append(entrySuccessInstructions); } // this is the same for both per and non-per weaveAfter(new BcelAdvice(null, null, null, 0, 0, 0, null, null) { public InstructionList getAdviceInstructions(BcelShadow s, BcelVar extraArgVar, InstructionHandle ifNoAdvice) { InstructionList exitInstructions = new InstructionList(); if (munger.hasDynamicTests()) { testResult.appendLoad(exitInstructions, fact); exitInstructions.append(fact.createBranchInstruction(Constants.IFEQ, ifNoAdvice)); } exitInstructions.append( Utility.createGet(fact, cflowStackField)); exitInstructions.append( fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "pop", Type.VOID, new Type[] {}, Constants.INVOKEVIRTUAL)); return exitInstructions; }}); range.insert(entryInstructions, Range.InsideBefore); } public void weaveAroundInline( BcelAdvice munger, boolean hasDynamicTest) { /* Implementation notes: * * AroundInline still extracts the instructions of the original shadow into * an extracted method. This allows inlining of even that advice that doesn't * call proceed or calls proceed more than once. * * It extracts the instructions of the original shadow into a method. * * Then it inlines the instructions of the advice in its place, taking care * to treat the closure argument specially (it doesn't exist). * * Then it searches in the instructions of the advice for any call to the * proceed method. * * At such a call, there is stuff on the stack representing the arguments to * proceed. Pop these into the frame. * * Now build the stack for the call to the extracted method, taking values * either from the join point state or from the new frame locs from proceed. * Now call the extracted method. The right return value should be on the * stack, so no cast is necessary. * * If only one call to proceed is made, we can re-inline the original shadow. * We are not doing that presently. */ // !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...); Member mungerSig = munger.getSignature(); ResolvedTypeX declaringType = world.resolve(mungerSig.getDeclaringType()); //??? might want some checks here to give better errors BcelObjectType ot = BcelWorld.getBcelObjectType(declaringType); LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig); if (!adviceMethod.getCanInline()) { weaveAroundClosure(munger, hasDynamicTest); return; } + // We can't inline around methods if they have around advice on them, this + // is because the weaving will extract the body and hence the proceed call. + //??? should consider optimizations to recognize simple cases that don't require body extraction + enclosingMethod.setCanInline(false); // start by exposing various useful things into the frame final InstructionFactory fact = getFactory(); // now generate the aroundBody method LazyMethodGen extractedMethod = extractMethod( NameMangler.aroundCallbackMethodName( getSignature(), getEnclosingClass())); // the shadow is now empty. First, create a correct call // to the around advice. This includes both the call (which may involve // value conversion of the advice arguments) and the return // (which may involve value conversion of the return value). Right now // we push a null for the unused closure. It's sad, but there it is. InstructionList advice = new InstructionList(); InstructionHandle adviceMethodInvocation; { // ??? we don't actually need to push NULL for the closure if we take care advice.append(munger.getAdviceArgSetup(this, null, new InstructionList(fact.ACONST_NULL))); adviceMethodInvocation = advice.append( Utility.createInvoke(fact, getWorld(), munger.getSignature())); advice.append( Utility.createConversion( getFactory(), world.makeBcelType(munger.getSignature().getReturnType()), extractedMethod.getReturnType())); if (! isFallsThrough()) { advice.append(fact.createReturn(extractedMethod.getReturnType())); } } // now, situate the call inside the possible dynamic tests, // and actually add the whole mess to the shadow if (! hasDynamicTest) { range.append(advice); } else { InstructionList afterThingie = new InstructionList(fact.NOP); InstructionList callback = makeCallToCallback(extractedMethod); if (terminatesWithReturn()) { callback.append(fact.createReturn(extractedMethod.getReturnType())); } else { //InstructionHandle endNop = range.insert(fact.NOP, Range.InsideAfter); advice.append(fact.createBranchInstruction(Constants.GOTO, afterThingie.getStart())); } range.append(munger.getTestInstructions(this, advice.getStart(), callback.getStart(), advice.getStart())); range.append(advice); range.append(callback); range.append(afterThingie); } // now the range contains everything we need. We now inline the advice method. BcelClassWeaver.inlineMethod(adviceMethod, enclosingMethod, adviceMethodInvocation); // now search through the advice, looking for a call to PROCEED. // Then we replace the call to proceed with some argument setup, and a // call to the extracted method. String proceedName = NameMangler.proceedMethodName(munger.getSignature().getName()); InstructionHandle curr = getRange().getStart(); InstructionHandle end = getRange().getEnd(); ConstantPoolGen cpg = extractedMethod.getEnclosingClass().getConstantPoolGen(); while (curr != end) { InstructionHandle next = curr.getNext(); Instruction inst = curr.getInstruction(); if ((inst instanceof INVOKESTATIC) && proceedName.equals(((INVOKESTATIC) inst).getMethodName(cpg))) { enclosingMethod.getBody().append(curr, getRedoneProceedCall(fact, extractedMethod, munger)); Utility.deleteInstruction(curr, enclosingMethod); } curr = next; } // and that's it. } private InstructionList getRedoneProceedCall( InstructionFactory fact, LazyMethodGen callbackMethod, BcelAdvice munger) { InstructionList ret = new InstructionList(); // we have on stack all the arguments for the ADVICE call. // we have in frame somewhere all the arguments for the non-advice call. List argVarList = new ArrayList(); // start w/ stuff if (thisVar != null) { argVarList.add(thisVar); } if (targetVar != null && targetVar != thisVar) { argVarList.add(targetVar); } for (int i = 0, len = getArgCount(); i < len; i++) { argVarList.add(argVars[i]); } if (thisJoinPointVar != null) { argVarList.add(thisJoinPointVar); } BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(); //??? this is too easy // for (int i=0; i < adviceVars.length; i++) { // if (adviceVars[i] != null) // adviceVars[i].setPositionInAroundState(i); // } IntMap proceedMap = makeProceedArgumentMap(adviceVars); // System.out.println(proceedMap + " for " + this); // System.out.println(argVarList); ResolvedTypeX[] proceedParamTypes = world.resolve(munger.getSignature().getParameterTypes()); // remove this*JoinPoint* as arguments to proceed if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) { int len = munger.getBaseParameterCount()+1; ResolvedTypeX[] newTypes = new ResolvedTypeX[len]; System.arraycopy(proceedParamTypes, 0, newTypes, 0, len); proceedParamTypes = newTypes; } //System.out.println("stateTypes: " + Arrays.asList(stateTypes)); BcelVar[] proceedVars = Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, enclosingMethod); Type[] stateTypes = callbackMethod.getArgumentTypes(); // System.out.println("stateTypes: " + Arrays.asList(stateTypes)); for (int i=0, len=stateTypes.length; i < len; i++) { Type stateType = stateTypes[i]; ResolvedTypeX stateTypeX = BcelWorld.fromBcel(stateType).resolve(world); if (proceedMap.hasKey(i)) { //throw new RuntimeException("unimplemented"); proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX); } else { ((BcelVar) argVarList.get(i)).appendLoad(ret, fact); } } ret.append(Utility.createInvoke(fact, callbackMethod)); ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(), BcelWorld.makeBcelType(munger.getSignature().getReturnType()))); return ret; } public void weaveAroundClosure( BcelAdvice munger, boolean hasDynamicTest) { InstructionFactory fact = getFactory(); enclosingMethod.setCanInline(false); // MOVE OUT ALL THE INSTRUCTIONS IN MY SHADOW INTO ANOTHER METHOD! LazyMethodGen callbackMethod = extractMethod( NameMangler.aroundCallbackMethodName( getSignature(), getEnclosingClass())); BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(); String closureClassName = NameMangler.makeClosureClassName( getEnclosingClass().getType(), getEnclosingClass().getNewGeneratedNameTag()); Member constructorSig = new Member(Member.CONSTRUCTOR, TypeX.forName(closureClassName), 0, "<init>", "([Ljava/lang/Object;)V"); BcelVar closureHolder = null; // This is not being used currently since getKind() == preinitializaiton // cannot happen in around advice if (getKind() == PreInitialization) { closureHolder = genTempVar(AjcMemberMaker.AROUND_CLOSURE_TYPE); } InstructionList closureInstantiation = makeClosureInstantiation(constructorSig, closureHolder); LazyMethodGen constructor = makeClosureClassAndReturnConstructor( closureClassName, callbackMethod, makeProceedArgumentMap(adviceVars) ); InstructionList returnConversionCode; if (getKind() == PreInitialization) { returnConversionCode = new InstructionList(); BcelVar stateTempVar = genTempVar(TypeX.OBJECTARRAY); closureHolder.appendLoad(returnConversionCode, fact); returnConversionCode.append( Utility.createInvoke( fact, world, AjcMemberMaker.aroundClosurePreInitializationGetter())); stateTempVar.appendStore(returnConversionCode, fact); Type[] stateTypes = getSuperConstructorParameterTypes(); returnConversionCode.append(fact.ALOAD_0); // put "this" back on the stack for (int i = 0, len = stateTypes.length; i < len; i++) { stateTempVar.appendConvertableArrayLoad( returnConversionCode, fact, i, world.resolve(BcelWorld.fromBcel(stateTypes[i]))); } } else { returnConversionCode = Utility.createConversion( getFactory(), world.makeBcelType(munger.getSignature().getReturnType()), callbackMethod.getReturnType()); if (! isFallsThrough()) { returnConversionCode.append(fact.createReturn(callbackMethod.getReturnType())); } } InstructionList advice = new InstructionList(); advice.append(munger.getAdviceArgSetup(this, null, closureInstantiation)); // advice.append(closureInstantiation); advice.append(munger.getNonTestAdviceInstructions(this)); advice.append(returnConversionCode); if (! hasDynamicTest) { range.append(advice); } else { InstructionList callback = makeCallToCallback(callbackMethod); InstructionList postCallback = new InstructionList(); if (terminatesWithReturn()) { callback.append(fact.createReturn(callbackMethod.getReturnType())); } else { advice.append(fact.createBranchInstruction(Constants.GOTO, postCallback.append(fact.NOP))); } range.append(munger.getTestInstructions(this, advice.getStart(), callback.getStart(), advice.getStart())); range.append(advice); range.append(callback); range.append(postCallback); } } // exposed for testing InstructionList makeCallToCallback(LazyMethodGen callbackMethod) { InstructionFactory fact = getFactory(); InstructionList callback = new InstructionList(); if (thisVar != null) { callback.append(fact.ALOAD_0); } if (targetVar != null && targetVar != thisVar) { callback.append(BcelRenderer.renderExpr(fact, world, targetVar)); } callback.append(BcelRenderer.renderExprs(fact, world, argVars)); // remember to render tjps if (thisJoinPointVar != null) { callback.append(BcelRenderer.renderExpr(fact, world, thisJoinPointVar)); } callback.append(Utility.createInvoke(fact, callbackMethod)); return callback; } /** side-effect-free */ private InstructionList makeClosureInstantiation(Member constructor, BcelVar holder) { // LazyMethodGen constructor) { InstructionFactory fact = getFactory(); BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY); //final Type objectArrayType = new ArrayType(Type.OBJECT, 1); final InstructionList il = new InstructionList(); int alen = getArgCount() + (thisVar == null ? 0 : 1) + ((targetVar != null && targetVar != thisVar) ? 1 : 0) + (thisJoinPointVar == null ? 0 : 1); il.append(Utility.createConstant(fact, alen)); il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1)); arrayVar.appendStore(il, fact); int stateIndex = 0; if (thisVar != null) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisVar); thisVar.setPositionInAroundState(stateIndex); stateIndex++; } if (targetVar != null && targetVar != thisVar) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, targetVar); targetVar.setPositionInAroundState(stateIndex); stateIndex++; } for (int i = 0, len = getArgCount(); i<len; i++) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, argVars[i]); argVars[i].setPositionInAroundState(stateIndex); stateIndex++; } if (thisJoinPointVar != null) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisJoinPointVar); thisJoinPointVar.setPositionInAroundState(stateIndex); stateIndex++; } il.append(fact.createNew(new ObjectType(constructor.getDeclaringType().getName()))); il.append(new DUP()); arrayVar.appendLoad(il, fact); il.append(Utility.createInvoke(fact, world, constructor)); if (getKind() == PreInitialization) { il.append(fact.DUP); holder.appendStore(il, fact); } return il; } private IntMap makeProceedArgumentMap(BcelVar[] adviceArgs) { //System.err.println("coming in with " + Arrays.asList(adviceArgs)); IntMap ret = new IntMap(); for(int i = 0, len = adviceArgs.length; i < len; i++) { BcelVar v = (BcelVar) adviceArgs[i]; if (v == null) continue; // XXX we don't know why this is required int pos = v.getPositionInAroundState(); if (pos >= 0) { // need this test to avoid args bound via cflow ret.put(pos, i); } } //System.err.println("returning " + ret); return ret; } /** * * * @param callbackMethod the method we will call back to when our run method gets called. * * @param proceedMap A map from state position to proceed argument position. May be * non covering on state position. */ private LazyMethodGen makeClosureClassAndReturnConstructor( String closureClassName, LazyMethodGen callbackMethod, IntMap proceedMap) { String superClassName = "org.aspectj.runtime.internal.AroundClosure"; Type objectArrayType = new ArrayType(Type.OBJECT, 1); LazyClassGen closureClass = new LazyClassGen(closureClassName, superClassName, getEnclosingClass().getFileName(), Modifier.PUBLIC, new String[] {}); InstructionFactory fact = new InstructionFactory(closureClass.getConstantPoolGen()); // constructor LazyMethodGen constructor = new LazyMethodGen(Modifier.PUBLIC, Type.VOID, "<init>", new Type[] {objectArrayType}, new String[] {}, closureClass); InstructionList cbody = constructor.getBody(); cbody.append(fact.createLoad(Type.OBJECT, 0)); cbody.append(fact.createLoad(objectArrayType, 1)); cbody.append(fact.createInvoke(superClassName, "<init>", Type.VOID, new Type[] {objectArrayType}, Constants.INVOKESPECIAL)); cbody.append(fact.createReturn(Type.VOID)); closureClass.addMethodGen(constructor); // method LazyMethodGen runMethod = new LazyMethodGen(Modifier.PUBLIC, Type.OBJECT, "run", new Type[] {objectArrayType}, new String[] {}, closureClass); InstructionList mbody = runMethod.getBody(); BcelVar proceedVar = new BcelVar(TypeX.OBJECTARRAY.resolve(world), 1); // int proceedVarIndex = 1; BcelVar stateVar = new BcelVar(TypeX.OBJECTARRAY.resolve(world), runMethod.allocateLocal(1)); // int stateVarIndex = runMethod.allocateLocal(1); mbody.append(fact.createThis()); mbody.append(fact.createGetField(superClassName, "state", objectArrayType)); mbody.append(stateVar.createStore(fact)); // mbody.append(fact.createStore(objectArrayType, stateVarIndex)); Type[] stateTypes = callbackMethod.getArgumentTypes(); for (int i=0, len=stateTypes.length; i < len; i++) { Type stateType = stateTypes[i]; ResolvedTypeX stateTypeX = BcelWorld.fromBcel(stateType).resolve(world); if (proceedMap.hasKey(i)) { mbody.append( proceedVar.createConvertableArrayLoad(fact, proceedMap.get(i), stateTypeX)); } else { mbody.append( stateVar.createConvertableArrayLoad(fact, i, stateTypeX)); } } mbody.append(Utility.createInvoke(fact, callbackMethod)); if (getKind() == PreInitialization) { mbody.append(Utility.createSet( fact, AjcMemberMaker.aroundClosurePreInitializationField())); mbody.append(fact.ACONST_NULL); } else { mbody.append( Utility.createConversion( fact, callbackMethod.getReturnType(), Type.OBJECT)); } mbody.append(fact.createReturn(Type.OBJECT)); closureClass.addMethodGen(runMethod); // class getEnclosingClass().addGeneratedInner(closureClass); return constructor; } // ---- extraction methods public LazyMethodGen extractMethod(String newMethodName) { LazyMethodGen.assertGoodBody(range.getBody(), newMethodName); if (!getKind().allowsExtraction()) throw new BCException(); LazyMethodGen freshMethod = createMethodGen(newMethodName); // System.err.println("******"); // System.err.println("ABOUT TO EXTRACT METHOD for" + this); // enclosingMethod.print(System.err); // System.err.println("INTO"); // freshMethod.print(System.err); // System.err.println("WITH REMAP"); // System.err.println(makeRemap()); range.extractInstructionsInto(freshMethod, makeRemap(), (getKind() != PreInitialization) && isFallsThrough()); if (getKind() == PreInitialization) { addPreInitializationReturnCode( freshMethod, getSuperConstructorParameterTypes()); } getEnclosingClass().addMethodGen(freshMethod); return freshMethod; } private void addPreInitializationReturnCode( LazyMethodGen extractedMethod, Type[] superConstructorTypes) { InstructionList body = extractedMethod.getBody(); final InstructionFactory fact = getFactory(); BcelVar arrayVar = new BcelVar( world.resolve(TypeX.OBJECTARRAY), extractedMethod.allocateLocal(1)); int len = superConstructorTypes.length; body.append(Utility.createConstant(fact, len)); body.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1)); arrayVar.appendStore(body, fact); for (int i = len - 1; i >= 0; i++) { // convert thing on top of stack to object body.append( Utility.createConversion(fact, superConstructorTypes[i], Type.OBJECT)); // push object array arrayVar.appendLoad(body, fact); // swap body.append(fact.SWAP); // do object array store. body.append(Utility.createConstant(fact, i)); body.append(fact.SWAP); body.append(fact.createArrayStore(Type.OBJECT)); } arrayVar.appendLoad(body, fact); body.append(fact.ARETURN); } private Type[] getSuperConstructorParameterTypes() { // assert getKind() == PreInitialization InstructionHandle superCallHandle = getRange().getEnd().getNext(); InvokeInstruction superCallInstruction = (InvokeInstruction) superCallHandle.getInstruction(); return superCallInstruction.getArgumentTypes( getEnclosingClass().getConstantPoolGen()); } /** make a map from old frame location to new frame location. Any unkeyed frame * location picks out a copied local */ private IntMap makeRemap() { IntMap ret = new IntMap(5); int reti = 0; if (thisVar != null) { ret.put(0, reti++); // thisVar guaranteed to be 0 } if (targetVar != null && targetVar != thisVar) { ret.put(targetVar.getSlot(), reti++); } for (int i = 0, len = argVars.length; i < len; i++) { ret.put(argVars[i].getSlot(), reti); reti += argVars[i].getType().getSize(); } if (thisJoinPointVar != null) { ret.put(thisJoinPointVar.getSlot(), reti++); } // we not only need to put the arguments, we also need to remap their // aliases, which we so helpfully put into temps at the beginning of this join // point. if (! getKind().argsOnStack()) { int oldi = 0; int newi = 0; // if we're passing in a this and we're not argsOnStack we're always // passing in a target too if (arg0HoldsThis()) { ret.put(0, 0); oldi++; newi+=1; } //assert targetVar == thisVar for (int i = 0; i < getArgCount(); i++) { TypeX type = getArgType(i); ret.put(oldi, newi); oldi += type.getSize(); newi += type.getSize(); } } // System.err.println("making remap for : " + this); // if (targetVar != null) System.err.println("target slot : " + targetVar.getSlot()); // if (thisVar != null) System.err.println(" this slot : " + thisVar.getSlot()); // System.err.println(ret); return ret; } /** * The new method always static. * It may take some extra arguments: this, target. * If it's argsOnStack, then it must take both this/target * If it's argsOnFrame, it shares this and target. * ??? rewrite this to do less array munging, please */ private LazyMethodGen createMethodGen(String newMethodName) { Type[] parameterTypes = world.makeBcelTypes(getArgTypes()); int modifiers = Modifier.FINAL; // XXX some bug // if (! isExpressionKind() && getSignature().isStrict(world)) { // modifiers |= Modifier.STRICT; // } modifiers |= Modifier.STATIC; if (targetVar != null && targetVar != thisVar) { TypeX targetType = getTargetType(); ResolvedMember resolvedMember = getSignature().resolve(world); if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers()) && !samePackage(targetType.getPackageName(), getEnclosingType().getPackageName())) { if (!targetType.isAssignableFrom(getThisType(), world)) { throw new BCException("bad bytecode"); } targetType = getThisType(); } parameterTypes = addType(world.makeBcelType(targetType), parameterTypes); } if (thisVar != null) { TypeX thisType = getThisType(); parameterTypes = addType(world.makeBcelType(thisType), parameterTypes); } // We always want to pass down thisJoinPoint in case we have already woven // some advice in here. If we only have a single piece of around advice on a // join point, it is unnecessary to accept (and pass) tjp. if (thisJoinPointVar != null) { parameterTypes = addTypeToEnd(LazyClassGen.tjpType, parameterTypes); } TypeX returnType; if (getKind() == PreInitialization) { returnType = TypeX.OBJECTARRAY; } else { returnType = getReturnType(); } return new LazyMethodGen( modifiers, world.makeBcelType(returnType), newMethodName, parameterTypes, new String[0], // XXX again, we need to look up methods! // TypeX.getNames(getSignature().getExceptions(world)), getEnclosingClass()); } private boolean samePackage(String p1, String p2) { if (p1 == null) return p2 == null; if (p2 == null) return false; return p1.equals(p2); } private Type[] addType(Type type, Type[] types) { int len = types.length; Type[] ret = new Type[len+1]; ret[0] = type; System.arraycopy(types, 0, ret, 1, len); return ret; } private Type[] addTypeToEnd(Type type, Type[] types) { int len = types.length; Type[] ret = new Type[len+1]; ret[len] = type; System.arraycopy(types, 0, ret, 0, len); return ret; } public BcelVar genTempVar(TypeX typeX) { return new BcelVar(typeX.resolve(world), genTempVarIndex(typeX.getSize())); } // public static final boolean CREATE_TEMP_NAMES = true; public BcelVar genTempVar(TypeX typeX, String localName) { BcelVar tv = genTempVar(typeX); // if (CREATE_TEMP_NAMES) { // for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) { // if (Range.isRangeHandle(ih)) continue; // ih.addTargeter(new LocalVariableTag(typeX, localName, tv.getSlot())); // } // } return tv; } // eh doesn't think we need to garbage collect these (64K is a big number...) private int genTempVarIndex(int size) { return enclosingMethod.allocateLocal(size); } public InstructionFactory getFactory() { return getEnclosingClass().getFactory(); } public ISourceLocation getSourceLocation() { int sourceLine = getSourceLine(); if (sourceLine == 0) { // Thread.currentThread().dumpStack(); // System.err.println(this + ": " + range); return getEnclosingClass().getType().getSourceLocation(); } else { return getEnclosingClass().getType().getSourceContext().makeSourceLocation(sourceLine); } } public Shadow getEnclosingShadow() { return enclosingShadow; } public LazyMethodGen getEnclosingMethod() { return enclosingMethod; } public boolean isFallsThrough() { return !terminatesWithReturn(); //fallsThrough; } }
true
true
public void weaveAroundInline( BcelAdvice munger, boolean hasDynamicTest) { /* Implementation notes: * * AroundInline still extracts the instructions of the original shadow into * an extracted method. This allows inlining of even that advice that doesn't * call proceed or calls proceed more than once. * * It extracts the instructions of the original shadow into a method. * * Then it inlines the instructions of the advice in its place, taking care * to treat the closure argument specially (it doesn't exist). * * Then it searches in the instructions of the advice for any call to the * proceed method. * * At such a call, there is stuff on the stack representing the arguments to * proceed. Pop these into the frame. * * Now build the stack for the call to the extracted method, taking values * either from the join point state or from the new frame locs from proceed. * Now call the extracted method. The right return value should be on the * stack, so no cast is necessary. * * If only one call to proceed is made, we can re-inline the original shadow. * We are not doing that presently. */ // !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...); Member mungerSig = munger.getSignature(); ResolvedTypeX declaringType = world.resolve(mungerSig.getDeclaringType()); //??? might want some checks here to give better errors BcelObjectType ot = BcelWorld.getBcelObjectType(declaringType); LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig); if (!adviceMethod.getCanInline()) { weaveAroundClosure(munger, hasDynamicTest); return; } // start by exposing various useful things into the frame final InstructionFactory fact = getFactory(); // now generate the aroundBody method LazyMethodGen extractedMethod = extractMethod( NameMangler.aroundCallbackMethodName( getSignature(), getEnclosingClass())); // the shadow is now empty. First, create a correct call // to the around advice. This includes both the call (which may involve // value conversion of the advice arguments) and the return // (which may involve value conversion of the return value). Right now // we push a null for the unused closure. It's sad, but there it is. InstructionList advice = new InstructionList(); InstructionHandle adviceMethodInvocation; { // ??? we don't actually need to push NULL for the closure if we take care advice.append(munger.getAdviceArgSetup(this, null, new InstructionList(fact.ACONST_NULL))); adviceMethodInvocation = advice.append( Utility.createInvoke(fact, getWorld(), munger.getSignature())); advice.append( Utility.createConversion( getFactory(), world.makeBcelType(munger.getSignature().getReturnType()), extractedMethod.getReturnType())); if (! isFallsThrough()) { advice.append(fact.createReturn(extractedMethod.getReturnType())); } } // now, situate the call inside the possible dynamic tests, // and actually add the whole mess to the shadow if (! hasDynamicTest) { range.append(advice); } else { InstructionList afterThingie = new InstructionList(fact.NOP); InstructionList callback = makeCallToCallback(extractedMethod); if (terminatesWithReturn()) { callback.append(fact.createReturn(extractedMethod.getReturnType())); } else { //InstructionHandle endNop = range.insert(fact.NOP, Range.InsideAfter); advice.append(fact.createBranchInstruction(Constants.GOTO, afterThingie.getStart())); } range.append(munger.getTestInstructions(this, advice.getStart(), callback.getStart(), advice.getStart())); range.append(advice); range.append(callback); range.append(afterThingie); } // now the range contains everything we need. We now inline the advice method. BcelClassWeaver.inlineMethod(adviceMethod, enclosingMethod, adviceMethodInvocation); // now search through the advice, looking for a call to PROCEED. // Then we replace the call to proceed with some argument setup, and a // call to the extracted method. String proceedName = NameMangler.proceedMethodName(munger.getSignature().getName()); InstructionHandle curr = getRange().getStart(); InstructionHandle end = getRange().getEnd(); ConstantPoolGen cpg = extractedMethod.getEnclosingClass().getConstantPoolGen(); while (curr != end) { InstructionHandle next = curr.getNext(); Instruction inst = curr.getInstruction(); if ((inst instanceof INVOKESTATIC) && proceedName.equals(((INVOKESTATIC) inst).getMethodName(cpg))) { enclosingMethod.getBody().append(curr, getRedoneProceedCall(fact, extractedMethod, munger)); Utility.deleteInstruction(curr, enclosingMethod); } curr = next; } // and that's it. }
public void weaveAroundInline( BcelAdvice munger, boolean hasDynamicTest) { /* Implementation notes: * * AroundInline still extracts the instructions of the original shadow into * an extracted method. This allows inlining of even that advice that doesn't * call proceed or calls proceed more than once. * * It extracts the instructions of the original shadow into a method. * * Then it inlines the instructions of the advice in its place, taking care * to treat the closure argument specially (it doesn't exist). * * Then it searches in the instructions of the advice for any call to the * proceed method. * * At such a call, there is stuff on the stack representing the arguments to * proceed. Pop these into the frame. * * Now build the stack for the call to the extracted method, taking values * either from the join point state or from the new frame locs from proceed. * Now call the extracted method. The right return value should be on the * stack, so no cast is necessary. * * If only one call to proceed is made, we can re-inline the original shadow. * We are not doing that presently. */ // !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...); Member mungerSig = munger.getSignature(); ResolvedTypeX declaringType = world.resolve(mungerSig.getDeclaringType()); //??? might want some checks here to give better errors BcelObjectType ot = BcelWorld.getBcelObjectType(declaringType); LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig); if (!adviceMethod.getCanInline()) { weaveAroundClosure(munger, hasDynamicTest); return; } // We can't inline around methods if they have around advice on them, this // is because the weaving will extract the body and hence the proceed call. //??? should consider optimizations to recognize simple cases that don't require body extraction enclosingMethod.setCanInline(false); // start by exposing various useful things into the frame final InstructionFactory fact = getFactory(); // now generate the aroundBody method LazyMethodGen extractedMethod = extractMethod( NameMangler.aroundCallbackMethodName( getSignature(), getEnclosingClass())); // the shadow is now empty. First, create a correct call // to the around advice. This includes both the call (which may involve // value conversion of the advice arguments) and the return // (which may involve value conversion of the return value). Right now // we push a null for the unused closure. It's sad, but there it is. InstructionList advice = new InstructionList(); InstructionHandle adviceMethodInvocation; { // ??? we don't actually need to push NULL for the closure if we take care advice.append(munger.getAdviceArgSetup(this, null, new InstructionList(fact.ACONST_NULL))); adviceMethodInvocation = advice.append( Utility.createInvoke(fact, getWorld(), munger.getSignature())); advice.append( Utility.createConversion( getFactory(), world.makeBcelType(munger.getSignature().getReturnType()), extractedMethod.getReturnType())); if (! isFallsThrough()) { advice.append(fact.createReturn(extractedMethod.getReturnType())); } } // now, situate the call inside the possible dynamic tests, // and actually add the whole mess to the shadow if (! hasDynamicTest) { range.append(advice); } else { InstructionList afterThingie = new InstructionList(fact.NOP); InstructionList callback = makeCallToCallback(extractedMethod); if (terminatesWithReturn()) { callback.append(fact.createReturn(extractedMethod.getReturnType())); } else { //InstructionHandle endNop = range.insert(fact.NOP, Range.InsideAfter); advice.append(fact.createBranchInstruction(Constants.GOTO, afterThingie.getStart())); } range.append(munger.getTestInstructions(this, advice.getStart(), callback.getStart(), advice.getStart())); range.append(advice); range.append(callback); range.append(afterThingie); } // now the range contains everything we need. We now inline the advice method. BcelClassWeaver.inlineMethod(adviceMethod, enclosingMethod, adviceMethodInvocation); // now search through the advice, looking for a call to PROCEED. // Then we replace the call to proceed with some argument setup, and a // call to the extracted method. String proceedName = NameMangler.proceedMethodName(munger.getSignature().getName()); InstructionHandle curr = getRange().getStart(); InstructionHandle end = getRange().getEnd(); ConstantPoolGen cpg = extractedMethod.getEnclosingClass().getConstantPoolGen(); while (curr != end) { InstructionHandle next = curr.getNext(); Instruction inst = curr.getInstruction(); if ((inst instanceof INVOKESTATIC) && proceedName.equals(((INVOKESTATIC) inst).getMethodName(cpg))) { enclosingMethod.getBody().append(curr, getRedoneProceedCall(fact, extractedMethod, munger)); Utility.deleteInstruction(curr, enclosingMethod); } curr = next; } // and that's it. }
diff --git a/src/plugin/Stalemate.java b/src/plugin/Stalemate.java index 3af2ac2..9940f30 100644 --- a/src/plugin/Stalemate.java +++ b/src/plugin/Stalemate.java @@ -1,859 +1,861 @@ package plugin; import java.io.*; import static util.ColorParser.parseColors; import org.bukkit.Location; import org.bukkit.World; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import net.minecraft.server.v1_5_R3.Block; import net.minecraft.server.v1_5_R3.Item; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Listener; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.java.JavaPlugin; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import amendedclasses.LoggerOutputStream; import controllers.RoundController; import defense.PlayerAI; import defense.Team; import serial.MapArea; import serial.RoundConfiguration; import serial.SerializableItemStack; import soldier.SoldierClass; import java.util.*; public class Stalemate extends JavaPlugin implements Listener { private Map<String, List<ItemStack>> itempacks = new ConcurrentHashMap<String, List<ItemStack>>(); public Map<String, String> settings = new ConcurrentHashMap<String, String>(); private static Stalemate instance; public final Map<String, PlayerAI> aiMap = new ConcurrentHashMap<String, PlayerAI>(); private List<RoundController> rounds = new Vector<RoundController>(); private Map<String, CommandCallback> cmdMap = new ConcurrentHashMap<String, CommandCallback>(); private Map<String, String> helpMap = new ConcurrentHashMap<String, String>(); private Map<String, TrapCallback> trapMap = new ConcurrentHashMap<String, TrapCallback>(); public final Map<Location, String> placedTraps = new ConcurrentHashMap<Location, String>(); public String getSetting(String key, String def) { String val = settings.get(key); if (val == null) val = def; return val; } private static TrapCallback createCallbackFromXML(Element e) { final List<TrapCallback> tasks = new Vector<TrapCallback>(); NodeList stuff = e.getChildNodes(); for (int i = 0; i < stuff.getLength(); i++) { Node n = stuff.item(i); if (!(n instanceof Element)) continue; Element task = (Element) n; String name = task.getNodeName(); switch (name.toLowerCase()) { case "explosion": tasks.add(new ExplosiveTrapCallback(task)); break; case "kill": tasks.add(new KillPlayerCallback(task)); break; case "sleep": tasks.add(new SleepTrapCallback(task)); break; case "command": tasks.add(new CommandTrapCallback(task)); break; default: System.out.println("Trap Callbacks: Unrecognized tag: "+name); } } String reusables = e.getAttribute("reusable"); boolean reusable = true; if (!reusables.equals("true")) { reusable = false; } final boolean reusableF = reusable; return new TrapCallback() { @Override public void onTriggered(Player p, Location loc, RoundController rnd) { for (TrapCallback c : tasks) try { c.onTriggered(p, loc, rnd); } catch (Throwable e) { RuntimeException e1 = new RuntimeException(Stalemate.getInstance().getSetting("trap_exc_msg", "Exception when triggering trap.")); e1.initCause(e); throw e1; } } @Override public boolean isReusable() { return reusableF; } }; } public static Stalemate getInstance() { return instance; } private static class AsyncTask { public long timeToWait; public long lastTimeUpdated; public final Callable<?> call; public AsyncTask(long t, Callable<?> c) { timeToWait = t; call = c; lastTimeUpdated = System.nanoTime()/1000000; } } public Map<String, TrapCallback> getTrapCallbacks() { return trapMap; } private List<AsyncTask> tasks = new Vector<AsyncTask>(); private Thread asyncUpdateThread = new Thread() { public void run() { while (Stalemate.getInstance().isEnabled()) { for (AsyncTask t : tasks) { t.timeToWait += -(t.lastTimeUpdated-(t.lastTimeUpdated = System.nanoTime()/1000000)); if (t.timeToWait <= 0) { tasks.remove(t); try { t.call.call(); } catch (Exception e) { throw new RuntimeException(e); } } } try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } }; public void setTimeout(long timeToWait, Callable<?> callback) { tasks.add(new AsyncTask(timeToWait, callback)); } public Stalemate() { instance = this; } private void join(Team t, Player p) { for (Team tt : Team.list()) { if (Arrays.asList(tt.getPlayers()).contains(p.getName().toUpperCase())) tt.removePlayer(p.getName().toUpperCase()); } t.addPlayer(p.getName()); for (RoundController rc : rounds) { if (rc.getConfig().getParticipatingTeams().contains(t)) { p.teleport(rc.getConfig().getArea().randomLoc()); } } } private void initRound(RoundController rnd) { rounds.add(rnd); rnd.startRound(); } private void placeTrap(String type, Location loc) { for (RoundController rc : rounds) { MapArea a = rc.getConfig().getArea(); if (a.contains(loc)) { rc.placeTrap(type, loc); break; } } } private Set<String> noChange = new HashSet<String>(); private Map<String, List<ItemStack>> itemsAccountableMap = new ConcurrentHashMap<String, List<ItemStack>>(); public void onEnable() { if (getDataFolder().isFile()) getDataFolder().delete(); if (!getDataFolder().exists()) getDataFolder().mkdir(); // TODO: Implement all commands registerCommand(getSetting("help_cmd", "help"), getSetting("help_help", "Shows the help page."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { for (String key : helpMap.keySet()) { sender.sendMessage(synColor(ChatColor.LIGHT_PURPLE)+"/stalemate "+synColor(ChatColor.RESET)+key.toLowerCase()+" - "+synColor(ChatColor.AQUA)+helpMap.get(key)); } } }); registerCommand(getSetting("remove_trap_cmd", "rtrap"), getSetting("remove_trap_help", "Defuses a trap. Has a chance to fail."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage(parseColors(getSetting("players_only_msg", "Only players may use this command."))); return; } // TODO: Finish } }); registerCommand(getSetting("join_war_cmd", "joinwar"), getSetting("join_war_help", "Joins a war"), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("join_war_perm", "stalemate.joinwar"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that.</font></xml>"))); return; } if (args.length < 2) { - sender.sendMessage(parseColors(getSetting("join_war_syntax", "Syntax: /"+args[0]+" &lt;teamname&gt;"))); + sender.sendMessage(parseColors(getSetting("join_war_syntax", "Syntax: /stalemate "+args[0]+" &lt;teamname&gt;"))); return; } Team t = Team.getTeam(args[1]); Team yours = null; for (Team te : Team.list()) { if (te.containsPlayer(sender.getName().toUpperCase())) { yours = te; } } if (yours == null) { sender.sendMessage(parseColors(getSetting("err_no_team_msg", "<root><font color=\"Red\">Join a team first.</font></root>"))); return; } if (!sender.getName().equalsIgnoreCase(yours.getOwner())) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } for (RoundController rc : rounds) { if (rc.getConfig().getParticipatingTeams().contains(t) && rc.isJoinable()) { rc.getConfig().addTeam(yours); } } } }); registerCommand(getSetting("war_cmd", "war"), getSetting("war_help", "Starts a new war"),new CommandCallback() { @Override public void onCommand(final CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("war_perm", "stalemate.start"))) { sender.sendMessage(getSetting("no_perm_msg", "<xml><font color=\"Red\"> You do not have permission to do that.</font></xml>")); return; } RoundController rnd = new RoundController(new RoundConfiguration((Location) null, null), new Callable<Object>(){ @Override public Object call() throws Exception { for (RoundController r : rounds) { if (r.getPlayers().contains(sender.getName().toUpperCase())) { for (String p : r.getPlayers()) { List<ItemStack> acct = Stalemate.this.itemsAccountableMap.get(p.toUpperCase()); Player pl = Stalemate.this.getServer().getPlayer(p); Map<Integer, ItemStack> failed = pl.getInventory().removeItem(acct.toArray(new ItemStack[0])); acct.clear(); acct.addAll(failed.values()); noChange.remove(p.toUpperCase()); } break; } } return null; }}); initRound(rnd); Team yours = null; for (Team t : Team.list()) { if (t.containsPlayer(sender.getName())) { yours = t; break; } } if (!yours.getOwner().equalsIgnoreCase(sender.getName())) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } rnd.getConfig().addTeam(yours); } }); registerCommand(getSetting("place_trap_cmd", "ptrap"), getSetting("place_trap_help", "Places a new trap."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { assert(args.length > 0); if (!sender.hasPermission(getSetting("place_trap_perm", "stalemate.ptrap"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (!(sender instanceof Player)) { if (args.length < 6) { - sender.sendMessage(getSetting("syntax_trap_console_msg", "Syntax: "+args[0]+" <world> <x> <y> <z>")); + sender.sendMessage(parseColors(getSetting("syntax_trap_console_msg", "Syntax: stalemate "+args[0]+" <world> <x> <y> <z>"))); return; } World w; int x, y, z; String trapName; try { w = getServer().getWorld(args[1]); if (w == null) { sender.sendMessage(getSetting("invworld_trap_console_msg", "Invalid World.")); return; } x = Integer.parseInt(args[2]); y = Integer.parseInt(args[3]); z = Integer.parseInt(args[4]); trapName = args[5]; } catch (NumberFormatException e) { sender.sendMessage(getSetting("integer_err_console", "Please provide integers for x, y, and z.")); return; } placeTrap(trapName, new Location(w, x, y, z)); sender.sendMessage(getSetting("trap_place_success_msg_console", "Trap Placed.")); } else { if (args.length < 2) { - sender.sendMessage(parseColors(getSetting("syntax_trap_player_msg", "Syntax: /"+args[0]+" <trap_type>"))); + sender.sendMessage(parseColors(getSetting("syntax_trap_player_msg", "Syntax: /stalemate "+args[0]+" <trap_type>"))); return; } Player p = (Player) sender; String trapName = args[1]; if (!trapMap.containsKey(trapName.toUpperCase())) { sender.sendMessage(parseColors(getSetting("no_trap_name", "<xml><font color=\"Purple\">That trap type does not exist!</font></xml>"))); return; } placeTrap(trapName, p.getLocation()); sender.sendMessage(parseColors(getSetting("trap_place_success_msg", "Trap Placed."))); } } }); registerCommand(getSetting("join_cmd", "join"), getSetting("join_help", "Joins the team of the specified player."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("join_perm", "stalemate.join"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (args.length < 2) { sender.sendMessage(parseColors(getSetting("syntax_join_msg", "/stalemate "+args[0]+" <player> or to create a team: /stalemate "+args[0]+" <teamname>"))); Team yours = null; for (Team tt : Team.list()) { if (tt.containsPlayer(sender.getName())) { yours = tt; break; } } - sender.sendMessage("Your current team is: "+yours.getName()); + if (yours != null) + sender.sendMessage("Your current team is: "+yours.getName()); + else sender.sendMessage("You do not have a team."); return; } Player target = getServer().getPlayer(args[1]); if (!(sender instanceof Player)) { sender.sendMessage(getSetting("players_only_msg", "Only players may execute this command.")); return; } for (Team t : Team.list()) { // TODO: Use linear search or hashing if (Arrays.binarySearch(t.getPlayers(), target.getName().toUpperCase()) > 0) { join(t, (Player) sender); sender.sendMessage(parseColors(getSetting("join_success_msg", "Success."))); return; } } Team x = new Team(args[1]); join(x, (Player) sender); } }); registerCommand(getSetting("leave_cmd", "leave"), getSetting("leave_help", "Leaves the current round."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("leave_perm", "stalemate.leave"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (!(sender instanceof Player)) { - sender.sendMessage(getSetting("players_only_msg", "Only players may use this feature.")); + sender.sendMessage(parseColors(getSetting("players_only_msg", "Only players may use this feature."))); return; } for (RoundController rc : rounds) { if (rc.getPlayers().contains(sender.getName().toUpperCase())) { List<Team> teams = rc.getConfig().getParticipatingTeams(); for (Team t : teams) if (t.removePlayer(sender.getName())) break; } } } }); registerCommand(getSetting("class_cmd", "class"), getSetting("class_help", "Changes your class (Gives you a class's items)"), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!(sender instanceof Player)) { - sender.sendMessage(getSetting("players_only_msg", "Only players may use this command.")); + sender.sendMessage(parseColors(getSetting("players_only_msg", "Only players may use this command."))); return; } if (!sender.hasPermission(getSetting("class_perm", "stalemate.changeclass"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (noChange.contains(sender.getName().toUpperCase()) && !sender.hasPermission("stalemate.changeclass.multiple")) { sender.sendMessage(parseColors(getSetting("class_nochange", "You may not change your class once you have selected it."))); return; } if (args.length < 2) { - sender.sendMessage(parseColors(getSetting("class_syntax", "Syntax: /"+args[0]+" <classname>"))); + sender.sendMessage(parseColors(getSetting("class_syntax", "Syntax: /stalemate "+args[0]+" <classname>"))); return; } SoldierClass s = SoldierClass.fromName(args[1]); if (s == null) { sender.sendMessage(parseColors(getSetting("class_nonexist_msg", "<xml><font color=\"Red\">That class does not exist!</font></xml>"))); return; } if (!sender.hasPermission(s.getPermission())) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "You do not have permission to change to the requested class."))); return; } ItemStack[] give = s.getItems(); List<ItemStack> account = (account=itemsAccountableMap.get(sender.getName().toUpperCase())) == null ? account == itemsAccountableMap.put(sender.getName().toUpperCase(), account = new Vector<ItemStack>()) ? account : account : account; for (ItemStack i : give) account.add(i.clone()); Map<Integer, ItemStack> failed = ((Player) sender).getInventory().addItem(give); account.removeAll(failed.values()); } }); try { onEnable0(); } catch (Throwable e) { getLogger().log(Level.SEVERE, "Unexpected exception while loading Stalemate."); e.printStackTrace(); } asyncUpdateThread.start(); getLogger().info("Wars? Battles? Skirmishes? Fistfights? Air punching? Stalemate loaded!"); } protected static boolean isInRound(Player sender) { // TODO Auto-generated method stub return false; } public CommandCallback registerCommand(String name, String desc, CommandCallback onCommand) { CommandCallback c = cmdMap.put(name.toUpperCase(), onCommand); helpMap.put(name.toUpperCase(), desc); return c; } public void onDisable() { getLogger().info("Peace! AAAAH!"); Map<String, List<SerializableItemStack>> saveAccount = new HashMap<String, List<SerializableItemStack>>(); for (String s : itemsAccountableMap.keySet()) { List<SerializableItemStack> l = SerializableItemStack.fromList(itemsAccountableMap.get(s)); saveAccount.put(s, l); } try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(getDataFolder(), "items.dat"))); oos.writeObject(saveAccount); oos.close(); } catch (IOException e) { e.printStackTrace(); } } private String synColor(ChatColor c) { return ChatColor.COLOR_CHAR+""+c.getChar(); } public boolean onCommand(CommandSender sender, Command cmd, String lbl, String args[]) { if (!cmd.getName().equalsIgnoreCase("stalemate")) return false; if (!sender.hasPermission("stalemate.basic")) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission.</font></xml>"))); return true; } if (args.length == 0) { args = new String[] {"help"}; } String name = args[0]; CommandCallback cb = cmdMap.get(name.toUpperCase()); if (cb == null) { sender.sendMessage(parseColors(getSetting("invalid_cmd_msg", "Invalid Command. Please type /stalemate "+getSetting("help_cmd", "help")+" for help."))); return false; } cb.onCommand(sender, args); return true; } private void generateConfig(File f) throws IOException { // Writing lines to translate CRLF -> LF and LF -> CRLF PrintWriter writer = new PrintWriter(new FileOutputStream(f)); InputStream in = getResource("config.xml"); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String ln; while ((ln = br.readLine()) != null) writer.println(ln); writer.close(); br.close(); } public void onEnable0() throws Throwable { File config = new File(this.getDataFolder(), "config.xml"); if (!config.exists()) { generateConfig(config); } if (!config.isFile()) { boolean success = config.delete(); if (!success) { config.deleteOnExit(); throw new RuntimeException("Failed to create config."); } else { generateConfig(config); } } FileInputStream stream = new FileInputStream(config); // Buffer the file in memory ByteArrayOutputStream b = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int bytesRead; while ((bytesRead = stream.read(buf)) != -1) { b.write(buf, 0, bytesRead); } stream.close(); buf = null; byte[] bytes = b.toByteArray(); b.close(); // Begin parsing DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbf.newDocumentBuilder(); Document doc; try { doc = builder.parse(new ByteArrayInputStream(bytes)); } catch (Throwable t) { Throwable exc = new RuntimeException("Config Error: Invalid XML File: config.xml"); exc.initCause(t); throw exc; } Element root = doc.getDocumentElement(); NodeList classes = root.getElementsByTagName("soldiers"); for (int i = 0; i < classes.getLength(); i++) { Node nn = classes.item(i); if (!(nn instanceof Element)) continue; Element section = (Element) nn; // Load item packs NodeList nodes = section.getElementsByTagName("itempack"); for (int j = 0; j < nodes.getLength(); j++) { Node nnn = nodes.item(j); if (!(nnn instanceof Element)) continue; Element pack = (Element) nnn; NodeList items = pack.getElementsByTagName("item"); List<ItemStack> packItems = new Vector<ItemStack>(); for (int k = 0; k < items.getLength(); k++) { Node nnnn = items.item(k); if (!(nnnn instanceof Element)) continue; Element item = (Element) nnnn; String idStr = item.getAttribute("id"); int id = -1; if (idStr.equals("")) { // Fetch according to name attribute String name = item.getAttribute("name"); for (Block block : Block.byId) { if (block == null) continue; if (block.getName().equalsIgnoreCase(name)) { id = block.id; break; } } if (id == -1) { for (Item mcItem : Item.byId) { if (mcItem == null) continue; if (mcItem.getName().equalsIgnoreCase(name)) { id = mcItem.id; break; } } if (id == -1) throw new RuntimeException("Config Error: Non-existent name: "+name); } } else { String name = item.getAttribute("name"); if (!name.equals("")) throw new RuntimeException("Both name and ID specified. Specify one or the other. Name: "+name+" ID: "+idStr); try { id = Integer.parseInt(idStr); } catch (NumberFormatException e) { throw new RuntimeException("Config Error: Expected a number for item ID. Got: "+idStr); } } String dmgStr = item.getAttribute("dmg"); int dmg; if (dmgStr.equals("")) { dmg = 0; } else { try { dmg = Integer.parseInt(dmgStr); } catch (NumberFormatException e) { throw new RuntimeException("Config Error: Expected an integer (-2147483648 -> 2147483647) for item damage. Got: "+dmgStr); } } int num; String numStr = item.getAttribute("num"); if (numStr.equals("")) { num = 1; } else { try { num = Integer.parseInt(numStr); if (num <= 0) throw new NumberFormatException("break"); } catch (NumberFormatException e) { throw new RuntimeException("Config Error: Expected a positive integer for item number. Got: "+numStr); } } ItemStack stack = new ItemStack(id, num, (short) dmg); packItems.add(stack); } if (pack.getAttribute("name").equals("")) throw new RuntimeException("Config Error: Item packs require a name attribute."); itempacks.put(pack.getAttribute("name").toUpperCase(), packItems); } NodeList classList = section.getElementsByTagName("sclass"); for (int j = 0; j < classList.getLength(); j++) { Element classElement = (Element) classList.item(j); String name = classElement.getAttribute("name"); String permission = classElement.getAttribute("permission"); if (permission.equals("")) permission = "stalemate.basic"; NodeList itemList = classElement.getElementsByTagName("item"); List<ItemStack> classItems = new Vector<ItemStack>(); for (int k = 0; k < itemList.getLength(); k++) { Element item = (Element) itemList.item(k); String n = item.getAttribute("name"); String isPackStr = item.getAttribute("isPack").toLowerCase(); boolean isPack; if (isPackStr.equals("")) { isPack = false; } else { try { isPack = Boolean.parseBoolean(isPackStr); } catch (RuntimeException e) { throw new RuntimeException("Config Error: Expected a true/false value for attribute isPack. Got: "+isPackStr); } } if (n.equals("") || !isPack) { // Normal Item Processing String idStr = item.getAttribute("id"); int id = -1; if (!n.equals("")) { if (!idStr.equals("")) throw new RuntimeException("Config Error: Name and ID specified. Please specify one or the other. Name: "+n+" ID: "+idStr); for (Block b1 : Block.byId) { if (b1.getName().equalsIgnoreCase(n)) { id = b1.id; break; } } if (id == -1) throw new RuntimeException("Config Error: Non-existent name: "+n); } else { try { id = Integer.parseInt(idStr); } catch (NumberFormatException e) { throw new RuntimeException("Config Error: ID must be a valid integer. Got: "+idStr); } } int num; String numStr = item.getAttribute("num"); if (numStr.equals("")) { num = 1; } else { try { num = Integer.parseInt(numStr); } catch (NumberFormatException e) { throw new RuntimeException("Config Error: Expected an integer for item amount. Got: "+numStr); } } int dmg; String dmgStr = item.getAttribute("dmg"); if (dmgStr.equals("")) { dmg = 0; } else { try { dmg = Integer.parseInt(dmgStr); } catch (NumberFormatException e) { throw new RuntimeException("Config Error: Expected an integer (-32768 -> 32767) for item damage. Got: "+dmgStr); } } ItemStack stack = new ItemStack(id, num, (short) dmg); classItems.add(stack); } else { // Fetch item pack and add in. if (!itempacks.containsKey(n.toUpperCase())) throw new RuntimeException("Config Error: Non-existent item pack: "+n); classItems.addAll(itempacks.get(n.toUpperCase())); } } new SoldierClass(name, classItems.toArray(new ItemStack[0]), permission); } } // Load Settings NodeList settings = root.getElementsByTagName("settings"); for (int i = 0; i < settings.getLength(); i++) { Node nnnn = settings.item(i); Element section = (Element) nnnn; NodeList tags = section.getElementsByTagName("setting"); for (int j = 0; j < tags.getLength(); j++) { Element setting = (Element) tags.item(j); String name = setting.getAttribute("name"); String value = setting.getAttribute("value"); if (name.equals("")) throw new RuntimeException("Please include a name attribute for all setting tags in config.xml"); this.settings.put(name, value); } } // Load Traps NodeList traps = root.getElementsByTagName("traps"); for (int i = 0; i < traps.getLength(); i++) { Element section = (Element) settings.item(i); NodeList trapList = section.getElementsByTagName("trap"); for (int j = 0; j < trapList.getLength(); j++) { Element trap = (Element) trapList.item(j); String name = trap.getAttribute("name"); if (name.equals("")) throw new RuntimeException("All traps must have a name."); TrapCallback call = createCallbackFromXML(trap); trapMap.put(name.toUpperCase(), call); } } // Load accounts File accountsFile = new File(getDataFolder(), "items.dat"); if (accountsFile.isDirectory()) accountsFile.delete(); if (!accountsFile.exists()) { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(accountsFile)); out.writeObject(new HashMap<String, List<SerializableItemStack>>()); out.close(); } try { // TODO: Fix race condition, so that checking and opening is atomic ObjectInputStream in = new ObjectInputStream(new FileInputStream(accountsFile)); @SuppressWarnings("unchecked") Map<String, List<SerializableItemStack>> read = (Map<String, List<SerializableItemStack>>) in.readObject(); in.close(); // Begin translation for (String s : read.keySet()) { itemsAccountableMap.put(s, SerializableItemStack.toList(read.get(s))); } } catch (Throwable t) { accountsFile.delete(); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(accountsFile)); out.writeObject(new HashMap<String, List<SerializableItemStack>>()); out.close(); System.err.println("Please restart the server. A data file has been corrupted."); throw new RuntimeException(t); } } }
false
true
public void onEnable() { if (getDataFolder().isFile()) getDataFolder().delete(); if (!getDataFolder().exists()) getDataFolder().mkdir(); // TODO: Implement all commands registerCommand(getSetting("help_cmd", "help"), getSetting("help_help", "Shows the help page."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { for (String key : helpMap.keySet()) { sender.sendMessage(synColor(ChatColor.LIGHT_PURPLE)+"/stalemate "+synColor(ChatColor.RESET)+key.toLowerCase()+" - "+synColor(ChatColor.AQUA)+helpMap.get(key)); } } }); registerCommand(getSetting("remove_trap_cmd", "rtrap"), getSetting("remove_trap_help", "Defuses a trap. Has a chance to fail."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage(parseColors(getSetting("players_only_msg", "Only players may use this command."))); return; } // TODO: Finish } }); registerCommand(getSetting("join_war_cmd", "joinwar"), getSetting("join_war_help", "Joins a war"), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("join_war_perm", "stalemate.joinwar"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that.</font></xml>"))); return; } if (args.length < 2) { sender.sendMessage(parseColors(getSetting("join_war_syntax", "Syntax: /"+args[0]+" &lt;teamname&gt;"))); return; } Team t = Team.getTeam(args[1]); Team yours = null; for (Team te : Team.list()) { if (te.containsPlayer(sender.getName().toUpperCase())) { yours = te; } } if (yours == null) { sender.sendMessage(parseColors(getSetting("err_no_team_msg", "<root><font color=\"Red\">Join a team first.</font></root>"))); return; } if (!sender.getName().equalsIgnoreCase(yours.getOwner())) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } for (RoundController rc : rounds) { if (rc.getConfig().getParticipatingTeams().contains(t) && rc.isJoinable()) { rc.getConfig().addTeam(yours); } } } }); registerCommand(getSetting("war_cmd", "war"), getSetting("war_help", "Starts a new war"),new CommandCallback() { @Override public void onCommand(final CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("war_perm", "stalemate.start"))) { sender.sendMessage(getSetting("no_perm_msg", "<xml><font color=\"Red\"> You do not have permission to do that.</font></xml>")); return; } RoundController rnd = new RoundController(new RoundConfiguration((Location) null, null), new Callable<Object>(){ @Override public Object call() throws Exception { for (RoundController r : rounds) { if (r.getPlayers().contains(sender.getName().toUpperCase())) { for (String p : r.getPlayers()) { List<ItemStack> acct = Stalemate.this.itemsAccountableMap.get(p.toUpperCase()); Player pl = Stalemate.this.getServer().getPlayer(p); Map<Integer, ItemStack> failed = pl.getInventory().removeItem(acct.toArray(new ItemStack[0])); acct.clear(); acct.addAll(failed.values()); noChange.remove(p.toUpperCase()); } break; } } return null; }}); initRound(rnd); Team yours = null; for (Team t : Team.list()) { if (t.containsPlayer(sender.getName())) { yours = t; break; } } if (!yours.getOwner().equalsIgnoreCase(sender.getName())) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } rnd.getConfig().addTeam(yours); } }); registerCommand(getSetting("place_trap_cmd", "ptrap"), getSetting("place_trap_help", "Places a new trap."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { assert(args.length > 0); if (!sender.hasPermission(getSetting("place_trap_perm", "stalemate.ptrap"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (!(sender instanceof Player)) { if (args.length < 6) { sender.sendMessage(getSetting("syntax_trap_console_msg", "Syntax: "+args[0]+" <world> <x> <y> <z>")); return; } World w; int x, y, z; String trapName; try { w = getServer().getWorld(args[1]); if (w == null) { sender.sendMessage(getSetting("invworld_trap_console_msg", "Invalid World.")); return; } x = Integer.parseInt(args[2]); y = Integer.parseInt(args[3]); z = Integer.parseInt(args[4]); trapName = args[5]; } catch (NumberFormatException e) { sender.sendMessage(getSetting("integer_err_console", "Please provide integers for x, y, and z.")); return; } placeTrap(trapName, new Location(w, x, y, z)); sender.sendMessage(getSetting("trap_place_success_msg_console", "Trap Placed.")); } else { if (args.length < 2) { sender.sendMessage(parseColors(getSetting("syntax_trap_player_msg", "Syntax: /"+args[0]+" <trap_type>"))); return; } Player p = (Player) sender; String trapName = args[1]; if (!trapMap.containsKey(trapName.toUpperCase())) { sender.sendMessage(parseColors(getSetting("no_trap_name", "<xml><font color=\"Purple\">That trap type does not exist!</font></xml>"))); return; } placeTrap(trapName, p.getLocation()); sender.sendMessage(parseColors(getSetting("trap_place_success_msg", "Trap Placed."))); } } }); registerCommand(getSetting("join_cmd", "join"), getSetting("join_help", "Joins the team of the specified player."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("join_perm", "stalemate.join"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (args.length < 2) { sender.sendMessage(parseColors(getSetting("syntax_join_msg", "/stalemate "+args[0]+" <player> or to create a team: /stalemate "+args[0]+" <teamname>"))); Team yours = null; for (Team tt : Team.list()) { if (tt.containsPlayer(sender.getName())) { yours = tt; break; } } sender.sendMessage("Your current team is: "+yours.getName()); return; } Player target = getServer().getPlayer(args[1]); if (!(sender instanceof Player)) { sender.sendMessage(getSetting("players_only_msg", "Only players may execute this command.")); return; } for (Team t : Team.list()) { // TODO: Use linear search or hashing if (Arrays.binarySearch(t.getPlayers(), target.getName().toUpperCase()) > 0) { join(t, (Player) sender); sender.sendMessage(parseColors(getSetting("join_success_msg", "Success."))); return; } } Team x = new Team(args[1]); join(x, (Player) sender); } }); registerCommand(getSetting("leave_cmd", "leave"), getSetting("leave_help", "Leaves the current round."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("leave_perm", "stalemate.leave"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (!(sender instanceof Player)) { sender.sendMessage(getSetting("players_only_msg", "Only players may use this feature.")); return; } for (RoundController rc : rounds) { if (rc.getPlayers().contains(sender.getName().toUpperCase())) { List<Team> teams = rc.getConfig().getParticipatingTeams(); for (Team t : teams) if (t.removePlayer(sender.getName())) break; } } } }); registerCommand(getSetting("class_cmd", "class"), getSetting("class_help", "Changes your class (Gives you a class's items)"), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage(getSetting("players_only_msg", "Only players may use this command.")); return; } if (!sender.hasPermission(getSetting("class_perm", "stalemate.changeclass"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (noChange.contains(sender.getName().toUpperCase()) && !sender.hasPermission("stalemate.changeclass.multiple")) { sender.sendMessage(parseColors(getSetting("class_nochange", "You may not change your class once you have selected it."))); return; } if (args.length < 2) { sender.sendMessage(parseColors(getSetting("class_syntax", "Syntax: /"+args[0]+" <classname>"))); return; } SoldierClass s = SoldierClass.fromName(args[1]); if (s == null) { sender.sendMessage(parseColors(getSetting("class_nonexist_msg", "<xml><font color=\"Red\">That class does not exist!</font></xml>"))); return; } if (!sender.hasPermission(s.getPermission())) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "You do not have permission to change to the requested class."))); return; } ItemStack[] give = s.getItems(); List<ItemStack> account = (account=itemsAccountableMap.get(sender.getName().toUpperCase())) == null ? account == itemsAccountableMap.put(sender.getName().toUpperCase(), account = new Vector<ItemStack>()) ? account : account : account; for (ItemStack i : give) account.add(i.clone()); Map<Integer, ItemStack> failed = ((Player) sender).getInventory().addItem(give); account.removeAll(failed.values()); } }); try { onEnable0(); } catch (Throwable e) { getLogger().log(Level.SEVERE, "Unexpected exception while loading Stalemate."); e.printStackTrace(); } asyncUpdateThread.start(); getLogger().info("Wars? Battles? Skirmishes? Fistfights? Air punching? Stalemate loaded!"); }
public void onEnable() { if (getDataFolder().isFile()) getDataFolder().delete(); if (!getDataFolder().exists()) getDataFolder().mkdir(); // TODO: Implement all commands registerCommand(getSetting("help_cmd", "help"), getSetting("help_help", "Shows the help page."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { for (String key : helpMap.keySet()) { sender.sendMessage(synColor(ChatColor.LIGHT_PURPLE)+"/stalemate "+synColor(ChatColor.RESET)+key.toLowerCase()+" - "+synColor(ChatColor.AQUA)+helpMap.get(key)); } } }); registerCommand(getSetting("remove_trap_cmd", "rtrap"), getSetting("remove_trap_help", "Defuses a trap. Has a chance to fail."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage(parseColors(getSetting("players_only_msg", "Only players may use this command."))); return; } // TODO: Finish } }); registerCommand(getSetting("join_war_cmd", "joinwar"), getSetting("join_war_help", "Joins a war"), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("join_war_perm", "stalemate.joinwar"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that.</font></xml>"))); return; } if (args.length < 2) { sender.sendMessage(parseColors(getSetting("join_war_syntax", "Syntax: /stalemate "+args[0]+" &lt;teamname&gt;"))); return; } Team t = Team.getTeam(args[1]); Team yours = null; for (Team te : Team.list()) { if (te.containsPlayer(sender.getName().toUpperCase())) { yours = te; } } if (yours == null) { sender.sendMessage(parseColors(getSetting("err_no_team_msg", "<root><font color=\"Red\">Join a team first.</font></root>"))); return; } if (!sender.getName().equalsIgnoreCase(yours.getOwner())) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } for (RoundController rc : rounds) { if (rc.getConfig().getParticipatingTeams().contains(t) && rc.isJoinable()) { rc.getConfig().addTeam(yours); } } } }); registerCommand(getSetting("war_cmd", "war"), getSetting("war_help", "Starts a new war"),new CommandCallback() { @Override public void onCommand(final CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("war_perm", "stalemate.start"))) { sender.sendMessage(getSetting("no_perm_msg", "<xml><font color=\"Red\"> You do not have permission to do that.</font></xml>")); return; } RoundController rnd = new RoundController(new RoundConfiguration((Location) null, null), new Callable<Object>(){ @Override public Object call() throws Exception { for (RoundController r : rounds) { if (r.getPlayers().contains(sender.getName().toUpperCase())) { for (String p : r.getPlayers()) { List<ItemStack> acct = Stalemate.this.itemsAccountableMap.get(p.toUpperCase()); Player pl = Stalemate.this.getServer().getPlayer(p); Map<Integer, ItemStack> failed = pl.getInventory().removeItem(acct.toArray(new ItemStack[0])); acct.clear(); acct.addAll(failed.values()); noChange.remove(p.toUpperCase()); } break; } } return null; }}); initRound(rnd); Team yours = null; for (Team t : Team.list()) { if (t.containsPlayer(sender.getName())) { yours = t; break; } } if (!yours.getOwner().equalsIgnoreCase(sender.getName())) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } rnd.getConfig().addTeam(yours); } }); registerCommand(getSetting("place_trap_cmd", "ptrap"), getSetting("place_trap_help", "Places a new trap."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { assert(args.length > 0); if (!sender.hasPermission(getSetting("place_trap_perm", "stalemate.ptrap"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (!(sender instanceof Player)) { if (args.length < 6) { sender.sendMessage(parseColors(getSetting("syntax_trap_console_msg", "Syntax: stalemate "+args[0]+" <world> <x> <y> <z>"))); return; } World w; int x, y, z; String trapName; try { w = getServer().getWorld(args[1]); if (w == null) { sender.sendMessage(getSetting("invworld_trap_console_msg", "Invalid World.")); return; } x = Integer.parseInt(args[2]); y = Integer.parseInt(args[3]); z = Integer.parseInt(args[4]); trapName = args[5]; } catch (NumberFormatException e) { sender.sendMessage(getSetting("integer_err_console", "Please provide integers for x, y, and z.")); return; } placeTrap(trapName, new Location(w, x, y, z)); sender.sendMessage(getSetting("trap_place_success_msg_console", "Trap Placed.")); } else { if (args.length < 2) { sender.sendMessage(parseColors(getSetting("syntax_trap_player_msg", "Syntax: /stalemate "+args[0]+" <trap_type>"))); return; } Player p = (Player) sender; String trapName = args[1]; if (!trapMap.containsKey(trapName.toUpperCase())) { sender.sendMessage(parseColors(getSetting("no_trap_name", "<xml><font color=\"Purple\">That trap type does not exist!</font></xml>"))); return; } placeTrap(trapName, p.getLocation()); sender.sendMessage(parseColors(getSetting("trap_place_success_msg", "Trap Placed."))); } } }); registerCommand(getSetting("join_cmd", "join"), getSetting("join_help", "Joins the team of the specified player."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("join_perm", "stalemate.join"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (args.length < 2) { sender.sendMessage(parseColors(getSetting("syntax_join_msg", "/stalemate "+args[0]+" <player> or to create a team: /stalemate "+args[0]+" <teamname>"))); Team yours = null; for (Team tt : Team.list()) { if (tt.containsPlayer(sender.getName())) { yours = tt; break; } } if (yours != null) sender.sendMessage("Your current team is: "+yours.getName()); else sender.sendMessage("You do not have a team."); return; } Player target = getServer().getPlayer(args[1]); if (!(sender instanceof Player)) { sender.sendMessage(getSetting("players_only_msg", "Only players may execute this command.")); return; } for (Team t : Team.list()) { // TODO: Use linear search or hashing if (Arrays.binarySearch(t.getPlayers(), target.getName().toUpperCase()) > 0) { join(t, (Player) sender); sender.sendMessage(parseColors(getSetting("join_success_msg", "Success."))); return; } } Team x = new Team(args[1]); join(x, (Player) sender); } }); registerCommand(getSetting("leave_cmd", "leave"), getSetting("leave_help", "Leaves the current round."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("leave_perm", "stalemate.leave"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (!(sender instanceof Player)) { sender.sendMessage(parseColors(getSetting("players_only_msg", "Only players may use this feature."))); return; } for (RoundController rc : rounds) { if (rc.getPlayers().contains(sender.getName().toUpperCase())) { List<Team> teams = rc.getConfig().getParticipatingTeams(); for (Team t : teams) if (t.removePlayer(sender.getName())) break; } } } }); registerCommand(getSetting("class_cmd", "class"), getSetting("class_help", "Changes your class (Gives you a class's items)"), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage(parseColors(getSetting("players_only_msg", "Only players may use this command."))); return; } if (!sender.hasPermission(getSetting("class_perm", "stalemate.changeclass"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (noChange.contains(sender.getName().toUpperCase()) && !sender.hasPermission("stalemate.changeclass.multiple")) { sender.sendMessage(parseColors(getSetting("class_nochange", "You may not change your class once you have selected it."))); return; } if (args.length < 2) { sender.sendMessage(parseColors(getSetting("class_syntax", "Syntax: /stalemate "+args[0]+" <classname>"))); return; } SoldierClass s = SoldierClass.fromName(args[1]); if (s == null) { sender.sendMessage(parseColors(getSetting("class_nonexist_msg", "<xml><font color=\"Red\">That class does not exist!</font></xml>"))); return; } if (!sender.hasPermission(s.getPermission())) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "You do not have permission to change to the requested class."))); return; } ItemStack[] give = s.getItems(); List<ItemStack> account = (account=itemsAccountableMap.get(sender.getName().toUpperCase())) == null ? account == itemsAccountableMap.put(sender.getName().toUpperCase(), account = new Vector<ItemStack>()) ? account : account : account; for (ItemStack i : give) account.add(i.clone()); Map<Integer, ItemStack> failed = ((Player) sender).getInventory().addItem(give); account.removeAll(failed.values()); } }); try { onEnable0(); } catch (Throwable e) { getLogger().log(Level.SEVERE, "Unexpected exception while loading Stalemate."); e.printStackTrace(); } asyncUpdateThread.start(); getLogger().info("Wars? Battles? Skirmishes? Fistfights? Air punching? Stalemate loaded!"); }
diff --git a/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/CancelBuildAction.java b/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/CancelBuildAction.java index a016c1c10..f7dc63506 100644 --- a/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/CancelBuildAction.java +++ b/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/CancelBuildAction.java @@ -1,124 +1,124 @@ package org.apache.maven.continuum.web.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.List; import org.apache.commons.lang.ArrayUtils; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.web.action.admin.AbstractBuildQueueAction; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.codehaus.plexus.util.StringUtils; /** * @author <a href="mailto:[email protected]">Emmanuel Venisse</a> * @version $Id$ * @plexus.component role="com.opensymphony.xwork.Action" role-hint="cancelBuild" */ public class CancelBuildAction extends AbstractBuildQueueAction { private int projectId; private int projectGroupId; private List<String> selectedProjects; private String projectGroupName = ""; public String execute() throws ContinuumException { try { checkBuildProjectInGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } cancelBuild( projectId ); return SUCCESS; } public String cancelBuilds() throws ContinuumException { // first we remove from the build queue - if ( getSelectedProjects().isEmpty() ) + if ( getSelectedProjects() != null && getSelectedProjects().isEmpty() ) { return SUCCESS; } int[] projectsId = new int[getSelectedProjects().size()]; for ( String selectedProjectId : getSelectedProjects() ) { int projectId = Integer.parseInt( selectedProjectId ); projectsId = ArrayUtils.add( projectsId, projectId ); } getContinuum().removeProjectsFromBuildingQueue( projectsId ); // now we must check if the current build is one of this int index = ArrayUtils.indexOf( projectsId, getCurrentProjectIdBuilding() ); if ( index > 0 ) { cancelBuild( projectsId[index] ); } return SUCCESS; } public void setProjectId( int projectId ) { this.projectId = projectId; } public String getProjectGroupName() throws ContinuumException { if ( StringUtils.isEmpty( projectGroupName ) ) { projectGroupName = getContinuum().getProjectGroupByProjectId( projectId ).getName(); } return projectGroupName; } public List<String> getSelectedProjects() { return selectedProjects; } public void setSelectedProjects( List<String> selectedProjects ) { this.selectedProjects = selectedProjects; } public int getProjectGroupId() { return projectGroupId; } public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } }
true
true
public String cancelBuilds() throws ContinuumException { // first we remove from the build queue if ( getSelectedProjects().isEmpty() ) { return SUCCESS; } int[] projectsId = new int[getSelectedProjects().size()]; for ( String selectedProjectId : getSelectedProjects() ) { int projectId = Integer.parseInt( selectedProjectId ); projectsId = ArrayUtils.add( projectsId, projectId ); } getContinuum().removeProjectsFromBuildingQueue( projectsId ); // now we must check if the current build is one of this int index = ArrayUtils.indexOf( projectsId, getCurrentProjectIdBuilding() ); if ( index > 0 ) { cancelBuild( projectsId[index] ); } return SUCCESS; }
public String cancelBuilds() throws ContinuumException { // first we remove from the build queue if ( getSelectedProjects() != null && getSelectedProjects().isEmpty() ) { return SUCCESS; } int[] projectsId = new int[getSelectedProjects().size()]; for ( String selectedProjectId : getSelectedProjects() ) { int projectId = Integer.parseInt( selectedProjectId ); projectsId = ArrayUtils.add( projectsId, projectId ); } getContinuum().removeProjectsFromBuildingQueue( projectsId ); // now we must check if the current build is one of this int index = ArrayUtils.indexOf( projectsId, getCurrentProjectIdBuilding() ); if ( index > 0 ) { cancelBuild( projectsId[index] ); } return SUCCESS; }
diff --git a/src/com/android/browser/OpenDownloadReceiver.java b/src/com/android/browser/OpenDownloadReceiver.java index 99e5f410..f66c332f 100644 --- a/src/com/android/browser/OpenDownloadReceiver.java +++ b/src/com/android/browser/OpenDownloadReceiver.java @@ -1,84 +1,84 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.browser; import android.app.DownloadManager; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.provider.Downloads; import android.widget.Toast; import java.io.File; /** * This {@link BroadcastReceiver} handles clicks to notifications that * downloads from the browser are in progress/complete. Clicking on an * in-progress or failed download will open the download manager. Clicking on * a complete, successful download will open the file. */ public class OpenDownloadReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { ContentResolver cr = context.getContentResolver(); Uri data = intent.getData(); Cursor cursor = null; try { cursor = cr.query(data, new String[] { Downloads.Impl._ID, Downloads.Impl._DATA, - Downloads.Impl.COLUMN_MIME_TYPE, Downloads.COLUMN_STATUS }, + Downloads.Impl.COLUMN_MIME_TYPE, Downloads.Impl.COLUMN_STATUS }, null, null, null); if (cursor.moveToFirst()) { String filename = cursor.getString(1); String mimetype = cursor.getString(2); String action = intent.getAction(); - if (Downloads.ACTION_NOTIFICATION_CLICKED.equals(action)) { + if (Downloads.Impl.ACTION_NOTIFICATION_CLICKED.equals(action)) { int status = cursor.getInt(3); - if (Downloads.isStatusCompleted(status) - && Downloads.isStatusSuccess(status)) { + if (Downloads.Impl.isStatusCompleted(status) + && Downloads.Impl.isStatusSuccess(status)) { Intent launchIntent = new Intent(Intent.ACTION_VIEW); Uri path = Uri.parse(filename); // If there is no scheme, then it must be a file if (path.getScheme() == null) { path = Uri.fromFile(new File(filename)); } launchIntent.setDataAndType(path, mimetype); launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { context.startActivity(launchIntent); } catch (ActivityNotFoundException ex) { Toast.makeText(context, R.string.download_no_application_title, Toast.LENGTH_LONG).show(); } } else { // Open the downloads page Intent pageView = new Intent( DownloadManager.ACTION_VIEW_DOWNLOADS); pageView.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(pageView); } } } } finally { if (cursor != null) cursor.close(); } } }
false
true
public void onReceive(Context context, Intent intent) { ContentResolver cr = context.getContentResolver(); Uri data = intent.getData(); Cursor cursor = null; try { cursor = cr.query(data, new String[] { Downloads.Impl._ID, Downloads.Impl._DATA, Downloads.Impl.COLUMN_MIME_TYPE, Downloads.COLUMN_STATUS }, null, null, null); if (cursor.moveToFirst()) { String filename = cursor.getString(1); String mimetype = cursor.getString(2); String action = intent.getAction(); if (Downloads.ACTION_NOTIFICATION_CLICKED.equals(action)) { int status = cursor.getInt(3); if (Downloads.isStatusCompleted(status) && Downloads.isStatusSuccess(status)) { Intent launchIntent = new Intent(Intent.ACTION_VIEW); Uri path = Uri.parse(filename); // If there is no scheme, then it must be a file if (path.getScheme() == null) { path = Uri.fromFile(new File(filename)); } launchIntent.setDataAndType(path, mimetype); launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { context.startActivity(launchIntent); } catch (ActivityNotFoundException ex) { Toast.makeText(context, R.string.download_no_application_title, Toast.LENGTH_LONG).show(); } } else { // Open the downloads page Intent pageView = new Intent( DownloadManager.ACTION_VIEW_DOWNLOADS); pageView.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(pageView); } } } } finally { if (cursor != null) cursor.close(); } }
public void onReceive(Context context, Intent intent) { ContentResolver cr = context.getContentResolver(); Uri data = intent.getData(); Cursor cursor = null; try { cursor = cr.query(data, new String[] { Downloads.Impl._ID, Downloads.Impl._DATA, Downloads.Impl.COLUMN_MIME_TYPE, Downloads.Impl.COLUMN_STATUS }, null, null, null); if (cursor.moveToFirst()) { String filename = cursor.getString(1); String mimetype = cursor.getString(2); String action = intent.getAction(); if (Downloads.Impl.ACTION_NOTIFICATION_CLICKED.equals(action)) { int status = cursor.getInt(3); if (Downloads.Impl.isStatusCompleted(status) && Downloads.Impl.isStatusSuccess(status)) { Intent launchIntent = new Intent(Intent.ACTION_VIEW); Uri path = Uri.parse(filename); // If there is no scheme, then it must be a file if (path.getScheme() == null) { path = Uri.fromFile(new File(filename)); } launchIntent.setDataAndType(path, mimetype); launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { context.startActivity(launchIntent); } catch (ActivityNotFoundException ex) { Toast.makeText(context, R.string.download_no_application_title, Toast.LENGTH_LONG).show(); } } else { // Open the downloads page Intent pageView = new Intent( DownloadManager.ACTION_VIEW_DOWNLOADS); pageView.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(pageView); } } } } finally { if (cursor != null) cursor.close(); } }
diff --git a/src/test/java/org/atlasapi/remotesite/channel4/C4AtoZAtomAdapterTest.java b/src/test/java/org/atlasapi/remotesite/channel4/C4AtoZAtomAdapterTest.java index da3be0d65..899515e75 100644 --- a/src/test/java/org/atlasapi/remotesite/channel4/C4AtoZAtomAdapterTest.java +++ b/src/test/java/org/atlasapi/remotesite/channel4/C4AtoZAtomAdapterTest.java @@ -1,72 +1,72 @@ /* Copyright 2009 Meta Broadcast Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.atlasapi.remotesite.channel4; import org.atlasapi.media.entity.Brand; import org.atlasapi.media.entity.Publisher; import org.atlasapi.persistence.content.ContentWriter; import org.atlasapi.persistence.logging.NullAdapterLog; import org.atlasapi.persistence.system.RemoteSiteClient; import org.jmock.Expectations; import org.jmock.integration.junit3.MockObjectTestCase; import com.google.common.io.Resources; import com.sun.syndication.feed.atom.Feed; /** * Unit test for {@link C4AtoZAtomContentLoader}. * * @author Robert Chatley ([email protected]) */ public class C4AtoZAtomAdapterTest extends MockObjectTestCase { String uri = "http://www.channel4.com/programmes/atoz/a"; private C4BrandUpdater brandAdapter; private RemoteSiteClient<Feed> itemClient; private C4AtoZAtomContentLoader adapter; private ContentWriter writer; Brand brand101 = new Brand("http://www.channel4.com/programmes/a-bipolar-expedition", "curie:101", Publisher.C4); Brand brand202 = new Brand("http://www.channel4.com/programmes/a-bipolar-expedition-part-2", "curie:202", Publisher.C4); private final AtomFeedBuilder atoza = new AtomFeedBuilder(Resources.getResource(getClass(), "a.atom")); private final AtomFeedBuilder atoza2 = new AtomFeedBuilder(Resources.getResource(getClass(), "a2.atom")); @SuppressWarnings("unchecked") @Override protected void setUp() throws Exception { super.setUp(); brandAdapter = mock(C4BrandUpdater.class); itemClient = mock(RemoteSiteClient.class); writer = mock(ContentWriter.class); adapter = new C4AtoZAtomContentLoader(itemClient, brandAdapter, new NullAdapterLog()); } public void testPerformsGetCorrespondingGivenUriAndPassesResultToExtractor() throws Exception { checking(new Expectations() {{ - one(itemClient).get("http://api.channel4.com/programmes/atoz/a.atom"); will(returnValue(atoza.build())); + one(itemClient).get("http://api.channel4.com/pmlsd/atoz/a.atom"); will(returnValue(atoza.build())); allowing(brandAdapter).canFetch("http://www.channel4.com/programmes/a-bipolar-expedition"); will(returnValue(true)); allowing(brandAdapter).createOrUpdateBrand("http://www.channel4.com/programmes/a-bipolar-expedition"); //will(returnValue(brand101)); - one(itemClient).get("http://api.channel4.com/programmes/atoz/a/page-2.atom"); will(returnValue(atoza2.build())); + one(itemClient).get("http://api.channel4.com/pmlsd/atoz/a/page-2.atom"); will(returnValue(atoza2.build())); allowing(brandAdapter).canFetch("http://www.channel4.com/programmes/a-bipolar-expedition-part-2"); will(returnValue(true)); allowing(brandAdapter).createOrUpdateBrand("http://www.channel4.com/programmes/a-bipolar-expedition-part-2"); //will(returnValue(brand202)); }}); adapter.loadAndSaveByLetter("a"); } }
false
true
public void testPerformsGetCorrespondingGivenUriAndPassesResultToExtractor() throws Exception { checking(new Expectations() {{ one(itemClient).get("http://api.channel4.com/programmes/atoz/a.atom"); will(returnValue(atoza.build())); allowing(brandAdapter).canFetch("http://www.channel4.com/programmes/a-bipolar-expedition"); will(returnValue(true)); allowing(brandAdapter).createOrUpdateBrand("http://www.channel4.com/programmes/a-bipolar-expedition"); //will(returnValue(brand101)); one(itemClient).get("http://api.channel4.com/programmes/atoz/a/page-2.atom"); will(returnValue(atoza2.build())); allowing(brandAdapter).canFetch("http://www.channel4.com/programmes/a-bipolar-expedition-part-2"); will(returnValue(true)); allowing(brandAdapter).createOrUpdateBrand("http://www.channel4.com/programmes/a-bipolar-expedition-part-2"); //will(returnValue(brand202)); }}); adapter.loadAndSaveByLetter("a"); }
public void testPerformsGetCorrespondingGivenUriAndPassesResultToExtractor() throws Exception { checking(new Expectations() {{ one(itemClient).get("http://api.channel4.com/pmlsd/atoz/a.atom"); will(returnValue(atoza.build())); allowing(brandAdapter).canFetch("http://www.channel4.com/programmes/a-bipolar-expedition"); will(returnValue(true)); allowing(brandAdapter).createOrUpdateBrand("http://www.channel4.com/programmes/a-bipolar-expedition"); //will(returnValue(brand101)); one(itemClient).get("http://api.channel4.com/pmlsd/atoz/a/page-2.atom"); will(returnValue(atoza2.build())); allowing(brandAdapter).canFetch("http://www.channel4.com/programmes/a-bipolar-expedition-part-2"); will(returnValue(true)); allowing(brandAdapter).createOrUpdateBrand("http://www.channel4.com/programmes/a-bipolar-expedition-part-2"); //will(returnValue(brand202)); }}); adapter.loadAndSaveByLetter("a"); }
diff --git a/src/com/android/email/activity/MessageListItem.java b/src/com/android/email/activity/MessageListItem.java index d69ab18b..8d6eaea8 100644 --- a/src/com/android/email/activity/MessageListItem.java +++ b/src/com/android/email/activity/MessageListItem.java @@ -1,507 +1,511 @@ /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.email.activity; import com.android.email.R; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.FontMetricsInt; import android.graphics.Typeface; import android.text.Layout.Alignment; import android.text.Spannable; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.StaticLayout; import android.text.TextPaint; import android.text.TextUtils; import android.text.TextUtils.TruncateAt; import android.text.format.DateUtils; import android.text.style.StyleSpan; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; /** * This custom View is the list item for the MessageList activity, and serves two purposes: * 1. It's a container to store message metadata (e.g. the ids of the message, mailbox, & account) * 2. It handles internal clicks such as the checkbox or the favorite star */ public class MessageListItem extends View { // Note: messagesAdapter directly fiddles with these fields. /* package */ long mMessageId; /* package */ long mMailboxId; /* package */ long mAccountId; private MessagesAdapter mAdapter; private boolean mDownEvent; public static final String MESSAGE_LIST_ITEMS_CLIP_LABEL = "com.android.email.MESSAGE_LIST_ITEMS"; public MessageListItem(Context context) { super(context); init(context); } public MessageListItem(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public MessageListItem(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } // We always show two lines of subject/snippet private static final int MAX_SUBJECT_SNIPPET_LINES = 2; // Narrow mode shows sender/snippet and time/favorite stacked to save real estate; due to this, // it is also somewhat taller private static final int MODE_NARROW = 1; // Wide mode shows sender, snippet, time, and favorite spread out across the screen private static final int MODE_WIDE = 2; // Sentinel indicating that the view needs layout public static final int NEEDS_LAYOUT = -1; private static boolean sInit = false; private static final TextPaint sDefaultPaint = new TextPaint(); private static final TextPaint sBoldPaint = new TextPaint(); private static final TextPaint sDatePaint = new TextPaint(); private static Bitmap sAttachmentIcon; private static Bitmap sInviteIcon; private static Bitmap sFavoriteIconOff; private static Bitmap sFavoriteIconOn; private static int sFavoriteIconWidth; private static Bitmap sSelectedIconOn; private static Bitmap sSelectedIconOff; private static String sSubjectSnippetDivider; public String mSender; public CharSequence mText; public String mSnippet; public String mSubject; public boolean mRead; public long mTimestamp; public boolean mHasAttachment = false; public boolean mHasInvite = true; public boolean mIsFavorite = false; /** {@link Paint} for account color chips. null if no chips should be drawn. */ public Paint mColorChipPaint; private int mMode = -1; private int mViewWidth = 0; private int mViewHeight = 0; private int mSenderSnippetWidth; private int mSnippetWidth; private int mDateFaveWidth; private static int sCheckboxHitWidth; private static int sDateIconWidthWide; private static int sDateIconWidthNarrow; private static int sFavoriteHitWidth; private static int sFavoritePaddingRight; private static int sSenderPaddingTopNarrow; private static int sSenderWidth; private static int sPaddingLarge; private static int sPaddingVerySmall; private static int sPaddingSmall; private static int sPaddingMedium; private static int sTextSize; private static int sItemHeightWide; private static int sItemHeightNarrow; private static int sMinimumWidthWideMode; private static int sColorTipWidth; private static int sColorTipHeight; private static int sColorTipRightMarginOnNarrow; private static int sColorTipRightMarginOnWide; public int mSnippetLineCount = NEEDS_LAYOUT; private final CharSequence[] mSnippetLines = new CharSequence[MAX_SUBJECT_SNIPPET_LINES]; private CharSequence mFormattedSender; private CharSequence mFormattedDate; private void init(Context context) { if (!sInit) { Resources r = context.getResources(); sSubjectSnippetDivider = r.getString(R.string.message_list_subject_snippet_divider); sCheckboxHitWidth = r.getDimensionPixelSize(R.dimen.message_list_item_checkbox_hit_width); sFavoriteHitWidth = r.getDimensionPixelSize(R.dimen.message_list_item_favorite_hit_width); sFavoritePaddingRight = r.getDimensionPixelSize(R.dimen.message_list_item_favorite_padding_right); sSenderPaddingTopNarrow = r.getDimensionPixelSize(R.dimen.message_list_item_sender_padding_top_narrow); sDateIconWidthWide = r.getDimensionPixelSize(R.dimen.message_list_item_date_icon_width_wide); sDateIconWidthNarrow = r.getDimensionPixelSize(R.dimen.message_list_item_date_icon_width_narrow); sSenderWidth = r.getDimensionPixelSize(R.dimen.message_list_item_sender_width); sPaddingLarge = r.getDimensionPixelSize(R.dimen.message_list_item_padding_large); sPaddingMedium = r.getDimensionPixelSize(R.dimen.message_list_item_padding_medium); sPaddingSmall = r.getDimensionPixelSize(R.dimen.message_list_item_padding_small); sPaddingVerySmall = r.getDimensionPixelSize(R.dimen.message_list_item_padding_very_small); sTextSize = r.getDimensionPixelSize(R.dimen.message_list_item_text_size); sItemHeightWide = r.getDimensionPixelSize(R.dimen.message_list_item_height_wide); sItemHeightNarrow = r.getDimensionPixelSize(R.dimen.message_list_item_height_narrow); sMinimumWidthWideMode = r.getDimensionPixelSize(R.dimen.message_list_item_minimum_width_wide_mode); sColorTipWidth = r.getDimensionPixelSize(R.dimen.message_list_item_color_tip_width); sColorTipHeight = r.getDimensionPixelSize(R.dimen.message_list_item_color_tip_height); sColorTipRightMarginOnNarrow = r.getDimensionPixelSize(R.dimen.message_list_item_color_tip_right_margin_on_narrow); sColorTipRightMarginOnWide = r.getDimensionPixelSize(R.dimen.message_list_item_color_tip_right_margin_on_wide); sDefaultPaint.setTypeface(Typeface.DEFAULT); sDefaultPaint.setTextSize(sTextSize); sDefaultPaint.setAntiAlias(true); sDatePaint.setTypeface(Typeface.DEFAULT); sDatePaint.setTextSize(sTextSize - 1); sDatePaint.setAntiAlias(true); sDatePaint.setTextAlign(Align.RIGHT); sBoldPaint.setTypeface(Typeface.DEFAULT_BOLD); sBoldPaint.setTextSize(sTextSize); sBoldPaint.setAntiAlias(true); sAttachmentIcon = BitmapFactory.decodeResource(r, R.drawable.ic_mms_attachment_small); sInviteIcon = BitmapFactory.decodeResource(r, R.drawable.ic_calendar_event_small); sFavoriteIconOff = BitmapFactory.decodeResource(r, R.drawable.btn_star_big_buttonless_dark_off); sFavoriteIconOn = BitmapFactory.decodeResource(r, R.drawable.btn_star_big_buttonless_dark_on); sSelectedIconOff = BitmapFactory.decodeResource(r, R.drawable.btn_check_off_normal_holo_light); sSelectedIconOn = BitmapFactory.decodeResource(r, R.drawable.btn_check_on_normal_holo_light); sFavoriteIconWidth = sFavoriteIconOff.getWidth(); sInit = true; } } /** * Determine the mode of this view (WIDE or NORMAL) * * @param width The width of the view * @return The mode of the view */ private int getViewMode(int width) { int mode = MODE_NARROW; if (width > sMinimumWidthWideMode) { mode = MODE_WIDE; } return mode; } private void calculateDrawingData() { SpannableStringBuilder ssb = new SpannableStringBuilder(); boolean hasSubject = false; if (!TextUtils.isEmpty(mSubject)) { SpannableString ss = new SpannableString(mSubject); ss.setSpan(new StyleSpan(mRead ? Typeface.NORMAL : Typeface.BOLD), 0, ss.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); ssb.append(ss); hasSubject = true; } if (!TextUtils.isEmpty(mSnippet)) { if (hasSubject) { ssb.append(sSubjectSnippetDivider); } ssb.append(mSnippet); } mText = ssb; if (mMode == MODE_WIDE) { mDateFaveWidth = sFavoriteHitWidth + sDateIconWidthWide; } else { mDateFaveWidth = sDateIconWidthNarrow; } mSenderSnippetWidth = mViewWidth - mDateFaveWidth - sCheckboxHitWidth; // In wide mode, we use 3/4 for snippet and 1/4 for sender mSnippetWidth = mSenderSnippetWidth; if (mMode == MODE_WIDE) { mSnippetWidth = mSenderSnippetWidth - sSenderWidth - sPaddingLarge; } // Create a StaticLayout with our snippet to get the line breaks StaticLayout layout = new StaticLayout(mText, 0, mText.length(), sDefaultPaint, mSnippetWidth, Alignment.ALIGN_NORMAL, 1, 0, true); // Get the number of lines needed to render the whole snippet mSnippetLineCount = layout.getLineCount(); // Go through our maximum number of lines, and save away what we'll end up displaying // for those lines for (int i = 0; i < MAX_SUBJECT_SNIPPET_LINES; i++) { int start = layout.getLineStart(i); if (i == MAX_SUBJECT_SNIPPET_LINES - 1) { int end = mText.length() - 1; if (start > end) continue; // For the final line, ellipsize the text to our width mSnippetLines[i] = TextUtils.ellipsize(mText.subSequence(start, end), sDefaultPaint, mSnippetWidth, TruncateAt.END); } else { // Just extract from start to end mSnippetLines[i] = mText.subSequence(start, layout.getLineEnd(i)); } } // Now, format the sender for its width TextPaint senderPaint = mRead ? sDefaultPaint : sBoldPaint; int senderWidth = (mMode == MODE_WIDE) ? sSenderWidth : mSenderSnippetWidth; // And get the ellipsized string for the calculated width mFormattedSender = TextUtils.ellipsize(mSender, senderPaint, senderWidth, TruncateAt.END); // Get a nicely formatted date string (relative to today) String date = DateUtils.getRelativeTimeSpanString(getContext(), mTimestamp).toString(); // And make it fit to our size mFormattedDate = TextUtils.ellipsize(date, sDatePaint, sDateIconWidthWide, TruncateAt.END); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (widthMeasureSpec != 0 || mViewWidth == 0) { mViewWidth = MeasureSpec.getSize(widthMeasureSpec); int mode = getViewMode(mViewWidth); if (mode != mMode) { // If the mode has changed, set the snippet line count to indicate layout required mMode = mode; mSnippetLineCount = NEEDS_LAYOUT; } mViewHeight = measureHeight(heightMeasureSpec, mMode); } setMeasuredDimension(mViewWidth, mViewHeight); } /** * Determine the height of this view * * @param measureSpec A measureSpec packed into an int * @param mode The current mode of this view * @return The height of the view, honoring constraints from measureSpec */ private int measureHeight(int measureSpec, int mode) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { // We were told how big to be result = specSize; } else { // Measure the text if (mMode == MODE_WIDE) { result = sItemHeightWide; } else { result = sItemHeightNarrow; } if (specMode == MeasureSpec.AT_MOST) { // Respect AT_MOST value if that was what is called for by // measureSpec result = Math.min(result, specSize); } } return result; } @Override protected void onDraw(Canvas canvas) { if (mSnippetLineCount == NEEDS_LAYOUT) { calculateDrawingData(); } // Snippet starts at right of checkbox int snippetX = sCheckboxHitWidth; int snippetY; int lineHeight = (int)sDefaultPaint.getFontSpacing() + sPaddingVerySmall; FontMetricsInt fontMetrics = sDefaultPaint.getFontMetricsInt(); int ascent = fontMetrics.ascent; int descent = fontMetrics.descent; int senderY; if (mMode == MODE_WIDE) { // Get the right starting point for the snippet snippetX += sSenderWidth + sPaddingLarge; // And center the sender and snippet senderY = (mViewHeight - descent - ascent) / 2; snippetY = ((mViewHeight - (2 * lineHeight)) / 2) - ascent; } else { senderY = -ascent + sSenderPaddingTopNarrow; snippetY = senderY + lineHeight + sPaddingVerySmall; } // Draw the color chip if (mColorChipPaint != null) { final int rightMargin = (mMode == MODE_WIDE) ? sColorTipRightMarginOnWide : sColorTipRightMarginOnNarrow; final int x = mViewWidth - rightMargin - sColorTipWidth; canvas.drawRect(x, 0, x + sColorTipWidth, sColorTipHeight, mColorChipPaint); } // Draw the checkbox int checkboxLeft = (sCheckboxHitWidth - sSelectedIconOff.getWidth()) / 2; int checkboxTop = (mViewHeight - sSelectedIconOff.getHeight()) / 2; canvas.drawBitmap(mAdapter.isSelected(this) ? sSelectedIconOn : sSelectedIconOff, checkboxLeft, checkboxTop, sDefaultPaint); // Draw the sender name canvas.drawText(mFormattedSender, 0, mFormattedSender.length(), sCheckboxHitWidth, senderY, mRead ? sDefaultPaint : sBoldPaint); // Draw each of the snippet lines int subjectEnd = (mSubject == null) ? 0 : mSubject.length(); int lineStart = 0; TextPaint subjectPaint = mRead ? sDefaultPaint : sBoldPaint; for (int i = 0; i < MAX_SUBJECT_SNIPPET_LINES; i++) { CharSequence line = mSnippetLines[i]; int drawX = snippetX; if (line != null) { int defaultPaintStart = 0; if (lineStart <= subjectEnd) { int boldPaintEnd = subjectEnd - lineStart; if (boldPaintEnd > line.length()) { boldPaintEnd = line.length(); } // From 0 to end, do in bold or default depending on the read flag canvas.drawText(line, 0, boldPaintEnd, drawX, snippetY, subjectPaint); defaultPaintStart = boldPaintEnd; drawX += subjectPaint.measureText(line, 0, boldPaintEnd); } canvas.drawText(line, defaultPaintStart, line.length(), drawX, snippetY, sDefaultPaint); snippetY += lineHeight; lineStart += line.length(); } } // Draw the attachment and invite icons, if necessary int datePaddingRight; if (mMode == MODE_WIDE) { datePaddingRight = sFavoriteHitWidth; } else { datePaddingRight = sPaddingLarge; } int left = mViewWidth - datePaddingRight - (int)sDefaultPaint.measureText(mFormattedDate, 0, mFormattedDate.length()) - sPaddingMedium; + int iconTop; if (mHasAttachment) { left -= sAttachmentIcon.getWidth() + sPaddingSmall; - int iconTop; if (mMode == MODE_WIDE) { iconTop = (mViewHeight - sAttachmentIcon.getHeight()) / 2; } else { iconTop = senderY - sAttachmentIcon.getHeight(); } canvas.drawBitmap(sAttachmentIcon, left, iconTop, sDefaultPaint); } if (mHasInvite) { left -= sInviteIcon.getWidth() + sPaddingSmall; - int iconTop = (mViewHeight - sInviteIcon.getHeight()) / 2; + if (mMode == MODE_WIDE) { + iconTop = (mViewHeight - sInviteIcon.getHeight()) / 2; + } else { + iconTop = senderY - sInviteIcon.getHeight(); + } canvas.drawBitmap(sInviteIcon, left, iconTop, sDefaultPaint); } // Draw the date canvas.drawText(mFormattedDate, 0, mFormattedDate.length(), mViewWidth - datePaddingRight, senderY, sDatePaint); // Draw the favorite icon int faveLeft = mViewWidth - sFavoriteIconWidth; if (mMode == MODE_WIDE) { faveLeft -= sFavoritePaddingRight; } else { faveLeft -= sPaddingLarge; } int faveTop = (mViewHeight - sFavoriteIconOff.getHeight()) / 2; if (mMode == MODE_NARROW) { faveTop += sSenderPaddingTopNarrow; } canvas.drawBitmap(mIsFavorite ? sFavoriteIconOn : sFavoriteIconOff, faveLeft, faveTop, sDefaultPaint); } /** * Called by the adapter at bindView() time * * @param adapter the adapter that creates this view */ public void bindViewInit(MessagesAdapter adapter) { mAdapter = adapter; } /** * Overriding this method allows us to "catch" clicks in the checkbox or star * and process them accordingly. */ @Override public boolean onTouchEvent(MotionEvent event) { boolean handled = false; int touchX = (int) event.getX(); int checkRight = sCheckboxHitWidth; int starLeft = mViewWidth - sFavoriteHitWidth; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (touchX < checkRight || touchX > starLeft) { mDownEvent = true; if ((touchX < checkRight) || (touchX > starLeft)) { handled = true; } } break; case MotionEvent.ACTION_CANCEL: mDownEvent = false; break; case MotionEvent.ACTION_UP: if (mDownEvent) { if (touchX < checkRight) { mAdapter.toggleSelected(this); handled = true; } else if (touchX > starLeft) { mIsFavorite = !mIsFavorite; mAdapter.updateFavorite(this, mIsFavorite); handled = true; } } break; } if (handled) { invalidate(); } else { handled = super.onTouchEvent(event); } return handled; } }
false
true
protected void onDraw(Canvas canvas) { if (mSnippetLineCount == NEEDS_LAYOUT) { calculateDrawingData(); } // Snippet starts at right of checkbox int snippetX = sCheckboxHitWidth; int snippetY; int lineHeight = (int)sDefaultPaint.getFontSpacing() + sPaddingVerySmall; FontMetricsInt fontMetrics = sDefaultPaint.getFontMetricsInt(); int ascent = fontMetrics.ascent; int descent = fontMetrics.descent; int senderY; if (mMode == MODE_WIDE) { // Get the right starting point for the snippet snippetX += sSenderWidth + sPaddingLarge; // And center the sender and snippet senderY = (mViewHeight - descent - ascent) / 2; snippetY = ((mViewHeight - (2 * lineHeight)) / 2) - ascent; } else { senderY = -ascent + sSenderPaddingTopNarrow; snippetY = senderY + lineHeight + sPaddingVerySmall; } // Draw the color chip if (mColorChipPaint != null) { final int rightMargin = (mMode == MODE_WIDE) ? sColorTipRightMarginOnWide : sColorTipRightMarginOnNarrow; final int x = mViewWidth - rightMargin - sColorTipWidth; canvas.drawRect(x, 0, x + sColorTipWidth, sColorTipHeight, mColorChipPaint); } // Draw the checkbox int checkboxLeft = (sCheckboxHitWidth - sSelectedIconOff.getWidth()) / 2; int checkboxTop = (mViewHeight - sSelectedIconOff.getHeight()) / 2; canvas.drawBitmap(mAdapter.isSelected(this) ? sSelectedIconOn : sSelectedIconOff, checkboxLeft, checkboxTop, sDefaultPaint); // Draw the sender name canvas.drawText(mFormattedSender, 0, mFormattedSender.length(), sCheckboxHitWidth, senderY, mRead ? sDefaultPaint : sBoldPaint); // Draw each of the snippet lines int subjectEnd = (mSubject == null) ? 0 : mSubject.length(); int lineStart = 0; TextPaint subjectPaint = mRead ? sDefaultPaint : sBoldPaint; for (int i = 0; i < MAX_SUBJECT_SNIPPET_LINES; i++) { CharSequence line = mSnippetLines[i]; int drawX = snippetX; if (line != null) { int defaultPaintStart = 0; if (lineStart <= subjectEnd) { int boldPaintEnd = subjectEnd - lineStart; if (boldPaintEnd > line.length()) { boldPaintEnd = line.length(); } // From 0 to end, do in bold or default depending on the read flag canvas.drawText(line, 0, boldPaintEnd, drawX, snippetY, subjectPaint); defaultPaintStart = boldPaintEnd; drawX += subjectPaint.measureText(line, 0, boldPaintEnd); } canvas.drawText(line, defaultPaintStart, line.length(), drawX, snippetY, sDefaultPaint); snippetY += lineHeight; lineStart += line.length(); } } // Draw the attachment and invite icons, if necessary int datePaddingRight; if (mMode == MODE_WIDE) { datePaddingRight = sFavoriteHitWidth; } else { datePaddingRight = sPaddingLarge; } int left = mViewWidth - datePaddingRight - (int)sDefaultPaint.measureText(mFormattedDate, 0, mFormattedDate.length()) - sPaddingMedium; if (mHasAttachment) { left -= sAttachmentIcon.getWidth() + sPaddingSmall; int iconTop; if (mMode == MODE_WIDE) { iconTop = (mViewHeight - sAttachmentIcon.getHeight()) / 2; } else { iconTop = senderY - sAttachmentIcon.getHeight(); } canvas.drawBitmap(sAttachmentIcon, left, iconTop, sDefaultPaint); } if (mHasInvite) { left -= sInviteIcon.getWidth() + sPaddingSmall; int iconTop = (mViewHeight - sInviteIcon.getHeight()) / 2; canvas.drawBitmap(sInviteIcon, left, iconTop, sDefaultPaint); } // Draw the date canvas.drawText(mFormattedDate, 0, mFormattedDate.length(), mViewWidth - datePaddingRight, senderY, sDatePaint); // Draw the favorite icon int faveLeft = mViewWidth - sFavoriteIconWidth; if (mMode == MODE_WIDE) { faveLeft -= sFavoritePaddingRight; } else { faveLeft -= sPaddingLarge; } int faveTop = (mViewHeight - sFavoriteIconOff.getHeight()) / 2; if (mMode == MODE_NARROW) { faveTop += sSenderPaddingTopNarrow; } canvas.drawBitmap(mIsFavorite ? sFavoriteIconOn : sFavoriteIconOff, faveLeft, faveTop, sDefaultPaint); }
protected void onDraw(Canvas canvas) { if (mSnippetLineCount == NEEDS_LAYOUT) { calculateDrawingData(); } // Snippet starts at right of checkbox int snippetX = sCheckboxHitWidth; int snippetY; int lineHeight = (int)sDefaultPaint.getFontSpacing() + sPaddingVerySmall; FontMetricsInt fontMetrics = sDefaultPaint.getFontMetricsInt(); int ascent = fontMetrics.ascent; int descent = fontMetrics.descent; int senderY; if (mMode == MODE_WIDE) { // Get the right starting point for the snippet snippetX += sSenderWidth + sPaddingLarge; // And center the sender and snippet senderY = (mViewHeight - descent - ascent) / 2; snippetY = ((mViewHeight - (2 * lineHeight)) / 2) - ascent; } else { senderY = -ascent + sSenderPaddingTopNarrow; snippetY = senderY + lineHeight + sPaddingVerySmall; } // Draw the color chip if (mColorChipPaint != null) { final int rightMargin = (mMode == MODE_WIDE) ? sColorTipRightMarginOnWide : sColorTipRightMarginOnNarrow; final int x = mViewWidth - rightMargin - sColorTipWidth; canvas.drawRect(x, 0, x + sColorTipWidth, sColorTipHeight, mColorChipPaint); } // Draw the checkbox int checkboxLeft = (sCheckboxHitWidth - sSelectedIconOff.getWidth()) / 2; int checkboxTop = (mViewHeight - sSelectedIconOff.getHeight()) / 2; canvas.drawBitmap(mAdapter.isSelected(this) ? sSelectedIconOn : sSelectedIconOff, checkboxLeft, checkboxTop, sDefaultPaint); // Draw the sender name canvas.drawText(mFormattedSender, 0, mFormattedSender.length(), sCheckboxHitWidth, senderY, mRead ? sDefaultPaint : sBoldPaint); // Draw each of the snippet lines int subjectEnd = (mSubject == null) ? 0 : mSubject.length(); int lineStart = 0; TextPaint subjectPaint = mRead ? sDefaultPaint : sBoldPaint; for (int i = 0; i < MAX_SUBJECT_SNIPPET_LINES; i++) { CharSequence line = mSnippetLines[i]; int drawX = snippetX; if (line != null) { int defaultPaintStart = 0; if (lineStart <= subjectEnd) { int boldPaintEnd = subjectEnd - lineStart; if (boldPaintEnd > line.length()) { boldPaintEnd = line.length(); } // From 0 to end, do in bold or default depending on the read flag canvas.drawText(line, 0, boldPaintEnd, drawX, snippetY, subjectPaint); defaultPaintStart = boldPaintEnd; drawX += subjectPaint.measureText(line, 0, boldPaintEnd); } canvas.drawText(line, defaultPaintStart, line.length(), drawX, snippetY, sDefaultPaint); snippetY += lineHeight; lineStart += line.length(); } } // Draw the attachment and invite icons, if necessary int datePaddingRight; if (mMode == MODE_WIDE) { datePaddingRight = sFavoriteHitWidth; } else { datePaddingRight = sPaddingLarge; } int left = mViewWidth - datePaddingRight - (int)sDefaultPaint.measureText(mFormattedDate, 0, mFormattedDate.length()) - sPaddingMedium; int iconTop; if (mHasAttachment) { left -= sAttachmentIcon.getWidth() + sPaddingSmall; if (mMode == MODE_WIDE) { iconTop = (mViewHeight - sAttachmentIcon.getHeight()) / 2; } else { iconTop = senderY - sAttachmentIcon.getHeight(); } canvas.drawBitmap(sAttachmentIcon, left, iconTop, sDefaultPaint); } if (mHasInvite) { left -= sInviteIcon.getWidth() + sPaddingSmall; if (mMode == MODE_WIDE) { iconTop = (mViewHeight - sInviteIcon.getHeight()) / 2; } else { iconTop = senderY - sInviteIcon.getHeight(); } canvas.drawBitmap(sInviteIcon, left, iconTop, sDefaultPaint); } // Draw the date canvas.drawText(mFormattedDate, 0, mFormattedDate.length(), mViewWidth - datePaddingRight, senderY, sDatePaint); // Draw the favorite icon int faveLeft = mViewWidth - sFavoriteIconWidth; if (mMode == MODE_WIDE) { faveLeft -= sFavoritePaddingRight; } else { faveLeft -= sPaddingLarge; } int faveTop = (mViewHeight - sFavoriteIconOff.getHeight()) / 2; if (mMode == MODE_NARROW) { faveTop += sSenderPaddingTopNarrow; } canvas.drawBitmap(mIsFavorite ? sFavoriteIconOn : sFavoriteIconOff, faveLeft, faveTop, sDefaultPaint); }
diff --git a/src/java/azkaban/trigger/builtin/ExecuteFlowAction.java b/src/java/azkaban/trigger/builtin/ExecuteFlowAction.java index d17aa9d0..36248a2d 100644 --- a/src/java/azkaban/trigger/builtin/ExecuteFlowAction.java +++ b/src/java/azkaban/trigger/builtin/ExecuteFlowAction.java @@ -1,276 +1,280 @@ package azkaban.trigger.builtin; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import azkaban.executor.ExecutableFlow; import azkaban.executor.ExecutionOptions; import azkaban.executor.ExecutorManagerAdapter; import azkaban.executor.ExecutorManagerException; import azkaban.executor.Status; import azkaban.flow.Flow; import azkaban.project.Project; import azkaban.project.ProjectManager; import azkaban.sla.SlaOption; import azkaban.trigger.Condition; import azkaban.trigger.ConditionChecker; import azkaban.trigger.Trigger; import azkaban.trigger.TriggerAction; import azkaban.trigger.TriggerManager; public class ExecuteFlowAction implements TriggerAction { public static final String type = "ExecuteFlowAction"; public static final String EXEC_ID = "ExecuteFlowAction.execid"; private static ExecutorManagerAdapter executorManager; private static TriggerManager triggerManager; private String actionId; private int projectId; private String projectName; private String flowName; private String submitUser; private static ProjectManager projectManager; private ExecutionOptions executionOptions = new ExecutionOptions(); private List<SlaOption> slaOptions; private static Logger logger = Logger.getLogger(ExecuteFlowAction.class); public ExecuteFlowAction(String actionId, int projectId, String projectName, String flowName, String submitUser, ExecutionOptions executionOptions, List<SlaOption> slaOptions) { this.actionId = actionId; this.projectId = projectId; this.projectName = projectName; this.flowName = flowName; this.submitUser = submitUser; this.executionOptions = executionOptions; this.slaOptions = slaOptions; } public static void setLogger(Logger logger) { ExecuteFlowAction.logger = logger; } public String getProjectName() { return projectName; } public int getProjectId() { return projectId; } protected void setProjectId(int projectId) { this.projectId = projectId; } public String getFlowName() { return flowName; } protected void setFlowName(String flowName) { this.flowName = flowName; } public String getSubmitUser() { return submitUser; } protected void setSubmitUser(String submitUser) { this.submitUser = submitUser; } public ExecutionOptions getExecutionOptions() { return executionOptions; } protected void setExecutionOptions(ExecutionOptions executionOptions) { this.executionOptions = executionOptions; } public List<SlaOption> getSlaOptions() { return slaOptions; } protected void setSlaOptions(List<SlaOption> slaOptions) { this.slaOptions = slaOptions; } public static ExecutorManagerAdapter getExecutorManager() { return executorManager; } public static void setExecutorManager(ExecutorManagerAdapter executorManager) { ExecuteFlowAction.executorManager = executorManager; } public static TriggerManager getTriggerManager() { return triggerManager; } public static void setTriggerManager(TriggerManager triggerManager) { ExecuteFlowAction.triggerManager = triggerManager; } public static ProjectManager getProjectManager() { return projectManager; } public static void setProjectManager(ProjectManager projectManager) { ExecuteFlowAction.projectManager = projectManager; } @Override public String getType() { return type; } @SuppressWarnings("unchecked") @Override public TriggerAction fromJson(Object obj) { return createFromJson((HashMap<String, Object>) obj); } @SuppressWarnings("unchecked") public static TriggerAction createFromJson(HashMap<String, Object> obj) { Map<String, Object> jsonObj = (HashMap<String, Object>) obj; String objType = (String) jsonObj.get("type"); if(! objType.equals(type)) { throw new RuntimeException("Cannot create action of " + type + " from " + objType); } String actionId = (String) jsonObj.get("actionId"); int projectId = Integer.valueOf((String)jsonObj.get("projectId")); String projectName = (String) jsonObj.get("projectName"); String flowName = (String) jsonObj.get("flowName"); String submitUser = (String) jsonObj.get("submitUser"); ExecutionOptions executionOptions = null; if(jsonObj.containsKey("executionOptions")) { executionOptions = ExecutionOptions.createFromObject(jsonObj.get("executionOptions")); } List<SlaOption> slaOptions = null; if(jsonObj.containsKey("slaOptions")) { slaOptions = new ArrayList<SlaOption>(); List<Object> slaOptionsObj = (List<Object>) jsonObj.get("slaOptions"); for(Object slaObj : slaOptionsObj) { slaOptions.add(SlaOption.fromObject(slaObj)); } } return new ExecuteFlowAction(actionId, projectId, projectName, flowName, submitUser, executionOptions, slaOptions); } @Override public Object toJson() { Map<String, Object> jsonObj = new HashMap<String, Object>(); jsonObj.put("actionId", actionId); jsonObj.put("type", type); jsonObj.put("projectId", String.valueOf(projectId)); jsonObj.put("projectName", projectName); jsonObj.put("flowName", flowName); jsonObj.put("submitUser", submitUser); if(executionOptions != null) { jsonObj.put("executionOptions", executionOptions.toObject()); } if(slaOptions != null) { List<Object> slaOptionsObj = new ArrayList<Object>(); for(SlaOption sla : slaOptions) { slaOptionsObj.add(sla.toObject()); } jsonObj.put("slaOptions", slaOptionsObj); } return jsonObj; } @Override public void doAction() throws Exception { if(projectManager == null || executorManager == null) { throw new Exception("ExecuteFlowAction not properly initialized!"); } Project project = projectManager.getProject(projectId); if(project == null) { logger.error("Project to execute " + projectId + " does not exist!"); throw new RuntimeException("Error finding the project to execute " + projectId); } Flow flow = project.getFlow(flowName); if(flow == null) { logger.error("Flow " + flowName + " cannot be found in project " + project.getName()); throw new RuntimeException("Error finding the flow to execute " + flowName); } ExecutableFlow exflow = new ExecutableFlow(flow); exflow.setSubmitUser(submitUser); exflow.addAllProxyUsers(project.getProxyUsers()); + if(executionOptions == null) { + executionOptions = new ExecutionOptions(); + } if(!executionOptions.isFailureEmailsOverridden()) { executionOptions.setFailureEmails(flow.getFailureEmails()); } if(!executionOptions.isSuccessEmailsOverridden()) { executionOptions.setSuccessEmails(flow.getSuccessEmails()); } exflow.setExecutionOptions(executionOptions); try{ executorManager.submitExecutableFlow(exflow, submitUser); // Map<String, Object> outputProps = new HashMap<String, Object>(); // outputProps.put(EXEC_ID, exflow.getExecutionId()); // context.put(actionId, outputProps); logger.info("Invoked flow " + project.getName() + "." + flowName); } catch (ExecutorManagerException e) { throw new RuntimeException(e); } // deal with sla if(slaOptions != null && slaOptions.size() > 0) { int execId = exflow.getExecutionId(); for(SlaOption sla : slaOptions) { logger.info("Adding sla trigger " + sla.toString() + " to execution " + execId); SlaChecker slaChecker = new SlaChecker("slaChecker", sla, execId); Map<String, ConditionChecker> slaCheckers = new HashMap<String, ConditionChecker>(); slaCheckers.put(slaChecker.getId(), slaChecker); Condition triggerCond = new Condition(slaCheckers, slaChecker.getId() + ".eval()"); // if whole flow finish before violate sla, just abort ExecutionChecker execChecker = new ExecutionChecker("execChecker", execId, null, Status.SUCCEEDED); Map<String, ConditionChecker> expireCheckers = new HashMap<String, ConditionChecker>(); expireCheckers.put(execChecker.getId(), execChecker); Condition expireCond = new Condition(expireCheckers, execChecker.getId() + ".eval()"); List<TriggerAction> actions = new ArrayList<TriggerAction>(); List<String> slaActions = sla.getActions(); for(String act : slaActions) { if(act.equals(SlaOption.ACTION_ALERT)) { SlaAlertAction slaAlert = new SlaAlertAction("slaAlert", sla, execId); actions.add(slaAlert); } else if(act.equals(SlaOption.ACTION_CANCEL_FLOW)) { KillExecutionAction killAct = new KillExecutionAction("killExecution", execId); actions.add(killAct); } } Trigger slaTrigger = new Trigger("azkaban_sla", "azkaban", triggerCond, expireCond, actions); slaTrigger.setResetOnTrigger(false); slaTrigger.setResetOnExpire(false); logger.info("Ready to put in the sla trigger"); triggerManager.insertTrigger(slaTrigger); + logger.info("Sla inserted."); } } } @Override public String getDescription() { return "Execute flow " + getFlowName() + " from project " + getProjectName(); } @Override public void setContext(Map<String, Object> context) { } @Override public String getId() { return actionId; } }
false
true
public void doAction() throws Exception { if(projectManager == null || executorManager == null) { throw new Exception("ExecuteFlowAction not properly initialized!"); } Project project = projectManager.getProject(projectId); if(project == null) { logger.error("Project to execute " + projectId + " does not exist!"); throw new RuntimeException("Error finding the project to execute " + projectId); } Flow flow = project.getFlow(flowName); if(flow == null) { logger.error("Flow " + flowName + " cannot be found in project " + project.getName()); throw new RuntimeException("Error finding the flow to execute " + flowName); } ExecutableFlow exflow = new ExecutableFlow(flow); exflow.setSubmitUser(submitUser); exflow.addAllProxyUsers(project.getProxyUsers()); if(!executionOptions.isFailureEmailsOverridden()) { executionOptions.setFailureEmails(flow.getFailureEmails()); } if(!executionOptions.isSuccessEmailsOverridden()) { executionOptions.setSuccessEmails(flow.getSuccessEmails()); } exflow.setExecutionOptions(executionOptions); try{ executorManager.submitExecutableFlow(exflow, submitUser); // Map<String, Object> outputProps = new HashMap<String, Object>(); // outputProps.put(EXEC_ID, exflow.getExecutionId()); // context.put(actionId, outputProps); logger.info("Invoked flow " + project.getName() + "." + flowName); } catch (ExecutorManagerException e) { throw new RuntimeException(e); } // deal with sla if(slaOptions != null && slaOptions.size() > 0) { int execId = exflow.getExecutionId(); for(SlaOption sla : slaOptions) { logger.info("Adding sla trigger " + sla.toString() + " to execution " + execId); SlaChecker slaChecker = new SlaChecker("slaChecker", sla, execId); Map<String, ConditionChecker> slaCheckers = new HashMap<String, ConditionChecker>(); slaCheckers.put(slaChecker.getId(), slaChecker); Condition triggerCond = new Condition(slaCheckers, slaChecker.getId() + ".eval()"); // if whole flow finish before violate sla, just abort ExecutionChecker execChecker = new ExecutionChecker("execChecker", execId, null, Status.SUCCEEDED); Map<String, ConditionChecker> expireCheckers = new HashMap<String, ConditionChecker>(); expireCheckers.put(execChecker.getId(), execChecker); Condition expireCond = new Condition(expireCheckers, execChecker.getId() + ".eval()"); List<TriggerAction> actions = new ArrayList<TriggerAction>(); List<String> slaActions = sla.getActions(); for(String act : slaActions) { if(act.equals(SlaOption.ACTION_ALERT)) { SlaAlertAction slaAlert = new SlaAlertAction("slaAlert", sla, execId); actions.add(slaAlert); } else if(act.equals(SlaOption.ACTION_CANCEL_FLOW)) { KillExecutionAction killAct = new KillExecutionAction("killExecution", execId); actions.add(killAct); } } Trigger slaTrigger = new Trigger("azkaban_sla", "azkaban", triggerCond, expireCond, actions); slaTrigger.setResetOnTrigger(false); slaTrigger.setResetOnExpire(false); logger.info("Ready to put in the sla trigger"); triggerManager.insertTrigger(slaTrigger); } } }
public void doAction() throws Exception { if(projectManager == null || executorManager == null) { throw new Exception("ExecuteFlowAction not properly initialized!"); } Project project = projectManager.getProject(projectId); if(project == null) { logger.error("Project to execute " + projectId + " does not exist!"); throw new RuntimeException("Error finding the project to execute " + projectId); } Flow flow = project.getFlow(flowName); if(flow == null) { logger.error("Flow " + flowName + " cannot be found in project " + project.getName()); throw new RuntimeException("Error finding the flow to execute " + flowName); } ExecutableFlow exflow = new ExecutableFlow(flow); exflow.setSubmitUser(submitUser); exflow.addAllProxyUsers(project.getProxyUsers()); if(executionOptions == null) { executionOptions = new ExecutionOptions(); } if(!executionOptions.isFailureEmailsOverridden()) { executionOptions.setFailureEmails(flow.getFailureEmails()); } if(!executionOptions.isSuccessEmailsOverridden()) { executionOptions.setSuccessEmails(flow.getSuccessEmails()); } exflow.setExecutionOptions(executionOptions); try{ executorManager.submitExecutableFlow(exflow, submitUser); // Map<String, Object> outputProps = new HashMap<String, Object>(); // outputProps.put(EXEC_ID, exflow.getExecutionId()); // context.put(actionId, outputProps); logger.info("Invoked flow " + project.getName() + "." + flowName); } catch (ExecutorManagerException e) { throw new RuntimeException(e); } // deal with sla if(slaOptions != null && slaOptions.size() > 0) { int execId = exflow.getExecutionId(); for(SlaOption sla : slaOptions) { logger.info("Adding sla trigger " + sla.toString() + " to execution " + execId); SlaChecker slaChecker = new SlaChecker("slaChecker", sla, execId); Map<String, ConditionChecker> slaCheckers = new HashMap<String, ConditionChecker>(); slaCheckers.put(slaChecker.getId(), slaChecker); Condition triggerCond = new Condition(slaCheckers, slaChecker.getId() + ".eval()"); // if whole flow finish before violate sla, just abort ExecutionChecker execChecker = new ExecutionChecker("execChecker", execId, null, Status.SUCCEEDED); Map<String, ConditionChecker> expireCheckers = new HashMap<String, ConditionChecker>(); expireCheckers.put(execChecker.getId(), execChecker); Condition expireCond = new Condition(expireCheckers, execChecker.getId() + ".eval()"); List<TriggerAction> actions = new ArrayList<TriggerAction>(); List<String> slaActions = sla.getActions(); for(String act : slaActions) { if(act.equals(SlaOption.ACTION_ALERT)) { SlaAlertAction slaAlert = new SlaAlertAction("slaAlert", sla, execId); actions.add(slaAlert); } else if(act.equals(SlaOption.ACTION_CANCEL_FLOW)) { KillExecutionAction killAct = new KillExecutionAction("killExecution", execId); actions.add(killAct); } } Trigger slaTrigger = new Trigger("azkaban_sla", "azkaban", triggerCond, expireCond, actions); slaTrigger.setResetOnTrigger(false); slaTrigger.setResetOnExpire(false); logger.info("Ready to put in the sla trigger"); triggerManager.insertTrigger(slaTrigger); logger.info("Sla inserted."); } } }
diff --git a/core/src/com/google/zxing/oned/Code128Reader.java b/core/src/com/google/zxing/oned/Code128Reader.java index b41d954d..e15370ae 100644 --- a/core/src/com/google/zxing/oned/Code128Reader.java +++ b/core/src/com/google/zxing/oned/Code128Reader.java @@ -1,473 +1,463 @@ /* * Copyright 2008 ZXing 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 com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.ChecksumException; import com.google.zxing.FormatException; import com.google.zxing.NotFoundException; import com.google.zxing.Result; import com.google.zxing.ResultPoint; import com.google.zxing.common.BitArray; import java.util.Hashtable; /** * <p>Decodes Code 128 barcodes.</p> * * @author Sean Owen */ public final class Code128Reader extends OneDReader { static final int[][] CODE_PATTERNS = { {2, 1, 2, 2, 2, 2}, // 0 {2, 2, 2, 1, 2, 2}, {2, 2, 2, 2, 2, 1}, {1, 2, 1, 2, 2, 3}, {1, 2, 1, 3, 2, 2}, {1, 3, 1, 2, 2, 2}, // 5 {1, 2, 2, 2, 1, 3}, {1, 2, 2, 3, 1, 2}, {1, 3, 2, 2, 1, 2}, {2, 2, 1, 2, 1, 3}, {2, 2, 1, 3, 1, 2}, // 10 {2, 3, 1, 2, 1, 2}, {1, 1, 2, 2, 3, 2}, {1, 2, 2, 1, 3, 2}, {1, 2, 2, 2, 3, 1}, {1, 1, 3, 2, 2, 2}, // 15 {1, 2, 3, 1, 2, 2}, {1, 2, 3, 2, 2, 1}, {2, 2, 3, 2, 1, 1}, {2, 2, 1, 1, 3, 2}, {2, 2, 1, 2, 3, 1}, // 20 {2, 1, 3, 2, 1, 2}, {2, 2, 3, 1, 1, 2}, {3, 1, 2, 1, 3, 1}, {3, 1, 1, 2, 2, 2}, {3, 2, 1, 1, 2, 2}, // 25 {3, 2, 1, 2, 2, 1}, {3, 1, 2, 2, 1, 2}, {3, 2, 2, 1, 1, 2}, {3, 2, 2, 2, 1, 1}, {2, 1, 2, 1, 2, 3}, // 30 {2, 1, 2, 3, 2, 1}, {2, 3, 2, 1, 2, 1}, {1, 1, 1, 3, 2, 3}, {1, 3, 1, 1, 2, 3}, {1, 3, 1, 3, 2, 1}, // 35 {1, 1, 2, 3, 1, 3}, {1, 3, 2, 1, 1, 3}, {1, 3, 2, 3, 1, 1}, {2, 1, 1, 3, 1, 3}, {2, 3, 1, 1, 1, 3}, // 40 {2, 3, 1, 3, 1, 1}, {1, 1, 2, 1, 3, 3}, {1, 1, 2, 3, 3, 1}, {1, 3, 2, 1, 3, 1}, {1, 1, 3, 1, 2, 3}, // 45 {1, 1, 3, 3, 2, 1}, {1, 3, 3, 1, 2, 1}, {3, 1, 3, 1, 2, 1}, {2, 1, 1, 3, 3, 1}, {2, 3, 1, 1, 3, 1}, // 50 {2, 1, 3, 1, 1, 3}, {2, 1, 3, 3, 1, 1}, {2, 1, 3, 1, 3, 1}, {3, 1, 1, 1, 2, 3}, {3, 1, 1, 3, 2, 1}, // 55 {3, 3, 1, 1, 2, 1}, {3, 1, 2, 1, 1, 3}, {3, 1, 2, 3, 1, 1}, {3, 3, 2, 1, 1, 1}, {3, 1, 4, 1, 1, 1}, // 60 {2, 2, 1, 4, 1, 1}, {4, 3, 1, 1, 1, 1}, {1, 1, 1, 2, 2, 4}, {1, 1, 1, 4, 2, 2}, {1, 2, 1, 1, 2, 4}, // 65 {1, 2, 1, 4, 2, 1}, {1, 4, 1, 1, 2, 2}, {1, 4, 1, 2, 2, 1}, {1, 1, 2, 2, 1, 4}, {1, 1, 2, 4, 1, 2}, // 70 {1, 2, 2, 1, 1, 4}, {1, 2, 2, 4, 1, 1}, {1, 4, 2, 1, 1, 2}, {1, 4, 2, 2, 1, 1}, {2, 4, 1, 2, 1, 1}, // 75 {2, 2, 1, 1, 1, 4}, {4, 1, 3, 1, 1, 1}, {2, 4, 1, 1, 1, 2}, {1, 3, 4, 1, 1, 1}, {1, 1, 1, 2, 4, 2}, // 80 {1, 2, 1, 1, 4, 2}, {1, 2, 1, 2, 4, 1}, {1, 1, 4, 2, 1, 2}, {1, 2, 4, 1, 1, 2}, {1, 2, 4, 2, 1, 1}, // 85 {4, 1, 1, 2, 1, 2}, {4, 2, 1, 1, 1, 2}, {4, 2, 1, 2, 1, 1}, {2, 1, 2, 1, 4, 1}, {2, 1, 4, 1, 2, 1}, // 90 {4, 1, 2, 1, 2, 1}, {1, 1, 1, 1, 4, 3}, {1, 1, 1, 3, 4, 1}, {1, 3, 1, 1, 4, 1}, {1, 1, 4, 1, 1, 3}, // 95 {1, 1, 4, 3, 1, 1}, {4, 1, 1, 1, 1, 3}, {4, 1, 1, 3, 1, 1}, {1, 1, 3, 1, 4, 1}, {1, 1, 4, 1, 3, 1}, // 100 {3, 1, 1, 1, 4, 1}, {4, 1, 1, 1, 3, 1}, {2, 1, 1, 4, 1, 2}, {2, 1, 1, 2, 1, 4}, {2, 1, 1, 2, 3, 2}, // 105 {2, 3, 3, 1, 1, 1, 2} }; private static final int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.25f); private static final int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f); private static final int CODE_SHIFT = 98; private static final int CODE_CODE_C = 99; private static final int CODE_CODE_B = 100; private static final int CODE_CODE_A = 101; private static final int CODE_FNC_1 = 102; private static final int CODE_FNC_2 = 97; private static final int CODE_FNC_3 = 96; private static final int CODE_FNC_4_A = 101; private static final int CODE_FNC_4_B = 100; private static final int CODE_START_A = 103; private static final int CODE_START_B = 104; private static final int CODE_START_C = 105; private static final int CODE_STOP = 106; private static int[] findStartPattern(BitArray row) throws NotFoundException { int width = row.getSize(); int rowOffset = 0; while (rowOffset < width) { if (row.get(rowOffset)) { break; } rowOffset++; } int counterPosition = 0; int[] counters = new int[6]; int patternStart = rowOffset; boolean isWhite = false; int patternLength = counters.length; for (int i = rowOffset; i < width; i++) { boolean pixel = row.get(i); if (pixel ^ isWhite) { counters[counterPosition]++; } else { if (counterPosition == patternLength - 1) { int bestVariance = MAX_AVG_VARIANCE; int bestMatch = -1; for (int startCode = CODE_START_A; startCode <= CODE_START_C; startCode++) { int variance = patternMatchVariance(counters, CODE_PATTERNS[startCode], MAX_INDIVIDUAL_VARIANCE); if (variance < bestVariance) { bestVariance = variance; bestMatch = startCode; } } if (bestMatch >= 0) { // Look for whitespace before start pattern, >= 50% of width of start pattern if (row.isRange(Math.max(0, patternStart - (i - patternStart) / 2), patternStart, false)) { return new int[]{patternStart, i, bestMatch}; } } patternStart += counters[0] + counters[1]; for (int y = 2; y < patternLength; y++) { counters[y - 2] = counters[y]; } counters[patternLength - 2] = 0; counters[patternLength - 1] = 0; counterPosition--; } else { counterPosition++; } counters[counterPosition] = 1; isWhite = !isWhite; } } throw NotFoundException.getNotFoundInstance(); } private static int decodeCode(BitArray row, int[] counters, int rowOffset) throws NotFoundException { recordPattern(row, rowOffset, counters); int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept int bestMatch = -1; for (int d = 0; d < CODE_PATTERNS.length; d++) { int[] pattern = CODE_PATTERNS[d]; int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE); if (variance < bestVariance) { bestVariance = variance; bestMatch = d; } } // TODO We're overlooking the fact that the STOP pattern has 7 values, not 6. if (bestMatch >= 0) { return bestMatch; } else { throw NotFoundException.getNotFoundInstance(); } } public Result decodeRow(int rowNumber, BitArray row, Hashtable hints) throws NotFoundException, FormatException, ChecksumException { int[] startPatternInfo = findStartPattern(row); int startCode = startPatternInfo[2]; int codeSet; switch (startCode) { case CODE_START_A: codeSet = CODE_CODE_A; break; case CODE_START_B: codeSet = CODE_CODE_B; break; case CODE_START_C: codeSet = CODE_CODE_C; break; default: throw FormatException.getFormatInstance(); } boolean done = false; boolean isNextShifted = false; StringBuffer result = new StringBuffer(20); int lastStart = startPatternInfo[0]; int nextStart = startPatternInfo[1]; int[] counters = new int[6]; int lastCode = 0; int code = 0; int checksumTotal = startCode; int multiplier = 0; boolean lastCharacterWasPrintable = true; while (!done) { boolean unshift = isNextShifted; isNextShifted = false; // Save off last code lastCode = code; // Decode another code from image code = decodeCode(row, counters, nextStart); // Remember whether the last code was printable or not (excluding CODE_STOP) if (code != CODE_STOP) { lastCharacterWasPrintable = true; } // Add to checksum computation (if not CODE_STOP of course) if (code != CODE_STOP) { multiplier++; checksumTotal += multiplier * code; } // Advance to where the next code will to start lastStart = nextStart; for (int i = 0; i < counters.length; i++) { nextStart += counters[i]; } // Take care of illegal start codes switch (code) { case CODE_START_A: case CODE_START_B: case CODE_START_C: throw FormatException.getFormatInstance(); } switch (codeSet) { case CODE_CODE_A: if (code < 64) { result.append((char) (' ' + code)); } else if (code < 96) { result.append((char) (code - 64)); } else { // Don't let CODE_STOP, which always appears, affect whether whether we think the last // code was printable or not. if (code != CODE_STOP) { lastCharacterWasPrintable = false; } switch (code) { case CODE_FNC_1: case CODE_FNC_2: case CODE_FNC_3: case CODE_FNC_4_A: // do nothing? break; case CODE_SHIFT: isNextShifted = true; codeSet = CODE_CODE_B; break; case CODE_CODE_B: codeSet = CODE_CODE_B; break; case CODE_CODE_C: codeSet = CODE_CODE_C; break; case CODE_STOP: done = true; break; } } break; case CODE_CODE_B: if (code < 96) { result.append((char) (' ' + code)); } else { if (code != CODE_STOP) { lastCharacterWasPrintable = false; } switch (code) { case CODE_FNC_1: case CODE_FNC_2: case CODE_FNC_3: case CODE_FNC_4_B: // do nothing? break; case CODE_SHIFT: isNextShifted = true; - codeSet = CODE_CODE_C; + codeSet = CODE_CODE_A; break; case CODE_CODE_A: codeSet = CODE_CODE_A; break; case CODE_CODE_C: codeSet = CODE_CODE_C; break; case CODE_STOP: done = true; break; } } break; case CODE_CODE_C: if (code < 100) { if (code < 10) { result.append('0'); } result.append(code); } else { if (code != CODE_STOP) { lastCharacterWasPrintable = false; } switch (code) { case CODE_FNC_1: // do nothing? break; case CODE_CODE_A: codeSet = CODE_CODE_A; break; case CODE_CODE_B: codeSet = CODE_CODE_B; break; case CODE_STOP: done = true; break; } } break; } // Unshift back to another code set if we were shifted if (unshift) { - switch (codeSet) { - case CODE_CODE_A: - codeSet = CODE_CODE_C; - break; - case CODE_CODE_B: - codeSet = CODE_CODE_A; - break; - case CODE_CODE_C: - codeSet = CODE_CODE_B; - break; - } + codeSet = codeSet == CODE_CODE_A ? CODE_CODE_B : CODE_CODE_A; } } // Check for ample whitespace following pattern, but, to do this we first need to remember that // we fudged decoding CODE_STOP since it actually has 7 bars, not 6. There is a black bar left // to read off. Would be slightly better to properly read. Here we just skip it: int width = row.getSize(); while (nextStart < width && row.get(nextStart)) { nextStart++; } if (!row.isRange(nextStart, Math.min(width, nextStart + (nextStart - lastStart) / 2), false)) { throw NotFoundException.getNotFoundInstance(); } // Pull out from sum the value of the penultimate check code checksumTotal -= multiplier * lastCode; // lastCode is the checksum then: if (checksumTotal % 103 != lastCode) { throw ChecksumException.getChecksumInstance(); } // Need to pull out the check digits from string int resultLength = result.length(); // Only bother if the result had at least one character, and if the checksum digit happened to // be a printable character. If it was just interpreted as a control code, nothing to remove. if (resultLength > 0 && lastCharacterWasPrintable) { if (codeSet == CODE_CODE_C) { result.delete(resultLength - 2, resultLength); } else { result.delete(resultLength - 1, resultLength); } } String resultString = result.toString(); if (resultString.length() == 0) { // Almost surely a false positive throw FormatException.getFormatInstance(); } float left = (float) (startPatternInfo[1] + startPatternInfo[0]) / 2.0f; float right = (float) (nextStart + lastStart) / 2.0f; return new Result( resultString, null, new ResultPoint[]{ new ResultPoint(left, (float) rowNumber), new ResultPoint(right, (float) rowNumber)}, BarcodeFormat.CODE_128); } }
false
true
public Result decodeRow(int rowNumber, BitArray row, Hashtable hints) throws NotFoundException, FormatException, ChecksumException { int[] startPatternInfo = findStartPattern(row); int startCode = startPatternInfo[2]; int codeSet; switch (startCode) { case CODE_START_A: codeSet = CODE_CODE_A; break; case CODE_START_B: codeSet = CODE_CODE_B; break; case CODE_START_C: codeSet = CODE_CODE_C; break; default: throw FormatException.getFormatInstance(); } boolean done = false; boolean isNextShifted = false; StringBuffer result = new StringBuffer(20); int lastStart = startPatternInfo[0]; int nextStart = startPatternInfo[1]; int[] counters = new int[6]; int lastCode = 0; int code = 0; int checksumTotal = startCode; int multiplier = 0; boolean lastCharacterWasPrintable = true; while (!done) { boolean unshift = isNextShifted; isNextShifted = false; // Save off last code lastCode = code; // Decode another code from image code = decodeCode(row, counters, nextStart); // Remember whether the last code was printable or not (excluding CODE_STOP) if (code != CODE_STOP) { lastCharacterWasPrintable = true; } // Add to checksum computation (if not CODE_STOP of course) if (code != CODE_STOP) { multiplier++; checksumTotal += multiplier * code; } // Advance to where the next code will to start lastStart = nextStart; for (int i = 0; i < counters.length; i++) { nextStart += counters[i]; } // Take care of illegal start codes switch (code) { case CODE_START_A: case CODE_START_B: case CODE_START_C: throw FormatException.getFormatInstance(); } switch (codeSet) { case CODE_CODE_A: if (code < 64) { result.append((char) (' ' + code)); } else if (code < 96) { result.append((char) (code - 64)); } else { // Don't let CODE_STOP, which always appears, affect whether whether we think the last // code was printable or not. if (code != CODE_STOP) { lastCharacterWasPrintable = false; } switch (code) { case CODE_FNC_1: case CODE_FNC_2: case CODE_FNC_3: case CODE_FNC_4_A: // do nothing? break; case CODE_SHIFT: isNextShifted = true; codeSet = CODE_CODE_B; break; case CODE_CODE_B: codeSet = CODE_CODE_B; break; case CODE_CODE_C: codeSet = CODE_CODE_C; break; case CODE_STOP: done = true; break; } } break; case CODE_CODE_B: if (code < 96) { result.append((char) (' ' + code)); } else { if (code != CODE_STOP) { lastCharacterWasPrintable = false; } switch (code) { case CODE_FNC_1: case CODE_FNC_2: case CODE_FNC_3: case CODE_FNC_4_B: // do nothing? break; case CODE_SHIFT: isNextShifted = true; codeSet = CODE_CODE_C; break; case CODE_CODE_A: codeSet = CODE_CODE_A; break; case CODE_CODE_C: codeSet = CODE_CODE_C; break; case CODE_STOP: done = true; break; } } break; case CODE_CODE_C: if (code < 100) { if (code < 10) { result.append('0'); } result.append(code); } else { if (code != CODE_STOP) { lastCharacterWasPrintable = false; } switch (code) { case CODE_FNC_1: // do nothing? break; case CODE_CODE_A: codeSet = CODE_CODE_A; break; case CODE_CODE_B: codeSet = CODE_CODE_B; break; case CODE_STOP: done = true; break; } } break; } // Unshift back to another code set if we were shifted if (unshift) { switch (codeSet) { case CODE_CODE_A: codeSet = CODE_CODE_C; break; case CODE_CODE_B: codeSet = CODE_CODE_A; break; case CODE_CODE_C: codeSet = CODE_CODE_B; break; } } } // Check for ample whitespace following pattern, but, to do this we first need to remember that // we fudged decoding CODE_STOP since it actually has 7 bars, not 6. There is a black bar left // to read off. Would be slightly better to properly read. Here we just skip it: int width = row.getSize(); while (nextStart < width && row.get(nextStart)) { nextStart++; } if (!row.isRange(nextStart, Math.min(width, nextStart + (nextStart - lastStart) / 2), false)) { throw NotFoundException.getNotFoundInstance(); } // Pull out from sum the value of the penultimate check code checksumTotal -= multiplier * lastCode; // lastCode is the checksum then: if (checksumTotal % 103 != lastCode) { throw ChecksumException.getChecksumInstance(); } // Need to pull out the check digits from string int resultLength = result.length(); // Only bother if the result had at least one character, and if the checksum digit happened to // be a printable character. If it was just interpreted as a control code, nothing to remove. if (resultLength > 0 && lastCharacterWasPrintable) { if (codeSet == CODE_CODE_C) { result.delete(resultLength - 2, resultLength); } else { result.delete(resultLength - 1, resultLength); } } String resultString = result.toString(); if (resultString.length() == 0) { // Almost surely a false positive throw FormatException.getFormatInstance(); } float left = (float) (startPatternInfo[1] + startPatternInfo[0]) / 2.0f; float right = (float) (nextStart + lastStart) / 2.0f; return new Result( resultString, null, new ResultPoint[]{ new ResultPoint(left, (float) rowNumber), new ResultPoint(right, (float) rowNumber)}, BarcodeFormat.CODE_128); }
public Result decodeRow(int rowNumber, BitArray row, Hashtable hints) throws NotFoundException, FormatException, ChecksumException { int[] startPatternInfo = findStartPattern(row); int startCode = startPatternInfo[2]; int codeSet; switch (startCode) { case CODE_START_A: codeSet = CODE_CODE_A; break; case CODE_START_B: codeSet = CODE_CODE_B; break; case CODE_START_C: codeSet = CODE_CODE_C; break; default: throw FormatException.getFormatInstance(); } boolean done = false; boolean isNextShifted = false; StringBuffer result = new StringBuffer(20); int lastStart = startPatternInfo[0]; int nextStart = startPatternInfo[1]; int[] counters = new int[6]; int lastCode = 0; int code = 0; int checksumTotal = startCode; int multiplier = 0; boolean lastCharacterWasPrintable = true; while (!done) { boolean unshift = isNextShifted; isNextShifted = false; // Save off last code lastCode = code; // Decode another code from image code = decodeCode(row, counters, nextStart); // Remember whether the last code was printable or not (excluding CODE_STOP) if (code != CODE_STOP) { lastCharacterWasPrintable = true; } // Add to checksum computation (if not CODE_STOP of course) if (code != CODE_STOP) { multiplier++; checksumTotal += multiplier * code; } // Advance to where the next code will to start lastStart = nextStart; for (int i = 0; i < counters.length; i++) { nextStart += counters[i]; } // Take care of illegal start codes switch (code) { case CODE_START_A: case CODE_START_B: case CODE_START_C: throw FormatException.getFormatInstance(); } switch (codeSet) { case CODE_CODE_A: if (code < 64) { result.append((char) (' ' + code)); } else if (code < 96) { result.append((char) (code - 64)); } else { // Don't let CODE_STOP, which always appears, affect whether whether we think the last // code was printable or not. if (code != CODE_STOP) { lastCharacterWasPrintable = false; } switch (code) { case CODE_FNC_1: case CODE_FNC_2: case CODE_FNC_3: case CODE_FNC_4_A: // do nothing? break; case CODE_SHIFT: isNextShifted = true; codeSet = CODE_CODE_B; break; case CODE_CODE_B: codeSet = CODE_CODE_B; break; case CODE_CODE_C: codeSet = CODE_CODE_C; break; case CODE_STOP: done = true; break; } } break; case CODE_CODE_B: if (code < 96) { result.append((char) (' ' + code)); } else { if (code != CODE_STOP) { lastCharacterWasPrintable = false; } switch (code) { case CODE_FNC_1: case CODE_FNC_2: case CODE_FNC_3: case CODE_FNC_4_B: // do nothing? break; case CODE_SHIFT: isNextShifted = true; codeSet = CODE_CODE_A; break; case CODE_CODE_A: codeSet = CODE_CODE_A; break; case CODE_CODE_C: codeSet = CODE_CODE_C; break; case CODE_STOP: done = true; break; } } break; case CODE_CODE_C: if (code < 100) { if (code < 10) { result.append('0'); } result.append(code); } else { if (code != CODE_STOP) { lastCharacterWasPrintable = false; } switch (code) { case CODE_FNC_1: // do nothing? break; case CODE_CODE_A: codeSet = CODE_CODE_A; break; case CODE_CODE_B: codeSet = CODE_CODE_B; break; case CODE_STOP: done = true; break; } } break; } // Unshift back to another code set if we were shifted if (unshift) { codeSet = codeSet == CODE_CODE_A ? CODE_CODE_B : CODE_CODE_A; } } // Check for ample whitespace following pattern, but, to do this we first need to remember that // we fudged decoding CODE_STOP since it actually has 7 bars, not 6. There is a black bar left // to read off. Would be slightly better to properly read. Here we just skip it: int width = row.getSize(); while (nextStart < width && row.get(nextStart)) { nextStart++; } if (!row.isRange(nextStart, Math.min(width, nextStart + (nextStart - lastStart) / 2), false)) { throw NotFoundException.getNotFoundInstance(); } // Pull out from sum the value of the penultimate check code checksumTotal -= multiplier * lastCode; // lastCode is the checksum then: if (checksumTotal % 103 != lastCode) { throw ChecksumException.getChecksumInstance(); } // Need to pull out the check digits from string int resultLength = result.length(); // Only bother if the result had at least one character, and if the checksum digit happened to // be a printable character. If it was just interpreted as a control code, nothing to remove. if (resultLength > 0 && lastCharacterWasPrintable) { if (codeSet == CODE_CODE_C) { result.delete(resultLength - 2, resultLength); } else { result.delete(resultLength - 1, resultLength); } } String resultString = result.toString(); if (resultString.length() == 0) { // Almost surely a false positive throw FormatException.getFormatInstance(); } float left = (float) (startPatternInfo[1] + startPatternInfo[0]) / 2.0f; float right = (float) (nextStart + lastStart) / 2.0f; return new Result( resultString, null, new ResultPoint[]{ new ResultPoint(left, (float) rowNumber), new ResultPoint(right, (float) rowNumber)}, BarcodeFormat.CODE_128); }
diff --git a/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/Quest11a.java b/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/Quest11a.java index de34cde..4624cfe 100644 --- a/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/Quest11a.java +++ b/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/Quest11a.java @@ -1,49 +1,49 @@ package org.akquinet.audit.bsi.httpd; import org.akquinet.audit.FormattedConsole; import org.akquinet.audit.YesNoQuestion; public class Quest11a implements YesNoQuestion { private static final String _id = "Quest11a"; private static final FormattedConsole _console = FormattedConsole.getDefault(); private static final FormattedConsole.OutputLevel _level = FormattedConsole.OutputLevel.Q2; public Quest11a() { } /** * checks whether there are any Include-directives in the config file */ @Override public boolean answer() { _console.println(FormattedConsole.OutputLevel.HEADING, "----" + _id + "----"); boolean ret = _console.askYesNoQuestion(_level, "Have you properly set up a chroot environment for the apache httpd server which will block access outside of the servers root directory?"); if(ret) { ret = _console.askYesNoQuestion(_level, "Have recently checked it's configuration?"); if(!ret) { _console.println(_level, "Please check that configuration. For now I will assume the chroot doesn't work properly."); } } _console.printAnswer(_level, ret, ret ? "Ok this should block access to files outside of the servers root directory." : "No chroot - it may be possible to access files outside of the servers root directory if not sealed otherwise."); - return false; + return ret; } @Override public boolean isCritical() { return false; } @Override public String getID() { return _id; } }
true
true
public boolean answer() { _console.println(FormattedConsole.OutputLevel.HEADING, "----" + _id + "----"); boolean ret = _console.askYesNoQuestion(_level, "Have you properly set up a chroot environment for the apache httpd server which will block access outside of the servers root directory?"); if(ret) { ret = _console.askYesNoQuestion(_level, "Have recently checked it's configuration?"); if(!ret) { _console.println(_level, "Please check that configuration. For now I will assume the chroot doesn't work properly."); } } _console.printAnswer(_level, ret, ret ? "Ok this should block access to files outside of the servers root directory." : "No chroot - it may be possible to access files outside of the servers root directory if not sealed otherwise."); return false; }
public boolean answer() { _console.println(FormattedConsole.OutputLevel.HEADING, "----" + _id + "----"); boolean ret = _console.askYesNoQuestion(_level, "Have you properly set up a chroot environment for the apache httpd server which will block access outside of the servers root directory?"); if(ret) { ret = _console.askYesNoQuestion(_level, "Have recently checked it's configuration?"); if(!ret) { _console.println(_level, "Please check that configuration. For now I will assume the chroot doesn't work properly."); } } _console.printAnswer(_level, ret, ret ? "Ok this should block access to files outside of the servers root directory." : "No chroot - it may be possible to access files outside of the servers root directory if not sealed otherwise."); return ret; }
diff --git a/email2/src/com/android/email/NotificationController.java b/email2/src/com/android/email/NotificationController.java index c0073f261..42112fbd7 100644 --- a/email2/src/com/android/email/NotificationController.java +++ b/email2/src/com/android/email/NotificationController.java @@ -1,1067 +1,1070 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.email; import android.app.Notification; import android.app.Notification.Builder; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.AudioManager; import android.net.Uri; import android.os.Handler; import android.os.Looper; import android.os.Process; import android.text.SpannableString; import android.text.TextUtils; import android.text.style.TextAppearanceSpan; import android.util.Log; import com.android.email.activity.ContactStatusLoader; import com.android.email.activity.setup.AccountSecurity; import com.android.email.activity.setup.AccountSettings; import com.android.email.provider.EmailProvider; import com.android.email.service.EmailBroadcastProcessorService; import com.android.email2.ui.MailActivityEmail; import com.android.emailcommon.Logging; import com.android.emailcommon.mail.Address; import com.android.emailcommon.provider.Account; import com.android.emailcommon.provider.EmailContent; import com.android.emailcommon.provider.EmailContent.Attachment; import com.android.emailcommon.provider.EmailContent.MailboxColumns; import com.android.emailcommon.provider.EmailContent.Message; import com.android.emailcommon.provider.Mailbox; import com.android.emailcommon.utility.EmailAsyncTask; import com.android.emailcommon.utility.Utility; import com.android.mail.providers.Conversation; import com.android.mail.providers.Folder; import com.android.mail.providers.UIProvider; import com.android.mail.utils.Utils; import com.google.common.annotations.VisibleForTesting; import java.util.HashMap; import java.util.HashSet; /** * Class that manages notifications. */ public class NotificationController { private static final String TAG = "NotificationController"; /** Reserved for {@link com.android.exchange.CalendarSyncEnabler} */ @SuppressWarnings("unused") private static final int NOTIFICATION_ID_EXCHANGE_CALENDAR_ADDED = 2; private static final int NOTIFICATION_ID_ATTACHMENT_WARNING = 3; private static final int NOTIFICATION_ID_PASSWORD_EXPIRING = 4; private static final int NOTIFICATION_ID_PASSWORD_EXPIRED = 5; private static final int NOTIFICATION_ID_BASE_MASK = 0xF0000000; private static final int NOTIFICATION_ID_BASE_NEW_MESSAGES = 0x10000000; private static final int NOTIFICATION_ID_BASE_LOGIN_WARNING = 0x20000000; private static final int NOTIFICATION_ID_BASE_SECURITY_NEEDED = 0x30000000; private static final int NOTIFICATION_ID_BASE_SECURITY_CHANGED = 0x40000000; /** Selection to retrieve accounts that should we notify user for changes */ private final static String NOTIFIED_ACCOUNT_SELECTION = Account.FLAGS + "&" + Account.FLAGS_NOTIFY_NEW_MAIL + " != 0"; private static final String NEW_MAIL_MAILBOX_ID = "com.android.email.new_mail.mailboxId"; private static final String NEW_MAIL_MESSAGE_ID = "com.android.email.new_mail.messageId"; private static final String NEW_MAIL_MESSAGE_COUNT = "com.android.email.new_mail.messageCount"; private static final String NEW_MAIL_UNREAD_COUNT = "com.android.email.new_mail.unreadCount"; private static NotificationThread sNotificationThread; private static Handler sNotificationHandler; private static NotificationController sInstance; private final Context mContext; private final NotificationManager mNotificationManager; private final AudioManager mAudioManager; private final Bitmap mGenericSenderIcon; private final Bitmap mGenericMultipleSenderIcon; private final Clock mClock; /** Maps account id to its observer */ private final HashMap<Long, ContentObserver> mNotificationMap; private ContentObserver mAccountObserver; /** * Timestamp indicating when the last message notification sound was played. * Used for throttling. */ private long mLastMessageNotifyTime; /** * Minimum interval between notification sounds. * Since a long sync (either on account setup or after a long period of being offline) can cause * several notifications consecutively, it can be pretty overwhelming to get a barrage of * notification sounds. Throttle them using this value. */ private static final long MIN_SOUND_INTERVAL_MS = 15 * 1000; // 15 seconds /** Constructor */ @VisibleForTesting NotificationController(Context context, Clock clock) { mContext = context.getApplicationContext(); mNotificationManager = (NotificationManager) context.getSystemService( Context.NOTIFICATION_SERVICE); mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); mGenericSenderIcon = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_contact_picture); mGenericMultipleSenderIcon = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_notification_multiple_mail_holo_dark); mClock = clock; mNotificationMap = new HashMap<Long, ContentObserver>(); } /** Singleton access */ public static synchronized NotificationController getInstance(Context context) { if (sInstance == null) { sInstance = new NotificationController(context, Clock.INSTANCE); } return sInstance; } /** * Return whether or not a notification, based on the passed-in id, needs to be "ongoing" * @param notificationId the notification id to check * @return whether or not the notification must be "ongoing" */ private boolean needsOngoingNotification(int notificationId) { // "Security needed" must be ongoing so that the user doesn't close it; otherwise, sync will // be prevented until a reboot. Consider also doing this for password expired. return (notificationId & NOTIFICATION_ID_BASE_MASK) == NOTIFICATION_ID_BASE_SECURITY_NEEDED; } /** * Returns a {@link Notification.Builder}} for an event with the given account. The account * contains specific rules on ring tone usage and these will be used to modify the notification * behaviour. * * @param accountId The id of the account this notification is being built for. * @param ticker Text displayed when the notification is first shown. May be {@code null}. * @param title The first line of text. May NOT be {@code null}. * @param contentText The second line of text. May NOT be {@code null}. * @param intent The intent to start if the user clicks on the notification. * @param largeIcon A large icon. May be {@code null} * @param number A number to display using {@link Builder#setNumber(int)}. May * be {@code null}. * @param enableAudio If {@code false}, do not play any sound. Otherwise, play sound according * to the settings for the given account. * @return A {@link Notification} that can be sent to the notification service. */ private Notification.Builder createBaseAccountNotificationBuilder(long accountId, String ticker, CharSequence title, String contentText, Intent intent, Bitmap largeIcon, Integer number, boolean enableAudio, boolean ongoing) { // Pending Intent PendingIntent pending = null; if (intent != null) { pending = PendingIntent.getActivity( mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } // NOTE: the ticker is not shown for notifications in the Holo UX final Notification.Builder builder = new Notification.Builder(mContext) .setContentTitle(title) .setContentText(contentText) .setContentIntent(pending) .setLargeIcon(largeIcon) .setNumber(number == null ? 0 : number) .setSmallIcon(R.drawable.stat_notify_email_generic) .setWhen(mClock.getTime()) .setTicker(ticker) .setOngoing(ongoing); if (enableAudio) { Account account = Account.restoreAccountWithId(mContext, accountId); setupSoundAndVibration(builder, account); } return builder; } /** * Generic notifier for any account. Uses notification rules from account. * * @param accountId The account id this notification is being built for. * @param ticker Text displayed when the notification is first shown. May be {@code null}. * @param title The first line of text. May NOT be {@code null}. * @param contentText The second line of text. May NOT be {@code null}. * @param intent The intent to start if the user clicks on the notification. * @param notificationId The ID of the notification to register with the service. */ private void showNotification(long accountId, String ticker, String title, String contentText, Intent intent, int notificationId) { final Notification.Builder builder = createBaseAccountNotificationBuilder(accountId, ticker, title, contentText, intent, null, null, true, needsOngoingNotification(notificationId)); mNotificationManager.notify(notificationId, builder.getNotification()); } /** * Returns a notification ID for new message notifications for the given account. */ private int getNewMessageNotificationId(long mailboxId) { // We assume accountId will always be less than 0x0FFFFFFF; is there a better way? return (int) (NOTIFICATION_ID_BASE_NEW_MESSAGES + mailboxId); } /** * Tells the notification controller if it should be watching for changes to the message table. * This is the main life cycle method for message notifications. When we stop observing * database changes, we save the state [e.g. message ID and count] of the most recent * notification shown to the user. And, when we start observing database changes, we restore * the saved state. * @param watch If {@code true}, we register observers for all accounts whose settings have * notifications enabled. Otherwise, all observers are unregistered. */ public void watchForMessages(final boolean watch) { if (MailActivityEmail.DEBUG) { Log.d(Logging.LOG_TAG, "Notifications being toggled: " + watch); } // Don't create the thread if we're only going to stop watching if (!watch && sNotificationThread == null) return; ensureHandlerExists(); // Run this on the message notification handler sNotificationHandler.post(new Runnable() { @Override public void run() { ContentResolver resolver = mContext.getContentResolver(); if (!watch) { unregisterMessageNotification(Account.ACCOUNT_ID_COMBINED_VIEW); if (mAccountObserver != null) { resolver.unregisterContentObserver(mAccountObserver); mAccountObserver = null; } // tear down the event loop sNotificationThread.quit(); sNotificationThread = null; return; } // otherwise, start new observers for all notified accounts registerMessageNotification(Account.ACCOUNT_ID_COMBINED_VIEW); // If we're already observing account changes, don't do anything else if (mAccountObserver == null) { if (MailActivityEmail.DEBUG) { Log.i(Logging.LOG_TAG, "Observing account changes for notifications"); } mAccountObserver = new AccountContentObserver(sNotificationHandler, mContext); resolver.registerContentObserver(Account.NOTIFIER_URI, true, mAccountObserver); } } }); } /** * Ensures the notification handler exists and is ready to handle requests. */ private static synchronized void ensureHandlerExists() { if (sNotificationThread == null) { sNotificationThread = new NotificationThread(); sNotificationHandler = new Handler(sNotificationThread.getLooper()); } } /** * Registers an observer for changes to mailboxes in the given account. * NOTE: This must be called on the notification handler thread. * @param accountId The ID of the account to register the observer for. May be * {@link Account#ACCOUNT_ID_COMBINED_VIEW} to register observers for all * accounts that allow for user notification. */ private void registerMessageNotification(long accountId) { ContentResolver resolver = mContext.getContentResolver(); if (accountId == Account.ACCOUNT_ID_COMBINED_VIEW) { Cursor c = resolver.query( Account.CONTENT_URI, EmailContent.ID_PROJECTION, NOTIFIED_ACCOUNT_SELECTION, null, null); try { while (c.moveToNext()) { long id = c.getLong(EmailContent.ID_PROJECTION_COLUMN); registerMessageNotification(id); } } finally { c.close(); } } else { ContentObserver obs = mNotificationMap.get(accountId); if (obs != null) return; // we're already observing; nothing to do if (MailActivityEmail.DEBUG) { Log.i(Logging.LOG_TAG, "Registering for notifications for account " + accountId); } ContentObserver observer = new MessageContentObserver( sNotificationHandler, mContext, accountId); resolver.registerContentObserver(Message.NOTIFIER_URI, true, observer); mNotificationMap.put(accountId, observer); // Now, ping the observer for any initial notifications observer.onChange(true); } } /** * Unregisters the observer for the given account. If the specified account does not have * a registered observer, no action is performed. This will not clear any existing notification * for the specified account. Use {@link NotificationManager#cancel(int)}. * NOTE: This must be called on the notification handler thread. * @param accountId The ID of the account to unregister from. To unregister all accounts that * have observers, specify an ID of {@link Account#ACCOUNT_ID_COMBINED_VIEW}. */ private void unregisterMessageNotification(long accountId) { ContentResolver resolver = mContext.getContentResolver(); if (accountId == Account.ACCOUNT_ID_COMBINED_VIEW) { if (MailActivityEmail.DEBUG) { Log.i(Logging.LOG_TAG, "Unregistering notifications for all accounts"); } // cancel all existing message observers for (ContentObserver observer : mNotificationMap.values()) { resolver.unregisterContentObserver(observer); } mNotificationMap.clear(); } else { if (MailActivityEmail.DEBUG) { Log.i(Logging.LOG_TAG, "Unregistering notifications for account " + accountId); } ContentObserver observer = mNotificationMap.remove(accountId); if (observer != null) { resolver.unregisterContentObserver(observer); } } } /** * Returns a picture of the sender of the given message. If no picture is available, returns * {@code null}. * * NOTE: DO NOT CALL THIS METHOD FROM THE UI THREAD (DATABASE ACCESS) */ private Bitmap getSenderPhoto(Message message) { Address sender = Address.unpackFirst(message.mFrom); if (sender == null) { return null; } String email = sender.getAddress(); if (TextUtils.isEmpty(email)) { return null; } Bitmap photo = ContactStatusLoader.getContactInfo(mContext, email).mPhoto; if (photo != null) { final Resources res = mContext.getResources(); final int idealIconHeight = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height); final int idealIconWidth = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width); if (photo.getHeight() < idealIconHeight) { // We should scale this image to fit the intended size photo = Bitmap.createScaledBitmap( photo, idealIconWidth, idealIconHeight, true); } } return photo; } public static final String EXTRA_ACCOUNT = "account"; public static final String EXTRA_CONVERSATION = "conversationUri"; public static final String EXTRA_FOLDER = "folder"; private Intent createViewConversationIntent(Conversation conversation, Folder folder, com.android.mail.providers.Account account) { final Intent intent = new Intent(Intent.ACTION_VIEW); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); intent.setDataAndType(conversation.uri, account.mimeType); intent.putExtra(EXTRA_ACCOUNT, account); intent.putExtra(EXTRA_FOLDER, folder); intent.putExtra(EXTRA_CONVERSATION, conversation); return intent; } private Cursor getUiCursor(Uri uri, String[] projection) { Cursor c = mContext.getContentResolver().query(uri, projection, null, null, null); if (c == null) return null; if (c.moveToFirst()) { return c; } else { c.close(); return null; } } private Intent createViewConversationIntent(Message message) { Cursor c = getUiCursor(EmailProvider.uiUri("uiaccount", message.mAccountKey), UIProvider.ACCOUNTS_PROJECTION); if (c == null) { Log.w(TAG, "Can't find account for message " + message.mId); return null; } com.android.mail.providers.Account acct = new com.android.mail.providers.Account(c); c.close(); c = getUiCursor(EmailProvider.uiUri("uifolder", message.mMailboxKey), UIProvider.FOLDERS_PROJECTION); if (c == null) { Log.w(TAG, "Can't find folder for message " + message.mId + ", folder " + message.mMailboxKey); return null; } Folder folder = new Folder(c); c.close(); c = getUiCursor(EmailProvider.uiUri("uiconversation", message.mId), UIProvider.CONVERSATION_PROJECTION); if (c == null) { Log.w(TAG, "Can't find conversation for message " + message.mId); return null; } Conversation conv = new Conversation(c); c.close(); return createViewConversationIntent(conv, folder, acct); } /** * Returns a "new message" notification for the given account. * * NOTE: DO NOT CALL THIS METHOD FROM THE UI THREAD (DATABASE ACCESS) */ @VisibleForTesting Notification createNewMessageNotification(long mailboxId, long newMessageId, int unseenMessageCount, int unreadCount) { final Mailbox mailbox = Mailbox.restoreMailboxWithId(mContext, mailboxId); if (mailbox == null) { return null; } final Account account = Account.restoreAccountWithId(mContext, mailbox.mAccountKey); if (account == null) { return null; } // Get the latest message final Message message = Message.restoreMessageWithId(mContext, newMessageId); if (message == null) { return null; // no message found??? } String senderName = Address.toFriendly(Address.unpack(message.mFrom)); if (senderName == null) { senderName = ""; // Happens when a message has no from. } final boolean multipleUnseen = unseenMessageCount > 1; final Bitmap senderPhoto = multipleUnseen ? mGenericMultipleSenderIcon : getSenderPhoto(message); final SpannableString title = getNewMessageTitle(senderName, unseenMessageCount); // TODO: add in display name on the second line for the text, once framework supports // multiline texts. // Show account name if an inbox; otherwise mailbox name final String text = multipleUnseen ? ((mailbox.mType == Mailbox.TYPE_INBOX) ? account.mDisplayName : mailbox.mDisplayName) : message.mSubject; final Bitmap largeIcon = senderPhoto != null ? senderPhoto : mGenericSenderIcon; final Integer number = unreadCount > 1 ? unreadCount : null; Intent intent = createViewConversationIntent(message); if (intent == null) { return null; } intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_TASK_ON_HOME); long now = mClock.getTime(); boolean enableAudio = (now - mLastMessageNotifyTime) > MIN_SOUND_INTERVAL_MS; final Notification.Builder builder = createBaseAccountNotificationBuilder( mailbox.mAccountKey, title.toString(), title, text, intent, largeIcon, number, enableAudio, false); if (Utils.isRunningJellybeanOrLater()) { // For a new-style notification if (multipleUnseen) { final Cursor messageCursor = mContext.getContentResolver().query(ContentUris.withAppendedId( EmailContent.MAILBOX_NOTIFICATION_URI, mailbox.mAccountKey), EmailContent.NOTIFICATION_PROJECTION, null, null, null); - if (messageCursor != null && messageCursor.getCount() > 0) { - try { + try { + if (messageCursor != null && messageCursor.getCount() > 0) { final int maxNumDigestItems = mContext.getResources().getInteger( R.integer.max_num_notification_digest_items); // The body of the notification is the account name, or the label name. builder.setSubText(text); Notification.InboxStyle digest = new Notification.InboxStyle(builder); digest.setBigContentTitle(title); int numDigestItems = 0; // We can assume that the current position of the cursor is on the // newest message + messageCursor.moveToFirst(); do { final long messageId = messageCursor.getLong(EmailContent.ID_PROJECTION_COLUMN); // Get the latest message final Message digestMessage = Message.restoreMessageWithId(mContext, messageId); if (digestMessage != null) { final CharSequence digestLine = getSingleMessageInboxLine(mContext, digestMessage); digest.addLine(digestLine); numDigestItems++; } } while (numDigestItems <= maxNumDigestItems && messageCursor.moveToNext()); // We want to clear the content text in this case. The content text would // have been set in createBaseAccountNotificationBuilder, but since the // same string was set in as the subtext, we don't want to show a // duplicate string. builder.setContentText(null); - } finally { + } + } finally { + if (messageCursor != null) { messageCursor.close(); } } } else { // The notification content will be the subject of the conversation. builder.setContentText(getSingleMessageLittleText(mContext, message.mSubject)); // The notification subtext will be the subject of the conversation for inbox // notifications, or will based on the the label name for user label notifications. builder.setSubText(account.mDisplayName); final Notification.BigTextStyle bigText = new Notification.BigTextStyle(builder); bigText.bigText(getSingleMessageBigText(mContext, message)); } } mLastMessageNotifyTime = now; return builder.getNotification(); } /** * Sets the bigtext for a notification for a single new conversation * @param context * @param message New message that triggered the notification. * @return a {@link CharSequence} suitable for use in {@link Notification.BigTextStyle} */ private static CharSequence getSingleMessageInboxLine(Context context, Message message) { final String subject = message.mSubject; final String snippet = message.mSnippet; final String senders = Address.toFriendly(Address.unpack(message.mFrom)); final String subjectSnippet = !TextUtils.isEmpty(subject) ? subject : snippet; final TextAppearanceSpan notificationPrimarySpan = new TextAppearanceSpan(context, R.style.NotificationPrimaryText); if (TextUtils.isEmpty(senders)) { // If the senders are empty, just use the subject/snippet. return subjectSnippet; } else if (TextUtils.isEmpty(subjectSnippet)) { // If the subject/snippet is empty, just use the senders. final SpannableString spannableString = new SpannableString(senders); spannableString.setSpan(notificationPrimarySpan, 0, senders.length(), 0); return spannableString; } else { final String formatString = context.getResources().getString( R.string.multiple_new_message_notification_item); final TextAppearanceSpan notificationSecondarySpan = new TextAppearanceSpan(context, R.style.NotificationSecondaryText); final String instantiatedString = String.format(formatString, senders, subjectSnippet); final SpannableString spannableString = new SpannableString(instantiatedString); final boolean isOrderReversed = formatString.indexOf("%2$s") < formatString.indexOf("%1$s"); final int primaryOffset = (isOrderReversed ? instantiatedString.lastIndexOf(senders) : instantiatedString.indexOf(senders)); final int secondaryOffset = (isOrderReversed ? instantiatedString.lastIndexOf(subjectSnippet) : instantiatedString.indexOf(subjectSnippet)); spannableString.setSpan(notificationPrimarySpan, primaryOffset, primaryOffset + senders.length(), 0); spannableString.setSpan(notificationSecondarySpan, secondaryOffset, secondaryOffset + subjectSnippet.length(), 0); return spannableString; } } /** * Sets the bigtext for a notification for a single new conversation * @param context * @param subject Subject of the new message that triggered the notification * @return a {@link CharSequence} suitable for use in {@link Notification.ContentText} */ private static CharSequence getSingleMessageLittleText(Context context, String subject) { if (subject == null) { return null; } final TextAppearanceSpan notificationSubjectSpan = new TextAppearanceSpan( context, R.style.NotificationPrimaryText); final SpannableString spannableString = new SpannableString(subject); spannableString.setSpan(notificationSubjectSpan, 0, subject.length(), 0); return spannableString; } /** * Sets the bigtext for a notification for a single new conversation * @param context * @param message New message that triggered the notification * @return a {@link CharSequence} suitable for use in {@link Notification.BigTextStyle} */ private static CharSequence getSingleMessageBigText(Context context, Message message) { final TextAppearanceSpan notificationSubjectSpan = new TextAppearanceSpan( context, R.style.NotificationPrimaryText); final String subject = message.mSubject; final String snippet = message.mSnippet; if (TextUtils.isEmpty(subject)) { // If the subject is empty, just use the snippet. return snippet; } else if (TextUtils.isEmpty(snippet)) { // If the snippet is empty, just use the subject. final SpannableString spannableString = new SpannableString(subject); spannableString.setSpan(notificationSubjectSpan, 0, subject.length(), 0); return spannableString; } else { final String notificationBigTextFormat = context.getResources().getString( R.string.single_new_message_notification_big_text); // Localizers may change the order of the parameters, look at how the format // string is structured. final boolean isSubjectFirst = notificationBigTextFormat.indexOf("%2$s") > notificationBigTextFormat.indexOf("%1$s"); final String bigText = String.format(notificationBigTextFormat, subject, snippet); final SpannableString spannableString = new SpannableString(bigText); final int subjectOffset = (isSubjectFirst ? bigText.indexOf(subject) : bigText.lastIndexOf(subject)); spannableString.setSpan(notificationSubjectSpan, subjectOffset, subjectOffset + subject.length(), 0); return spannableString; } } /** * Creates a notification title for a new message. If there is only a single message, * show the sender name. Otherwise, show "X new messages". */ @VisibleForTesting SpannableString getNewMessageTitle(String sender, int unseenCount) { String title; if (unseenCount > 1) { title = String.format( mContext.getString(R.string.notification_multiple_new_messages_fmt), unseenCount); } else { title = sender; } return new SpannableString(title); } /** Returns the system's current ringer mode */ @VisibleForTesting int getRingerMode() { return mAudioManager.getRingerMode(); } /** Sets up the notification's sound and vibration based upon account details. */ @VisibleForTesting void setupSoundAndVibration(Notification.Builder builder, Account account) { final int flags = account.mFlags; final String ringtoneUri = account.mRingtoneUri; final boolean vibrate = (flags & Account.FLAGS_VIBRATE_ALWAYS) != 0; final boolean vibrateWhenSilent = (flags & Account.FLAGS_VIBRATE_WHEN_SILENT) != 0; final boolean isRingerSilent = getRingerMode() != AudioManager.RINGER_MODE_NORMAL; int defaults = Notification.DEFAULT_LIGHTS; if (vibrate || (vibrateWhenSilent && isRingerSilent)) { defaults |= Notification.DEFAULT_VIBRATE; } builder.setSound((ringtoneUri == null) ? null : Uri.parse(ringtoneUri)) .setDefaults(defaults); } /** * Show (or update) a notification that the given attachment could not be forwarded. This * is a very unusual case, and perhaps we shouldn't even send a notification. For now, * it's helpful for debugging. * * NOTE: DO NOT CALL THIS METHOD FROM THE UI THREAD (DATABASE ACCESS) */ public void showDownloadForwardFailedNotification(Attachment attachment) { Message message = Message.restoreMessageWithId(mContext, attachment.mMessageKey); if (message == null) return; Mailbox mailbox = Mailbox.restoreMailboxWithId(mContext, message.mMailboxKey); showNotification(mailbox.mAccountKey, mContext.getString(R.string.forward_download_failed_ticker), mContext.getString(R.string.forward_download_failed_title), attachment.mFileName, null, NOTIFICATION_ID_ATTACHMENT_WARNING); } /** * Returns a notification ID for login failed notifications for the given account account. */ private int getLoginFailedNotificationId(long accountId) { return NOTIFICATION_ID_BASE_LOGIN_WARNING + (int)accountId; } /** * Show (or update) a notification that there was a login failure for the given account. * * NOTE: DO NOT CALL THIS METHOD FROM THE UI THREAD (DATABASE ACCESS) */ public void showLoginFailedNotification(long accountId) { final Account account = Account.restoreAccountWithId(mContext, accountId); if (account == null) return; final Mailbox mailbox = Mailbox.restoreMailboxOfType(mContext, account.mId, Mailbox.TYPE_INBOX); if (mailbox == null) return; showNotification(mailbox.mAccountKey, mContext.getString(R.string.login_failed_ticker, account.mDisplayName), mContext.getString(R.string.login_failed_title), account.getDisplayName(), AccountSettings.createAccountSettingsIntent(mContext, accountId, account.mDisplayName), getLoginFailedNotificationId(accountId)); } /** * Cancels the login failed notification for the given account. */ public void cancelLoginFailedNotification(long accountId) { mNotificationManager.cancel(getLoginFailedNotificationId(accountId)); } /** * Cancels the new message notification for a given mailbox */ public void cancelNewMessageNotification(long mailboxId) { mNotificationManager.cancel(getNewMessageNotificationId(mailboxId)); } /** * Show (or update) a notification that the user's password is expiring. The given account * is used to update the display text, but, all accounts share the same notification ID. * * NOTE: DO NOT CALL THIS METHOD FROM THE UI THREAD (DATABASE ACCESS) */ public void showPasswordExpiringNotification(long accountId) { Account account = Account.restoreAccountWithId(mContext, accountId); if (account == null) return; Intent intent = AccountSecurity.actionDevicePasswordExpirationIntent(mContext, accountId, false); String accountName = account.getDisplayName(); String ticker = mContext.getString(R.string.password_expire_warning_ticker_fmt, accountName); String title = mContext.getString(R.string.password_expire_warning_content_title); showNotification(accountId, ticker, title, accountName, intent, NOTIFICATION_ID_PASSWORD_EXPIRING); } /** * Show (or update) a notification that the user's password has expired. The given account * is used to update the display text, but, all accounts share the same notification ID. * * NOTE: DO NOT CALL THIS METHOD FROM THE UI THREAD (DATABASE ACCESS) */ public void showPasswordExpiredNotification(long accountId) { Account account = Account.restoreAccountWithId(mContext, accountId); if (account == null) return; Intent intent = AccountSecurity.actionDevicePasswordExpirationIntent(mContext, accountId, true); String accountName = account.getDisplayName(); String ticker = mContext.getString(R.string.password_expired_ticker); String title = mContext.getString(R.string.password_expired_content_title); showNotification(accountId, ticker, title, accountName, intent, NOTIFICATION_ID_PASSWORD_EXPIRED); } /** * Cancels any password expire notifications [both expired & expiring]. */ public void cancelPasswordExpirationNotifications() { mNotificationManager.cancel(NOTIFICATION_ID_PASSWORD_EXPIRING); mNotificationManager.cancel(NOTIFICATION_ID_PASSWORD_EXPIRED); } /** * Show (or update) a security needed notification. If tapped, the user is taken to a * dialog asking whether he wants to update his settings. */ public void showSecurityNeededNotification(Account account) { Intent intent = AccountSecurity.actionUpdateSecurityIntent(mContext, account.mId, true); String accountName = account.getDisplayName(); String ticker = mContext.getString(R.string.security_needed_ticker_fmt, accountName); String title = mContext.getString(R.string.security_notification_content_update_title); showNotification(account.mId, ticker, title, accountName, intent, (int)(NOTIFICATION_ID_BASE_SECURITY_NEEDED + account.mId)); } /** * Show (or update) a security changed notification. If tapped, the user is taken to the * account settings screen where he can view the list of enforced policies */ public void showSecurityChangedNotification(Account account) { Intent intent = AccountSettings.createAccountSettingsIntent(mContext, account.mId, null); String accountName = account.getDisplayName(); String ticker = mContext.getString(R.string.security_changed_ticker_fmt, accountName); String title = mContext.getString(R.string.security_notification_content_change_title); showNotification(account.mId, ticker, title, accountName, intent, (int)(NOTIFICATION_ID_BASE_SECURITY_CHANGED + account.mId)); } /** * Show (or update) a security unsupported notification. If tapped, the user is taken to the * account settings screen where he can view the list of unsupported policies */ public void showSecurityUnsupportedNotification(Account account) { Intent intent = AccountSettings.createAccountSettingsIntent(mContext, account.mId, null); String accountName = account.getDisplayName(); String ticker = mContext.getString(R.string.security_unsupported_ticker_fmt, accountName); String title = mContext.getString(R.string.security_notification_content_unsupported_title); showNotification(account.mId, ticker, title, accountName, intent, (int)(NOTIFICATION_ID_BASE_SECURITY_NEEDED + account.mId)); } /** * Cancels all security needed notifications. */ public void cancelSecurityNeededNotification() { EmailAsyncTask.runAsyncParallel(new Runnable() { @Override public void run() { Cursor c = mContext.getContentResolver().query(Account.CONTENT_URI, Account.ID_PROJECTION, null, null, null); try { while (c.moveToNext()) { long id = c.getLong(Account.ID_PROJECTION_COLUMN); mNotificationManager.cancel( (int)(NOTIFICATION_ID_BASE_SECURITY_NEEDED + id)); } } finally { c.close(); } }}); } /** * Observer invoked whenever a message we're notifying the user about changes. */ private static class MessageContentObserver extends ContentObserver { private final Context mContext; private final long mAccountId; public MessageContentObserver( Handler handler, Context context, long accountId) { super(handler); mContext = context; mAccountId = accountId; } @Override public void onChange(boolean selfChange) { ContentObserver observer = sInstance.mNotificationMap.get(mAccountId); Account account = Account.restoreAccountWithId(mContext, mAccountId); if (observer == null || account == null) { Log.w(Logging.LOG_TAG, "Couldn't find account for changed message notification"); return; } ContentResolver resolver = mContext.getContentResolver(); Cursor c = resolver.query(ContentUris.withAppendedId( EmailContent.MAILBOX_NOTIFICATION_URI, mAccountId), EmailContent.NOTIFICATION_PROJECTION, null, null, null); try { while (c.moveToNext()) { long mailboxId = c.getLong(EmailContent.NOTIFICATION_MAILBOX_ID_COLUMN); if (mailboxId == 0) continue; int messageCount = c.getInt(EmailContent.NOTIFICATION_MAILBOX_MESSAGE_COUNT_COLUMN); int unreadCount = c.getInt(EmailContent.NOTIFICATION_MAILBOX_UNREAD_COUNT_COLUMN); Mailbox m = Mailbox.restoreMailboxWithId(mContext, mailboxId); long newMessageId = Utility.getFirstRowLong(mContext, ContentUris.withAppendedId( EmailContent.MAILBOX_MOST_RECENT_MESSAGE_URI, mailboxId), Message.ID_COLUMN_PROJECTION, null, null, null, Message.ID_MAILBOX_COLUMN_ID, -1L); Log.d(Logging.LOG_TAG, "Changes to " + account.mDisplayName + "/" + m.mDisplayName + ", count: " + messageCount + ", lastNotified: " + m.mLastNotifiedMessageKey + ", mostRecent: " + newMessageId); // Broadcast intent here Intent i = new Intent(EmailBroadcastProcessorService.ACTION_NOTIFY_NEW_MAIL); // Required by UIProvider i.setType(EmailProvider.EMAIL_APP_MIME_TYPE); i.putExtra(UIProvider.UpdateNotificationExtras.EXTRA_FOLDER, Uri.parse(EmailProvider.uiUriString("uifolder", mailboxId))); i.putExtra(UIProvider.UpdateNotificationExtras.EXTRA_ACCOUNT, Uri.parse(EmailProvider.uiUriString("uiaccount", m.mAccountKey))); i.putExtra(UIProvider.UpdateNotificationExtras.EXTRA_UPDATED_UNREAD_COUNT, unreadCount); // Required by our notification controller i.putExtra(NEW_MAIL_MAILBOX_ID, mailboxId); i.putExtra(NEW_MAIL_MESSAGE_ID, newMessageId); i.putExtra(NEW_MAIL_MESSAGE_COUNT, messageCount); i.putExtra(NEW_MAIL_UNREAD_COUNT, unreadCount); mContext.sendOrderedBroadcast(i, null); } } finally { c.close(); } } } public static void notifyNewMail(Context context, Intent i) { Log.d(Logging.LOG_TAG, "Sending notification to system..."); NotificationController nc = NotificationController.getInstance(context); ContentResolver resolver = context.getContentResolver(); long mailboxId = i.getLongExtra(NEW_MAIL_MAILBOX_ID, -1); long newMessageId = i.getLongExtra(NEW_MAIL_MESSAGE_ID, -1); int messageCount = i.getIntExtra(NEW_MAIL_MESSAGE_COUNT, 0); int unreadCount = i.getIntExtra(NEW_MAIL_UNREAD_COUNT, 0); Notification n = nc.createNewMessageNotification(mailboxId, newMessageId, messageCount, unreadCount); if (n != null) { // Make the notification visible nc.mNotificationManager.notify(nc.getNewMessageNotificationId(mailboxId), n); } // Save away the new values ContentValues cv = new ContentValues(); cv.put(MailboxColumns.LAST_NOTIFIED_MESSAGE_KEY, newMessageId); cv.put(MailboxColumns.LAST_NOTIFIED_MESSAGE_COUNT, messageCount); resolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId), cv, null, null); } /** * Observer invoked whenever an account is modified. This could mean the user changed the * notification settings. */ private static class AccountContentObserver extends ContentObserver { private final Context mContext; public AccountContentObserver(Handler handler, Context context) { super(handler); mContext = context; } @Override public void onChange(boolean selfChange) { final ContentResolver resolver = mContext.getContentResolver(); final Cursor c = resolver.query(Account.CONTENT_URI, EmailContent.ID_PROJECTION, NOTIFIED_ACCOUNT_SELECTION, null, null); final HashSet<Long> newAccountList = new HashSet<Long>(); final HashSet<Long> removedAccountList = new HashSet<Long>(); if (c == null) { // Suspender time ... theoretically, this will never happen Log.wtf(Logging.LOG_TAG, "#onChange(); NULL response for account id query"); return; } try { while (c.moveToNext()) { long accountId = c.getLong(EmailContent.ID_PROJECTION_COLUMN); newAccountList.add(accountId); } } finally { if (c != null) { c.close(); } } // NOTE: Looping over three lists is not necessarily the most efficient. However, the // account lists are going to be very small, so, this will not be necessarily bad. // Cycle through existing notification list and adjust as necessary for (long accountId : sInstance.mNotificationMap.keySet()) { if (!newAccountList.remove(accountId)) { // account id not in the current set of notifiable accounts removedAccountList.add(accountId); } } // A new account was added to the notification list for (long accountId : newAccountList) { sInstance.registerMessageNotification(accountId); } // An account was removed from the notification list for (long accountId : removedAccountList) { sInstance.unregisterMessageNotification(accountId); int notificationId = sInstance.getNewMessageNotificationId(accountId); sInstance.mNotificationManager.cancel(notificationId); } } } /** * Thread to handle all notification actions through its own {@link Looper}. */ private static class NotificationThread implements Runnable { /** Lock to ensure proper initialization */ private final Object mLock = new Object(); /** The {@link Looper} that handles messages for this thread */ private Looper mLooper; NotificationThread() { new Thread(null, this, "EmailNotification").start(); synchronized (mLock) { while (mLooper == null) { try { mLock.wait(); } catch (InterruptedException ex) { } } } } @Override public void run() { synchronized (mLock) { Looper.prepare(); mLooper = Looper.myLooper(); mLock.notifyAll(); } Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); Looper.loop(); } void quit() { mLooper.quit(); } Looper getLooper() { return mLooper; } } }
false
true
Notification createNewMessageNotification(long mailboxId, long newMessageId, int unseenMessageCount, int unreadCount) { final Mailbox mailbox = Mailbox.restoreMailboxWithId(mContext, mailboxId); if (mailbox == null) { return null; } final Account account = Account.restoreAccountWithId(mContext, mailbox.mAccountKey); if (account == null) { return null; } // Get the latest message final Message message = Message.restoreMessageWithId(mContext, newMessageId); if (message == null) { return null; // no message found??? } String senderName = Address.toFriendly(Address.unpack(message.mFrom)); if (senderName == null) { senderName = ""; // Happens when a message has no from. } final boolean multipleUnseen = unseenMessageCount > 1; final Bitmap senderPhoto = multipleUnseen ? mGenericMultipleSenderIcon : getSenderPhoto(message); final SpannableString title = getNewMessageTitle(senderName, unseenMessageCount); // TODO: add in display name on the second line for the text, once framework supports // multiline texts. // Show account name if an inbox; otherwise mailbox name final String text = multipleUnseen ? ((mailbox.mType == Mailbox.TYPE_INBOX) ? account.mDisplayName : mailbox.mDisplayName) : message.mSubject; final Bitmap largeIcon = senderPhoto != null ? senderPhoto : mGenericSenderIcon; final Integer number = unreadCount > 1 ? unreadCount : null; Intent intent = createViewConversationIntent(message); if (intent == null) { return null; } intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_TASK_ON_HOME); long now = mClock.getTime(); boolean enableAudio = (now - mLastMessageNotifyTime) > MIN_SOUND_INTERVAL_MS; final Notification.Builder builder = createBaseAccountNotificationBuilder( mailbox.mAccountKey, title.toString(), title, text, intent, largeIcon, number, enableAudio, false); if (Utils.isRunningJellybeanOrLater()) { // For a new-style notification if (multipleUnseen) { final Cursor messageCursor = mContext.getContentResolver().query(ContentUris.withAppendedId( EmailContent.MAILBOX_NOTIFICATION_URI, mailbox.mAccountKey), EmailContent.NOTIFICATION_PROJECTION, null, null, null); if (messageCursor != null && messageCursor.getCount() > 0) { try { final int maxNumDigestItems = mContext.getResources().getInteger( R.integer.max_num_notification_digest_items); // The body of the notification is the account name, or the label name. builder.setSubText(text); Notification.InboxStyle digest = new Notification.InboxStyle(builder); digest.setBigContentTitle(title); int numDigestItems = 0; // We can assume that the current position of the cursor is on the // newest message do { final long messageId = messageCursor.getLong(EmailContent.ID_PROJECTION_COLUMN); // Get the latest message final Message digestMessage = Message.restoreMessageWithId(mContext, messageId); if (digestMessage != null) { final CharSequence digestLine = getSingleMessageInboxLine(mContext, digestMessage); digest.addLine(digestLine); numDigestItems++; } } while (numDigestItems <= maxNumDigestItems && messageCursor.moveToNext()); // We want to clear the content text in this case. The content text would // have been set in createBaseAccountNotificationBuilder, but since the // same string was set in as the subtext, we don't want to show a // duplicate string. builder.setContentText(null); } finally { messageCursor.close(); } } } else { // The notification content will be the subject of the conversation. builder.setContentText(getSingleMessageLittleText(mContext, message.mSubject)); // The notification subtext will be the subject of the conversation for inbox // notifications, or will based on the the label name for user label notifications. builder.setSubText(account.mDisplayName); final Notification.BigTextStyle bigText = new Notification.BigTextStyle(builder); bigText.bigText(getSingleMessageBigText(mContext, message)); } } mLastMessageNotifyTime = now; return builder.getNotification(); }
Notification createNewMessageNotification(long mailboxId, long newMessageId, int unseenMessageCount, int unreadCount) { final Mailbox mailbox = Mailbox.restoreMailboxWithId(mContext, mailboxId); if (mailbox == null) { return null; } final Account account = Account.restoreAccountWithId(mContext, mailbox.mAccountKey); if (account == null) { return null; } // Get the latest message final Message message = Message.restoreMessageWithId(mContext, newMessageId); if (message == null) { return null; // no message found??? } String senderName = Address.toFriendly(Address.unpack(message.mFrom)); if (senderName == null) { senderName = ""; // Happens when a message has no from. } final boolean multipleUnseen = unseenMessageCount > 1; final Bitmap senderPhoto = multipleUnseen ? mGenericMultipleSenderIcon : getSenderPhoto(message); final SpannableString title = getNewMessageTitle(senderName, unseenMessageCount); // TODO: add in display name on the second line for the text, once framework supports // multiline texts. // Show account name if an inbox; otherwise mailbox name final String text = multipleUnseen ? ((mailbox.mType == Mailbox.TYPE_INBOX) ? account.mDisplayName : mailbox.mDisplayName) : message.mSubject; final Bitmap largeIcon = senderPhoto != null ? senderPhoto : mGenericSenderIcon; final Integer number = unreadCount > 1 ? unreadCount : null; Intent intent = createViewConversationIntent(message); if (intent == null) { return null; } intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_TASK_ON_HOME); long now = mClock.getTime(); boolean enableAudio = (now - mLastMessageNotifyTime) > MIN_SOUND_INTERVAL_MS; final Notification.Builder builder = createBaseAccountNotificationBuilder( mailbox.mAccountKey, title.toString(), title, text, intent, largeIcon, number, enableAudio, false); if (Utils.isRunningJellybeanOrLater()) { // For a new-style notification if (multipleUnseen) { final Cursor messageCursor = mContext.getContentResolver().query(ContentUris.withAppendedId( EmailContent.MAILBOX_NOTIFICATION_URI, mailbox.mAccountKey), EmailContent.NOTIFICATION_PROJECTION, null, null, null); try { if (messageCursor != null && messageCursor.getCount() > 0) { final int maxNumDigestItems = mContext.getResources().getInteger( R.integer.max_num_notification_digest_items); // The body of the notification is the account name, or the label name. builder.setSubText(text); Notification.InboxStyle digest = new Notification.InboxStyle(builder); digest.setBigContentTitle(title); int numDigestItems = 0; // We can assume that the current position of the cursor is on the // newest message messageCursor.moveToFirst(); do { final long messageId = messageCursor.getLong(EmailContent.ID_PROJECTION_COLUMN); // Get the latest message final Message digestMessage = Message.restoreMessageWithId(mContext, messageId); if (digestMessage != null) { final CharSequence digestLine = getSingleMessageInboxLine(mContext, digestMessage); digest.addLine(digestLine); numDigestItems++; } } while (numDigestItems <= maxNumDigestItems && messageCursor.moveToNext()); // We want to clear the content text in this case. The content text would // have been set in createBaseAccountNotificationBuilder, but since the // same string was set in as the subtext, we don't want to show a // duplicate string. builder.setContentText(null); } } finally { if (messageCursor != null) { messageCursor.close(); } } } else { // The notification content will be the subject of the conversation. builder.setContentText(getSingleMessageLittleText(mContext, message.mSubject)); // The notification subtext will be the subject of the conversation for inbox // notifications, or will based on the the label name for user label notifications. builder.setSubText(account.mDisplayName); final Notification.BigTextStyle bigText = new Notification.BigTextStyle(builder); bigText.bigText(getSingleMessageBigText(mContext, message)); } } mLastMessageNotifyTime = now; return builder.getNotification(); }
diff --git a/src/FallingBall.java b/src/FallingBall.java index bdd7007..ab51db2 100644 --- a/src/FallingBall.java +++ b/src/FallingBall.java @@ -1,93 +1,91 @@ /** * Class FallingBall * @author Casey Harford * @version 1.0 */ import java.awt.Color; import java.util.Random; import java.awt.Graphics; class FallingBall implements Runnable { public static final int BALL_SIZE = 30; private BallManager manager; private int slot; private int height; private int oldHeight; private Color ballColor; private boolean keepRunning; private Thread myThread; public FallingBall(int aSlot, BallManager theManager) { manager = theManager; /** set slot and height */ slot = aSlot; height = 0; oldHeight = height; /** set ball color */ Random rand = new Random(); float r = rand.nextFloat(); float g = rand.nextFloat(); float b = rand.nextFloat(); ballColor = new Color(r,g,b); /** start the thread */ myThread = new Thread(this); myThread.start(); keepRunning = true; } public void run() { - int ballBelow; + int ballBelow = 0; while (keepRunning) { try { Thread.sleep(10); /** check if ball below */ - if(!manager.available(slot,(height/BALL_SIZE)+1)) { - ballBelow = (manager.MAX_BALLS*BALL_SIZE-BALL_SIZE)-((height/BALL_SIZE)+1)*BALL_SIZE; - } - else { - ballBelow = (manager.MAX_BALLS*BALL_SIZE-BALL_SIZE); + if(manager.available(slot,(height/BALL_SIZE)+1)) { + ballBelow = height + BALL_SIZE; } - if(height <= ballBelow) { + if( (height+BALL_SIZE) <= ballBelow) { + System.out.println(ballBelow); height += 3; if( (height/BALL_SIZE) > (oldHeight/BALL_SIZE) ) { manager.moveBall(slot, (oldHeight/BALL_SIZE), slot, (height/BALL_SIZE)); oldHeight = height; } } else { /** check if ball to the left */ if(manager.available(slot-1,(oldHeight/BALL_SIZE)+1)) { manager.moveBall(slot, (oldHeight/BALL_SIZE), slot-1, (oldHeight/BALL_SIZE)+1); slot = slot-1; height = ((oldHeight/BALL_SIZE)+1)*BALL_SIZE; oldHeight = height; } /** check if ball to the right */ if(manager.available(slot+1,(oldHeight/BALL_SIZE)+1)) { manager.moveBall(slot, (oldHeight/BALL_SIZE), slot+1, (oldHeight/BALL_SIZE)+1); slot = slot+1; height = ((oldHeight/BALL_SIZE)+1)*BALL_SIZE; oldHeight = height; } } } catch (Exception e) { } } } public void draw(Graphics g) { g.setColor(ballColor); g.fillOval(slot*BALL_SIZE,height, BALL_SIZE, BALL_SIZE); } public void killBall() { keepRunning = false; } }
false
true
public void run() { int ballBelow; while (keepRunning) { try { Thread.sleep(10); /** check if ball below */ if(!manager.available(slot,(height/BALL_SIZE)+1)) { ballBelow = (manager.MAX_BALLS*BALL_SIZE-BALL_SIZE)-((height/BALL_SIZE)+1)*BALL_SIZE; } else { ballBelow = (manager.MAX_BALLS*BALL_SIZE-BALL_SIZE); } if(height <= ballBelow) { height += 3; if( (height/BALL_SIZE) > (oldHeight/BALL_SIZE) ) { manager.moveBall(slot, (oldHeight/BALL_SIZE), slot, (height/BALL_SIZE)); oldHeight = height; } } else { /** check if ball to the left */ if(manager.available(slot-1,(oldHeight/BALL_SIZE)+1)) { manager.moveBall(slot, (oldHeight/BALL_SIZE), slot-1, (oldHeight/BALL_SIZE)+1); slot = slot-1; height = ((oldHeight/BALL_SIZE)+1)*BALL_SIZE; oldHeight = height; } /** check if ball to the right */ if(manager.available(slot+1,(oldHeight/BALL_SIZE)+1)) { manager.moveBall(slot, (oldHeight/BALL_SIZE), slot+1, (oldHeight/BALL_SIZE)+1); slot = slot+1; height = ((oldHeight/BALL_SIZE)+1)*BALL_SIZE; oldHeight = height; } } } catch (Exception e) { } } }
public void run() { int ballBelow = 0; while (keepRunning) { try { Thread.sleep(10); /** check if ball below */ if(manager.available(slot,(height/BALL_SIZE)+1)) { ballBelow = height + BALL_SIZE; } if( (height+BALL_SIZE) <= ballBelow) { System.out.println(ballBelow); height += 3; if( (height/BALL_SIZE) > (oldHeight/BALL_SIZE) ) { manager.moveBall(slot, (oldHeight/BALL_SIZE), slot, (height/BALL_SIZE)); oldHeight = height; } } else { /** check if ball to the left */ if(manager.available(slot-1,(oldHeight/BALL_SIZE)+1)) { manager.moveBall(slot, (oldHeight/BALL_SIZE), slot-1, (oldHeight/BALL_SIZE)+1); slot = slot-1; height = ((oldHeight/BALL_SIZE)+1)*BALL_SIZE; oldHeight = height; } /** check if ball to the right */ if(manager.available(slot+1,(oldHeight/BALL_SIZE)+1)) { manager.moveBall(slot, (oldHeight/BALL_SIZE), slot+1, (oldHeight/BALL_SIZE)+1); slot = slot+1; height = ((oldHeight/BALL_SIZE)+1)*BALL_SIZE; oldHeight = height; } } } catch (Exception e) { } } }
diff --git a/test-modules/functional-tests/src/test/java/org/openlmis/functional/ConfigureRegimenProgramTemplate.java b/test-modules/functional-tests/src/test/java/org/openlmis/functional/ConfigureRegimenProgramTemplate.java index 0d8fdef034..6bb61d9f02 100644 --- a/test-modules/functional-tests/src/test/java/org/openlmis/functional/ConfigureRegimenProgramTemplate.java +++ b/test-modules/functional-tests/src/test/java/org/openlmis/functional/ConfigureRegimenProgramTemplate.java @@ -1,102 +1,102 @@ /* * Copyright © 2013 VillageReach. All Rights Reserved. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. * * If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.openlmis.functional; import com.thoughtworks.selenium.SeleneseTestNgHelper; import org.openlmis.UiUtils.CaptureScreenshotOnFailureListener; import org.openlmis.UiUtils.TestCaseHelper; import org.openlmis.pageobjects.*; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; import org.testng.annotations.*; import java.util.ArrayList; import java.util.List; import static com.thoughtworks.selenium.SeleneseTestBase.assertTrue; @TransactionConfiguration(defaultRollback = true) @Transactional @Listeners(CaptureScreenshotOnFailureListener.class) public class ConfigureRegimenProgramTemplate extends TestCaseHelper { private static String adultsRegimen = "Adults"; private static String paediatricsRegimen = "Paediatrics"; @BeforeMethod(groups = {"functional2", "smoke"}) public void setUp() throws Exception { super.setup(); } @Test(groups = {"smoke"}, dataProvider = "Data-Provider") public void testVerifyNewRegimenCreated(String program, String[] credentials) throws Exception { dbWrapper.setRegimenTemplateConfiguredForProgram(false, program); String expectedProgramsString = dbWrapper.getAllActivePrograms(); LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal); HomePage homePage = loginPage.loginAs(credentials[0], credentials[1]); RegimenTemplateConfigPage regimenTemplateConfigPage = homePage.navigateToRegimenConfigTemplate(); List<String> programsList = getProgramsListedOnRegimeScreen(); verifyProgramsListedOnManageRegimenTemplateScreen(programsList, expectedProgramsString); regimenTemplateConfigPage.configureProgram(program); regimenTemplateConfigPage.AddNewRegimen(adultsRegimen, "Code1", "Name1", true); regimenTemplateConfigPage.SaveRegime(); - verifySuccessMessage(regimenTemplateConfigPage); + //verifySuccessMessage(regimenTemplateConfigPage); verifyProgramConfigured(program); } private void verifyProgramsListedOnManageRegimenTemplateScreen(List<String> actualProgramsString, String expectedProgramsString) { for (String program : actualProgramsString) SeleneseTestNgHelper.assertTrue("Program " + program + " not present in expected string : " + expectedProgramsString, expectedProgramsString.contains(program)); } private List<String> getProgramsListedOnRegimeScreen() { List<String> programsList = new ArrayList<String>(); String regimenTableTillTR = "//table[@id='configureProgramRegimensTable']/tbody/tr"; int size = testWebDriver.getElementsSizeByXpath(regimenTableTillTR); for (int counter = 1; counter < size + 1; counter++) { testWebDriver.waitForElementToAppear(testWebDriver.getElementByXpath(regimenTableTillTR + "[" + counter + "]/td[1]")); programsList.add(testWebDriver.getElementByXpath(regimenTableTillTR + "[" + counter + "]/td[1]").getText().trim()); } return programsList; } private void verifySuccessMessage(RegimenTemplateConfigPage regimenTemplateConfigPage) { testWebDriver.waitForElementToAppear(regimenTemplateConfigPage.getSaveSuccessMsgDiv()); assertTrue("saveSuccessMsgDiv should show up", regimenTemplateConfigPage.getSaveSuccessMsgDiv().isDisplayed()); String saveSuccessfullyMessage = "Regimens saved successfully"; assertTrue("Message showing '" + saveSuccessfullyMessage + "' should show up", regimenTemplateConfigPage.getSaveSuccessMsgDiv().getText().trim().equals(saveSuccessfullyMessage)); } private void verifyProgramConfigured(String program) { testWebDriver.waitForElementToAppear(testWebDriver.getElementByXpath("//a[@id='" + program + "']")); assertTrue("", testWebDriver.getElementByXpath("//a[@id='" + program + "']").getText().trim().equals("Edit")); } @AfterMethod(groups = {"smoke", "functional2"}) public void tearDown() throws Exception { HomePage homePage = new HomePage(testWebDriver); homePage.logout(baseUrlGlobal); dbWrapper.deleteData(); dbWrapper.closeConnection(); } @DataProvider(name = "Data-Provider") public Object[][] parameterVerifyRnRScreen() { return new Object[][]{ {"ESSENTIAL MEDICINES", new String[]{"Admin123", "Admin123"}} }; } }
true
true
public void testVerifyNewRegimenCreated(String program, String[] credentials) throws Exception { dbWrapper.setRegimenTemplateConfiguredForProgram(false, program); String expectedProgramsString = dbWrapper.getAllActivePrograms(); LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal); HomePage homePage = loginPage.loginAs(credentials[0], credentials[1]); RegimenTemplateConfigPage regimenTemplateConfigPage = homePage.navigateToRegimenConfigTemplate(); List<String> programsList = getProgramsListedOnRegimeScreen(); verifyProgramsListedOnManageRegimenTemplateScreen(programsList, expectedProgramsString); regimenTemplateConfigPage.configureProgram(program); regimenTemplateConfigPage.AddNewRegimen(adultsRegimen, "Code1", "Name1", true); regimenTemplateConfigPage.SaveRegime(); verifySuccessMessage(regimenTemplateConfigPage); verifyProgramConfigured(program); }
public void testVerifyNewRegimenCreated(String program, String[] credentials) throws Exception { dbWrapper.setRegimenTemplateConfiguredForProgram(false, program); String expectedProgramsString = dbWrapper.getAllActivePrograms(); LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal); HomePage homePage = loginPage.loginAs(credentials[0], credentials[1]); RegimenTemplateConfigPage regimenTemplateConfigPage = homePage.navigateToRegimenConfigTemplate(); List<String> programsList = getProgramsListedOnRegimeScreen(); verifyProgramsListedOnManageRegimenTemplateScreen(programsList, expectedProgramsString); regimenTemplateConfigPage.configureProgram(program); regimenTemplateConfigPage.AddNewRegimen(adultsRegimen, "Code1", "Name1", true); regimenTemplateConfigPage.SaveRegime(); //verifySuccessMessage(regimenTemplateConfigPage); verifyProgramConfigured(program); }
diff --git a/src/jrds/probe/RMI.java b/src/jrds/probe/RMI.java index e7855e4..32fb84b 100644 --- a/src/jrds/probe/RMI.java +++ b/src/jrds/probe/RMI.java @@ -1,49 +1,53 @@ package jrds.probe; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import jrds.ProbeConnected; import jrds.agent.RProbe; import org.apache.log4j.Level; public class RMI extends ProbeConnected<String, Number, RMIConnection> { List<?> args = new ArrayList<Object>(0); private String remoteName = null; public RMI() { super(RMIConnection.class.getName()); } public Map<String, Number> getNewSampleValuesConnected(RMIConnection cnx) { Map<String, Number> retValues = new HashMap<String, Number>(0); try { RProbe rp = (RProbe) cnx.getConnection(); remoteName = rp.prepare(getPd().getSpecific("remote"), args); retValues = rp.query(remoteName); } catch (RemoteException e) { - Throwable root = e.getCause().getCause(); - if(root == null) - root = e.getCause(); + Throwable root = e; + while(root.getCause() != null) { + root = root.getCause(); + } + //e.getCause().getCause(); + //if(root == null) + // root = e.getCause(); log(Level.ERROR, root, "Remote exception on server: %s", root); } return retValues; } public List<?> getArgs() { return args; } public void setArgs(List<?> l) { this.args = l; } public String getSourceType() { return "JRDS Agent"; } }
true
true
public Map<String, Number> getNewSampleValuesConnected(RMIConnection cnx) { Map<String, Number> retValues = new HashMap<String, Number>(0); try { RProbe rp = (RProbe) cnx.getConnection(); remoteName = rp.prepare(getPd().getSpecific("remote"), args); retValues = rp.query(remoteName); } catch (RemoteException e) { Throwable root = e.getCause().getCause(); if(root == null) root = e.getCause(); log(Level.ERROR, root, "Remote exception on server: %s", root); } return retValues; }
public Map<String, Number> getNewSampleValuesConnected(RMIConnection cnx) { Map<String, Number> retValues = new HashMap<String, Number>(0); try { RProbe rp = (RProbe) cnx.getConnection(); remoteName = rp.prepare(getPd().getSpecific("remote"), args); retValues = rp.query(remoteName); } catch (RemoteException e) { Throwable root = e; while(root.getCause() != null) { root = root.getCause(); } //e.getCause().getCause(); //if(root == null) // root = e.getCause(); log(Level.ERROR, root, "Remote exception on server: %s", root); } return retValues; }
diff --git a/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/admin/LockssAuthServiceBean.java b/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/admin/LockssAuthServiceBean.java index b5768d21..c4045feb 100644 --- a/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/admin/LockssAuthServiceBean.java +++ b/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/admin/LockssAuthServiceBean.java @@ -1,189 +1,188 @@ /* * Dataverse Network - A web application to distribute, share and analyze quantitative data. * Copyright (C) 2007 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses * or write to the Free Software Foundation,Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301 USA */ /* * LockssServerAuth.java * * Created on Mar 23, 2007, 3:13 PM * */ package edu.harvard.iq.dvn.core.admin; import edu.harvard.iq.dvn.core.vdc.VDC; import edu.harvard.iq.dvn.core.vdc.VDCNetworkServiceLocal; import edu.harvard.iq.dvn.core.vdc.LockssServer; import edu.harvard.iq.dvn.core.vdc.LockssConfig; import edu.harvard.iq.dvn.core.vdc.LockssConfig.ServerAccess; import edu.harvard.iq.dvn.core.util.DomainMatchUtil; import java.util.*; import java.util.logging.*; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.servlet.http.HttpServletRequest; /** * * @author landreev */ @Stateless public class LockssAuthServiceBean implements LockssAuthServiceLocal { @EJB VDCNetworkServiceLocal vdcNetworkService; private static Logger dbgLog = Logger.getLogger(LockssAuthServiceBean.class.getPackage().getName()); /* constructor: */ public LockssAuthServiceBean() { } /* * isAuthorizedLockssServer method is used to check if the remote LOCKSS * server is authorized to crawl this set/dv at all; meaning, at this * point we are not authorizing them to download any particular files, * just deciding whether to show them the Manifest page. */ public Boolean isAuthorizedLockssServer ( VDC vdc, HttpServletRequest req ) { String remoteAddress = req.getRemoteHost(); if (remoteAddress == null || remoteAddress.equals("")) { return false; } LockssConfig lockssConfig = null; if (vdc != null) { lockssConfig = vdc.getLockssConfig(); } else { lockssConfig = vdcNetworkService.getLockssConfig(); } if (lockssConfig == null) { return false; } if (ServerAccess.ALL.equals(lockssConfig.getserverAccess())) { return true; } List<LockssServer> lockssServers = lockssConfig.getLockssServers(); if (lockssServers == null || lockssServers.size() == 0) { return false; } for (Iterator<LockssServer> it = lockssServers.iterator(); it.hasNext();) { LockssServer elem = it.next(); if (elem.getIpAddress() != null) { if (DomainMatchUtil.isDomainMatch(remoteAddress, elem.getIpAddress())) { return true; } } } return false; } /* * isAuthorizedLockssDownload performs authorization on individual files * that the crawler is trying to download. This authorization depends on * how this configuration is configured, whether it's open to all lockss * servers or an IP group, and whether the file in question is restricted. */ public Boolean isAuthorizedLockssDownload ( VDC vdc, HttpServletRequest req, Boolean fileIsRestricted) { String remoteAddress = req.getRemoteHost(); if (remoteAddress == null || remoteAddress.equals("")) { return false; } LockssConfig lockssConfig = null; if (vdc != null) { if (vdc.getLockssConfig()!=null) { lockssConfig = vdc.getLockssConfig(); - } else { - lockssConfig = vdcNetworkService.getLockssConfig(); - } + } } if (lockssConfig == null) { return false; } // If this LOCKSS configuration is open to ALL, we allow downloads - // of public files but not of the restricted ones: + // of public files; so if the file is public, we can return true. + // We *may* also allow access to restricted ones; but only to + // select servers (we'll check for that further below). if (ServerAccess.ALL.equals(lockssConfig.getserverAccess())) { - if (fileIsRestricted) { - return false; + if (!fileIsRestricted) { + return true; } - return true; } // This is a LOCKSS configuration open only to group of servers. // // Before we go through the list of the authorized IP addresses // and see if the remote address matches, let's first check if // the file is restricted and if so, whether the LOCKSS config // allows downloads of restricted files; because if not, we can // return false right away: if (fileIsRestricted) { if (!lockssConfig.isAllowRestricted()) { return false; } } // Now let's get the list of the authorized servers: List<LockssServer> lockssServers = lockssConfig.getLockssServers(); if (lockssServers == null || lockssServers.size() == 0) { return false; } for (Iterator<LockssServer> it = lockssServers.iterator(); it.hasNext();) { LockssServer elem = it.next(); if (elem.getIpAddress() != null) { if (DomainMatchUtil.isDomainMatch(remoteAddress, elem.getIpAddress())) { return true; } } } // We've exhausted the possibilities, returning false: return false; } }
false
true
public Boolean isAuthorizedLockssDownload ( VDC vdc, HttpServletRequest req, Boolean fileIsRestricted) { String remoteAddress = req.getRemoteHost(); if (remoteAddress == null || remoteAddress.equals("")) { return false; } LockssConfig lockssConfig = null; if (vdc != null) { if (vdc.getLockssConfig()!=null) { lockssConfig = vdc.getLockssConfig(); } else { lockssConfig = vdcNetworkService.getLockssConfig(); } } if (lockssConfig == null) { return false; } // If this LOCKSS configuration is open to ALL, we allow downloads // of public files but not of the restricted ones: if (ServerAccess.ALL.equals(lockssConfig.getserverAccess())) { if (fileIsRestricted) { return false; } return true; } // This is a LOCKSS configuration open only to group of servers. // // Before we go through the list of the authorized IP addresses // and see if the remote address matches, let's first check if // the file is restricted and if so, whether the LOCKSS config // allows downloads of restricted files; because if not, we can // return false right away: if (fileIsRestricted) { if (!lockssConfig.isAllowRestricted()) { return false; } } // Now let's get the list of the authorized servers: List<LockssServer> lockssServers = lockssConfig.getLockssServers(); if (lockssServers == null || lockssServers.size() == 0) { return false; } for (Iterator<LockssServer> it = lockssServers.iterator(); it.hasNext();) { LockssServer elem = it.next(); if (elem.getIpAddress() != null) { if (DomainMatchUtil.isDomainMatch(remoteAddress, elem.getIpAddress())) { return true; } } } // We've exhausted the possibilities, returning false: return false; }
public Boolean isAuthorizedLockssDownload ( VDC vdc, HttpServletRequest req, Boolean fileIsRestricted) { String remoteAddress = req.getRemoteHost(); if (remoteAddress == null || remoteAddress.equals("")) { return false; } LockssConfig lockssConfig = null; if (vdc != null) { if (vdc.getLockssConfig()!=null) { lockssConfig = vdc.getLockssConfig(); } } if (lockssConfig == null) { return false; } // If this LOCKSS configuration is open to ALL, we allow downloads // of public files; so if the file is public, we can return true. // We *may* also allow access to restricted ones; but only to // select servers (we'll check for that further below). if (ServerAccess.ALL.equals(lockssConfig.getserverAccess())) { if (!fileIsRestricted) { return true; } } // This is a LOCKSS configuration open only to group of servers. // // Before we go through the list of the authorized IP addresses // and see if the remote address matches, let's first check if // the file is restricted and if so, whether the LOCKSS config // allows downloads of restricted files; because if not, we can // return false right away: if (fileIsRestricted) { if (!lockssConfig.isAllowRestricted()) { return false; } } // Now let's get the list of the authorized servers: List<LockssServer> lockssServers = lockssConfig.getLockssServers(); if (lockssServers == null || lockssServers.size() == 0) { return false; } for (Iterator<LockssServer> it = lockssServers.iterator(); it.hasNext();) { LockssServer elem = it.next(); if (elem.getIpAddress() != null) { if (DomainMatchUtil.isDomainMatch(remoteAddress, elem.getIpAddress())) { return true; } } } // We've exhausted the possibilities, returning false: return false; }
diff --git a/src/com/google/android/apps/dashclock/calendar/CalendarExtension.java b/src/com/google/android/apps/dashclock/calendar/CalendarExtension.java index bfb354d..beb2f44 100644 --- a/src/com/google/android/apps/dashclock/calendar/CalendarExtension.java +++ b/src/com/google/android/apps/dashclock/calendar/CalendarExtension.java @@ -1,387 +1,387 @@ /* * Copyright 2013 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.android.apps.dashclock.calendar; import com.google.android.apps.dashclock.LogUtils; import com.google.android.apps.dashclock.api.DashClockExtension; import com.google.android.apps.dashclock.api.ExtensionData; import net.nurik.roman.dashclock.R; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.preference.PreferenceManager; import android.provider.CalendarContract; import android.text.TextUtils; import android.text.format.DateFormat; import android.util.Pair; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TimeZone; import static com.google.android.apps.dashclock.LogUtils.LOGD; import static com.google.android.apps.dashclock.LogUtils.LOGE; /** * Calendar "upcoming appointment" extension. */ public class CalendarExtension extends DashClockExtension { private static final String TAG = LogUtils.makeLogTag(CalendarExtension.class); public static final String PREF_CUSTOM_VISIBILITY = "pref_calendar_custom_visibility"; public static final String PREF_SELECTED_CALENDARS = "pref_calendar_selected"; public static final String PREF_LOOK_AHEAD_HOURS = "pref_calendar_look_ahead_hours"; public static final String PREF_SHOW_ALL_DAY = "pref_calendar_show_all_day"; private static final String SQL_TAUTOLOGY = "1=1"; private static final long MINUTE_MILLIS = 60 * 1000; private static final long HOUR_MILLIS = 60 * MINUTE_MILLIS; private static final int DEFAULT_LOOK_AHEAD_HOURS = 6; private int mLookAheadHours = DEFAULT_LOOK_AHEAD_HOURS; static List<Pair<String, Boolean>> getAllCalendars(Context context) { // Only return calendars that are marked as synced to device. // (This is different from the display flag) List<Pair<String, Boolean>> calendars = new ArrayList<Pair<String, Boolean>>(); try { Cursor cursor = context.getContentResolver().query( CalendarContract.Calendars.CONTENT_URI, CalendarsQuery.PROJECTION, CalendarContract.Calendars.SYNC_EVENTS + "=1", null, null); if (cursor != null) { while (cursor.moveToNext()) { calendars.add(new Pair<String, Boolean>( cursor.getString(CalendarsQuery.ID), cursor.getInt(CalendarsQuery.VISIBLE) == 1)); } cursor.close(); } } catch (SecurityException e) { LOGE(TAG, "Error querying calendar API", e); return null; } return calendars; } private Set<String> getSelectedCalendars() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); boolean customVisibility = sp.getBoolean(PREF_CUSTOM_VISIBILITY, false); Set<String> selectedCalendars = sp.getStringSet(PREF_SELECTED_CALENDARS, null); if (!customVisibility || selectedCalendars == null) { final List<Pair<String, Boolean>> allCalendars = getAllCalendars(this); // Build a set of all visible calendars in case we don't have a selection set in // the preferences. selectedCalendars = new HashSet<String>(); for (Pair<String, Boolean> pair : allCalendars) { if (pair.second) { selectedCalendars.add(pair.first); } } } return selectedCalendars; } @Override protected void onInitialize(boolean isReconnect) { super.onInitialize(isReconnect); if (!isReconnect) { addWatchContentUris(new String[]{ CalendarContract.Events.CONTENT_URI.toString() }); } setUpdateWhenScreenOn(true); } @Override protected void onUpdateData(int reason) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); boolean showAllDay = sp.getBoolean(PREF_SHOW_ALL_DAY, false); try { mLookAheadHours = Integer.parseInt(sp.getString(PREF_LOOK_AHEAD_HOURS, Integer.toString(mLookAheadHours))); } catch (NumberFormatException e) { mLookAheadHours = DEFAULT_LOOK_AHEAD_HOURS; } Cursor cursor = tryOpenEventsCursor(showAllDay); if (cursor == null) { LOGE(TAG, "Null events cursor, short-circuiting."); return; } long currentTimestamp = getCurrentTimestamp(); long nextTimestamp = 0; long endTimestamp = 0; - int tzOffset = TimeZone.getDefault().getOffset(nextTimestamp); long timeUntilNextAppointent = 0; boolean allDay = false; int allDayPosition = -1; - long allDayTimestamp = 0; + long allDayTimestampLocalMidnight = 0; while (cursor.moveToNext()) { nextTimestamp = cursor.getLong(EventsQuery.BEGIN); + int tzOffset = TimeZone.getDefault().getOffset(nextTimestamp); allDay = cursor.getInt(EventsQuery.ALL_DAY) != 0; if (allDay) { endTimestamp = cursor.getLong(EventsQuery.END) - tzOffset; if (showAllDay && allDayPosition < 0 && endTimestamp > currentTimestamp) { // Store the position of this all day event. If no regular events are found // and the user wanted to see all day events, then show this all day event. allDayPosition = cursor.getPosition(); // For all day events (if the user wants to see them), convert the begin // timestamp, which is the midnight UTC time, to local time. That is, - // nextTimestamp will now be midnight in local time since that's a more - // relevant representation of that day to the user. - allDayTimestamp = nextTimestamp - tzOffset; + // allDayTimestampLocalMidnight will be midnight in local time since that's a + // more relevant representation of that day to the user. + allDayTimestampLocalMidnight = nextTimestamp - tzOffset; } continue; } timeUntilNextAppointent = nextTimestamp - currentTimestamp; if (timeUntilNextAppointent >= 0) { break; } // Skip over events that are not ALL_DAY but span multiple days, including // the next 6 hours. An example is an event that starts at 4pm yesterday // day and ends 6pm tomorrow. LOGD(TAG, "Skipping over event with start timestamp " + nextTimestamp + ". " + "Current timestamp " + currentTimestamp); } if (allDayPosition >= 0) { // Only show all day events if there's no regular event (cursor is after last) // or if the all day event is tomorrow or later and the all day event is later than // the regular event. if (cursor.isAfterLast() - || ((allDayTimestamp - currentTimestamp) > 0 - && allDayTimestamp < nextTimestamp)) { + || ((allDayTimestampLocalMidnight - currentTimestamp) > 0 + && allDayTimestampLocalMidnight < nextTimestamp)) { cursor.moveToPosition(allDayPosition); allDay = true; - nextTimestamp = allDayTimestamp; + nextTimestamp = allDayTimestampLocalMidnight; timeUntilNextAppointent = nextTimestamp - currentTimestamp; LOGD(TAG, "Showing an all day event because either no regular event was found or " + "it's a full day later than the all-day event."); } } if (cursor.isAfterLast()) { LOGD(TAG, "No upcoming appointments found."); cursor.close(); publishUpdate(new ExtensionData()); return; } Calendar nextEventCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); nextEventCalendar.setTimeInMillis(nextTimestamp); int minutesUntilNextAppointment = (int) (timeUntilNextAppointent / MINUTE_MILLIS); String untilString; if (allDay) { if (timeUntilNextAppointent <= 0) { // All day event happening today (its start time is past today's midnight // offset. untilString = getString(R.string.today); } else { untilString = new SimpleDateFormat("E").format(nextEventCalendar.getTime()); } } else if (minutesUntilNextAppointment < 60) { untilString = getResources().getQuantityString( R.plurals.calendar_template_mins, minutesUntilNextAppointment, minutesUntilNextAppointment); } else { int hours = Math.round(minutesUntilNextAppointment / 60f); if (hours < 24) { untilString = getResources().getQuantityString( R.plurals.calendar_template_hours, hours, hours); } else { untilString = new SimpleDateFormat("E").format(nextEventCalendar.getTime()); } } String eventTitle = cursor.getString(EventsQuery.TITLE); String eventLocation = cursor.getString(EventsQuery.EVENT_LOCATION); long eventId = cursor.getLong(EventsQuery.EVENT_ID); long eventBegin = cursor.getLong(EventsQuery.BEGIN); long eventEnd = cursor.getLong(EventsQuery.END); cursor.close(); String expandedTime = null; StringBuilder expandedTimeFormat = new StringBuilder(); if (allDay) { if (timeUntilNextAppointent <= 0) { // All day event happening today (its start time is past today's midnight // offset. expandedTimeFormat.setLength(0); expandedTime = getString(R.string.today); } else { expandedTimeFormat.append("EEEE, MMM dd"); } } else { if (nextTimestamp - currentTimestamp > 24 * HOUR_MILLIS) { expandedTimeFormat.append("EEEE, "); } if (DateFormat.is24HourFormat(this)) { expandedTimeFormat.append("HH:mm"); } else { expandedTimeFormat.append("h:mm a"); } } if (expandedTimeFormat.length() > 0) { expandedTime = new SimpleDateFormat(expandedTimeFormat.toString()) .format(nextEventCalendar.getTime()); } String expandedBody = expandedTime; if (!TextUtils.isEmpty(eventLocation)) { expandedBody = getString(R.string.calendar_with_location_template, expandedTime, eventLocation); } publishUpdate(new ExtensionData() .visible(allDay || (timeUntilNextAppointent >= 0 && timeUntilNextAppointent <= mLookAheadHours * HOUR_MILLIS)) .icon(R.drawable.ic_extension_calendar) .status(untilString) .expandedTitle(eventTitle) .expandedBody(expandedBody) .clickIntent(new Intent(Intent.ACTION_VIEW) .setData(Uri.withAppendedPath(CalendarContract.Events.CONTENT_URI, Long.toString(eventId))) .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, eventBegin) .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, eventEnd))); } private static long getCurrentTimestamp() { return Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis(); } private Cursor tryOpenEventsCursor(boolean showAllDay) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); boolean customVisibility = sp.getBoolean(PREF_CUSTOM_VISIBILITY, false); // Filter out all day events unless the user expressly requested to show all day events String allDaySelection = SQL_TAUTOLOGY; if (!showAllDay) { allDaySelection = CalendarContract.Instances.ALL_DAY + "=0"; } // Only filter on visible calendars if there isn't custom visibility String visibleCalendarsSelection = SQL_TAUTOLOGY; if (!customVisibility) { allDaySelection = CalendarContract.Instances.VISIBLE + "!=0"; } String calendarSelection = generateCalendarSelection(); Set<String> calendarSet = getSelectedCalendars(); String[] calendarsSelectionArgs = calendarSet.toArray(new String[calendarSet.size()]); long now = getCurrentTimestamp(); try { return getContentResolver().query( CalendarContract.Instances.CONTENT_URI.buildUpon() .appendPath(Long.toString(now)) .appendPath(Long.toString(now + mLookAheadHours * HOUR_MILLIS)) .build(), EventsQuery.PROJECTION, allDaySelection + " AND " + CalendarContract.Instances.SELF_ATTENDEE_STATUS + "!=" + CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED + " AND " + "IFNULL(" + CalendarContract.Instances.STATUS + ",0)!=" + CalendarContract.Instances.STATUS_CANCELED + " AND " + visibleCalendarsSelection + " AND (" + calendarSelection + ")", calendarsSelectionArgs, CalendarContract.Instances.BEGIN); } catch (Exception e) { LOGE(TAG, "Error querying calendar API", e); return null; } } private String generateCalendarSelection() { Set<String> calendars = getSelectedCalendars(); int count = calendars.size(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < count; i++) { if (i != 0) { sb.append(" OR "); } sb.append(CalendarContract.Events.CALENDAR_ID); sb.append(" = ?"); } if (sb.length() == 0) { sb.append(SQL_TAUTOLOGY); // constant expression to prevent returning null } return sb.toString(); } private interface EventsQuery { String[] PROJECTION = { CalendarContract.Instances.EVENT_ID, CalendarContract.Instances.BEGIN, CalendarContract.Instances.END, CalendarContract.Instances.TITLE, CalendarContract.Instances.EVENT_LOCATION, CalendarContract.Instances.ALL_DAY, }; int EVENT_ID = 0; int BEGIN = 1; int END = 2; int TITLE = 3; int EVENT_LOCATION = 4; int ALL_DAY = 5; } private interface CalendarsQuery { String[] PROJECTION = { CalendarContract.Calendars._ID, CalendarContract.Calendars.VISIBLE, }; int ID = 0; int VISIBLE = 1; } }
false
true
protected void onUpdateData(int reason) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); boolean showAllDay = sp.getBoolean(PREF_SHOW_ALL_DAY, false); try { mLookAheadHours = Integer.parseInt(sp.getString(PREF_LOOK_AHEAD_HOURS, Integer.toString(mLookAheadHours))); } catch (NumberFormatException e) { mLookAheadHours = DEFAULT_LOOK_AHEAD_HOURS; } Cursor cursor = tryOpenEventsCursor(showAllDay); if (cursor == null) { LOGE(TAG, "Null events cursor, short-circuiting."); return; } long currentTimestamp = getCurrentTimestamp(); long nextTimestamp = 0; long endTimestamp = 0; int tzOffset = TimeZone.getDefault().getOffset(nextTimestamp); long timeUntilNextAppointent = 0; boolean allDay = false; int allDayPosition = -1; long allDayTimestamp = 0; while (cursor.moveToNext()) { nextTimestamp = cursor.getLong(EventsQuery.BEGIN); allDay = cursor.getInt(EventsQuery.ALL_DAY) != 0; if (allDay) { endTimestamp = cursor.getLong(EventsQuery.END) - tzOffset; if (showAllDay && allDayPosition < 0 && endTimestamp > currentTimestamp) { // Store the position of this all day event. If no regular events are found // and the user wanted to see all day events, then show this all day event. allDayPosition = cursor.getPosition(); // For all day events (if the user wants to see them), convert the begin // timestamp, which is the midnight UTC time, to local time. That is, // nextTimestamp will now be midnight in local time since that's a more // relevant representation of that day to the user. allDayTimestamp = nextTimestamp - tzOffset; } continue; } timeUntilNextAppointent = nextTimestamp - currentTimestamp; if (timeUntilNextAppointent >= 0) { break; } // Skip over events that are not ALL_DAY but span multiple days, including // the next 6 hours. An example is an event that starts at 4pm yesterday // day and ends 6pm tomorrow. LOGD(TAG, "Skipping over event with start timestamp " + nextTimestamp + ". " + "Current timestamp " + currentTimestamp); } if (allDayPosition >= 0) { // Only show all day events if there's no regular event (cursor is after last) // or if the all day event is tomorrow or later and the all day event is later than // the regular event. if (cursor.isAfterLast() || ((allDayTimestamp - currentTimestamp) > 0 && allDayTimestamp < nextTimestamp)) { cursor.moveToPosition(allDayPosition); allDay = true; nextTimestamp = allDayTimestamp; timeUntilNextAppointent = nextTimestamp - currentTimestamp; LOGD(TAG, "Showing an all day event because either no regular event was found or " + "it's a full day later than the all-day event."); } } if (cursor.isAfterLast()) { LOGD(TAG, "No upcoming appointments found."); cursor.close(); publishUpdate(new ExtensionData()); return; } Calendar nextEventCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); nextEventCalendar.setTimeInMillis(nextTimestamp); int minutesUntilNextAppointment = (int) (timeUntilNextAppointent / MINUTE_MILLIS); String untilString; if (allDay) { if (timeUntilNextAppointent <= 0) { // All day event happening today (its start time is past today's midnight // offset. untilString = getString(R.string.today); } else { untilString = new SimpleDateFormat("E").format(nextEventCalendar.getTime()); } } else if (minutesUntilNextAppointment < 60) { untilString = getResources().getQuantityString( R.plurals.calendar_template_mins, minutesUntilNextAppointment, minutesUntilNextAppointment); } else { int hours = Math.round(minutesUntilNextAppointment / 60f); if (hours < 24) { untilString = getResources().getQuantityString( R.plurals.calendar_template_hours, hours, hours); } else { untilString = new SimpleDateFormat("E").format(nextEventCalendar.getTime()); } } String eventTitle = cursor.getString(EventsQuery.TITLE); String eventLocation = cursor.getString(EventsQuery.EVENT_LOCATION); long eventId = cursor.getLong(EventsQuery.EVENT_ID); long eventBegin = cursor.getLong(EventsQuery.BEGIN); long eventEnd = cursor.getLong(EventsQuery.END); cursor.close(); String expandedTime = null; StringBuilder expandedTimeFormat = new StringBuilder(); if (allDay) { if (timeUntilNextAppointent <= 0) { // All day event happening today (its start time is past today's midnight // offset. expandedTimeFormat.setLength(0); expandedTime = getString(R.string.today); } else { expandedTimeFormat.append("EEEE, MMM dd"); } } else { if (nextTimestamp - currentTimestamp > 24 * HOUR_MILLIS) { expandedTimeFormat.append("EEEE, "); } if (DateFormat.is24HourFormat(this)) { expandedTimeFormat.append("HH:mm"); } else { expandedTimeFormat.append("h:mm a"); } } if (expandedTimeFormat.length() > 0) { expandedTime = new SimpleDateFormat(expandedTimeFormat.toString()) .format(nextEventCalendar.getTime()); } String expandedBody = expandedTime; if (!TextUtils.isEmpty(eventLocation)) { expandedBody = getString(R.string.calendar_with_location_template, expandedTime, eventLocation); } publishUpdate(new ExtensionData() .visible(allDay || (timeUntilNextAppointent >= 0 && timeUntilNextAppointent <= mLookAheadHours * HOUR_MILLIS)) .icon(R.drawable.ic_extension_calendar) .status(untilString) .expandedTitle(eventTitle) .expandedBody(expandedBody) .clickIntent(new Intent(Intent.ACTION_VIEW) .setData(Uri.withAppendedPath(CalendarContract.Events.CONTENT_URI, Long.toString(eventId))) .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, eventBegin) .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, eventEnd))); }
protected void onUpdateData(int reason) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); boolean showAllDay = sp.getBoolean(PREF_SHOW_ALL_DAY, false); try { mLookAheadHours = Integer.parseInt(sp.getString(PREF_LOOK_AHEAD_HOURS, Integer.toString(mLookAheadHours))); } catch (NumberFormatException e) { mLookAheadHours = DEFAULT_LOOK_AHEAD_HOURS; } Cursor cursor = tryOpenEventsCursor(showAllDay); if (cursor == null) { LOGE(TAG, "Null events cursor, short-circuiting."); return; } long currentTimestamp = getCurrentTimestamp(); long nextTimestamp = 0; long endTimestamp = 0; long timeUntilNextAppointent = 0; boolean allDay = false; int allDayPosition = -1; long allDayTimestampLocalMidnight = 0; while (cursor.moveToNext()) { nextTimestamp = cursor.getLong(EventsQuery.BEGIN); int tzOffset = TimeZone.getDefault().getOffset(nextTimestamp); allDay = cursor.getInt(EventsQuery.ALL_DAY) != 0; if (allDay) { endTimestamp = cursor.getLong(EventsQuery.END) - tzOffset; if (showAllDay && allDayPosition < 0 && endTimestamp > currentTimestamp) { // Store the position of this all day event. If no regular events are found // and the user wanted to see all day events, then show this all day event. allDayPosition = cursor.getPosition(); // For all day events (if the user wants to see them), convert the begin // timestamp, which is the midnight UTC time, to local time. That is, // allDayTimestampLocalMidnight will be midnight in local time since that's a // more relevant representation of that day to the user. allDayTimestampLocalMidnight = nextTimestamp - tzOffset; } continue; } timeUntilNextAppointent = nextTimestamp - currentTimestamp; if (timeUntilNextAppointent >= 0) { break; } // Skip over events that are not ALL_DAY but span multiple days, including // the next 6 hours. An example is an event that starts at 4pm yesterday // day and ends 6pm tomorrow. LOGD(TAG, "Skipping over event with start timestamp " + nextTimestamp + ". " + "Current timestamp " + currentTimestamp); } if (allDayPosition >= 0) { // Only show all day events if there's no regular event (cursor is after last) // or if the all day event is tomorrow or later and the all day event is later than // the regular event. if (cursor.isAfterLast() || ((allDayTimestampLocalMidnight - currentTimestamp) > 0 && allDayTimestampLocalMidnight < nextTimestamp)) { cursor.moveToPosition(allDayPosition); allDay = true; nextTimestamp = allDayTimestampLocalMidnight; timeUntilNextAppointent = nextTimestamp - currentTimestamp; LOGD(TAG, "Showing an all day event because either no regular event was found or " + "it's a full day later than the all-day event."); } } if (cursor.isAfterLast()) { LOGD(TAG, "No upcoming appointments found."); cursor.close(); publishUpdate(new ExtensionData()); return; } Calendar nextEventCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); nextEventCalendar.setTimeInMillis(nextTimestamp); int minutesUntilNextAppointment = (int) (timeUntilNextAppointent / MINUTE_MILLIS); String untilString; if (allDay) { if (timeUntilNextAppointent <= 0) { // All day event happening today (its start time is past today's midnight // offset. untilString = getString(R.string.today); } else { untilString = new SimpleDateFormat("E").format(nextEventCalendar.getTime()); } } else if (minutesUntilNextAppointment < 60) { untilString = getResources().getQuantityString( R.plurals.calendar_template_mins, minutesUntilNextAppointment, minutesUntilNextAppointment); } else { int hours = Math.round(minutesUntilNextAppointment / 60f); if (hours < 24) { untilString = getResources().getQuantityString( R.plurals.calendar_template_hours, hours, hours); } else { untilString = new SimpleDateFormat("E").format(nextEventCalendar.getTime()); } } String eventTitle = cursor.getString(EventsQuery.TITLE); String eventLocation = cursor.getString(EventsQuery.EVENT_LOCATION); long eventId = cursor.getLong(EventsQuery.EVENT_ID); long eventBegin = cursor.getLong(EventsQuery.BEGIN); long eventEnd = cursor.getLong(EventsQuery.END); cursor.close(); String expandedTime = null; StringBuilder expandedTimeFormat = new StringBuilder(); if (allDay) { if (timeUntilNextAppointent <= 0) { // All day event happening today (its start time is past today's midnight // offset. expandedTimeFormat.setLength(0); expandedTime = getString(R.string.today); } else { expandedTimeFormat.append("EEEE, MMM dd"); } } else { if (nextTimestamp - currentTimestamp > 24 * HOUR_MILLIS) { expandedTimeFormat.append("EEEE, "); } if (DateFormat.is24HourFormat(this)) { expandedTimeFormat.append("HH:mm"); } else { expandedTimeFormat.append("h:mm a"); } } if (expandedTimeFormat.length() > 0) { expandedTime = new SimpleDateFormat(expandedTimeFormat.toString()) .format(nextEventCalendar.getTime()); } String expandedBody = expandedTime; if (!TextUtils.isEmpty(eventLocation)) { expandedBody = getString(R.string.calendar_with_location_template, expandedTime, eventLocation); } publishUpdate(new ExtensionData() .visible(allDay || (timeUntilNextAppointent >= 0 && timeUntilNextAppointent <= mLookAheadHours * HOUR_MILLIS)) .icon(R.drawable.ic_extension_calendar) .status(untilString) .expandedTitle(eventTitle) .expandedBody(expandedBody) .clickIntent(new Intent(Intent.ACTION_VIEW) .setData(Uri.withAppendedPath(CalendarContract.Events.CONTENT_URI, Long.toString(eventId))) .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, eventBegin) .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, eventEnd))); }
diff --git a/TechGuard/Archers/Arrow/ArrowHandler.java b/TechGuard/Archers/Arrow/ArrowHandler.java index 2b0ce82..556dc79 100644 --- a/TechGuard/Archers/Arrow/ArrowHandler.java +++ b/TechGuard/Archers/Arrow/ArrowHandler.java @@ -1,58 +1,60 @@ package TechGuard.Archers.Arrow; import net.minecraft.server.EntityArrow; import org.bukkit.entity.Player; import org.bukkit.event.entity.EntityDamageByProjectileEvent; import org.bukkit.craftbukkit.entity.CraftArrow; /** * @author �TechGuard */ public class ArrowHandler { public static short lastData = 0; public static void onArrowCreate(Player p, Arrow arrow){ org.bukkit.entity.Arrow ea = ((org.bukkit.entity.Arrow)arrow.getBukkitEntity()); if(arrow.material == EnumBowMaterial.FIRE){ ea.setFireTicks(300); } arrow.world.addEntity((EntityArrow)arrow); } public static void onArrowDestroy(EntityDamageByProjectileEvent event){ Arrow arrow = (Arrow)((CraftArrow)event.getProjectile()).getHandle(); event.setDamage(arrow.material.getDamageValue()); arrow.destroy(); if(arrow.material == EnumBowMaterial.FIRE){ event.getEntity().setFireTicks(80); } else if(arrow.material == EnumBowMaterial.ZOMBIE){ if(event.getEntity() instanceof Zombie){ Zombie zombie = (Zombie)event.getEntity(); Giant giant = (Giant)zombie.getWorld().spawnCreature(zombie.getLocation(), CreatureType.GIANT); giant.setHealth(zombie.getHealth()); zombie.remove(); } else if(event.getEntity() instanceof Giant){ Giant giant = (Giant)event.getEntity(); Zombie zombie = (Zombie)giant.getWorld().spawnCreature(giant.getLocation(), CreatureType.ZOMBIE); zombie.setHealth(giant.getHealth()); giant.remove(); } } - if(arrow.material == EnumBowMaterial.PIG){ + if(arrow.material == EnumBowMaterial.PIG){ if(event.getEntity() instanceof Pig){ Pig pig = (Pig)event.getEntity(); PigZombie pigman = (PigZombie) pig.getWorld().spawnCreature(pig.getLocation(), CreatureType.PIG_ZOMBIE); + pigman.setHealth(pig.getHealth()); pig.remove(); } else if(event.getEntity() instanceof PigZombie){ - PigZombie pigzombie = (PigZombie)event.getEntity(); - Pig pig = (Pig) pigzombie.getWorld().spawnCreature(pigzombie.getLocation(), CreatureType.PIG); - pigzombie.remove(); + PigZombie pigman = (PigZombie)event.getEntity(); + Pig pig = (Pig) pigman.getWorld().spawnCreature(pigman.getLocation(), CreatureType.PIG); + pig.setHealth(pigman.getHealth()); + pigman.remove(); } } } }
false
true
public static void onArrowDestroy(EntityDamageByProjectileEvent event){ Arrow arrow = (Arrow)((CraftArrow)event.getProjectile()).getHandle(); event.setDamage(arrow.material.getDamageValue()); arrow.destroy(); if(arrow.material == EnumBowMaterial.FIRE){ event.getEntity().setFireTicks(80); } else if(arrow.material == EnumBowMaterial.ZOMBIE){ if(event.getEntity() instanceof Zombie){ Zombie zombie = (Zombie)event.getEntity(); Giant giant = (Giant)zombie.getWorld().spawnCreature(zombie.getLocation(), CreatureType.GIANT); giant.setHealth(zombie.getHealth()); zombie.remove(); } else if(event.getEntity() instanceof Giant){ Giant giant = (Giant)event.getEntity(); Zombie zombie = (Zombie)giant.getWorld().spawnCreature(giant.getLocation(), CreatureType.ZOMBIE); zombie.setHealth(giant.getHealth()); giant.remove(); } } if(arrow.material == EnumBowMaterial.PIG){ if(event.getEntity() instanceof Pig){ Pig pig = (Pig)event.getEntity(); PigZombie pigman = (PigZombie) pig.getWorld().spawnCreature(pig.getLocation(), CreatureType.PIG_ZOMBIE); pig.remove(); } else if(event.getEntity() instanceof PigZombie){ PigZombie pigzombie = (PigZombie)event.getEntity(); Pig pig = (Pig) pigzombie.getWorld().spawnCreature(pigzombie.getLocation(), CreatureType.PIG); pigzombie.remove(); } } }
public static void onArrowDestroy(EntityDamageByProjectileEvent event){ Arrow arrow = (Arrow)((CraftArrow)event.getProjectile()).getHandle(); event.setDamage(arrow.material.getDamageValue()); arrow.destroy(); if(arrow.material == EnumBowMaterial.FIRE){ event.getEntity().setFireTicks(80); } else if(arrow.material == EnumBowMaterial.ZOMBIE){ if(event.getEntity() instanceof Zombie){ Zombie zombie = (Zombie)event.getEntity(); Giant giant = (Giant)zombie.getWorld().spawnCreature(zombie.getLocation(), CreatureType.GIANT); giant.setHealth(zombie.getHealth()); zombie.remove(); } else if(event.getEntity() instanceof Giant){ Giant giant = (Giant)event.getEntity(); Zombie zombie = (Zombie)giant.getWorld().spawnCreature(giant.getLocation(), CreatureType.ZOMBIE); zombie.setHealth(giant.getHealth()); giant.remove(); } } if(arrow.material == EnumBowMaterial.PIG){ if(event.getEntity() instanceof Pig){ Pig pig = (Pig)event.getEntity(); PigZombie pigman = (PigZombie) pig.getWorld().spawnCreature(pig.getLocation(), CreatureType.PIG_ZOMBIE); pigman.setHealth(pig.getHealth()); pig.remove(); } else if(event.getEntity() instanceof PigZombie){ PigZombie pigman = (PigZombie)event.getEntity(); Pig pig = (Pig) pigman.getWorld().spawnCreature(pigman.getLocation(), CreatureType.PIG); pig.setHealth(pigman.getHealth()); pigman.remove(); } } }
diff --git a/java/src/org/broadinstitute/sting/gatk/dataSources/simpleDataSources/SAMDataSource.java b/java/src/org/broadinstitute/sting/gatk/dataSources/simpleDataSources/SAMDataSource.java index bf7f2622e..cd72550af 100755 --- a/java/src/org/broadinstitute/sting/gatk/dataSources/simpleDataSources/SAMDataSource.java +++ b/java/src/org/broadinstitute/sting/gatk/dataSources/simpleDataSources/SAMDataSource.java @@ -1,389 +1,391 @@ package org.broadinstitute.sting.gatk.dataSources.simpleDataSources; import edu.mit.broad.picard.sam.SamFileHeaderMerger; import net.sf.samtools.SAMFileHeader; import net.sf.samtools.SAMFileReader; import net.sf.samtools.SAMReadGroupRecord; import net.sf.samtools.SAMRecord; import org.apache.log4j.Logger; import org.broadinstitute.sting.gatk.dataSources.shards.ReadShard; import org.broadinstitute.sting.gatk.dataSources.shards.Shard; import org.broadinstitute.sting.gatk.iterators.BoundedReadIterator; import org.broadinstitute.sting.gatk.iterators.MergingSamRecordIterator2; import org.broadinstitute.sting.gatk.iterators.StingSAMIterator; import org.broadinstitute.sting.utils.GenomeLoc; import org.broadinstitute.sting.utils.StingException; import java.io.File; import java.util.ArrayList; import java.util.List; /** * User: aaron * Date: Mar 26, 2009 * Time: 2:36:16 PM * <p/> * The Broad Institute * SOFTWARE COPYRIGHT NOTICE AGREEMENT * This software and its documentation are copyright 2009 by the * Broad Institute/Massachusetts Institute of Technology. All rights are reserved. * <p/> * This software is supplied without any warranty or guaranteed support whatsoever. Neither * the Broad Institute nor MIT can be responsible for its use, misuse, or functionality. */ public class SAMDataSource implements SimpleDataSource { /** our SAM data files */ private final SAMFileHeader.SortOrder SORT_ORDER = SAMFileHeader.SortOrder.coordinate; /** our log, which we want to capture anything from this class */ protected static Logger logger = Logger.getLogger(SAMDataSource.class); // How strict should we be with SAM/BAM parsing? protected SAMFileReader.ValidationStringency strictness = SAMFileReader.ValidationStringency.SILENT; // our list of readers private final List<File> samFileList = new ArrayList<File>(); /** * SAM header file. */ private final SAMFileHeader header; // used for the reads case, the last count of reads retrieved private long readsTaken = 0; // our last genome loc position private GenomeLoc lastReadPos = null; // do we take unmapped reads private boolean includeUnmappedReads = true; // reads based traversal variables private boolean intoUnmappedReads = false; private int readsAtLastPos = 0; /** * constructor, given sam files * * @param samFiles the list of sam files */ public SAMDataSource(List<?> samFiles) throws SimpleDataSourceLoadException { // check the length if (samFiles.size() < 1) { throw new SimpleDataSourceLoadException("SAMDataSource: you must provide a list of length greater then 0"); } for (Object fileName : samFiles) { File smFile; if (samFiles.get(0) instanceof String) { smFile = new File((String) samFiles.get(0)); } else if (samFiles.get(0) instanceof File) { smFile = (File) fileName; } else { throw new SimpleDataSourceLoadException("SAMDataSource: unknown samFile list type, must be String or File"); } if (!smFile.canRead()) { throw new SimpleDataSourceLoadException("SAMDataSource: Unable to load file: " + fileName); } samFileList.add(smFile); } header = createHeaderMerger().getMergedHeader(); } /** * Load up a sam file. * * @param samFile the file name * @return a SAMFileReader for the file */ private SAMFileReader initializeSAMFile(final File samFile) { if (samFile.toString().endsWith(".list")) { return null; } else { SAMFileReader samReader = new SAMFileReader(samFile, true); samReader.setValidationStringency(strictness); final SAMFileHeader header = samReader.getFileHeader(); logger.debug(String.format("Sort order is: " + header.getSortOrder())); return samReader; } } /** * <p> * seek * </p> * * @param location the genome location to extract data for * @return an iterator for that region */ public MergingSamRecordIterator2 seekLocus(GenomeLoc location) throws SimpleDataSourceLoadException { // right now this is pretty damn heavy, it copies the file list into a reader list every time SamFileHeaderMerger headerMerger = createHeaderMerger(); // make a merging iterator for this record MergingSamRecordIterator2 iter = new MergingSamRecordIterator2(headerMerger); // we do different things for locus and read modes iter.queryOverlapping(location.getContig(), (int) location.getStart(), (int) location.getStop() + 1); // return the iterator return iter; } /** * <p> * seek * </p> * * @param shard the shard to get data for * @return an iterator for that region */ public StingSAMIterator seek(Shard shard) throws SimpleDataSourceLoadException { if (shard.getShardType() == Shard.ShardType.READ) { return seekRead((ReadShard) shard); } else if (shard.getShardType() == Shard.ShardType.LOCUS) { return seekLocus(shard.getGenomeLoc()); } else { throw new StingException("seek: Unknown shard type"); } } /** * If we're in by-read mode, this indicates if we want * to see unmapped reads too. Only seeing mapped reads * is much faster, but most BAM files have significant * unmapped read counts. * * @param seeUnMappedReads true to see unmapped reads, false otherwise */ public void viewUnmappedReads(boolean seeUnMappedReads) { includeUnmappedReads = seeUnMappedReads; } /** * Gets the (potentially merged) SAM file header. * @return SAM file header. */ public SAMFileHeader getHeader() { return header; } /** * <p> * seek * </p> * * @param shard the read shard to extract from * @return an iterator for that region */ private BoundedReadIterator seekRead(ReadShard shard) throws SimpleDataSourceLoadException { BoundedReadIterator bound = null; SamFileHeaderMerger headerMerger = createHeaderMerger(); MergingSamRecordIterator2 iter = null; if (!intoUnmappedReads) { // make a merging iterator for this record iter = new MergingSamRecordIterator2(headerMerger); bound = fastMappedReadSeek(shard.getSize(), iter); } if ((bound == null || intoUnmappedReads) && includeUnmappedReads) { if (iter != null) { iter.close(); } iter = new MergingSamRecordIterator2(createHeaderMerger()); bound = toUnmappedReads(shard.getSize(), iter); } if (bound == null) { shard.signalDone(); bound = new BoundedReadIterator(iter, 0); } return bound; } private SamFileHeaderMerger createHeaderMerger() { // TODO: make extremely less horrible List<SAMFileReader> lst = GetReaderList(); // now merge the headers SamFileHeaderMerger headerMerger = new SamFileHeaderMerger(lst, SORT_ORDER); return headerMerger; } /** * Seek, if we want unmapped reads. This method will be faster then the unmapped read method, but you cannot extract the * unmapped reads. * * @param readCount how many reads to retrieve * @param iter the iterator to use * @return the bounded iterator that you can use to get the intervaled reads from * @throws SimpleDataSourceLoadException */ private BoundedReadIterator toUnmappedReads(long readCount, MergingSamRecordIterator2 iter) throws SimpleDataSourceLoadException { BoundedReadIterator bound;// is this the first time we're doing this? int count = 0; SAMRecord d = null; while (iter.hasNext()) { d = iter.peek(); int x = d.getReferenceIndex(); if (x < 0 || x >= d.getHeader().getSequenceDictionary().getSequences().size()) { // we have the magic read that starts the unmapped read segment! break; } iter.next(); } // check to see what happened, did we run out of reads? if (!iter.hasNext()) { return null; } // now walk until we've taken the unmapped read count while (iter.hasNext() && count < this.readsTaken) { iter.next(); } // check to see what happened, did we run out of reads? if (!iter.hasNext()) { return null; } // we're good, increment our read cout this.readsTaken += readCount; return new BoundedReadIterator(iter, readCount); } /** * unmapped reads. * * @param readCount how many reads to retrieve * @param iter the iterator to use * @return the bounded iterator that you can use to get the intervaled reads from * @throws SimpleDataSourceLoadException */ private BoundedReadIterator fastMappedReadSeek(long readCount, MergingSamRecordIterator2 iter) throws SimpleDataSourceLoadException { BoundedReadIterator bound;// is this the first time we're doing this? if (lastReadPos == null) { lastReadPos = new GenomeLoc(iter.getHeader().getSequenceDictionary().getSequence(0).getSequenceIndex(), 0, 0); iter.queryContained(lastReadPos.getContig(), 1, -1); bound = new BoundedReadIterator(iter, readCount); this.readsTaken = readCount; } // we're not at the beginning, not at the end, so we move forward with our ghastly plan... else { iter.queryContained(lastReadPos.getContig(), (int) lastReadPos.getStop(), -1); // move the number of reads we read from the last pos + boolean atLeastOneReadSeen = false; // we have a problem where some chomesomes don't have a single read (i.e. the chrN_random chrom.) while (iter.hasNext() && this.readsAtLastPos > 0) { iter.next(); --readsAtLastPos; + atLeastOneReadSeen = true; } - if (readsAtLastPos != 0) { + if (readsAtLastPos != 0 && atLeastOneReadSeen) { throw new SimpleDataSourceLoadException("Seek problem: reads at last position count != 0"); } int x = 0; SAMRecord rec = null; int lastPos = 0; while (x < readsTaken) { if (iter.hasNext()) { rec = iter.next(); if (lastPos == rec.getAlignmentStart()) { ++this.readsAtLastPos; } else { this.readsAtLastPos = 1; } lastPos = rec.getAlignmentStart(); ++x; } else { // jump contigs if (lastReadPos.toNextContig() == false) { // check to see if we're using unmapped reads, if not return, we're done readsTaken = 0; intoUnmappedReads = true; return null; } else { iter.close(); // now merge the headers // right now this is pretty damn heavy, it copies the file list into a reader list every time SamFileHeaderMerger mg = createHeaderMerger(); iter = new MergingSamRecordIterator2(mg); iter.queryContained(lastReadPos.getContig(), 1, Integer.MAX_VALUE); return new BoundedReadIterator(iter,readCount); } } } // if we're off the end of the last contig (into unmapped territory) if (rec != null && rec.getAlignmentStart() == 0) { readsTaken += readCount; intoUnmappedReads = true; } // else we're not off the end, store our location else if (rec != null) { int stopPos = rec.getAlignmentStart(); if (stopPos < lastReadPos.getStart()) { lastReadPos = new GenomeLoc(lastReadPos.getContigIndex() + 1, stopPos, stopPos); } else { lastReadPos.setStop(rec.getAlignmentStart()); } } // in case we're run out of reads, get out else { throw new StingException("Danger: weve run out reads in fastMappedReadSeek"); //return null; } bound = new BoundedReadIterator(iter, readCount); } // return the iterator return bound; } /** * A private function that, given the internal file list, generates a SamFileReader * list of validated files. * * @return a list of SAMFileReaders that represent the stored file names * @throws SimpleDataSourceLoadException if there's a problem loading the files */ private List<SAMFileReader> GetReaderList() throws SimpleDataSourceLoadException { // right now this is pretty damn heavy, it copies the file list into a reader list every time List<SAMFileReader> lst = new ArrayList<SAMFileReader>(); for (File f : this.samFileList) { SAMFileReader reader = initializeSAMFile(f); if (reader.getFileHeader().getReadGroups().size() < 1) { //logger.warn("Setting header in reader " + f.getName()); SAMReadGroupRecord rec = new SAMReadGroupRecord(f.getName()); rec.setLibrary(f.getName()); rec.setSample(f.getName()); reader.getFileHeader().addReadGroup(rec); } if (reader == null) { throw new SimpleDataSourceLoadException("SAMDataSource: Unable to load file: " + f); } lst.add(reader); } return lst; } }
false
true
private BoundedReadIterator fastMappedReadSeek(long readCount, MergingSamRecordIterator2 iter) throws SimpleDataSourceLoadException { BoundedReadIterator bound;// is this the first time we're doing this? if (lastReadPos == null) { lastReadPos = new GenomeLoc(iter.getHeader().getSequenceDictionary().getSequence(0).getSequenceIndex(), 0, 0); iter.queryContained(lastReadPos.getContig(), 1, -1); bound = new BoundedReadIterator(iter, readCount); this.readsTaken = readCount; } // we're not at the beginning, not at the end, so we move forward with our ghastly plan... else { iter.queryContained(lastReadPos.getContig(), (int) lastReadPos.getStop(), -1); // move the number of reads we read from the last pos while (iter.hasNext() && this.readsAtLastPos > 0) { iter.next(); --readsAtLastPos; } if (readsAtLastPos != 0) { throw new SimpleDataSourceLoadException("Seek problem: reads at last position count != 0"); } int x = 0; SAMRecord rec = null; int lastPos = 0; while (x < readsTaken) { if (iter.hasNext()) { rec = iter.next(); if (lastPos == rec.getAlignmentStart()) { ++this.readsAtLastPos; } else { this.readsAtLastPos = 1; } lastPos = rec.getAlignmentStart(); ++x; } else { // jump contigs if (lastReadPos.toNextContig() == false) { // check to see if we're using unmapped reads, if not return, we're done readsTaken = 0; intoUnmappedReads = true; return null; } else { iter.close(); // now merge the headers // right now this is pretty damn heavy, it copies the file list into a reader list every time SamFileHeaderMerger mg = createHeaderMerger(); iter = new MergingSamRecordIterator2(mg); iter.queryContained(lastReadPos.getContig(), 1, Integer.MAX_VALUE); return new BoundedReadIterator(iter,readCount); } } } // if we're off the end of the last contig (into unmapped territory) if (rec != null && rec.getAlignmentStart() == 0) { readsTaken += readCount; intoUnmappedReads = true; } // else we're not off the end, store our location else if (rec != null) { int stopPos = rec.getAlignmentStart(); if (stopPos < lastReadPos.getStart()) { lastReadPos = new GenomeLoc(lastReadPos.getContigIndex() + 1, stopPos, stopPos); } else { lastReadPos.setStop(rec.getAlignmentStart()); } } // in case we're run out of reads, get out else { throw new StingException("Danger: weve run out reads in fastMappedReadSeek"); //return null; } bound = new BoundedReadIterator(iter, readCount); } // return the iterator return bound; }
private BoundedReadIterator fastMappedReadSeek(long readCount, MergingSamRecordIterator2 iter) throws SimpleDataSourceLoadException { BoundedReadIterator bound;// is this the first time we're doing this? if (lastReadPos == null) { lastReadPos = new GenomeLoc(iter.getHeader().getSequenceDictionary().getSequence(0).getSequenceIndex(), 0, 0); iter.queryContained(lastReadPos.getContig(), 1, -1); bound = new BoundedReadIterator(iter, readCount); this.readsTaken = readCount; } // we're not at the beginning, not at the end, so we move forward with our ghastly plan... else { iter.queryContained(lastReadPos.getContig(), (int) lastReadPos.getStop(), -1); // move the number of reads we read from the last pos boolean atLeastOneReadSeen = false; // we have a problem where some chomesomes don't have a single read (i.e. the chrN_random chrom.) while (iter.hasNext() && this.readsAtLastPos > 0) { iter.next(); --readsAtLastPos; atLeastOneReadSeen = true; } if (readsAtLastPos != 0 && atLeastOneReadSeen) { throw new SimpleDataSourceLoadException("Seek problem: reads at last position count != 0"); } int x = 0; SAMRecord rec = null; int lastPos = 0; while (x < readsTaken) { if (iter.hasNext()) { rec = iter.next(); if (lastPos == rec.getAlignmentStart()) { ++this.readsAtLastPos; } else { this.readsAtLastPos = 1; } lastPos = rec.getAlignmentStart(); ++x; } else { // jump contigs if (lastReadPos.toNextContig() == false) { // check to see if we're using unmapped reads, if not return, we're done readsTaken = 0; intoUnmappedReads = true; return null; } else { iter.close(); // now merge the headers // right now this is pretty damn heavy, it copies the file list into a reader list every time SamFileHeaderMerger mg = createHeaderMerger(); iter = new MergingSamRecordIterator2(mg); iter.queryContained(lastReadPos.getContig(), 1, Integer.MAX_VALUE); return new BoundedReadIterator(iter,readCount); } } } // if we're off the end of the last contig (into unmapped territory) if (rec != null && rec.getAlignmentStart() == 0) { readsTaken += readCount; intoUnmappedReads = true; } // else we're not off the end, store our location else if (rec != null) { int stopPos = rec.getAlignmentStart(); if (stopPos < lastReadPos.getStart()) { lastReadPos = new GenomeLoc(lastReadPos.getContigIndex() + 1, stopPos, stopPos); } else { lastReadPos.setStop(rec.getAlignmentStart()); } } // in case we're run out of reads, get out else { throw new StingException("Danger: weve run out reads in fastMappedReadSeek"); //return null; } bound = new BoundedReadIterator(iter, readCount); } // return the iterator return bound; }
diff --git a/src/com/twitstreet/twitter/AnnouncerMgrImpl.java b/src/com/twitstreet/twitter/AnnouncerMgrImpl.java index dfbaacc..3eb7bb3 100644 --- a/src/com/twitstreet/twitter/AnnouncerMgrImpl.java +++ b/src/com/twitstreet/twitter/AnnouncerMgrImpl.java @@ -1,271 +1,271 @@ /** TwitStreet - Twitter Stock Market Game Copyright (C) 2012 Engin Guller ([email protected]), Cagdas Ozek ([email protected]) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **/ package com.twitstreet.twitter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import org.apache.log4j.Logger; import twitter4j.StatusUpdate; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.auth.AccessToken; import com.google.inject.Inject; import com.twitstreet.db.base.DBConstants; import com.twitstreet.db.base.DBMgr; import com.twitstreet.db.data.Announcer; import com.twitstreet.localization.LocalizationUtil; public class AnnouncerMgrImpl implements AnnouncerMgr { private static Logger logger = Logger.getLogger(AnnouncerMgrImpl.class); @Inject private DBMgr dbMgr; private static final String LOAD_ANNOUNCER = "select * from announcer"; ArrayList<Twitter> announcerList = new ArrayList<Twitter>(); ArrayList<Announcer> announcerDataList = new ArrayList<Announcer>(); Twitter twitstreetGame = null; Twitter diablobird = null; public void loadAnnouncers() { Connection connection = null; PreparedStatement ps = null; ResultSet rs = null; try { connection = dbMgr.getConnection(); ps = connection.prepareStatement(LOAD_ANNOUNCER); rs = ps.executeQuery(); while (rs.next()) { Announcer announcer = new Announcer(); announcer.getDataFromResultSet(rs); announcerDataList.add(announcer); if (TWITSTREET_GAME.equals(announcer.getName())) { twitstreetGame = new TwitterFactory().getInstance(); twitstreetGame.setOAuthConsumer(announcer.getConsumerKey(), announcer.getConsumerSecret()); twitstreetGame.setOAuthAccessToken(new AccessToken(announcer.getAccessToken(), announcer.getAccessTokenSecret())); } - if (DIABLOBIRD.equals(announcer.getName())) { + else if (DIABLOBIRD.equals(announcer.getName())) { diablobird = new TwitterFactory().getInstance(); diablobird.setOAuthConsumer(announcer.getConsumerKey(), announcer.getConsumerSecret()); diablobird.setOAuthAccessToken(new AccessToken(announcer.getAccessToken(), announcer.getAccessTokenSecret())); } else { Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(announcer.getConsumerKey(), announcer.getConsumerSecret()); twitter.setOAuthAccessToken(new AccessToken(announcer.getAccessToken(), announcer.getAccessTokenSecret())); announcerList.add(twitter); } } logger.debug(DBConstants.QUERY_EXECUTION_SUCC + ps.toString()); } catch (SQLException ex) { logger.error(DBConstants.QUERY_EXECUTION_FAIL + ps.toString(), ex); } finally { dbMgr.closeResources(connection, ps, rs); } } @Override public Twitter random() { if (announcerList.size() > 0) { return announcerList.get((int) (Math.random() * announcerList.size())); } else { return null; } } @Override public void announceFromRandomAnnouncer(String message) { Twitter twitter = random(); String screenName = ""; if (twitter != null) { try { twitter.updateStatus(message); screenName = twitter.getScreenName(); } catch (TwitterException e) { logger.error("Announcement failed: " + screenName, e); } } else { logger.error("TwitStreet announcer is null"); } } @Override public void announceForDiabloBird(String message) { Twitter twitter = diablobird; String screenName = ""; if (twitter != null) { try { twitter.updateStatus(message); screenName = twitter.getScreenName(); logger.info("announceForDiabloBird"); } catch (TwitterException e) { logger.error("Announcement failed: " + screenName, e); } } else { logger.error("TwitStreet announcer is null"); } } public Twitter getTwitstreetGame() { return twitstreetGame; } @Override public void announceFromTwitStreetGame(String message) { String screenName = ""; if (twitstreetGame != null) { try { twitstreetGame.updateStatus(message); } catch (TwitterException e) { logger.error("Announcement failed: " + screenName, e); } } else { logger.error("Twitstreet game is null"); } } @Override public ArrayList<Announcer> getAnnouncerDataList() { return announcerDataList; } @Override public Announcer randomAnnouncerData() { return announcerDataList.get((int) (Math.random() * announcerDataList.size())); } @Override public void retweet(long statusId) { Twitter twitter = random(); String screenName = ""; try { twitter.retweetStatus(statusId); screenName = twitter.getScreenName(); } catch (TwitterException e) { logger.error("Error while retweeting: " + statusId + " Announcer: " + screenName, e); } } @Override public void retweetForDiabloBird(long statusId) { Twitter twitter = diablobird; String screenName = ""; try { twitter.retweetStatus(statusId); screenName = twitter.getScreenName(); logger.info("retweetForDiabloBird"); } catch (TwitterException e) { logger.error("Error while retweeting: " + statusId + " Announcer: " + screenName, e); } } @Override public void follow(long userId) { Twitter twitter = random(); String screenName = ""; try { twitter.createFriendship(userId); screenName = twitter.getScreenName(); } catch (TwitterException e) { logger.error("Error while following: " + userId + " Announcer: " + screenName, e); } } @Override public void followForDiabloBird(long userId) { Twitter twitter = diablobird; String screenName = ""; try { twitter.createFriendship(userId); screenName = twitter.getScreenName(); logger.info("followForDiabloBird"); } catch (TwitterException e) { logger.error("Error while following: " + userId + " Announcer: " + screenName, e); } } @Override public void favourite(long statusId) { Twitter twitter = random(); String screenName = ""; try { twitter.createFavorite(statusId); screenName = twitter.getScreenName(); } catch (TwitterException e) { logger.error("Error while creating favorite: " + statusId + " Announcer: " + screenName, e); } } @Override public void favouriteForDiabloBird(long statusId) { Twitter twitter = diablobird; String screenName = ""; try { twitter.createFavorite(statusId); screenName = twitter.getScreenName(); logger.info("favouriteForDiabloBird"); } catch (TwitterException e) { logger.error("Error while creating favorite: " + statusId + " Announcer: " + screenName, e); } } @Override public void reply(String message, long statusId) { Twitter twitter = random(); String screenName = ""; if (twitter != null) { try { twitter.updateStatus(new StatusUpdate(message).inReplyToStatusId(statusId)); screenName = twitter.getScreenName(); } catch (TwitterException e) { logger.error("Announcement failed: " + screenName, e); } } else { logger.error("TwitStreet announcer is null"); } } @Override public void replyForDiabloBird(String message, long statusId) { Twitter twitter = diablobird; String screenName = ""; if (twitter != null) { try { twitter.updateStatus(new StatusUpdate(message).inReplyToStatusId(statusId)); screenName = twitter.getScreenName(); logger.info("replyForDiabloBird"); } catch (TwitterException e) { logger.error("Announcement failed: " + screenName, e); } } else { logger.error("TwitStreet announcer is null"); } } }
true
true
public void loadAnnouncers() { Connection connection = null; PreparedStatement ps = null; ResultSet rs = null; try { connection = dbMgr.getConnection(); ps = connection.prepareStatement(LOAD_ANNOUNCER); rs = ps.executeQuery(); while (rs.next()) { Announcer announcer = new Announcer(); announcer.getDataFromResultSet(rs); announcerDataList.add(announcer); if (TWITSTREET_GAME.equals(announcer.getName())) { twitstreetGame = new TwitterFactory().getInstance(); twitstreetGame.setOAuthConsumer(announcer.getConsumerKey(), announcer.getConsumerSecret()); twitstreetGame.setOAuthAccessToken(new AccessToken(announcer.getAccessToken(), announcer.getAccessTokenSecret())); } if (DIABLOBIRD.equals(announcer.getName())) { diablobird = new TwitterFactory().getInstance(); diablobird.setOAuthConsumer(announcer.getConsumerKey(), announcer.getConsumerSecret()); diablobird.setOAuthAccessToken(new AccessToken(announcer.getAccessToken(), announcer.getAccessTokenSecret())); } else { Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(announcer.getConsumerKey(), announcer.getConsumerSecret()); twitter.setOAuthAccessToken(new AccessToken(announcer.getAccessToken(), announcer.getAccessTokenSecret())); announcerList.add(twitter); } } logger.debug(DBConstants.QUERY_EXECUTION_SUCC + ps.toString()); } catch (SQLException ex) { logger.error(DBConstants.QUERY_EXECUTION_FAIL + ps.toString(), ex); } finally { dbMgr.closeResources(connection, ps, rs); } }
public void loadAnnouncers() { Connection connection = null; PreparedStatement ps = null; ResultSet rs = null; try { connection = dbMgr.getConnection(); ps = connection.prepareStatement(LOAD_ANNOUNCER); rs = ps.executeQuery(); while (rs.next()) { Announcer announcer = new Announcer(); announcer.getDataFromResultSet(rs); announcerDataList.add(announcer); if (TWITSTREET_GAME.equals(announcer.getName())) { twitstreetGame = new TwitterFactory().getInstance(); twitstreetGame.setOAuthConsumer(announcer.getConsumerKey(), announcer.getConsumerSecret()); twitstreetGame.setOAuthAccessToken(new AccessToken(announcer.getAccessToken(), announcer.getAccessTokenSecret())); } else if (DIABLOBIRD.equals(announcer.getName())) { diablobird = new TwitterFactory().getInstance(); diablobird.setOAuthConsumer(announcer.getConsumerKey(), announcer.getConsumerSecret()); diablobird.setOAuthAccessToken(new AccessToken(announcer.getAccessToken(), announcer.getAccessTokenSecret())); } else { Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(announcer.getConsumerKey(), announcer.getConsumerSecret()); twitter.setOAuthAccessToken(new AccessToken(announcer.getAccessToken(), announcer.getAccessTokenSecret())); announcerList.add(twitter); } } logger.debug(DBConstants.QUERY_EXECUTION_SUCC + ps.toString()); } catch (SQLException ex) { logger.error(DBConstants.QUERY_EXECUTION_FAIL + ps.toString(), ex); } finally { dbMgr.closeResources(connection, ps, rs); } }
diff --git a/src/com/chess/genesis/NetworkClient.java b/src/com/chess/genesis/NetworkClient.java index d27cb9d..d2edade 100644 --- a/src/com/chess/genesis/NetworkClient.java +++ b/src/com/chess/genesis/NetworkClient.java @@ -1,524 +1,524 @@ package com.chess.genesis; import android.content.Context; import android.content.SharedPreferences; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import java.io.IOException; import java.net.SocketException; import org.json.JSONException; import org.json.JSONObject; class NetworkClient implements Runnable { public final static int NONE = 0; public final static int LOGIN = 1; public final static int REGISTER = 2; public final static int JOIN_GAME = 3; public final static int NEW_GAME = 4; public final static int READ_INBOX = 5; public final static int CLEAR_INBOX = 6; public final static int GAME_STATUS = 7; public final static int GAME_INFO = 8; public final static int SUBMIT_MOVE = 9; public final static int SUBMIT_MSG = 10; public final static int SYNC_GAMIDS = 11; public final static int GAME_SCORE = 12; public final static int GAME_DATA = 13; public final static int RESIGN_GAME = 14; public final static int SYNC_LIST = 15; private final Context context; private final Handler callback; private JSONObject json; private int fid = NONE; private boolean loginRequired; private boolean error = false; public NetworkClient(final Context _context, final Handler handler) { callback = handler; context = _context; } private boolean relogin(final SocketClient net) { - if (SocketClient.isLoggedin) + if (net.isLoggedin) return true; final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); final String username = pref.getString("username", "!error!"); final String password = pref.getString("passhash", "!error!"); JSONObject json2 = new JSONObject(); try { try { json2.put("request", "login"); json2.put("username", username); json2.put("passhash", Crypto.LoginKey(password)); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } } catch (SocketException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Can't contact server for sending data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } error = true; } catch (IOException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Lost connection durring sending data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } error = true; } if (error) { callback.sendMessage(Message.obtain(callback, fid, json2)); error = false; return false; } try { net.write(json2); } catch (SocketException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Can't contact server for sending data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } error = true; } catch (IOException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Lost connection durring sending data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } error = true; } if (error) { callback.sendMessage(Message.obtain(callback, fid, json2)); error = false; return false; } try { json2 = net.read(); } catch (SocketException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Can't contact server for recieving data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } } catch (IOException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Lost connection durring recieving data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } } catch (JSONException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Server response illogical"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } } if (error) { callback.sendMessage(Message.obtain(callback, fid, json2)); error = false; return false; } try { if (!json2.getString("result").equals("ok")) { callback.sendMessage(Message.obtain(callback, fid, json2)); return false; } - SocketClient.isLoggedin = true; + net.isLoggedin = true; return true; } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } } public void run() { final SocketClient net = new SocketClient(); JSONObject json2 = null; if (error) { error = false; net.disconnect(); return; } else if (loginRequired && !relogin(net)) { net.disconnect(); return; } try { net.write(json); } catch (SocketException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Can't contact server for sending data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } error = true; } catch (IOException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Lost connection durring sending data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } error = true; } if (error) { net.disconnect(); callback.sendMessage(Message.obtain(callback, fid, json2)); error = false; return; } try { json2 = net.read(); } catch (SocketException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Can't contact server for recieving data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } } catch (IOException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Lost connection durring recieving data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } } catch (JSONException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Server response illogical"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } } if (error) error = false; callback.sendMessage(Message.obtain(callback, fid, json2)); net.disconnect(); } public void register(final String username, final String password, final String email) { fid = REGISTER; loginRequired = false; json = new JSONObject(); try { json.put("request", "register"); json.put("username", username); json.put("passhash", Crypto.HashPasswd(password)); json.put("email", email); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } } public void login_user(final String username, final String password) { fid = LOGIN; loginRequired = false; JSONObject json2 = null; json = new JSONObject(); try { try { json.put("request", "login"); json.put("username", username); json.put("passhash", Crypto.LoginKey(password)); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } } catch (SocketException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Can't contact server for sending data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } error = true; } catch (IOException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Lost connection durring sending data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } error = true; } if (error) { callback.sendMessage(Message.obtain(callback, fid, json2)); error = true; } } public void join_game(final String gametype) { fid = JOIN_GAME; loginRequired = true; json = new JSONObject(); try { json.put("request", "joingame"); json.put("gametype", gametype); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } } public void new_game(final String opponent, final String gametype, final String color) { fid = NEW_GAME; loginRequired = true; json = new JSONObject(); try { json.put("request", "newgame"); json.put("opponent", opponent); json.put("gametype", gametype); json.put("color", color); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } } public void submit_move(final String gameid, final String move) { fid = SUBMIT_MOVE; loginRequired = true; json = new JSONObject(); try { json.put("request", "sendmove"); json.put("gameid", gameid); json.put("move", move); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } } public void resign_game(final String gameid) { fid = RESIGN_GAME; loginRequired = true; json = new JSONObject(); try { json.put("request", "resign"); json.put("gameid", gameid); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } } public void submit_msg(final String gameid, final String msg) { fid = SUBMIT_MSG; loginRequired = true; json = new JSONObject(); try { json.put("request", "sendmsg"); json.put("gameid", gameid); json.put("msg", msg); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } } public void game_status(final String gameid) { fid = GAME_STATUS; loginRequired = true; json = new JSONObject(); try { json.put("request", "gamestatus"); json.put("gameid", gameid); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } } public void game_info(final String gameid) { fid = GAME_INFO; loginRequired = true; json = new JSONObject(); try { json.put("request", "gameinfo"); json.put("gameid", gameid); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } } public void game_data(final String gameid) { fid = GAME_DATA; loginRequired = true; json = new JSONObject(); try { json.put("request", "gamedata"); json.put("gameid", gameid); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } } public void read_inbox() { fid = READ_INBOX; loginRequired = true; json = new JSONObject(); try { json.put("request", "inbox"); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } } public void clear_inbox(final long time) { fid = CLEAR_INBOX; loginRequired = true; json = new JSONObject(); try { json.put("request", "clearinbox"); json.put("time", time); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } } public void sync_gameids(final String type) { fid = SYNC_GAMIDS; loginRequired = true; json = new JSONObject(); try { json.put("request", "gameids"); json.put("type", type); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } } public void sync_list(final long time) { fid = SYNC_LIST; loginRequired = true; json = new JSONObject(); try { json.put("request", "synclist"); json.put("time", time); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } } public void game_score(final String gameid) { fid = GAME_SCORE; loginRequired = true; json = new JSONObject(); try { json.put("request", "gamescore"); json.put("gameid", gameid); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } } }
false
true
private boolean relogin(final SocketClient net) { if (SocketClient.isLoggedin) return true; final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); final String username = pref.getString("username", "!error!"); final String password = pref.getString("passhash", "!error!"); JSONObject json2 = new JSONObject(); try { try { json2.put("request", "login"); json2.put("username", username); json2.put("passhash", Crypto.LoginKey(password)); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } } catch (SocketException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Can't contact server for sending data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } error = true; } catch (IOException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Lost connection durring sending data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } error = true; } if (error) { callback.sendMessage(Message.obtain(callback, fid, json2)); error = false; return false; } try { net.write(json2); } catch (SocketException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Can't contact server for sending data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } error = true; } catch (IOException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Lost connection durring sending data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } error = true; } if (error) { callback.sendMessage(Message.obtain(callback, fid, json2)); error = false; return false; } try { json2 = net.read(); } catch (SocketException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Can't contact server for recieving data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } } catch (IOException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Lost connection durring recieving data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } } catch (JSONException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Server response illogical"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } } if (error) { callback.sendMessage(Message.obtain(callback, fid, json2)); error = false; return false; } try { if (!json2.getString("result").equals("ok")) { callback.sendMessage(Message.obtain(callback, fid, json2)); return false; } SocketClient.isLoggedin = true; return true; } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } }
private boolean relogin(final SocketClient net) { if (net.isLoggedin) return true; final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); final String username = pref.getString("username", "!error!"); final String password = pref.getString("passhash", "!error!"); JSONObject json2 = new JSONObject(); try { try { json2.put("request", "login"); json2.put("username", username); json2.put("passhash", Crypto.LoginKey(password)); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } } catch (SocketException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Can't contact server for sending data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } error = true; } catch (IOException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Lost connection durring sending data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } error = true; } if (error) { callback.sendMessage(Message.obtain(callback, fid, json2)); error = false; return false; } try { net.write(json2); } catch (SocketException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Can't contact server for sending data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } error = true; } catch (IOException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Lost connection durring sending data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } error = true; } if (error) { callback.sendMessage(Message.obtain(callback, fid, json2)); error = false; return false; } try { json2 = net.read(); } catch (SocketException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Can't contact server for recieving data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } } catch (IOException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Lost connection durring recieving data"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } } catch (JSONException e) { json2 = new JSONObject(); try { json2.put("result", "error"); json2.put("reason", "Server response illogical"); } catch (JSONException j) { j.printStackTrace(); throw new RuntimeException(); } } if (error) { callback.sendMessage(Message.obtain(callback, fid, json2)); error = false; return false; } try { if (!json2.getString("result").equals("ok")) { callback.sendMessage(Message.obtain(callback, fid, json2)); return false; } net.isLoggedin = true; return true; } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } }
diff --git a/src/main/java/info/somethingodd/OddItem/OddItemCommandExecutor.java b/src/main/java/info/somethingodd/OddItem/OddItemCommandExecutor.java index bb1b2c1..25aa736 100644 --- a/src/main/java/info/somethingodd/OddItem/OddItemCommandExecutor.java +++ b/src/main/java/info/somethingodd/OddItem/OddItemCommandExecutor.java @@ -1,85 +1,85 @@ /* This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package info.somethingodd.OddItem; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; /** * @author Gordon Pettey ([email protected]) */ public class OddItemCommandExecutor implements CommandExecutor { private OddItemBase oddItemBase; /** * Constructor * @param oddItemBase Base plugin */ public OddItemCommandExecutor(OddItemBase oddItemBase) { this.oddItemBase = oddItemBase; } /** * @inheritDoc */ @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (command.getName().equals("odditem")) { if (sender.hasPermission("odditem.alias")) { switch (args.length) { case 0: if (sender instanceof Player) { ItemStack itemStack = ((Player) sender).getItemInHand(); ItemStack temp = new ItemStack(itemStack.getTypeId(), itemStack.getDurability()); if (temp.getTypeId() > 255) - itemStack.setDurability((short) 0); + temp.setDurability((short) 0); sender.sendMessage(OddItem.getAliases(temp).toString()); return true; } break; case 1: try { sender.sendMessage(OddItem.getAliases(args[0]).toString()); } catch (IllegalArgumentException e) { sender.sendMessage("[OddItem] No such alias. Similar: " + e.getMessage()); } return true; } } else { sender.sendMessage("DENIED"); } } else if (command.getName().equals("odditeminfo")) { if (sender.hasPermission("odditem.info")) { sender.sendMessage("[OddItem] " + OddItem.items.itemCount() + " items with " + OddItem.items.aliasCount() + " aliases"); sender.sendMessage("[OddItem] " + OddItem.groups.groupCount() + " groups with " + OddItem.groups.aliasCount() + " aliases"); } else { sender.sendMessage("DENIED"); } return true; } else if (command.getName().equals("odditemreload")) { if (sender.hasPermission("odditem.reload")) { sender.sendMessage("[OddItem] Reloading..."); OddItem.clear(); new OddItemConfiguration(oddItemBase).configure(); } else { sender.sendMessage("DENIED"); } return true; } return false; } }
true
true
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (command.getName().equals("odditem")) { if (sender.hasPermission("odditem.alias")) { switch (args.length) { case 0: if (sender instanceof Player) { ItemStack itemStack = ((Player) sender).getItemInHand(); ItemStack temp = new ItemStack(itemStack.getTypeId(), itemStack.getDurability()); if (temp.getTypeId() > 255) itemStack.setDurability((short) 0); sender.sendMessage(OddItem.getAliases(temp).toString()); return true; } break; case 1: try { sender.sendMessage(OddItem.getAliases(args[0]).toString()); } catch (IllegalArgumentException e) { sender.sendMessage("[OddItem] No such alias. Similar: " + e.getMessage()); } return true; } } else { sender.sendMessage("DENIED"); } } else if (command.getName().equals("odditeminfo")) { if (sender.hasPermission("odditem.info")) { sender.sendMessage("[OddItem] " + OddItem.items.itemCount() + " items with " + OddItem.items.aliasCount() + " aliases"); sender.sendMessage("[OddItem] " + OddItem.groups.groupCount() + " groups with " + OddItem.groups.aliasCount() + " aliases"); } else { sender.sendMessage("DENIED"); } return true; } else if (command.getName().equals("odditemreload")) { if (sender.hasPermission("odditem.reload")) { sender.sendMessage("[OddItem] Reloading..."); OddItem.clear(); new OddItemConfiguration(oddItemBase).configure(); } else { sender.sendMessage("DENIED"); } return true; } return false; }
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (command.getName().equals("odditem")) { if (sender.hasPermission("odditem.alias")) { switch (args.length) { case 0: if (sender instanceof Player) { ItemStack itemStack = ((Player) sender).getItemInHand(); ItemStack temp = new ItemStack(itemStack.getTypeId(), itemStack.getDurability()); if (temp.getTypeId() > 255) temp.setDurability((short) 0); sender.sendMessage(OddItem.getAliases(temp).toString()); return true; } break; case 1: try { sender.sendMessage(OddItem.getAliases(args[0]).toString()); } catch (IllegalArgumentException e) { sender.sendMessage("[OddItem] No such alias. Similar: " + e.getMessage()); } return true; } } else { sender.sendMessage("DENIED"); } } else if (command.getName().equals("odditeminfo")) { if (sender.hasPermission("odditem.info")) { sender.sendMessage("[OddItem] " + OddItem.items.itemCount() + " items with " + OddItem.items.aliasCount() + " aliases"); sender.sendMessage("[OddItem] " + OddItem.groups.groupCount() + " groups with " + OddItem.groups.aliasCount() + " aliases"); } else { sender.sendMessage("DENIED"); } return true; } else if (command.getName().equals("odditemreload")) { if (sender.hasPermission("odditem.reload")) { sender.sendMessage("[OddItem] Reloading..."); OddItem.clear(); new OddItemConfiguration(oddItemBase).configure(); } else { sender.sendMessage("DENIED"); } return true; } return false; }
diff --git a/src/main/java/cc/kune/tasks/client/actions/TasksClientActions.java b/src/main/java/cc/kune/tasks/client/actions/TasksClientActions.java index 0f1959ef9..0a65cb2bf 100644 --- a/src/main/java/cc/kune/tasks/client/actions/TasksClientActions.java +++ b/src/main/java/cc/kune/tasks/client/actions/TasksClientActions.java @@ -1,91 +1,93 @@ /* * * Copyright (C) 2007-2009 The kune development team (see CREDITS for details) * This file is part of kune. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * \*/ package cc.kune.tasks.client.actions; import static cc.kune.tasks.shared.TasksConstants.TYPE_FOLDER; import static cc.kune.tasks.shared.TasksConstants.TYPE_ROOT; import static cc.kune.tasks.shared.TasksConstants.TYPE_TASK; import cc.kune.chat.client.actions.ChatAboutContentBtn; import cc.kune.core.client.actions.ActionRegistryByType; import cc.kune.core.client.i18n.I18nUITranslationService; import cc.kune.core.client.registry.NewMenusForTypeIdsRegistry; import cc.kune.core.client.resources.CoreResources; import cc.kune.core.client.state.Session; import cc.kune.core.client.state.StateManager; import cc.kune.core.shared.domain.ContentStatus; import cc.kune.gspace.client.actions.AbstractFoldableToolActions; import cc.kune.gspace.client.actions.ActionGroups; import cc.kune.gspace.client.actions.ContentViewerOptionsMenu; import cc.kune.gspace.client.actions.ParticipateInContentBtn; import cc.kune.gspace.client.actions.RefreshContentMenuItem; import cc.kune.gspace.client.actions.SetAsHomePageMenuItem; import com.google.inject.Inject; import com.google.inject.Provider; public class TasksClientActions extends AbstractFoldableToolActions { final String[] all = { TYPE_ROOT, TYPE_FOLDER, TYPE_TASK }; final String[] containers = { TYPE_ROOT, TYPE_FOLDER }; final String[] containersNoRoot = { TYPE_FOLDER }; final String[] contents = { TYPE_TASK }; final String[] noRoot = { TYPE_FOLDER, TYPE_TASK }; @Inject public TasksClientActions(final I18nUITranslationService i18n, final Session session, final StateManager stateManager, final ActionRegistryByType registry, final CoreResources res, final Provider<GoParentFolderBtn> folderGoUp, final Provider<NewTaskMenuItem> newTaskItem, final Provider<NewTaskIconBtn> newTaskIconBtn, final Provider<NewFolderMenuItem> newFolderMenuItem, final Provider<OpenFolderMenuItem> openContentMenuItem, final Provider<MarkAsDoneTaskMenuItem> marksAsDoneMenuItem, final Provider<MarkAsNotDoneTaskMenuItem> marksAsNotDoneMenuItem, final Provider<RefreshContentMenuItem> refresh, final Provider<ContentViewerOptionsMenu> optionsMenuContent, final Provider<ParticipateInContentBtn> participateBtn, final TasksNewMenu taskNewMenu, final NewMenusForTypeIdsRegistry newMenusRegistry, final Provider<ChatAboutContentBtn> chatAbout, final Provider<DelFolderMenuItem> delFolderMenuItem, final Provider<SetAsHomePageMenuItem> setAsHomePage) { super(session, stateManager, i18n, registry); actionsRegistry.addAction(ActionGroups.TOOLBAR, optionsMenuContent, all); actionsRegistry.addAction(ActionGroups.TOOLBAR, taskNewMenu, containers); actionsRegistry.addAction(ActionGroups.TOOLBAR, refresh, all); actionsRegistry.addAction(ActionGroups.TOOLBAR, newTaskItem, containers); actionsRegistry.addAction(ActionGroups.TOOLBAR, newTaskIconBtn, all); actionsRegistry.addAction(ActionGroups.TOOLBAR, newFolderMenuItem, containers); actionsRegistry.addAction(ActionGroups.TOOLBAR, folderGoUp, contents); actionsRegistry.addAction(ActionGroups.TOOLBAR, folderGoUp, containers); actionsRegistry.addAction(ActionGroups.TOOLBAR, participateBtn, contents); actionsRegistry.addAction(ActionGroups.TOOLBAR, chatAbout, contents); actionsRegistry.addAction(ActionGroups.ITEM_MENU, openContentMenuItem, contents); actionsRegistry.addAction(ActionGroups.ITEM_MENU, openContentMenuItem, containersNoRoot); actionsRegistry.addAction(ActionGroups.ITEM_MENU, marksAsDoneMenuItem, ContentStatus.publishedOnline, TYPE_TASK); + actionsRegistry.addAction(ActionGroups.ITEM_MENU, marksAsDoneMenuItem, + ContentStatus.editingInProgress, TYPE_TASK); actionsRegistry.addAction(ActionGroups.ITEM_MENU, marksAsNotDoneMenuItem, ContentStatus.inTheDustbin, TYPE_TASK); actionsRegistry.addAction(ActionGroups.ITEM_MENU, delFolderMenuItem, containersNoRoot); newMenusRegistry.register(TYPE_FOLDER, taskNewMenu.get()); newMenusRegistry.register(TYPE_ROOT, taskNewMenu.get()); } @Override protected void createPostSessionInitActions() { } }
true
true
public TasksClientActions(final I18nUITranslationService i18n, final Session session, final StateManager stateManager, final ActionRegistryByType registry, final CoreResources res, final Provider<GoParentFolderBtn> folderGoUp, final Provider<NewTaskMenuItem> newTaskItem, final Provider<NewTaskIconBtn> newTaskIconBtn, final Provider<NewFolderMenuItem> newFolderMenuItem, final Provider<OpenFolderMenuItem> openContentMenuItem, final Provider<MarkAsDoneTaskMenuItem> marksAsDoneMenuItem, final Provider<MarkAsNotDoneTaskMenuItem> marksAsNotDoneMenuItem, final Provider<RefreshContentMenuItem> refresh, final Provider<ContentViewerOptionsMenu> optionsMenuContent, final Provider<ParticipateInContentBtn> participateBtn, final TasksNewMenu taskNewMenu, final NewMenusForTypeIdsRegistry newMenusRegistry, final Provider<ChatAboutContentBtn> chatAbout, final Provider<DelFolderMenuItem> delFolderMenuItem, final Provider<SetAsHomePageMenuItem> setAsHomePage) { super(session, stateManager, i18n, registry); actionsRegistry.addAction(ActionGroups.TOOLBAR, optionsMenuContent, all); actionsRegistry.addAction(ActionGroups.TOOLBAR, taskNewMenu, containers); actionsRegistry.addAction(ActionGroups.TOOLBAR, refresh, all); actionsRegistry.addAction(ActionGroups.TOOLBAR, newTaskItem, containers); actionsRegistry.addAction(ActionGroups.TOOLBAR, newTaskIconBtn, all); actionsRegistry.addAction(ActionGroups.TOOLBAR, newFolderMenuItem, containers); actionsRegistry.addAction(ActionGroups.TOOLBAR, folderGoUp, contents); actionsRegistry.addAction(ActionGroups.TOOLBAR, folderGoUp, containers); actionsRegistry.addAction(ActionGroups.TOOLBAR, participateBtn, contents); actionsRegistry.addAction(ActionGroups.TOOLBAR, chatAbout, contents); actionsRegistry.addAction(ActionGroups.ITEM_MENU, openContentMenuItem, contents); actionsRegistry.addAction(ActionGroups.ITEM_MENU, openContentMenuItem, containersNoRoot); actionsRegistry.addAction(ActionGroups.ITEM_MENU, marksAsDoneMenuItem, ContentStatus.publishedOnline, TYPE_TASK); actionsRegistry.addAction(ActionGroups.ITEM_MENU, marksAsNotDoneMenuItem, ContentStatus.inTheDustbin, TYPE_TASK); actionsRegistry.addAction(ActionGroups.ITEM_MENU, delFolderMenuItem, containersNoRoot); newMenusRegistry.register(TYPE_FOLDER, taskNewMenu.get()); newMenusRegistry.register(TYPE_ROOT, taskNewMenu.get()); }
public TasksClientActions(final I18nUITranslationService i18n, final Session session, final StateManager stateManager, final ActionRegistryByType registry, final CoreResources res, final Provider<GoParentFolderBtn> folderGoUp, final Provider<NewTaskMenuItem> newTaskItem, final Provider<NewTaskIconBtn> newTaskIconBtn, final Provider<NewFolderMenuItem> newFolderMenuItem, final Provider<OpenFolderMenuItem> openContentMenuItem, final Provider<MarkAsDoneTaskMenuItem> marksAsDoneMenuItem, final Provider<MarkAsNotDoneTaskMenuItem> marksAsNotDoneMenuItem, final Provider<RefreshContentMenuItem> refresh, final Provider<ContentViewerOptionsMenu> optionsMenuContent, final Provider<ParticipateInContentBtn> participateBtn, final TasksNewMenu taskNewMenu, final NewMenusForTypeIdsRegistry newMenusRegistry, final Provider<ChatAboutContentBtn> chatAbout, final Provider<DelFolderMenuItem> delFolderMenuItem, final Provider<SetAsHomePageMenuItem> setAsHomePage) { super(session, stateManager, i18n, registry); actionsRegistry.addAction(ActionGroups.TOOLBAR, optionsMenuContent, all); actionsRegistry.addAction(ActionGroups.TOOLBAR, taskNewMenu, containers); actionsRegistry.addAction(ActionGroups.TOOLBAR, refresh, all); actionsRegistry.addAction(ActionGroups.TOOLBAR, newTaskItem, containers); actionsRegistry.addAction(ActionGroups.TOOLBAR, newTaskIconBtn, all); actionsRegistry.addAction(ActionGroups.TOOLBAR, newFolderMenuItem, containers); actionsRegistry.addAction(ActionGroups.TOOLBAR, folderGoUp, contents); actionsRegistry.addAction(ActionGroups.TOOLBAR, folderGoUp, containers); actionsRegistry.addAction(ActionGroups.TOOLBAR, participateBtn, contents); actionsRegistry.addAction(ActionGroups.TOOLBAR, chatAbout, contents); actionsRegistry.addAction(ActionGroups.ITEM_MENU, openContentMenuItem, contents); actionsRegistry.addAction(ActionGroups.ITEM_MENU, openContentMenuItem, containersNoRoot); actionsRegistry.addAction(ActionGroups.ITEM_MENU, marksAsDoneMenuItem, ContentStatus.publishedOnline, TYPE_TASK); actionsRegistry.addAction(ActionGroups.ITEM_MENU, marksAsDoneMenuItem, ContentStatus.editingInProgress, TYPE_TASK); actionsRegistry.addAction(ActionGroups.ITEM_MENU, marksAsNotDoneMenuItem, ContentStatus.inTheDustbin, TYPE_TASK); actionsRegistry.addAction(ActionGroups.ITEM_MENU, delFolderMenuItem, containersNoRoot); newMenusRegistry.register(TYPE_FOLDER, taskNewMenu.get()); newMenusRegistry.register(TYPE_ROOT, taskNewMenu.get()); }
diff --git a/osmdroid-android/src/main/java/org/osmdroid/views/overlay/SafeDrawOverlay.java b/osmdroid-android/src/main/java/org/osmdroid/views/overlay/SafeDrawOverlay.java index c04b041..5629c5a 100644 --- a/osmdroid-android/src/main/java/org/osmdroid/views/overlay/SafeDrawOverlay.java +++ b/osmdroid-android/src/main/java/org/osmdroid/views/overlay/SafeDrawOverlay.java @@ -1,99 +1,97 @@ package org.osmdroid.views.overlay; import org.osmdroid.ResourceProxy; import org.osmdroid.views.MapView; import org.osmdroid.views.safecanvas.ISafeCanvas; import org.osmdroid.views.safecanvas.SafeTranslatedCanvas; import android.content.Context; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Rect; import android.os.Build; /** * An overlay class that uses the safe drawing canvas to draw itself and can be zoomed in to high * levels without drawing issues. * * @see {@link ISafeCanvas} */ public abstract class SafeDrawOverlay extends Overlay { private static final SafeTranslatedCanvas sSafeCanvas = new SafeTranslatedCanvas(); private static final Matrix sMatrix = new Matrix(); private boolean mUseSafeCanvas = true; protected abstract void drawSafe(final ISafeCanvas c, final MapView osmv, final boolean shadow); public SafeDrawOverlay(Context ctx) { super(ctx); } public SafeDrawOverlay(ResourceProxy pResourceProxy) { super(pResourceProxy); } @Override protected void draw(final Canvas c, final MapView osmv, final boolean shadow) { sSafeCanvas.setCanvas(c); if (this.isUsingSafeCanvas()) { // Find the screen offset Rect screenRect = osmv.getProjection().getScreenRect(); sSafeCanvas.xOffset = -screenRect.left; sSafeCanvas.yOffset = -screenRect.top; // Save the canvas state c.save(); if (osmv.getMapOrientation() != 0) { // Un-rotate the maps so we can rotate them accurately using the safe canvas c.rotate(-osmv.getMapOrientation(), screenRect.exactCenterX(), screenRect.exactCenterY()); } // Since the translate calls still take a float, there can be rounding errors // Let's calculate the error, and adjust for it. final int floatErrorX = screenRect.left - (int) (float) screenRect.left; final int floatErrorY = screenRect.top - (int) (float) screenRect.top; // Translate the coordinates if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { - final float scaleX = osmv.getScaleX(); - final float scaleY = osmv.getScaleY(); - c.translate(screenRect.left * scaleX, screenRect.top * scaleY); + c.translate(screenRect.left, screenRect.top); c.translate(floatErrorX, floatErrorY); } else { c.getMatrix(sMatrix); sMatrix.preTranslate(screenRect.left, screenRect.top); sMatrix.preTranslate(floatErrorX, floatErrorY); c.setMatrix(sMatrix); } if (osmv.getMapOrientation() != 0) { // Safely re-rotate the maps sSafeCanvas.rotate(osmv.getMapOrientation(), (double) screenRect.exactCenterX(), (double) screenRect.exactCenterY()); } } else { sSafeCanvas.xOffset = 0; sSafeCanvas.yOffset = 0; } this.drawSafe(sSafeCanvas, osmv, shadow); if (this.isUsingSafeCanvas()) { c.restore(); } } public boolean isUsingSafeCanvas() { return mUseSafeCanvas; } public void setUseSafeCanvas(boolean useSafeCanvas) { mUseSafeCanvas = useSafeCanvas; } }
true
true
protected void draw(final Canvas c, final MapView osmv, final boolean shadow) { sSafeCanvas.setCanvas(c); if (this.isUsingSafeCanvas()) { // Find the screen offset Rect screenRect = osmv.getProjection().getScreenRect(); sSafeCanvas.xOffset = -screenRect.left; sSafeCanvas.yOffset = -screenRect.top; // Save the canvas state c.save(); if (osmv.getMapOrientation() != 0) { // Un-rotate the maps so we can rotate them accurately using the safe canvas c.rotate(-osmv.getMapOrientation(), screenRect.exactCenterX(), screenRect.exactCenterY()); } // Since the translate calls still take a float, there can be rounding errors // Let's calculate the error, and adjust for it. final int floatErrorX = screenRect.left - (int) (float) screenRect.left; final int floatErrorY = screenRect.top - (int) (float) screenRect.top; // Translate the coordinates if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { final float scaleX = osmv.getScaleX(); final float scaleY = osmv.getScaleY(); c.translate(screenRect.left * scaleX, screenRect.top * scaleY); c.translate(floatErrorX, floatErrorY); } else { c.getMatrix(sMatrix); sMatrix.preTranslate(screenRect.left, screenRect.top); sMatrix.preTranslate(floatErrorX, floatErrorY); c.setMatrix(sMatrix); } if (osmv.getMapOrientation() != 0) { // Safely re-rotate the maps sSafeCanvas.rotate(osmv.getMapOrientation(), (double) screenRect.exactCenterX(), (double) screenRect.exactCenterY()); } } else { sSafeCanvas.xOffset = 0; sSafeCanvas.yOffset = 0; } this.drawSafe(sSafeCanvas, osmv, shadow); if (this.isUsingSafeCanvas()) { c.restore(); } }
protected void draw(final Canvas c, final MapView osmv, final boolean shadow) { sSafeCanvas.setCanvas(c); if (this.isUsingSafeCanvas()) { // Find the screen offset Rect screenRect = osmv.getProjection().getScreenRect(); sSafeCanvas.xOffset = -screenRect.left; sSafeCanvas.yOffset = -screenRect.top; // Save the canvas state c.save(); if (osmv.getMapOrientation() != 0) { // Un-rotate the maps so we can rotate them accurately using the safe canvas c.rotate(-osmv.getMapOrientation(), screenRect.exactCenterX(), screenRect.exactCenterY()); } // Since the translate calls still take a float, there can be rounding errors // Let's calculate the error, and adjust for it. final int floatErrorX = screenRect.left - (int) (float) screenRect.left; final int floatErrorY = screenRect.top - (int) (float) screenRect.top; // Translate the coordinates if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { c.translate(screenRect.left, screenRect.top); c.translate(floatErrorX, floatErrorY); } else { c.getMatrix(sMatrix); sMatrix.preTranslate(screenRect.left, screenRect.top); sMatrix.preTranslate(floatErrorX, floatErrorY); c.setMatrix(sMatrix); } if (osmv.getMapOrientation() != 0) { // Safely re-rotate the maps sSafeCanvas.rotate(osmv.getMapOrientation(), (double) screenRect.exactCenterX(), (double) screenRect.exactCenterY()); } } else { sSafeCanvas.xOffset = 0; sSafeCanvas.yOffset = 0; } this.drawSafe(sSafeCanvas, osmv, shadow); if (this.isUsingSafeCanvas()) { c.restore(); } }
diff --git a/splat/src/main/uk/ac/starlink/splat/iface/ProgressFrame.java b/splat/src/main/uk/ac/starlink/splat/iface/ProgressFrame.java index 5658e6726..16317af02 100644 --- a/splat/src/main/uk/ac/starlink/splat/iface/ProgressFrame.java +++ b/splat/src/main/uk/ac/starlink/splat/iface/ProgressFrame.java @@ -1,153 +1,153 @@ /* * Copyright (C) 2009 Science and Technology Facilities Council. * * History: * 19-NOV-2009 (Peter W. Draper): * Original version. */ package uk.ac.starlink.splat.iface; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; import uk.ac.starlink.splat.util.Utilities; /** * Frame for displaying a ProgressPanel, so that a long running process can be * monitored by stopping, starting and changing the title and message. Note * that the instance is never disposed and this may not appear unless the * process takes more than TIMER_DELAY to do the job. */ public class ProgressFrame extends JFrame { private ProgressPanel progressPanel = new ProgressPanel( "Progress..." ); private boolean makeVisible = false; private Timer timer = null; private static int TIMER_DELAY = 10000; // 10 seconds. /** * Create a top level window populated with a ProgressPanel. * Note this remains invisible until after a call to start(). * * @param title the component title. */ public ProgressFrame( String title ) { initUI(); initFrame( title ); } protected void initUI() { getContentPane().setLayout( new BorderLayout() ); JPanel mainPanel = new JPanel( new BorderLayout() ); getContentPane().add( progressPanel, BorderLayout.CENTER ); // Just one action, so we want this on all the time. progressPanel.setDisableOnStop( false ); } // Initialise frame properties. Note remains invisible until start(). protected void initFrame( String title ) { setTitle( Utilities.getTitle( title ) ); setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE ); pack(); makeVisible = false; setVisible( false ); } /** * Stop all progress panel. */ public void stop() { synchronized( this ) { makeVisible = false; progressPanel.stop(); setVisible( false ); } } /** * Start the progress panel. */ public void start() { synchronized( this ) { if ( ! isVisible() ) { makeVisible = true; progressPanel.start(); eventuallyMakeVisible(); } } } /** * Make visible after a while, but only if not made invisible in the * intervening period. */ protected void eventuallyMakeVisible() { // In fact this timer run continually and will check makeVisible // on the next timed event. if ( timer == null ) { timer = new Timer( TIMER_DELAY, new ActionListener() { public void actionPerformed( ActionEvent e ) { - if ( makeVisible ) { - synchronized( this ) { + synchronized( this ) { + if ( makeVisible ) { setVisible( true ); makeVisible = false; } } } }); timer.start(); } else { // Reinitialise timer so that we get the full TIMER_DELAY each // request for visibility. XXX may need a Timer per request if // this means the frame never appears for multiple repeated // requests. timer.restart(); } } /** * Set the progress panel title. */ public void setTitle( String title ) { progressPanel.setTitle( title ); } /** * Set the progress panel message. */ public void setMessage( String message ) { progressPanel.setText( message ); } /** * Have we been told to stop? If so the controller class should arrange to * halt the related thread. */ public boolean isInterrupted() { synchronized( this ) { return progressPanel.isInterrupted(); } } }
true
true
protected void eventuallyMakeVisible() { // In fact this timer run continually and will check makeVisible // on the next timed event. if ( timer == null ) { timer = new Timer( TIMER_DELAY, new ActionListener() { public void actionPerformed( ActionEvent e ) { if ( makeVisible ) { synchronized( this ) { setVisible( true ); makeVisible = false; } } } }); timer.start(); } else { // Reinitialise timer so that we get the full TIMER_DELAY each // request for visibility. XXX may need a Timer per request if // this means the frame never appears for multiple repeated // requests. timer.restart(); } }
protected void eventuallyMakeVisible() { // In fact this timer run continually and will check makeVisible // on the next timed event. if ( timer == null ) { timer = new Timer( TIMER_DELAY, new ActionListener() { public void actionPerformed( ActionEvent e ) { synchronized( this ) { if ( makeVisible ) { setVisible( true ); makeVisible = false; } } } }); timer.start(); } else { // Reinitialise timer so that we get the full TIMER_DELAY each // request for visibility. XXX may need a Timer per request if // this means the frame never appears for multiple repeated // requests. timer.restart(); } }
diff --git a/common/java/com/android/common/contacts/DataUsageStatUpdater.java b/common/java/com/android/common/contacts/DataUsageStatUpdater.java index bc1f8ea..de1cddd 100644 --- a/common/java/com/android/common/contacts/DataUsageStatUpdater.java +++ b/common/java/com/android/common/contacts/DataUsageStatUpdater.java @@ -1,263 +1,263 @@ /* * Copyright (C) 2011 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.common.contacts; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.Data; import android.text.TextUtils; import android.text.util.Rfc822Token; import android.text.util.Rfc822Tokenizer; import android.util.Log; import android.widget.TextView; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * Convenient class for updating usage statistics in ContactsProvider. * * Applications like Email, Sms, etc. can promote recipients for better sorting with this class * * @see ContactsContract.Contacts */ public class DataUsageStatUpdater { private static final String TAG = DataUsageStatUpdater.class.getSimpleName(); /** * Copied from API in ICS (not available before it). You can use values here if you are sure * it is supported by the device. */ public static final class DataUsageFeedback { private static final Uri FEEDBACK_URI = Uri.withAppendedPath(Data.CONTENT_URI, "usagefeedback"); private static final String USAGE_TYPE = "type"; public static final String USAGE_TYPE_CALL = "call"; public static final String USAGE_TYPE_LONG_TEXT = "long_text"; public static final String USAGE_TYPE_SHORT_TEXT = "short_text"; } private final ContentResolver mResolver; public DataUsageStatUpdater(Context context) { mResolver = context.getContentResolver(); } /** * Updates usage statistics using comma-separated RFC822 address like * "Joe <[email protected]>, Due <[email protected]>". * * This will cause Disk access so should be called in a background thread. * * @return true when update request is correctly sent. False when the request fails, * input has no valid entities. */ public boolean updateWithRfc822Address(Collection<CharSequence> texts){ if (texts == null) { return false; } else { final Set<String> addresses = new HashSet<String>(); for (CharSequence text : texts) { Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(text.toString().trim()); for (Rfc822Token token : tokens) { addresses.add(token.getAddress()); } } return updateWithAddress(addresses); } } /** * Update usage statistics information using a list of email addresses. * * This will cause Disk access so should be called in a background thread. * * @see #update(Collection, Collection, String) * * @return true when update request is correctly sent. False when the request fails, * input has no valid entities. */ public boolean updateWithAddress(Collection<String> addresses) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "updateWithAddress: " + Arrays.toString(addresses.toArray())); } if (addresses != null && !addresses.isEmpty()) { final ArrayList<String> whereArgs = new ArrayList<String>(); final StringBuilder whereBuilder = new StringBuilder(); final String[] questionMarks = new String[addresses.size()]; whereArgs.addAll(addresses); Arrays.fill(questionMarks, "?"); // Email.ADDRESS == Email.DATA1. Email.ADDRESS can be available from API Level 11. whereBuilder.append(Email.DATA1 + " IN (") .append(TextUtils.join(",", questionMarks)) .append(")"); final Cursor cursor = mResolver.query(Email.CONTENT_URI, new String[] {Email.CONTACT_ID, Email._ID}, whereBuilder.toString(), whereArgs.toArray(new String[0]), null); if (cursor == null) { Log.w(TAG, "Cursor for Email.CONTENT_URI became null."); } else { final Set<Long> contactIds = new HashSet<Long>(cursor.getCount()); final Set<Long> dataIds = new HashSet<Long>(cursor.getCount()); try { cursor.move(-1); while(cursor.moveToNext()) { contactIds.add(cursor.getLong(0)); dataIds.add(cursor.getLong(1)); } } finally { cursor.close(); } return update(contactIds, dataIds, DataUsageFeedback.USAGE_TYPE_LONG_TEXT); } } return false; } /** * Update usage statistics information using a list of phone numbers. * * This will cause Disk access so should be called in a background thread. * * @see #update(Collection, Collection, String) * * @return true when update request is correctly sent. False when the request fails, * input has no valid entities. */ public boolean updateWithPhoneNumber(Collection<String> numbers) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "updateWithPhoneNumber: " + Arrays.toString(numbers.toArray())); } if (numbers != null && !numbers.isEmpty()) { final ArrayList<String> whereArgs = new ArrayList<String>(); final StringBuilder whereBuilder = new StringBuilder(); final String[] questionMarks = new String[numbers.size()]; whereArgs.addAll(numbers); Arrays.fill(questionMarks, "?"); // Phone.NUMBER == Phone.DATA1. NUMBER can be available from API Level 11. whereBuilder.append(Phone.DATA1 + " IN (") .append(TextUtils.join(",", questionMarks)) .append(")"); final Cursor cursor = mResolver.query(Phone.CONTENT_URI, new String[] {Phone.CONTACT_ID, Phone._ID}, whereBuilder.toString(), whereArgs.toArray(new String[0]), null); if (cursor == null) { Log.w(TAG, "Cursor for Phone.CONTENT_URI became null."); } else { final Set<Long> contactIds = new HashSet<Long>(cursor.getCount()); final Set<Long> dataIds = new HashSet<Long>(cursor.getCount()); try { cursor.move(-1); while(cursor.moveToNext()) { contactIds.add(cursor.getLong(0)); dataIds.add(cursor.getLong(1)); } } finally { cursor.close(); } return update(contactIds, dataIds, DataUsageFeedback.USAGE_TYPE_SHORT_TEXT); } } return false; } /** * @return true when one or more of update requests are correctly sent. * False when all the requests fail. */ private boolean update(Collection<Long> contactIds, Collection<Long> dataIds, String type) { final long currentTimeMillis = System.currentTimeMillis(); boolean successful = false; // From ICS we can use per-contact-method structure. We'll check if the device supports it // and call the API. // - // STOPSHIP: Use 13 or later when we're sure ICS has correct SDK version - if (Build.VERSION.SDK_INT >= 12) { + // STOPSHIP: Use 14 or later when we're sure ICS has correct SDK version + if (Build.VERSION.SDK_INT >= 13) { if (dataIds.isEmpty()) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Given list for data IDs is null. Ignoring."); } } else { final Uri uri = DataUsageFeedback.FEEDBACK_URI.buildUpon() .appendPath(TextUtils.join(",", dataIds)) .appendQueryParameter(DataUsageFeedback.USAGE_TYPE, type) .build(); if (mResolver.update(uri, new ContentValues(), null, null) > 0) { successful = true; } else { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "update toward data rows " + dataIds + " failed"); } } } } else { // Use older API. if (contactIds.isEmpty()) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Given list for contact IDs is null. Ignoring."); } } else { final StringBuilder whereBuilder = new StringBuilder(); final ArrayList<String> whereArgs = new ArrayList<String>(); final String[] questionMarks = new String[contactIds.size()]; for (long contactId : contactIds) { whereArgs.add(String.valueOf(contactId)); } Arrays.fill(questionMarks, "?"); whereBuilder.append(ContactsContract.Contacts._ID + " IN ("). append(TextUtils.join(",", questionMarks)). append(")"); if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "contactId where: " + whereBuilder.toString()); Log.d(TAG, "contactId selection: " + whereArgs); } final ContentValues values = new ContentValues(); values.put(ContactsContract.Contacts.LAST_TIME_CONTACTED, currentTimeMillis); if (mResolver.update(ContactsContract.Contacts.CONTENT_URI, values, whereBuilder.toString(), whereArgs.toArray(new String[0])) > 0) { successful = true; } else { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "update toward raw contacts " + contactIds + " failed"); } } } } return successful; } }
true
true
private boolean update(Collection<Long> contactIds, Collection<Long> dataIds, String type) { final long currentTimeMillis = System.currentTimeMillis(); boolean successful = false; // From ICS we can use per-contact-method structure. We'll check if the device supports it // and call the API. // // STOPSHIP: Use 13 or later when we're sure ICS has correct SDK version if (Build.VERSION.SDK_INT >= 12) { if (dataIds.isEmpty()) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Given list for data IDs is null. Ignoring."); } } else { final Uri uri = DataUsageFeedback.FEEDBACK_URI.buildUpon() .appendPath(TextUtils.join(",", dataIds)) .appendQueryParameter(DataUsageFeedback.USAGE_TYPE, type) .build(); if (mResolver.update(uri, new ContentValues(), null, null) > 0) { successful = true; } else { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "update toward data rows " + dataIds + " failed"); } } } } else { // Use older API. if (contactIds.isEmpty()) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Given list for contact IDs is null. Ignoring."); } } else { final StringBuilder whereBuilder = new StringBuilder(); final ArrayList<String> whereArgs = new ArrayList<String>(); final String[] questionMarks = new String[contactIds.size()]; for (long contactId : contactIds) { whereArgs.add(String.valueOf(contactId)); } Arrays.fill(questionMarks, "?"); whereBuilder.append(ContactsContract.Contacts._ID + " IN ("). append(TextUtils.join(",", questionMarks)). append(")"); if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "contactId where: " + whereBuilder.toString()); Log.d(TAG, "contactId selection: " + whereArgs); } final ContentValues values = new ContentValues(); values.put(ContactsContract.Contacts.LAST_TIME_CONTACTED, currentTimeMillis); if (mResolver.update(ContactsContract.Contacts.CONTENT_URI, values, whereBuilder.toString(), whereArgs.toArray(new String[0])) > 0) { successful = true; } else { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "update toward raw contacts " + contactIds + " failed"); } } } } return successful; }
private boolean update(Collection<Long> contactIds, Collection<Long> dataIds, String type) { final long currentTimeMillis = System.currentTimeMillis(); boolean successful = false; // From ICS we can use per-contact-method structure. We'll check if the device supports it // and call the API. // // STOPSHIP: Use 14 or later when we're sure ICS has correct SDK version if (Build.VERSION.SDK_INT >= 13) { if (dataIds.isEmpty()) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Given list for data IDs is null. Ignoring."); } } else { final Uri uri = DataUsageFeedback.FEEDBACK_URI.buildUpon() .appendPath(TextUtils.join(",", dataIds)) .appendQueryParameter(DataUsageFeedback.USAGE_TYPE, type) .build(); if (mResolver.update(uri, new ContentValues(), null, null) > 0) { successful = true; } else { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "update toward data rows " + dataIds + " failed"); } } } } else { // Use older API. if (contactIds.isEmpty()) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Given list for contact IDs is null. Ignoring."); } } else { final StringBuilder whereBuilder = new StringBuilder(); final ArrayList<String> whereArgs = new ArrayList<String>(); final String[] questionMarks = new String[contactIds.size()]; for (long contactId : contactIds) { whereArgs.add(String.valueOf(contactId)); } Arrays.fill(questionMarks, "?"); whereBuilder.append(ContactsContract.Contacts._ID + " IN ("). append(TextUtils.join(",", questionMarks)). append(")"); if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "contactId where: " + whereBuilder.toString()); Log.d(TAG, "contactId selection: " + whereArgs); } final ContentValues values = new ContentValues(); values.put(ContactsContract.Contacts.LAST_TIME_CONTACTED, currentTimeMillis); if (mResolver.update(ContactsContract.Contacts.CONTENT_URI, values, whereBuilder.toString(), whereArgs.toArray(new String[0])) > 0) { successful = true; } else { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "update toward raw contacts " + contactIds + " failed"); } } } } return successful; }
diff --git a/src/org/biojava/bio/program/sax/BlastSAXParser.java b/src/org/biojava/bio/program/sax/BlastSAXParser.java index 1400d3fc2..5754fe8b9 100755 --- a/src/org/biojava/bio/program/sax/BlastSAXParser.java +++ b/src/org/biojava/bio/program/sax/BlastSAXParser.java @@ -1,802 +1,802 @@ /* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * */ package org.biojava.bio.program.sax; import java.util.*; import java.io.*; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * A SAX-like parser for dealing with native NCBI-Blast,Wu-Blastoutput, * and HMMER output (a single dataset). That is this class allows * native BLAST-like format files to be processed as if they were in * an XML format i.e. it sends messages to a user-written XML Handler. * * This class has package-level visibility, and is used * by generic BlastLikeSAXParser objects. * * Some functionality is delegated to Part objects within the class * whose implementations are selected on-the-fly according * the the program/version that produced the output. * SummaryLineHelperIF * * NB Support for HMMER is currently only partial and likely to change * without notice as more functionality is added. * * Primary author - * Simon Brocklehurst (CAT) * Other authors - * Tim Dilks (CAT) * Colin Hardman (CAT) * Stuart Johnston (CAT) * Mathieu Wiepert (Mayo Foundation) * * Copyright 2000 Cambridge Antibody Technology Group plc. * All Rights Reserved. * * This code released to the biojava project, May 2000 * under the LGPL license. * * @author Cambridge Antibody Technology Group plc * @version 0.1 * * @see BlastLikeSAXParser */ final class BlastSAXParser extends AbstractNativeAppSAXParser { private BufferedReader oContents; private AttributesImpl oAtts = new AttributesImpl(); private QName oAttQName = new QName(this); private ArrayList oBuffer = new ArrayList(); private char[] aoChars; private char[] aoLineSeparator; private String[] aoKeys; private String[] aoArrayType = new String[1]; private HashMap oMap = new HashMap(); private int iVer; private BlastLikeVersionSupport oVersion; private HitSectionSAXParser oHits; private SummaryLineHelperIF oSummaryLineHelper; private static final int STARTUP = 0; private static final int IN_TRAILER = 1; private static final int AT_END = 2; private static final int IN_HEADER = 3; private static final int IN_SUMMARY = 4; private static final int FINISHED_HITS = 5; private boolean tDoneSummary = false; /** * Creates a new <code>BlastSAXParser</code> instance. * * @param poVersion a <code>BlastLikeVersionSupport</code> value. * * @exception SAXException if an error occurs */ BlastSAXParser(BlastLikeVersionSupport poVersion, String poNamespacePrefix) throws SAXException { oVersion = poVersion; this.setNamespacePrefix(poNamespacePrefix); this.addPrefixMapping("biojava","http://www.biojava.org"); oHits = new HitSectionSAXParser(oVersion,this.getNamespacePrefix()); this.changeState(STARTUP); aoLineSeparator = System.getProperty("line.separator").toCharArray(); //Beginnings of using a Builder type pattern to create //parser from part objects. Only for done //Summary sections at present according to program type //at present. Significant benefit would be //for detail, allowing choice of part object optimised //for speed of processing etc. this.choosePartImplementations(); } /** * Describe 'parse' method here. * */ public String parse(BufferedReader poContents, String poLine) throws SAXException { String oLine = null; oContents = poContents; //First deal with first line which must be the start of //a new Blast output //For a brand new collection, check for the start of a //new BlastDataSet //look for characteristic of start of dataset if (oVersion.isStartOfDataSet(poLine)) { //just figure out whether it's a new DataSet //or not. i The onNewBlastDatSet method //takes care of the rest... this.onNewBlastDataSet(poLine); } else { //should throw excpetion here //message should be unexpected poLine parameter return poLine; } //now parse stream... try { oLine = oContents.readLine(); while ( (oLine != null) && (!checkNewBlastLikeDataSet(oLine)) ) { //System.out.println(oLine); //interpret line and send messages accordingly this.interpret(oLine); oLine = oContents.readLine(); } // end while } catch (java.io.IOException x) { System.out.println(x.getMessage()); System.out.println("File read interrupted"); } // end try/catch //Now close open elements... if (iState == IN_TRAILER) { this.emitRawOutput(oBuffer); this.endElement(new QName(this,this.prefix("Trailer"))); this.changeState(AT_END); } this.endElement(new QName(this,this.prefix("BlastLikeDataSet"))); return oLine; } /** * Deal with line according to state parser is in. * * @param poLine A line of Blast output */ private void interpret(String poLine) throws SAXException { if (iState == IN_HEADER) { //accumulate header information //things that can end header section //start of summmary section //start of detail section if ( (poLine.startsWith( "Sequences producing significant alignments")) || (poLine.startsWith( "Sequences producing High-scoring Segment Pairs")) || (poLine.startsWith( "-------- ")) ) { this.emitRawOutput(oBuffer); this.endElement(new QName(this,this.prefix("Header"))); //change state this.changeState(IN_SUMMARY); oAtts.clear(); this.startElement(new QName(this,this.prefix("Summary")), (Attributes)oAtts); //eat a blank line if there is one... // this.interpret(oLine); //read next line try { poLine = oContents.readLine(); } catch (java.io.IOException x) { System.err.println(x.getMessage()); System.err.println("File read interrupted"); } // end try/catch if (poLine.trim().equals("")) { //System.out.println("BLANK LINE"); } else { //recursively interpret it... this.interpret(poLine); } return; } //end check start of summary //Currently doesn't handle output that starts //with a detail section i.e. no summary. //This is a BUG/FEATURE. oBuffer.add(poLine); } //end if inHeader state //Deal with summary state if (iState == IN_SUMMARY) { //check to see if end of summary //has been reached... //(signal is a blank line for NCBIBlast and Wu-Blast, //(signal is either a blank line or //Signal is \\End of List for GCG // HMMR has a longer summary section to include the // domain summary and the check for a blank line // will prematurely end the summary section so // skip this check for HMMR int iProgram = oVersion.getProgram(); if ( iProgram == BlastLikeVersionSupport.HMMER ) { if ( poLine.trim().equals("") ) { return; // skip } //HMMER-specific if (poLine.startsWith("Parsed for domains:")) { //signifies domain summary info String oAfterHmmr = this.hmmerDomainSummaryReached(poLine); // System.err.println( "Last-->" + oAfterHmmr + "<--" ); return; } } else if ( (poLine.trim().equals("")) || (poLine.trim().startsWith("[no more scores")) || (poLine.trim().startsWith("\\")) ) { //Can't change state, because we still want to //check for start of detail... //Forgive non-standard white-space //between end of summary and start of detail if (!tDoneSummary) { tDoneSummary = true; this.endElement(new QName(this,this.prefix("Summary"))); } return; //return before attempting to parse Summary Line } if (poLine.startsWith(">")) { //signifies start of detail section this.hitsSectionReached(poLine); return; } //need to check that we've end of summary //'cos could be spurious data between end of //summary and start of detail e.g. multi-line WARNINGs //at end of Summary section in Wu-Blast. if (!tDoneSummary) { this.parseSummaryLine(poLine); } return; } //State set to this when parsing of Hits finished if (iState == FINISHED_HITS) { //check end of detail section this.endElement(new QName(this,this.prefix("Detail"))); oAtts.clear(); this.startElement(new QName(this,this.prefix("Trailer")), (Attributes)oAtts); //change state to Trailer and initialse Buffer this.changeState(IN_TRAILER); oBuffer.clear(); return; } //end if finishedHists if (iState == IN_TRAILER) { oBuffer.add(poLine); } } /** * This method is called when a line indicating that * that a new BlastLikeDataSet has been reached. * * NB This class deals NCBI-BLAST WU-BLAST and HMMER: * * o flavours of NCBI Blast (e.g. blastn, blastp etc) * o flavours of WU Blast (e.g. blastn, blastp etc) * * When this method is called, the line will look something line: * * BLASTN 2.0.11 [Jan-20-2000] for NCBI Blast * * The above would be parsed to program ncbi-blastn, and version number * 2.0.11 * * @param poLine - */ private void onNewBlastDataSet(String poLine) throws SAXException { if (!oVersion.isSupported()) { throw (new SAXException( "Program " + oVersion.getProgramString() + " Version " + oVersion.getVersionString() + " is not supported by the biojava blast-like parsing framework")); } oAtts.clear(); oAttQName.setQName("program"); oAtts.addAttribute(oAttQName.getURI(), oAttQName.getLocalName(), oAttQName.getQName(), "CDATA",oVersion.getProgramString()); oAttQName.setQName("version"); oAtts.addAttribute(oAttQName.getURI(), oAttQName.getLocalName(), oAttQName.getQName(), "CDATA",oVersion.getVersionString()); this.startElement(new QName(this,this.prefix("BlastLikeDataSet")), (Attributes)oAtts); //change state to reflect the fact we're in the Header iState = IN_HEADER; oBuffer.clear(); oAtts.clear(); this.startElement(new QName(this,this.prefix("Header")), (Attributes)oAtts); } /** * Describe constructor here. * * @param oArrayList - */ private void emitRawOutput(ArrayList poList) throws SAXException { oAtts.clear(); oAttQName.setQName("xml:space"); oAtts.addAttribute(oAttQName.getURI(), oAttQName.getLocalName(), oAttQName.getQName(), "NMTOKEN","preserve"); this.startElement(new QName (this,this.prefix("RawOutput")), (Attributes)oAtts); //Cycle through ArrayList and send character array data to //XML ContentHandler. int iTmpListSize = poList.size(); for (int i = 0; i < iTmpListSize; i++) { //System.out.println("RAW:" + (String)poList.get(i)); aoChars = ((String)poList.get(i)).toCharArray(); this.characters(aoLineSeparator,0,1); this.characters(aoChars,0,aoChars.length); } this.endElement(new QName(this,this.prefix("RawOutput"))); } /** * Parses a summary line. Actualy parsing functionality * is delegated to static method of a reusable Helper Class. * * For NCBI Blast, a summary line looks something like: * * U00431 Mus musculus HMG-1 mRNA, complete cds. 353 7e-95 * * UO0431 is typically a database accession code * Mus musculs.. is a description of the hit (this is optional) * * 353 is a bit score * * 7e-95 is an E Value * */ private void parseSummaryLine(String poLine) throws SAXException { //Also remember in header add query attribute and database type? //Should split this out into different implementations //according to program and version oSummaryLineHelper.parse(poLine,oMap,oVersion); //Eat a line for GCG, which has two lines for a summary. //The first line becomes the beginning of the description if (iVer == BlastLikeVersionSupport.GCG_BLASTN) { try { poLine = oContents.readLine(); oSummaryLineHelper.parse(poLine,oMap,oVersion); } catch (IOException x) { System.out.println(x.getMessage()); System.out.println("GCG File read interrupted"); } // end try/catch } /* Note have to do this check a hmmer can have empty summary * sections and oMap.keySet().toArray will return an array * of size 1 with a null first element if the map is empty. */ if ( oMap.size() == 0 ) { return; } aoKeys = (String[])(oMap.keySet().toArray(aoArrayType)); oAtts.clear(); //output contents of Map as either elements or //attribute lists //two passes first get HitsSummary element started for (int i = 0; i < aoKeys.length; i++) { if ( (aoKeys[i].equals("hitId")) || (aoKeys[i].equals("hitDescription")) ) { //do nothing } else { oAttQName.setQName(aoKeys[i]); oAtts.addAttribute(oAttQName.getURI(), oAttQName.getLocalName(), oAttQName.getQName(), "CDATA",(String)oMap.get(aoKeys[i])); } } this.startElement(new QName(this,this.prefix("HitSummary")), (Attributes)oAtts); for (int i = 0; i < aoKeys.length; i++) { if (aoKeys[i].equals("hitId")) { oAtts.clear(); oAttQName.setQName("id"); oAtts.addAttribute(oAttQName.getURI(), oAttQName.getLocalName(), oAttQName.getQName(), "CDATA",(String)oMap.get(aoKeys[i])); oAttQName.setQName("metaData"); oAtts.addAttribute(oAttQName.getURI(), oAttQName.getLocalName(), oAttQName.getQName(), "CDATA","none"); this.startElement(new QName(this,this.prefix("HitId")), (Attributes)oAtts); this.endElement(new QName(this,this.prefix("HitId"))); } else if (aoKeys[i].equals("hitDescription")) { oAtts.clear(); this.startElement(new QName(this,this.prefix("HitDescription")), (Attributes)oAtts); aoChars = ((String)oMap.get(aoKeys[i])).toCharArray(); this.characters(aoChars,0,aoChars.length); this.endElement(new QName(this,this.prefix("HitDescription"))); } //System.out.print(aoKeys[i] + ": "); //System.out.println(oMap.get(aoKeys[i])); } this.endElement(new QName(this,this.prefix("HitSummary"))); oMap.clear(); } /** * From the specified line, hand over * parsing of stream to a helperclass * * @param poLine - * @exception SAXException thrown if * @exception thrown if */ private void hitsSectionReached(String poLine) throws SAXException { //Parse Contents stream up to end of Hits oHits.setContentHandler(oHandler); //this returns when end of hits section reached... oAtts.clear(); this.startElement(new QName(this,this.prefix("Detail")), (Attributes)oAtts); int iProgram = oVersion.getProgram(); if ( (iProgram == BlastLikeVersionSupport.NCBI_BLASTN) || (iProgram == BlastLikeVersionSupport.NCBI_BLASTX) || (iProgram == BlastLikeVersionSupport.NCBI_BLASTP) || (iProgram == BlastLikeVersionSupport.NCBI_TBLASTN) || (iProgram == BlastLikeVersionSupport.NCBI_TBLASTX) ) { oHits.parse(oContents,poLine,"Database:"); } if ( (iProgram == BlastLikeVersionSupport.WU_BLASTN) || (iProgram == BlastLikeVersionSupport.WU_BLASTX) || (iProgram == BlastLikeVersionSupport.WU_BLASTP) || (iProgram == BlastLikeVersionSupport.WU_TBLASTN) || (iProgram == BlastLikeVersionSupport.WU_TBLASTX) ) { oHits.parse(oContents,poLine,"Parameters:"); } //Same as NCBI, left here for organization I suppose if (iProgram == BlastLikeVersionSupport.GCG_BLASTN) { oHits.parse(oContents,poLine,"Database:"); } this.changeState(FINISHED_HITS); } /** * Method to be implemented. * * @param poLine a <code>String</code> value * @exception SAXException if an error occurs */ private String hmmerDomainSummaryReached(String poLine) throws SAXException { //To be implemented - parse Contents stream up to end of //domain summary via delegation (analagous to hits parsing oAtts.clear(); this.startElement(new QName(this,this.prefix("DomainSummary")), (Attributes)oAtts); int iProgram = oVersion.getProgram(); if ( iProgram == BlastLikeVersionSupport.HMMER ) { DomainSectionSAXParser oDomains = new DomainSectionSAXParser ( oVersion, this.getNamespacePrefix() ); oDomains.setContentHandler( oHandler ); oDomains.parse( oContents, poLine ); this.endElement(new QName(this,this.prefix("DomainSummary"))); this.endElement(new QName(this,this.prefix("Summary"))); String oLine = null; try { oLine = oContents.readLine(); while( oLine != null && ( !oLine.startsWith ( "Alignments of top-scoring domains:" ) ) && ( !oLine.startsWith( "//" ) ) && ( !oLine.startsWith( "Histogram of all scores:" ) ) ) { oLine = oContents.readLine(); } } catch ( IOException e ) { System.err.println( e.getMessage()); System.err.println("File read interrupted"); throw new SAXException( "File read interrupted" ); } if ( oLine != null && oLine.startsWith( "Alignments of top-scoring domains:" ) ) { oAtts.clear(); this.startElement(new QName(this,this.prefix("Detail")), (Attributes)oAtts); HmmerAlignmentSAXParser oAlignments = new HmmerAlignmentSAXParser ( oVersion, this.getNamespacePrefix() ); oAlignments.setContentHandler( oHandler ); String oLastLine = oAlignments.parse( oContents, poLine ); if ( oLastLine.trim().equals("//") ) { // hmmpfam // then close details, BlastLikeDataSet // if more stuff this.endElement(new QName(this,this.prefix("Detail"))); try { oLine = oContents.readLine(); while ( (oLine != null) && (!oLine.startsWith( "Query:" ) ) ) { oLine = oContents.readLine(); } } catch ( IOException e ) { System.err.println( "Read interrupted" ); System.err.println( e ); e.printStackTrace(); throw new SAXException( "File read interupted" ); } if ( oLine == null ) { this.changeState(AT_END); return oLine; } else { this.endElement(new QName(this,this.prefix ("BlastLikeDataSet"))); // need to start a new one ( if there is ) oAtts.clear(); oAttQName.setQName("program"); oAtts.addAttribute(oAttQName.getURI(), oAttQName.getLocalName(), oAttQName.getQName(), "CDATA",oVersion.getProgramString()); oAttQName.setQName("version"); oAtts.addAttribute(oAttQName.getURI(), oAttQName.getLocalName(), oAttQName.getQName(), "CDATA",oVersion.getVersionString()); this.startElement(new QName(this,this.prefix ("BlastLikeDataSet")), (Attributes)oAtts); oAtts.clear(); this.startElement(new QName(this,this.prefix("Header")), (Attributes)oAtts); oBuffer.clear(); oBuffer.add( oLine ); this.emitRawOutput(oBuffer); this.endElement(new QName(this,this.prefix("Header"))); this.changeState( IN_SUMMARY ); oAtts.clear(); this.startElement(new QName(this,this.prefix ("Summary")), (Attributes)oAtts); try{ // fast forward to first summary while (! oLine.startsWith( "-------- " ) ) { oLine = oContents.readLine(); } } catch (java.io.IOException x) { System.err.println(x.getMessage()); System.err.println("File read interrupted"); throw new SAXException( "File read interrupted" ); } // end try/catch } } else { // System.err.println( "FINISHED HITS>>>>>>" ); oLine = oLastLine; this.changeState( FINISHED_HITS ); } } else { // passed Alignment section // // Either trailer with histogram or a new entry with '//' // look for the start of a new file with 'hmmsearch'? this.changeState(FINISHED_HITS); } return oLine; } - return poLine;; + return poLine; // this.endElement(new QName(this,this.prefix("Detail"))); } /** * Checks to see if a line of Blast like output * represents the start of a new BlastLike data set. * Current supports: * o ncbi-blast all variants * o wu-blast all variants * * @param poLine A String representation of the line * @return boolean true if it is a new dataset, false if not. */ private boolean checkNewBlastLikeDataSet(String poLine) { if ( (poLine.startsWith("BLAST")) || (poLine.startsWith("TBLAST")) ) { return true; } else { return false; } } /** * Choose particular implementations of Part objects * that comprise the aggregate object according * to version/type of program * * @param nil - */ private void choosePartImplementations() throws SAXException { iVer = oVersion.getProgram(); if ( (iVer == BlastLikeVersionSupport.NCBI_BLASTN) || (iVer == BlastLikeVersionSupport.NCBI_BLASTX) || (iVer == BlastLikeVersionSupport.NCBI_BLASTP) || (iVer == BlastLikeVersionSupport.NCBI_TBLASTN) || (iVer == BlastLikeVersionSupport.NCBI_TBLASTX) ) { oSummaryLineHelper = (SummaryLineHelperIF) new NcbiBlastSummaryLineHelper(); return; } if ( (iVer == BlastLikeVersionSupport.WU_BLASTN) || (iVer == BlastLikeVersionSupport.WU_BLASTX) || (iVer == BlastLikeVersionSupport.WU_BLASTP) || (iVer == BlastLikeVersionSupport.WU_TBLASTN) || (iVer == BlastLikeVersionSupport.WU_TBLASTX) ) { oSummaryLineHelper = (SummaryLineHelperIF) new WuBlastSummaryLineHelper(); return; } if (iVer == BlastLikeVersionSupport.HMMER) { oSummaryLineHelper = (SummaryLineHelperIF) new HmmerSummaryLineHelper(); return; } if (iVer == BlastLikeVersionSupport.GCG_BLASTN) { oSummaryLineHelper = (SummaryLineHelperIF) new GCGBlastSummaryLineHelper(); return; } //If get to here, no implementation available //Exception to help SAX parser writers track down //problems writing software to support the framework throw (new SAXException( "Could not choose a suitable implementation of the ". concat("SummaryLineHelperIF for program "). concat(oVersion.getProgramString()). concat(" version "). concat(oVersion.getVersionString()))); } }
true
true
private String hmmerDomainSummaryReached(String poLine) throws SAXException { //To be implemented - parse Contents stream up to end of //domain summary via delegation (analagous to hits parsing oAtts.clear(); this.startElement(new QName(this,this.prefix("DomainSummary")), (Attributes)oAtts); int iProgram = oVersion.getProgram(); if ( iProgram == BlastLikeVersionSupport.HMMER ) { DomainSectionSAXParser oDomains = new DomainSectionSAXParser ( oVersion, this.getNamespacePrefix() ); oDomains.setContentHandler( oHandler ); oDomains.parse( oContents, poLine ); this.endElement(new QName(this,this.prefix("DomainSummary"))); this.endElement(new QName(this,this.prefix("Summary"))); String oLine = null; try { oLine = oContents.readLine(); while( oLine != null && ( !oLine.startsWith ( "Alignments of top-scoring domains:" ) ) && ( !oLine.startsWith( "//" ) ) && ( !oLine.startsWith( "Histogram of all scores:" ) ) ) { oLine = oContents.readLine(); } } catch ( IOException e ) { System.err.println( e.getMessage()); System.err.println("File read interrupted"); throw new SAXException( "File read interrupted" ); } if ( oLine != null && oLine.startsWith( "Alignments of top-scoring domains:" ) ) { oAtts.clear(); this.startElement(new QName(this,this.prefix("Detail")), (Attributes)oAtts); HmmerAlignmentSAXParser oAlignments = new HmmerAlignmentSAXParser ( oVersion, this.getNamespacePrefix() ); oAlignments.setContentHandler( oHandler ); String oLastLine = oAlignments.parse( oContents, poLine ); if ( oLastLine.trim().equals("//") ) { // hmmpfam // then close details, BlastLikeDataSet // if more stuff this.endElement(new QName(this,this.prefix("Detail"))); try { oLine = oContents.readLine(); while ( (oLine != null) && (!oLine.startsWith( "Query:" ) ) ) { oLine = oContents.readLine(); } } catch ( IOException e ) { System.err.println( "Read interrupted" ); System.err.println( e ); e.printStackTrace(); throw new SAXException( "File read interupted" ); } if ( oLine == null ) { this.changeState(AT_END); return oLine; } else { this.endElement(new QName(this,this.prefix ("BlastLikeDataSet"))); // need to start a new one ( if there is ) oAtts.clear(); oAttQName.setQName("program"); oAtts.addAttribute(oAttQName.getURI(), oAttQName.getLocalName(), oAttQName.getQName(), "CDATA",oVersion.getProgramString()); oAttQName.setQName("version"); oAtts.addAttribute(oAttQName.getURI(), oAttQName.getLocalName(), oAttQName.getQName(), "CDATA",oVersion.getVersionString()); this.startElement(new QName(this,this.prefix ("BlastLikeDataSet")), (Attributes)oAtts); oAtts.clear(); this.startElement(new QName(this,this.prefix("Header")), (Attributes)oAtts); oBuffer.clear(); oBuffer.add( oLine ); this.emitRawOutput(oBuffer); this.endElement(new QName(this,this.prefix("Header"))); this.changeState( IN_SUMMARY ); oAtts.clear(); this.startElement(new QName(this,this.prefix ("Summary")), (Attributes)oAtts); try{ // fast forward to first summary while (! oLine.startsWith( "-------- " ) ) { oLine = oContents.readLine(); } } catch (java.io.IOException x) { System.err.println(x.getMessage()); System.err.println("File read interrupted"); throw new SAXException( "File read interrupted" ); } // end try/catch } } else { // System.err.println( "FINISHED HITS>>>>>>" ); oLine = oLastLine; this.changeState( FINISHED_HITS ); } } else { // passed Alignment section // // Either trailer with histogram or a new entry with '//' // look for the start of a new file with 'hmmsearch'? this.changeState(FINISHED_HITS); } return oLine; } return poLine;; // this.endElement(new QName(this,this.prefix("Detail"))); }
private String hmmerDomainSummaryReached(String poLine) throws SAXException { //To be implemented - parse Contents stream up to end of //domain summary via delegation (analagous to hits parsing oAtts.clear(); this.startElement(new QName(this,this.prefix("DomainSummary")), (Attributes)oAtts); int iProgram = oVersion.getProgram(); if ( iProgram == BlastLikeVersionSupport.HMMER ) { DomainSectionSAXParser oDomains = new DomainSectionSAXParser ( oVersion, this.getNamespacePrefix() ); oDomains.setContentHandler( oHandler ); oDomains.parse( oContents, poLine ); this.endElement(new QName(this,this.prefix("DomainSummary"))); this.endElement(new QName(this,this.prefix("Summary"))); String oLine = null; try { oLine = oContents.readLine(); while( oLine != null && ( !oLine.startsWith ( "Alignments of top-scoring domains:" ) ) && ( !oLine.startsWith( "//" ) ) && ( !oLine.startsWith( "Histogram of all scores:" ) ) ) { oLine = oContents.readLine(); } } catch ( IOException e ) { System.err.println( e.getMessage()); System.err.println("File read interrupted"); throw new SAXException( "File read interrupted" ); } if ( oLine != null && oLine.startsWith( "Alignments of top-scoring domains:" ) ) { oAtts.clear(); this.startElement(new QName(this,this.prefix("Detail")), (Attributes)oAtts); HmmerAlignmentSAXParser oAlignments = new HmmerAlignmentSAXParser ( oVersion, this.getNamespacePrefix() ); oAlignments.setContentHandler( oHandler ); String oLastLine = oAlignments.parse( oContents, poLine ); if ( oLastLine.trim().equals("//") ) { // hmmpfam // then close details, BlastLikeDataSet // if more stuff this.endElement(new QName(this,this.prefix("Detail"))); try { oLine = oContents.readLine(); while ( (oLine != null) && (!oLine.startsWith( "Query:" ) ) ) { oLine = oContents.readLine(); } } catch ( IOException e ) { System.err.println( "Read interrupted" ); System.err.println( e ); e.printStackTrace(); throw new SAXException( "File read interupted" ); } if ( oLine == null ) { this.changeState(AT_END); return oLine; } else { this.endElement(new QName(this,this.prefix ("BlastLikeDataSet"))); // need to start a new one ( if there is ) oAtts.clear(); oAttQName.setQName("program"); oAtts.addAttribute(oAttQName.getURI(), oAttQName.getLocalName(), oAttQName.getQName(), "CDATA",oVersion.getProgramString()); oAttQName.setQName("version"); oAtts.addAttribute(oAttQName.getURI(), oAttQName.getLocalName(), oAttQName.getQName(), "CDATA",oVersion.getVersionString()); this.startElement(new QName(this,this.prefix ("BlastLikeDataSet")), (Attributes)oAtts); oAtts.clear(); this.startElement(new QName(this,this.prefix("Header")), (Attributes)oAtts); oBuffer.clear(); oBuffer.add( oLine ); this.emitRawOutput(oBuffer); this.endElement(new QName(this,this.prefix("Header"))); this.changeState( IN_SUMMARY ); oAtts.clear(); this.startElement(new QName(this,this.prefix ("Summary")), (Attributes)oAtts); try{ // fast forward to first summary while (! oLine.startsWith( "-------- " ) ) { oLine = oContents.readLine(); } } catch (java.io.IOException x) { System.err.println(x.getMessage()); System.err.println("File read interrupted"); throw new SAXException( "File read interrupted" ); } // end try/catch } } else { // System.err.println( "FINISHED HITS>>>>>>" ); oLine = oLastLine; this.changeState( FINISHED_HITS ); } } else { // passed Alignment section // // Either trailer with histogram or a new entry with '//' // look for the start of a new file with 'hmmsearch'? this.changeState(FINISHED_HITS); } return oLine; } return poLine; // this.endElement(new QName(this,this.prefix("Detail"))); }
diff --git a/src/java/com/scriptographer/ai/Timer.java b/src/java/com/scriptographer/ai/Timer.java index 6ca017c3..87893537 100644 --- a/src/java/com/scriptographer/ai/Timer.java +++ b/src/java/com/scriptographer/ai/Timer.java @@ -1,182 +1,188 @@ /* * Scriptographer * * This file is part of Scriptographer, a Plugin for Adobe Illustrator. * * Copyright (c) 2002-2010 Juerg Lehni, http://www.scratchdisk.com. * All rights reserved. * * Please visit http://scriptographer.org/ for updates and contact. * * -- GPL LICENSE NOTICE -- * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * -- GPL LICENSE NOTICE -- * * File created on May 29, 2010. */ package com.scriptographer.ai; import com.scratchdisk.script.Callable; import com.scratchdisk.util.ConversionUtils; import com.scratchdisk.util.IntMap; import com.scriptographer.ScriptographerEngine; import com.scriptographer.ScriptographerException; import com.scriptographer.sg.Script; /** * @author lehni * */ public class Timer extends NativeObject { private int period; private boolean periodic; private Script script = null; private static IntMap<Timer> timers = new IntMap<Timer>(); /** * Creates a timer object. * * @param period The timer's period in milliseconds. * @param periodic Controls whether the timer is one-shop or periodic. */ public Timer(int period, boolean periodic) { script = ScriptographerEngine.getCurrentScript(); this.period = period; this.periodic = periodic; handle = nativeCreate(period); if (handle == 0) throw new ScriptographerException("Unable to create Timer."); timers.put(handle, this); } public Timer(int period) { this(period, true); } public void abort() { if (handle != 0) { timers.remove(handle); nativeAbort(handle); handle = 0; } } private native int nativeCreate(int period); private native void nativeAbort(int handle); public double getPeriod() { return period; } public boolean isPeriodic() { return periodic; } protected boolean canAbort(boolean ignoreKeepAlive) { return script == null || script.canRemove(ignoreKeepAlive); } public static void abortAll(boolean ignoreKeepAlive, boolean force) { // As abort() modifies the Map, using an iterator is not possible here: Object[] timers = Timer.timers.values().toArray(); for (int i = 0; i < timers.length; i++) { Timer timer = (Timer) timers[i]; if (force || timer.canAbort(ignoreKeepAlive)) timer.abort(); } } private Callable onExecute = null; public void setOnExecute(Callable onExecute) { this.onExecute = onExecute; } public Callable getOnExecute() { return onExecute; } /** * The timer callback. * * Return true if document should be redrawn automatically. */ protected boolean onExecute() { if (onExecute != null) { Object result = ScriptographerEngine.invoke(onExecute, this); if (result != null) return ConversionUtils.toBoolean(result); } return false; } /** * To be called from the native environment: */ private static boolean onExecute(int handle) { Timer timer = getTimer(handle); if (timer != null) { try { Document document = Document.getActiveDocument(); // Produce a normal undo cycle if in the previous cycle we have // created or removed items. Otherwise just merge the changes of // this cycle with the previous one. // It is important to create new cycles when such changes // happen, as they affect the live span of items within the undo // history, and if all cycles were merged, the history tracking // code in Document would not be able to track their life span. int undoType = document == null || document.hasCreatedState() || document.hasRemovedState() ? Document.UNDO_STANDARD : Document.UNDO_MERGE; // Clear changed states now to track for new changes in // onExecute() if (document != null) document.clearChangedStates(); boolean changed = timer.onExecute() || document != null && document.hasChangedSates(); - // Only change undo type if the document have actually changed. - // This prevents issues with situations where Timers are used - // for ADM interface stuff, e.g. invokeLater(). - if (document != null && changed) + // Only change undo type if the document have actually changed, + // or if the type is MERGE, in which case we will not add new + // unto levels. This is actually needed to prevent a weird bug + // that occasionally happens where Ai keeps adding new levels. + // To not set STANDARD in all cases prevents issues with + // situations where Timers are used for ADM interface stuff, + // e.g. invokeLater(). + if (document != null && (changed + || undoType == Document.UNDO_MERGE)) { document.setUndoType(undoType); + } return changed; } finally { // Simulate one shot timers by aborting: if (!timer.periodic) timer.abort(); } } return false; } private static Timer getTimer(int handle) { return (Timer) timers.get(handle); } protected void finalize() { abort(); } public Object getId() { // Return the integer handle as id instead of a formated string, as the // script side wants to work with numeric timer ids. return handle; } }
false
true
private static boolean onExecute(int handle) { Timer timer = getTimer(handle); if (timer != null) { try { Document document = Document.getActiveDocument(); // Produce a normal undo cycle if in the previous cycle we have // created or removed items. Otherwise just merge the changes of // this cycle with the previous one. // It is important to create new cycles when such changes // happen, as they affect the live span of items within the undo // history, and if all cycles were merged, the history tracking // code in Document would not be able to track their life span. int undoType = document == null || document.hasCreatedState() || document.hasRemovedState() ? Document.UNDO_STANDARD : Document.UNDO_MERGE; // Clear changed states now to track for new changes in // onExecute() if (document != null) document.clearChangedStates(); boolean changed = timer.onExecute() || document != null && document.hasChangedSates(); // Only change undo type if the document have actually changed. // This prevents issues with situations where Timers are used // for ADM interface stuff, e.g. invokeLater(). if (document != null && changed) document.setUndoType(undoType); return changed; } finally { // Simulate one shot timers by aborting: if (!timer.periodic) timer.abort(); } } return false; }
private static boolean onExecute(int handle) { Timer timer = getTimer(handle); if (timer != null) { try { Document document = Document.getActiveDocument(); // Produce a normal undo cycle if in the previous cycle we have // created or removed items. Otherwise just merge the changes of // this cycle with the previous one. // It is important to create new cycles when such changes // happen, as they affect the live span of items within the undo // history, and if all cycles were merged, the history tracking // code in Document would not be able to track their life span. int undoType = document == null || document.hasCreatedState() || document.hasRemovedState() ? Document.UNDO_STANDARD : Document.UNDO_MERGE; // Clear changed states now to track for new changes in // onExecute() if (document != null) document.clearChangedStates(); boolean changed = timer.onExecute() || document != null && document.hasChangedSates(); // Only change undo type if the document have actually changed, // or if the type is MERGE, in which case we will not add new // unto levels. This is actually needed to prevent a weird bug // that occasionally happens where Ai keeps adding new levels. // To not set STANDARD in all cases prevents issues with // situations where Timers are used for ADM interface stuff, // e.g. invokeLater(). if (document != null && (changed || undoType == Document.UNDO_MERGE)) { document.setUndoType(undoType); } return changed; } finally { // Simulate one shot timers by aborting: if (!timer.periodic) timer.abort(); } } return false; }
diff --git a/src/org/x3/mail/SimpleMail.java b/src/org/x3/mail/SimpleMail.java index b3d8eb0..fcbb092 100644 --- a/src/org/x3/mail/SimpleMail.java +++ b/src/org/x3/mail/SimpleMail.java @@ -1,122 +1,122 @@ package org.x3.mail; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import org.x3.mail.util.Message; public class SimpleMail extends JavaPlugin { HashMap<String, ArrayList<Message>> mail; MailHandler mailHandler; Logger log; @Override public void onEnable() { log = this.getLogger(); mailHandler = new MailHandler(new File(getDataFolder(), "simplemail.map")); mail = new HashMap<String, ArrayList<Message>>(); this.getCommand("mail").setExecutor(new SMExecutor(this)); log.info("SimpleMail enabled."); } /** * Returns the result of JavaPlugin.getServer().getPlayer(name) * * @param name * Name of the player * @return The associated player, or null if not found. */ public Player getPlayer(String name) { return getServer().getPlayer(name); } /** * Returns whether the specified player has unread mail. * * @param player * The player's name * @return Whether the player has unread mail. */ public boolean hasMail(String player) { return mail.containsKey(player.toLowerCase()); } /** * Returns the player's mail. * * @param player * Name of the player * @return Unread messages, or null if the player has no new mail. */ public ArrayList<Message> getMail(String player) { return (mail.containsKey(player.toLowerCase())) ? mail.get(player .toLowerCase()) : new ArrayList<Message>(); } /** * Deletes all of the player's mail. * * @param player * Name of the player */ public void removeMail(String player) { mail.remove(player.toLowerCase()); } /** * Determines if the player is online. * * @param player * Name of the player * @return True if online, else false. */ public boolean isOnline(String player) { for (Player p : getServer().getOnlinePlayers()) { if (p.getName().equalsIgnoreCase(player)) { return true; } } return false; } /** * Send a message. The target player is specified within the message. * * @param message * The message to send */ public void send(Message message) { String recipient = message.getRecipient(); ArrayList<Message> playerMail = getMail(recipient); if (hasMail(recipient)) { mail.remove(recipient); } playerMail.add(message); mail.put(recipient, playerMail); if (recipient.equalsIgnoreCase("console")) { - log.info(ChatColor.GREEN + "New mail for Console"); + log.info("New mail for Console"); } else if (isOnline(recipient)) { notifyPlayer(getServer().getPlayer(recipient)); } } /** * Notify the player that they have new messages. * * @param player * Player to notify */ public void notifyPlayer(Player player) { player.sendMessage(ChatColor.GREEN + String.format("You have %s new message(s).", getMail(player.getName()).size())); } }
true
true
public void send(Message message) { String recipient = message.getRecipient(); ArrayList<Message> playerMail = getMail(recipient); if (hasMail(recipient)) { mail.remove(recipient); } playerMail.add(message); mail.put(recipient, playerMail); if (recipient.equalsIgnoreCase("console")) { log.info(ChatColor.GREEN + "New mail for Console"); } else if (isOnline(recipient)) { notifyPlayer(getServer().getPlayer(recipient)); } }
public void send(Message message) { String recipient = message.getRecipient(); ArrayList<Message> playerMail = getMail(recipient); if (hasMail(recipient)) { mail.remove(recipient); } playerMail.add(message); mail.put(recipient, playerMail); if (recipient.equalsIgnoreCase("console")) { log.info("New mail for Console"); } else if (isOnline(recipient)) { notifyPlayer(getServer().getPlayer(recipient)); } }
diff --git a/src/nu/nerd/modmode/ModMode.java b/src/nu/nerd/modmode/ModMode.java index 82f022a..e2ed1cb 100644 --- a/src/nu/nerd/modmode/ModMode.java +++ b/src/nu/nerd/modmode/ModMode.java @@ -1,401 +1,403 @@ package nu.nerd.modmode; import de.bananaco.bpermissions.api.ApiLayer; import de.bananaco.bpermissions.api.util.CalculableType; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import net.minecraft.server.v1_5_R2.EntityPlayer; import net.minecraft.server.v1_5_R2.MinecraftServer; import net.minecraft.server.v1_5_R2.MobEffect; import net.minecraft.server.v1_5_R2.Packet; import net.minecraft.server.v1_5_R2.Packet3Chat; import net.minecraft.server.v1_5_R2.Packet41MobEffect; import net.minecraft.server.v1_5_R2.WorldServer; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.craftbukkit.v1_5_R2.CraftServer; import org.bukkit.craftbukkit.v1_5_R2.entity.CraftPlayer; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.potion.PotionEffect; public class ModMode extends JavaPlugin { private final ModModeListener listener = new ModModeListener(this); public List<String> vanished; public List<String> fullvanished; public List<String> modmode; public boolean allowFlight; public boolean usingbperms; public String bPermsModGroup; public String bPermsModModeGroup; public HashMap<String, Collection<PotionEffect>> potionMap; public boolean isInvisible(Player player) { return vanished.contains(player.getName()) || fullvanished.contains(player.getName()); } public boolean isModMode(Player player) { return modmode.contains(player.getDisplayName()); } public void enableVanish(Player player) { for (Player other : getServer().getOnlinePlayers()) { if (Permissions.hasPermission(other, Permissions.SHOWVANISHED)) { continue; } if (Permissions.hasPermission(other, Permissions.SHOWMODS)) { continue; } other.hidePlayer(player); } player.sendMessage(ChatColor.RED + "Poof!"); } public void enableFullVanish(Player player) { for (Player other : getServer().getOnlinePlayers()) { if (Permissions.hasPermission(other, Permissions.SHOWVANISHED)) { continue; } other.hidePlayer(player); } player.sendMessage(ChatColor.RED + "You are fully vanished!"); } public void disableVanish(Player player) { if (vanished.remove(player.getName()) || fullvanished.remove(player.getName())) { for (Player other : getServer().getOnlinePlayers()) { other.showPlayer(player); } player.sendMessage(ChatColor.RED + "You have reappeared!"); } else { player.sendMessage(ChatColor.RED + "You are not vanished!"); } } public void showVanishList(Player player) { String result = ""; boolean first = true; for (String hidden : vanished) { if (getServer().getPlayerExact(hidden) == null) { continue; } if (first) { result += hidden + ChatColor.RED; first = false; continue; } result += ", " + hidden + ChatColor.RED; } for (String hidden : fullvanished) { if (getServer().getPlayerExact(hidden) == null) { continue; } if (first) { result += hidden + ChatColor.RED; first = false; continue; } result += ", " + hidden + ChatColor.RED; } if (result.length() == 0) { player.sendMessage(ChatColor.RED + "All players are visible!"); } else { player.sendMessage(ChatColor.RED + "Vanished players: " + result); } } public void toggleModMode(final Player player, boolean toggle, boolean onJoin) { String displayName = player.getName(); String name = ChatColor.GREEN + player.getDisplayName() + ChatColor.WHITE; if (!toggle) { displayName = player.getDisplayName(); name = displayName; if (usingbperms) { List<org.bukkit.World> worlds = getServer().getWorlds(); for (org.bukkit.World world : worlds) { ApiLayer.removeGroup(world.getName(), CalculableType.USER, name, bPermsModModeGroup); List<String> groups = Arrays.asList(ApiLayer.getGroups(world.getName(), CalculableType.USER, name)); if (!groups.contains(bPermsModGroup)) { ApiLayer.addGroup(world.getName(), CalculableType.USER, name, bPermsModGroup); } } } player.sendMessage(ChatColor.RED + "You are no longer in ModMode!"); } else { if (usingbperms) { List<org.bukkit.World> worlds = getServer().getWorlds(); for (org.bukkit.World world : worlds) { ApiLayer.addGroup(world.getName(), CalculableType.USER, name, bPermsModModeGroup); List<String> groups = Arrays.asList(ApiLayer.getGroups(world.getName(), CalculableType.USER, name)); if (groups.contains(bPermsModGroup)) { ApiLayer.removeGroup(world.getName(), CalculableType.USER, name, bPermsModGroup); } } } player.sendMessage(ChatColor.RED + "You are now in ModMode!"); } Location loc = player.getLocation(); final EntityPlayer entityplayer = ((CraftPlayer) player).getHandle(); final MinecraftServer server = entityplayer.server; //send fake quit message if (!onJoin) { PlayerQuitEvent playerQuitEvent = new PlayerQuitEvent(player, "\u00A7e" + entityplayer.name + " left the game."); getServer().getPluginManager().callEvent(playerQuitEvent); if ((playerQuitEvent.getQuitMessage() != null) && (playerQuitEvent.getQuitMessage().length() > 0)) { sendPacketToAll(new Packet3Chat(playerQuitEvent.getQuitMessage())); } } // Save current potion effects Collection<PotionEffect> activeEffects = player.getActivePotionEffects(); potionMap.put(entityplayer.name, activeEffects); //save with the old name, change it, then load with the new name server.getPlayerList().playerFileData.save(entityplayer); entityplayer.name = name; entityplayer.displayName = displayName; server.getPlayerList().playerFileData.load(entityplayer); //send fake join message PlayerJoinEvent playerJoinEvent = new PlayerJoinEvent(player, "\u00A7e" + entityplayer.name + " joined the game."); getServer().getPluginManager().callEvent(playerJoinEvent); if ((playerJoinEvent.getJoinMessage() != null) && (playerJoinEvent.getJoinMessage().length() > 0)) { sendPacketToAll(new Packet3Chat(playerJoinEvent.getJoinMessage())); } //untrack and track to show new name to clients ((WorldServer) entityplayer.world).tracker.untrackEntity(entityplayer); ((WorldServer) entityplayer.world).tracker.track(entityplayer); //teleport to avoid speedhack if (!toggle || onJoin) { loc = new Location(entityplayer.world.getWorld(), entityplayer.locX, entityplayer.locY, entityplayer.locZ, entityplayer.yaw, entityplayer.pitch); } player.teleport(loc); //unvanish the player when they leave modmode if (!toggle) { for (Player other : getServer().getOnlinePlayers()) { other.showPlayer(player); } } // Load new potion effects for (PotionEffect effect : activeEffects){ player.removePotionEffect(effect.getType()); } Collection<PotionEffect> newEffects = potionMap.get(entityplayer.name); - for (PotionEffect effect : newEffects){ - player.addPotionEffect(effect); - // addPotionEffect doesn't send this packet for some reason, so we'll do it manually - entityplayer.playerConnection.sendPacket(new Packet41MobEffect(entityplayer.id, new MobEffect(effect.getType().getId(), effect.getDuration(), effect.getAmplifier()))); + if (newEffects != null) { + for (PotionEffect effect : newEffects){ + player.addPotionEffect(effect); + // addPotionEffect doesn't send this packet for some reason, so we'll do it manually + entityplayer.playerConnection.sendPacket(new Packet41MobEffect(entityplayer.id, new MobEffect(effect.getType().getId(), effect.getDuration(), effect.getAmplifier()))); + } } potionMap.remove(entityplayer.name); // final Location loc2 = loc.clone(); // // getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { // public void run() { // Packet20NamedEntitySpawn packet = new Packet20NamedEntitySpawn(entityplayer); // server.getServerConfigurationManager().sendPacketNearby(loc2.getX(), loc2.getY(), loc2.getZ(), 128, ((CraftWorld) loc2.getWorld()).getHandle().dimension, packet); // Packet29DestroyEntity destroy = new Packet29DestroyEntity(entityplayer.id); // server.getServerConfigurationManager().sendPacketNearby(loc2.getX(), loc2.getY(), loc2.getZ(), 1, ((CraftWorld) loc2.getWorld()).getHandle().dimension, destroy); // } // }, 10); //toggle flight, set via the config path "allow.flight" if (allowFlight) { player.setAllowFlight(toggle); } /* * EntityPlayer oldplayer = ((CraftPlayer) player).getHandle(); * MinecraftServer server = oldplayer.server; NetServerHandler * netServerHandler = oldplayer.netServerHandler; * * // remove old entity String quitMessage = * server.serverConfigurationManager.disconnect(oldplayer); if * ((quitMessage != null) && (quitMessage.length() > 0)) { * server.serverConfigurationManager.sendAll(new * Packet3Chat(quitMessage)); } * * // ((WorldServer) oldplayer.world).tracker.untrackPlayer(oldplayer); * // oldplayer.die(); * * // make new one with same NetServerHandler and ItemInWorldManager * EntityPlayer entityplayer = new EntityPlayer(server, * server.getWorldServer(0), name, oldplayer.itemInWorldManager); Player * newplayer = entityplayer.getBukkitEntity(); * * entityplayer.displayName = displayName; entityplayer.listName = * displayName; entityplayer.netServerHandler = netServerHandler; * entityplayer.netServerHandler.player = entityplayer; entityplayer.id * = oldplayer.id; * server.serverConfigurationManager.playerFileData.load(entityplayer); * if (toggle) { entityplayer.locX = oldplayer.locX; entityplayer.locY = * oldplayer.locY; entityplayer.locZ = oldplayer.locZ; entityplayer.yaw * = oldplayer.yaw; entityplayer.pitch = oldplayer.pitch; } * server.serverConfigurationManager.c(entityplayer); * entityplayer.syncInventory(); * * // untrack and track to make sure we can see everyone ((WorldServer) * entityplayer.world).tracker.untrackEntity(entityplayer); * ((WorldServer) entityplayer.world).tracker.track(entityplayer); * * // teleport to the player's location to avoid speedhack kick if * (!toggle) { Location loc = new * Location(entityplayer.world.getWorld(), entityplayer.locX, * entityplayer.locY, entityplayer.locZ, entityplayer.yaw, * entityplayer.pitch); newplayer.teleport(loc); } */ } private static void sendPacketToAll(Packet p){ MinecraftServer server = ((CraftServer)Bukkit.getServer()).getServer(); for (int i = 0; i < server.getPlayerList().players.size(); ++i) { EntityPlayer ep = (EntityPlayer) server.getPlayerList().players.get(i); ep.playerConnection.sendPacket(p); } } public void updateVanishLists(Player player) { //first show everyone, then decide who to hide for (Player other : getServer().getOnlinePlayers()) { player.showPlayer(other); } if (Permissions.hasPermission(player, Permissions.SHOWVANISHED)) { return; } for (String hidden : fullvanished) { Player hiddenPlayer = getServer().getPlayerExact(hidden); if (hiddenPlayer != null) { player.hidePlayer(hiddenPlayer); } } if (Permissions.hasPermission(player, Permissions.SHOWMODS)) { return; } for (String hidden : vanished) { Player hiddenPlayer = getServer().getPlayerExact(hidden); if (hiddenPlayer != null) { player.hidePlayer(hiddenPlayer); } } } @Override public void onEnable() { getServer().getPluginManager().registerEvents(listener, this); vanished = getConfig().getStringList("vanished"); fullvanished = getConfig().getStringList("fullvanished"); modmode = getConfig().getStringList("modmode"); allowFlight = getConfig().getBoolean("allow.flight", true); usingbperms = getConfig().getBoolean("bperms.enabled", false); bPermsModGroup = getConfig().getString("bperms.modgroup", "Moderators"); bPermsModModeGroup = getConfig().getString("bperms.modmodegroup", "ModMode"); potionMap = new HashMap<String, Collection<PotionEffect>>(); if (usingbperms) { de.bananaco.bpermissions.imp.Permissions bPermsPlugin = null; bPermsPlugin = (de.bananaco.bpermissions.imp.Permissions)getServer().getPluginManager().getPlugin("bPermissions"); if (bPermsPlugin == null || !(bPermsPlugin instanceof de.bananaco.bpermissions.imp.Permissions)) { if (!bPermsPlugin.isEnabled()) { getPluginLoader().enablePlugin(bPermsPlugin); } getLogger().log(Level.INFO, "bperms turned on, but plugin could not be loaded."); getPluginLoader().disablePlugin(this); } } } @Override public void onDisable() { getConfig().set("vanished", vanished); getConfig().set("fullvanished", fullvanished); getConfig().set("modmode", modmode); getConfig().set("allow.flight", allowFlight); getConfig().set("bperms.enabled", usingbperms); getConfig().set("bperms.modgroup", bPermsModGroup); getConfig().set("bperms.modmodegroup", bPermsModModeGroup); saveConfig(); } @Override public boolean onCommand(CommandSender sender, Command command, String name, String[] args) { if (!(sender instanceof Player)) { return false; } Player player = (Player) sender; if (command.getName().equalsIgnoreCase("vanish")) { if (args.length == 1 && args[0].equalsIgnoreCase("list")) { showVanishList(player); } else { if (vanished.contains(player.getName())) { player.sendMessage(ChatColor.RED + "You are already vanished!"); } else { // special case, we need to appear to mods but not everyone if (fullvanished.remove(player.getName())) { for (Player other : getServer().getOnlinePlayers()) { if (Permissions.hasPermission(other, Permissions.SHOWMODS)) { other.showPlayer(player); } } } vanished.add(player.getName()); enableVanish(player); } } } else if (command.getName().equalsIgnoreCase("fullvanish")) { if (fullvanished.contains(player.getName())) { player.sendMessage(ChatColor.RED + "You are already vanished!"); } else { fullvanished.add(player.getName()); vanished.remove(player.getName()); enableFullVanish(player); } } else if (command.getName().equalsIgnoreCase("unvanish")) { disableVanish(player); } else if (command.getName().equalsIgnoreCase("modmode")) { if (modmode.remove(player.getDisplayName())) { toggleModMode(player, false, false); } else { modmode.add(player.getDisplayName()); toggleModMode(player, true, false); } } return true; } }
true
true
public void toggleModMode(final Player player, boolean toggle, boolean onJoin) { String displayName = player.getName(); String name = ChatColor.GREEN + player.getDisplayName() + ChatColor.WHITE; if (!toggle) { displayName = player.getDisplayName(); name = displayName; if (usingbperms) { List<org.bukkit.World> worlds = getServer().getWorlds(); for (org.bukkit.World world : worlds) { ApiLayer.removeGroup(world.getName(), CalculableType.USER, name, bPermsModModeGroup); List<String> groups = Arrays.asList(ApiLayer.getGroups(world.getName(), CalculableType.USER, name)); if (!groups.contains(bPermsModGroup)) { ApiLayer.addGroup(world.getName(), CalculableType.USER, name, bPermsModGroup); } } } player.sendMessage(ChatColor.RED + "You are no longer in ModMode!"); } else { if (usingbperms) { List<org.bukkit.World> worlds = getServer().getWorlds(); for (org.bukkit.World world : worlds) { ApiLayer.addGroup(world.getName(), CalculableType.USER, name, bPermsModModeGroup); List<String> groups = Arrays.asList(ApiLayer.getGroups(world.getName(), CalculableType.USER, name)); if (groups.contains(bPermsModGroup)) { ApiLayer.removeGroup(world.getName(), CalculableType.USER, name, bPermsModGroup); } } } player.sendMessage(ChatColor.RED + "You are now in ModMode!"); } Location loc = player.getLocation(); final EntityPlayer entityplayer = ((CraftPlayer) player).getHandle(); final MinecraftServer server = entityplayer.server; //send fake quit message if (!onJoin) { PlayerQuitEvent playerQuitEvent = new PlayerQuitEvent(player, "\u00A7e" + entityplayer.name + " left the game."); getServer().getPluginManager().callEvent(playerQuitEvent); if ((playerQuitEvent.getQuitMessage() != null) && (playerQuitEvent.getQuitMessage().length() > 0)) { sendPacketToAll(new Packet3Chat(playerQuitEvent.getQuitMessage())); } } // Save current potion effects Collection<PotionEffect> activeEffects = player.getActivePotionEffects(); potionMap.put(entityplayer.name, activeEffects); //save with the old name, change it, then load with the new name server.getPlayerList().playerFileData.save(entityplayer); entityplayer.name = name; entityplayer.displayName = displayName; server.getPlayerList().playerFileData.load(entityplayer); //send fake join message PlayerJoinEvent playerJoinEvent = new PlayerJoinEvent(player, "\u00A7e" + entityplayer.name + " joined the game."); getServer().getPluginManager().callEvent(playerJoinEvent); if ((playerJoinEvent.getJoinMessage() != null) && (playerJoinEvent.getJoinMessage().length() > 0)) { sendPacketToAll(new Packet3Chat(playerJoinEvent.getJoinMessage())); } //untrack and track to show new name to clients ((WorldServer) entityplayer.world).tracker.untrackEntity(entityplayer); ((WorldServer) entityplayer.world).tracker.track(entityplayer); //teleport to avoid speedhack if (!toggle || onJoin) { loc = new Location(entityplayer.world.getWorld(), entityplayer.locX, entityplayer.locY, entityplayer.locZ, entityplayer.yaw, entityplayer.pitch); } player.teleport(loc); //unvanish the player when they leave modmode if (!toggle) { for (Player other : getServer().getOnlinePlayers()) { other.showPlayer(player); } } // Load new potion effects for (PotionEffect effect : activeEffects){ player.removePotionEffect(effect.getType()); } Collection<PotionEffect> newEffects = potionMap.get(entityplayer.name); for (PotionEffect effect : newEffects){ player.addPotionEffect(effect); // addPotionEffect doesn't send this packet for some reason, so we'll do it manually entityplayer.playerConnection.sendPacket(new Packet41MobEffect(entityplayer.id, new MobEffect(effect.getType().getId(), effect.getDuration(), effect.getAmplifier()))); } potionMap.remove(entityplayer.name); // final Location loc2 = loc.clone(); // // getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { // public void run() { // Packet20NamedEntitySpawn packet = new Packet20NamedEntitySpawn(entityplayer); // server.getServerConfigurationManager().sendPacketNearby(loc2.getX(), loc2.getY(), loc2.getZ(), 128, ((CraftWorld) loc2.getWorld()).getHandle().dimension, packet); // Packet29DestroyEntity destroy = new Packet29DestroyEntity(entityplayer.id); // server.getServerConfigurationManager().sendPacketNearby(loc2.getX(), loc2.getY(), loc2.getZ(), 1, ((CraftWorld) loc2.getWorld()).getHandle().dimension, destroy); // } // }, 10); //toggle flight, set via the config path "allow.flight" if (allowFlight) { player.setAllowFlight(toggle); } /* * EntityPlayer oldplayer = ((CraftPlayer) player).getHandle(); * MinecraftServer server = oldplayer.server; NetServerHandler * netServerHandler = oldplayer.netServerHandler; * * // remove old entity String quitMessage = * server.serverConfigurationManager.disconnect(oldplayer); if * ((quitMessage != null) && (quitMessage.length() > 0)) { * server.serverConfigurationManager.sendAll(new * Packet3Chat(quitMessage)); } * * // ((WorldServer) oldplayer.world).tracker.untrackPlayer(oldplayer); * // oldplayer.die(); * * // make new one with same NetServerHandler and ItemInWorldManager * EntityPlayer entityplayer = new EntityPlayer(server, * server.getWorldServer(0), name, oldplayer.itemInWorldManager); Player * newplayer = entityplayer.getBukkitEntity(); * * entityplayer.displayName = displayName; entityplayer.listName = * displayName; entityplayer.netServerHandler = netServerHandler; * entityplayer.netServerHandler.player = entityplayer; entityplayer.id * = oldplayer.id; * server.serverConfigurationManager.playerFileData.load(entityplayer); * if (toggle) { entityplayer.locX = oldplayer.locX; entityplayer.locY = * oldplayer.locY; entityplayer.locZ = oldplayer.locZ; entityplayer.yaw * = oldplayer.yaw; entityplayer.pitch = oldplayer.pitch; } * server.serverConfigurationManager.c(entityplayer); * entityplayer.syncInventory(); * * // untrack and track to make sure we can see everyone ((WorldServer) * entityplayer.world).tracker.untrackEntity(entityplayer); * ((WorldServer) entityplayer.world).tracker.track(entityplayer); * * // teleport to the player's location to avoid speedhack kick if * (!toggle) { Location loc = new * Location(entityplayer.world.getWorld(), entityplayer.locX, * entityplayer.locY, entityplayer.locZ, entityplayer.yaw, * entityplayer.pitch); newplayer.teleport(loc); }
public void toggleModMode(final Player player, boolean toggle, boolean onJoin) { String displayName = player.getName(); String name = ChatColor.GREEN + player.getDisplayName() + ChatColor.WHITE; if (!toggle) { displayName = player.getDisplayName(); name = displayName; if (usingbperms) { List<org.bukkit.World> worlds = getServer().getWorlds(); for (org.bukkit.World world : worlds) { ApiLayer.removeGroup(world.getName(), CalculableType.USER, name, bPermsModModeGroup); List<String> groups = Arrays.asList(ApiLayer.getGroups(world.getName(), CalculableType.USER, name)); if (!groups.contains(bPermsModGroup)) { ApiLayer.addGroup(world.getName(), CalculableType.USER, name, bPermsModGroup); } } } player.sendMessage(ChatColor.RED + "You are no longer in ModMode!"); } else { if (usingbperms) { List<org.bukkit.World> worlds = getServer().getWorlds(); for (org.bukkit.World world : worlds) { ApiLayer.addGroup(world.getName(), CalculableType.USER, name, bPermsModModeGroup); List<String> groups = Arrays.asList(ApiLayer.getGroups(world.getName(), CalculableType.USER, name)); if (groups.contains(bPermsModGroup)) { ApiLayer.removeGroup(world.getName(), CalculableType.USER, name, bPermsModGroup); } } } player.sendMessage(ChatColor.RED + "You are now in ModMode!"); } Location loc = player.getLocation(); final EntityPlayer entityplayer = ((CraftPlayer) player).getHandle(); final MinecraftServer server = entityplayer.server; //send fake quit message if (!onJoin) { PlayerQuitEvent playerQuitEvent = new PlayerQuitEvent(player, "\u00A7e" + entityplayer.name + " left the game."); getServer().getPluginManager().callEvent(playerQuitEvent); if ((playerQuitEvent.getQuitMessage() != null) && (playerQuitEvent.getQuitMessage().length() > 0)) { sendPacketToAll(new Packet3Chat(playerQuitEvent.getQuitMessage())); } } // Save current potion effects Collection<PotionEffect> activeEffects = player.getActivePotionEffects(); potionMap.put(entityplayer.name, activeEffects); //save with the old name, change it, then load with the new name server.getPlayerList().playerFileData.save(entityplayer); entityplayer.name = name; entityplayer.displayName = displayName; server.getPlayerList().playerFileData.load(entityplayer); //send fake join message PlayerJoinEvent playerJoinEvent = new PlayerJoinEvent(player, "\u00A7e" + entityplayer.name + " joined the game."); getServer().getPluginManager().callEvent(playerJoinEvent); if ((playerJoinEvent.getJoinMessage() != null) && (playerJoinEvent.getJoinMessage().length() > 0)) { sendPacketToAll(new Packet3Chat(playerJoinEvent.getJoinMessage())); } //untrack and track to show new name to clients ((WorldServer) entityplayer.world).tracker.untrackEntity(entityplayer); ((WorldServer) entityplayer.world).tracker.track(entityplayer); //teleport to avoid speedhack if (!toggle || onJoin) { loc = new Location(entityplayer.world.getWorld(), entityplayer.locX, entityplayer.locY, entityplayer.locZ, entityplayer.yaw, entityplayer.pitch); } player.teleport(loc); //unvanish the player when they leave modmode if (!toggle) { for (Player other : getServer().getOnlinePlayers()) { other.showPlayer(player); } } // Load new potion effects for (PotionEffect effect : activeEffects){ player.removePotionEffect(effect.getType()); } Collection<PotionEffect> newEffects = potionMap.get(entityplayer.name); if (newEffects != null) { for (PotionEffect effect : newEffects){ player.addPotionEffect(effect); // addPotionEffect doesn't send this packet for some reason, so we'll do it manually entityplayer.playerConnection.sendPacket(new Packet41MobEffect(entityplayer.id, new MobEffect(effect.getType().getId(), effect.getDuration(), effect.getAmplifier()))); } } potionMap.remove(entityplayer.name); // final Location loc2 = loc.clone(); // // getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { // public void run() { // Packet20NamedEntitySpawn packet = new Packet20NamedEntitySpawn(entityplayer); // server.getServerConfigurationManager().sendPacketNearby(loc2.getX(), loc2.getY(), loc2.getZ(), 128, ((CraftWorld) loc2.getWorld()).getHandle().dimension, packet); // Packet29DestroyEntity destroy = new Packet29DestroyEntity(entityplayer.id); // server.getServerConfigurationManager().sendPacketNearby(loc2.getX(), loc2.getY(), loc2.getZ(), 1, ((CraftWorld) loc2.getWorld()).getHandle().dimension, destroy); // } // }, 10); //toggle flight, set via the config path "allow.flight" if (allowFlight) { player.setAllowFlight(toggle); } /* * EntityPlayer oldplayer = ((CraftPlayer) player).getHandle(); * MinecraftServer server = oldplayer.server; NetServerHandler * netServerHandler = oldplayer.netServerHandler; * * // remove old entity String quitMessage = * server.serverConfigurationManager.disconnect(oldplayer); if * ((quitMessage != null) && (quitMessage.length() > 0)) { * server.serverConfigurationManager.sendAll(new * Packet3Chat(quitMessage)); } * * // ((WorldServer) oldplayer.world).tracker.untrackPlayer(oldplayer); * // oldplayer.die(); * * // make new one with same NetServerHandler and ItemInWorldManager * EntityPlayer entityplayer = new EntityPlayer(server, * server.getWorldServer(0), name, oldplayer.itemInWorldManager); Player * newplayer = entityplayer.getBukkitEntity(); * * entityplayer.displayName = displayName; entityplayer.listName = * displayName; entityplayer.netServerHandler = netServerHandler; * entityplayer.netServerHandler.player = entityplayer; entityplayer.id * = oldplayer.id; * server.serverConfigurationManager.playerFileData.load(entityplayer); * if (toggle) { entityplayer.locX = oldplayer.locX; entityplayer.locY = * oldplayer.locY; entityplayer.locZ = oldplayer.locZ; entityplayer.yaw * = oldplayer.yaw; entityplayer.pitch = oldplayer.pitch; } * server.serverConfigurationManager.c(entityplayer); * entityplayer.syncInventory(); * * // untrack and track to make sure we can see everyone ((WorldServer) * entityplayer.world).tracker.untrackEntity(entityplayer); * ((WorldServer) entityplayer.world).tracker.track(entityplayer); * * // teleport to the player's location to avoid speedhack kick if * (!toggle) { Location loc = new * Location(entityplayer.world.getWorld(), entityplayer.locX, * entityplayer.locY, entityplayer.locZ, entityplayer.yaw, * entityplayer.pitch); newplayer.teleport(loc); }
diff --git a/Enduro/src/sort/ResultCompilerMain.java b/Enduro/src/sort/ResultCompilerMain.java index 7d941d7..a409fd7 100644 --- a/Enduro/src/sort/ResultCompilerMain.java +++ b/Enduro/src/sort/ResultCompilerMain.java @@ -1,76 +1,73 @@ package sort; import java.io.File; import java.io.FileNotFoundException; import java.net.URISyntaxException; import java.security.CodeSource; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import members.Competitor; import result.CvsReader; import result.Parser; import result.ParserException; public class ResultCompilerMain { public static final String STARTTIMES = "start"; public static final String NAMEFILE = "namn"; public static final String FINISHTIMES = "slut"; public static final String RESULTFILE = "resultat"; public static final String EXTENSION = ".txt"; /** * * Read input files and create list with competitors, and call printResults * to print the results to the output file. * * @throws URISyntaxException * */ public static void main(String[] args) throws URISyntaxException { CodeSource codeSource = ResultCompilerMain.class.getProtectionDomain() .getCodeSource(); File jarFile = new File(codeSource.getLocation().toURI().getPath()); String jarDir = jarFile.getParentFile().getPath(); Parser p = new Parser(); String startPath = jarDir + File.separator + STARTTIMES + EXTENSION; String namePath = jarDir + File.separator + NAMEFILE + EXTENSION; String finishPathPart = jarDir + File.separator + FINISHTIMES; String resultPath = jarDir + File.separator + RESULTFILE + EXTENSION; CvsReader startReader = new CvsReader(startPath); CvsReader nameReader = new CvsReader(namePath); ArrayList<CvsReader> endReaderList = new ArrayList<CvsReader>(); for (int i = 0; new File(finishPathPart + i + EXTENSION).exists(); i++) { endReaderList.add(new CvsReader(finishPathPart + i + EXTENSION)); } - // CvsReader nameReader = new CvsReader(jarDir + File.separator + - // NAMEFILE); Map<Integer, Competitor> map = new HashMap<Integer, Competitor>(); try { p.parse(startReader.readAll(), map); for (CvsReader end : endReaderList) { p.parse(end.readAll(), map); - // System.out.println("DERP"); } // if(new File(jarDir + File.separator + NAMEFILE).exists()){ p.parse(nameReader.readAll(), map); // } - StdCompetitorPrinter printer = new StdCompetitorPrinter(); + LapCompetitorPrinter printer = new LapCompetitorPrinter(); printer.printResults(new ArrayList<Competitor>(map.values()), resultPath); } catch (FileNotFoundException e) { System.exit(-1); } catch (ParserException e) { System.exit(-1); } } }
false
true
public static void main(String[] args) throws URISyntaxException { CodeSource codeSource = ResultCompilerMain.class.getProtectionDomain() .getCodeSource(); File jarFile = new File(codeSource.getLocation().toURI().getPath()); String jarDir = jarFile.getParentFile().getPath(); Parser p = new Parser(); String startPath = jarDir + File.separator + STARTTIMES + EXTENSION; String namePath = jarDir + File.separator + NAMEFILE + EXTENSION; String finishPathPart = jarDir + File.separator + FINISHTIMES; String resultPath = jarDir + File.separator + RESULTFILE + EXTENSION; CvsReader startReader = new CvsReader(startPath); CvsReader nameReader = new CvsReader(namePath); ArrayList<CvsReader> endReaderList = new ArrayList<CvsReader>(); for (int i = 0; new File(finishPathPart + i + EXTENSION).exists(); i++) { endReaderList.add(new CvsReader(finishPathPart + i + EXTENSION)); } // CvsReader nameReader = new CvsReader(jarDir + File.separator + // NAMEFILE); Map<Integer, Competitor> map = new HashMap<Integer, Competitor>(); try { p.parse(startReader.readAll(), map); for (CvsReader end : endReaderList) { p.parse(end.readAll(), map); // System.out.println("DERP"); } // if(new File(jarDir + File.separator + NAMEFILE).exists()){ p.parse(nameReader.readAll(), map); // } StdCompetitorPrinter printer = new StdCompetitorPrinter(); printer.printResults(new ArrayList<Competitor>(map.values()), resultPath); } catch (FileNotFoundException e) { System.exit(-1); } catch (ParserException e) { System.exit(-1); } }
public static void main(String[] args) throws URISyntaxException { CodeSource codeSource = ResultCompilerMain.class.getProtectionDomain() .getCodeSource(); File jarFile = new File(codeSource.getLocation().toURI().getPath()); String jarDir = jarFile.getParentFile().getPath(); Parser p = new Parser(); String startPath = jarDir + File.separator + STARTTIMES + EXTENSION; String namePath = jarDir + File.separator + NAMEFILE + EXTENSION; String finishPathPart = jarDir + File.separator + FINISHTIMES; String resultPath = jarDir + File.separator + RESULTFILE + EXTENSION; CvsReader startReader = new CvsReader(startPath); CvsReader nameReader = new CvsReader(namePath); ArrayList<CvsReader> endReaderList = new ArrayList<CvsReader>(); for (int i = 0; new File(finishPathPart + i + EXTENSION).exists(); i++) { endReaderList.add(new CvsReader(finishPathPart + i + EXTENSION)); } Map<Integer, Competitor> map = new HashMap<Integer, Competitor>(); try { p.parse(startReader.readAll(), map); for (CvsReader end : endReaderList) { p.parse(end.readAll(), map); } // if(new File(jarDir + File.separator + NAMEFILE).exists()){ p.parse(nameReader.readAll(), map); // } LapCompetitorPrinter printer = new LapCompetitorPrinter(); printer.printResults(new ArrayList<Competitor>(map.values()), resultPath); } catch (FileNotFoundException e) { System.exit(-1); } catch (ParserException e) { System.exit(-1); } }
diff --git a/src/main/java/com/gitblit/wicket/pages/ForksPage.java b/src/main/java/com/gitblit/wicket/pages/ForksPage.java index cc483878..f59955ee 100644 --- a/src/main/java/com/gitblit/wicket/pages/ForksPage.java +++ b/src/main/java/com/gitblit/wicket/pages/ForksPage.java @@ -1,156 +1,160 @@ /* * Copyright 2012 gitblit.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gitblit.wicket.pages; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.apache.wicket.Component; import org.apache.wicket.PageParameters; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.markup.repeater.data.DataView; import org.apache.wicket.markup.repeater.data.ListDataProvider; import org.eclipse.jgit.lib.PersonIdent; import com.gitblit.GitBlit; import com.gitblit.Keys; import com.gitblit.models.ForkModel; import com.gitblit.models.RepositoryModel; import com.gitblit.models.UserModel; import com.gitblit.utils.StringUtils; import com.gitblit.wicket.GitBlitWebSession; import com.gitblit.wicket.WicketUtils; import com.gitblit.wicket.panels.GravatarImage; import com.gitblit.wicket.panels.LinkPanel; public class ForksPage extends RepositoryPage { public ForksPage(PageParameters params) { super(params); final RepositoryModel pageRepository = getRepositoryModel(); ForkModel root = GitBlit.self().getForkNetwork(pageRepository.name); List<FlatFork> network = flatten(root); ListDataProvider<FlatFork> forksDp = new ListDataProvider<FlatFork>(network); DataView<FlatFork> forksList = new DataView<FlatFork>("fork", forksDp) { private static final long serialVersionUID = 1L; public void populateItem(final Item<FlatFork> item) { FlatFork fork = item.getModelObject(); RepositoryModel repository = fork.repository; if (repository.isPersonalRepository()) { UserModel user = GitBlit.self().getUserModel(repository.projectPath.substring(1)); + if (user == null) { + // user account no longer exists + user = new UserModel(repository.projectPath.substring(1)); + } PersonIdent ident = new PersonIdent(user.getDisplayName(), user.emailAddress == null ? user.getDisplayName() : user.emailAddress); item.add(new GravatarImage("anAvatar", ident, 20)); if (pageRepository.equals(repository)) { // do not link to self item.add(new Label("aProject", user.getDisplayName())); } else { item.add(new LinkPanel("aProject", null, user.getDisplayName(), UserPage.class, WicketUtils.newUsernameParameter(user.username))); } } else { Component swatch; if (repository.isBare){ swatch = new Label("anAvatar", "&nbsp;").setEscapeModelStrings(false); } else { swatch = new Label("anAvatar", "!"); WicketUtils.setHtmlTooltip(swatch, getString("gb.workingCopyWarning")); } WicketUtils.setCssClass(swatch, "repositorySwatch"); WicketUtils.setCssBackground(swatch, repository.toString()); item.add(swatch); String projectName = repository.projectPath; if (StringUtils.isEmpty(projectName)) { projectName = GitBlit.getString(Keys.web.repositoryRootGroupName, "main"); } if (pageRepository.equals(repository)) { // do not link to self item.add(new Label("aProject", projectName)); } else { item.add(new LinkPanel("aProject", null, projectName, ProjectPage.class, WicketUtils.newProjectParameter(projectName))); } } String repo = StringUtils.getLastPathElement(repository.name); UserModel user = GitBlitWebSession.get().getUser(); if (user == null) { user = UserModel.ANONYMOUS; } if (user.canView(repository)) { if (pageRepository.equals(repository)) { // do not link to self item.add(new Label("aFork", StringUtils.stripDotGit(repo))); } else { item.add(new LinkPanel("aFork", null, StringUtils.stripDotGit(repo), SummaryPage.class, WicketUtils.newRepositoryParameter(repository.name))); } item.add(WicketUtils.createDateLabel("lastChange", repository.lastChange, getTimeZone(), getTimeUtils())); } else { item.add(new Label("aFork", repo)); item.add(new Label("lastChange").setVisible(false)); } WicketUtils.setCssStyle(item, "margin-left:" + (32*fork.level) + "px;"); if (fork.level == 0) { WicketUtils.setCssClass(item, "forkSource"); } else { WicketUtils.setCssClass(item, "forkEntry"); } } }; add(forksList); } @Override protected String getPageName() { return getString("gb.forks"); } protected List<FlatFork> flatten(ForkModel root) { List<FlatFork> list = new ArrayList<FlatFork>(); list.addAll(flatten(root, 0)); return list; } protected List<FlatFork> flatten(ForkModel node, int level) { List<FlatFork> list = new ArrayList<FlatFork>(); list.add(new FlatFork(node.repository, level)); if (!node.isLeaf()) { for (ForkModel fork : node.forks) { list.addAll(flatten(fork, level + 1)); } } return list; } private class FlatFork implements Serializable { private static final long serialVersionUID = 1L; public final RepositoryModel repository; public final int level; public FlatFork(RepositoryModel repository, int level) { this.repository = repository; this.level = level; } } }
true
true
public ForksPage(PageParameters params) { super(params); final RepositoryModel pageRepository = getRepositoryModel(); ForkModel root = GitBlit.self().getForkNetwork(pageRepository.name); List<FlatFork> network = flatten(root); ListDataProvider<FlatFork> forksDp = new ListDataProvider<FlatFork>(network); DataView<FlatFork> forksList = new DataView<FlatFork>("fork", forksDp) { private static final long serialVersionUID = 1L; public void populateItem(final Item<FlatFork> item) { FlatFork fork = item.getModelObject(); RepositoryModel repository = fork.repository; if (repository.isPersonalRepository()) { UserModel user = GitBlit.self().getUserModel(repository.projectPath.substring(1)); PersonIdent ident = new PersonIdent(user.getDisplayName(), user.emailAddress == null ? user.getDisplayName() : user.emailAddress); item.add(new GravatarImage("anAvatar", ident, 20)); if (pageRepository.equals(repository)) { // do not link to self item.add(new Label("aProject", user.getDisplayName())); } else { item.add(new LinkPanel("aProject", null, user.getDisplayName(), UserPage.class, WicketUtils.newUsernameParameter(user.username))); } } else { Component swatch; if (repository.isBare){ swatch = new Label("anAvatar", "&nbsp;").setEscapeModelStrings(false); } else { swatch = new Label("anAvatar", "!"); WicketUtils.setHtmlTooltip(swatch, getString("gb.workingCopyWarning")); } WicketUtils.setCssClass(swatch, "repositorySwatch"); WicketUtils.setCssBackground(swatch, repository.toString()); item.add(swatch); String projectName = repository.projectPath; if (StringUtils.isEmpty(projectName)) { projectName = GitBlit.getString(Keys.web.repositoryRootGroupName, "main"); } if (pageRepository.equals(repository)) { // do not link to self item.add(new Label("aProject", projectName)); } else { item.add(new LinkPanel("aProject", null, projectName, ProjectPage.class, WicketUtils.newProjectParameter(projectName))); } } String repo = StringUtils.getLastPathElement(repository.name); UserModel user = GitBlitWebSession.get().getUser(); if (user == null) { user = UserModel.ANONYMOUS; } if (user.canView(repository)) { if (pageRepository.equals(repository)) { // do not link to self item.add(new Label("aFork", StringUtils.stripDotGit(repo))); } else { item.add(new LinkPanel("aFork", null, StringUtils.stripDotGit(repo), SummaryPage.class, WicketUtils.newRepositoryParameter(repository.name))); } item.add(WicketUtils.createDateLabel("lastChange", repository.lastChange, getTimeZone(), getTimeUtils())); } else { item.add(new Label("aFork", repo)); item.add(new Label("lastChange").setVisible(false)); } WicketUtils.setCssStyle(item, "margin-left:" + (32*fork.level) + "px;"); if (fork.level == 0) { WicketUtils.setCssClass(item, "forkSource"); } else { WicketUtils.setCssClass(item, "forkEntry"); } } }; add(forksList); }
public ForksPage(PageParameters params) { super(params); final RepositoryModel pageRepository = getRepositoryModel(); ForkModel root = GitBlit.self().getForkNetwork(pageRepository.name); List<FlatFork> network = flatten(root); ListDataProvider<FlatFork> forksDp = new ListDataProvider<FlatFork>(network); DataView<FlatFork> forksList = new DataView<FlatFork>("fork", forksDp) { private static final long serialVersionUID = 1L; public void populateItem(final Item<FlatFork> item) { FlatFork fork = item.getModelObject(); RepositoryModel repository = fork.repository; if (repository.isPersonalRepository()) { UserModel user = GitBlit.self().getUserModel(repository.projectPath.substring(1)); if (user == null) { // user account no longer exists user = new UserModel(repository.projectPath.substring(1)); } PersonIdent ident = new PersonIdent(user.getDisplayName(), user.emailAddress == null ? user.getDisplayName() : user.emailAddress); item.add(new GravatarImage("anAvatar", ident, 20)); if (pageRepository.equals(repository)) { // do not link to self item.add(new Label("aProject", user.getDisplayName())); } else { item.add(new LinkPanel("aProject", null, user.getDisplayName(), UserPage.class, WicketUtils.newUsernameParameter(user.username))); } } else { Component swatch; if (repository.isBare){ swatch = new Label("anAvatar", "&nbsp;").setEscapeModelStrings(false); } else { swatch = new Label("anAvatar", "!"); WicketUtils.setHtmlTooltip(swatch, getString("gb.workingCopyWarning")); } WicketUtils.setCssClass(swatch, "repositorySwatch"); WicketUtils.setCssBackground(swatch, repository.toString()); item.add(swatch); String projectName = repository.projectPath; if (StringUtils.isEmpty(projectName)) { projectName = GitBlit.getString(Keys.web.repositoryRootGroupName, "main"); } if (pageRepository.equals(repository)) { // do not link to self item.add(new Label("aProject", projectName)); } else { item.add(new LinkPanel("aProject", null, projectName, ProjectPage.class, WicketUtils.newProjectParameter(projectName))); } } String repo = StringUtils.getLastPathElement(repository.name); UserModel user = GitBlitWebSession.get().getUser(); if (user == null) { user = UserModel.ANONYMOUS; } if (user.canView(repository)) { if (pageRepository.equals(repository)) { // do not link to self item.add(new Label("aFork", StringUtils.stripDotGit(repo))); } else { item.add(new LinkPanel("aFork", null, StringUtils.stripDotGit(repo), SummaryPage.class, WicketUtils.newRepositoryParameter(repository.name))); } item.add(WicketUtils.createDateLabel("lastChange", repository.lastChange, getTimeZone(), getTimeUtils())); } else { item.add(new Label("aFork", repo)); item.add(new Label("lastChange").setVisible(false)); } WicketUtils.setCssStyle(item, "margin-left:" + (32*fork.level) + "px;"); if (fork.level == 0) { WicketUtils.setCssClass(item, "forkSource"); } else { WicketUtils.setCssClass(item, "forkEntry"); } } }; add(forksList); }
diff --git a/src/test/java/pl/psnc/dl/wf4ever/monitoring/ChecksumVerificationJobTest.java b/src/test/java/pl/psnc/dl/wf4ever/monitoring/ChecksumVerificationJobTest.java index 631c4192..4c83a82a 100644 --- a/src/test/java/pl/psnc/dl/wf4ever/monitoring/ChecksumVerificationJobTest.java +++ b/src/test/java/pl/psnc/dl/wf4ever/monitoring/ChecksumVerificationJobTest.java @@ -1,120 +1,122 @@ package pl.psnc.dl.wf4ever.monitoring; import javax.ws.rs.core.UriBuilder; import org.apache.commons.io.IOUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import pl.psnc.dl.wf4ever.db.ResourceInfo; import pl.psnc.dl.wf4ever.dl.DigitalLibrary; import pl.psnc.dl.wf4ever.model.BaseTest; import pl.psnc.dl.wf4ever.model.Builder; import pl.psnc.dl.wf4ever.monitoring.ChecksumVerificationJob.Mismatch; /** * Test that the checksum verification plugin detects checksum inconsistencies. * * @author piotrekhol * */ public class ChecksumVerificationJobTest extends BaseTest { /** The only file that the mock DL will handle. */ private static final String FILE_PATH = "a workflow.t2flow"; /** Result of the last job call. */ private ResultAnswer resultAnswer; /** A builder using the mock digital library. */ private Builder fsBuilder; /** Context with the input data. */ private JobExecutionContext context; /** * Prepare the mock digital library. * * @throws Exception * it shouldn't happen */ @Override @Before public void setUp() throws Exception { super.setUp(); DigitalLibrary dlMock = Mockito.mock(DigitalLibrary.class); Mockito.when(dlMock.getFileContents(researchObject.getUri(), FILE_PATH)).thenReturn( IOUtils.toInputStream("lorem ipsum")); Mockito.when(dlMock.getFileInfo(researchObject.getUri(), FILE_PATH)).thenReturn( new ResourceInfo(null, null, "80a751fde577028640c419000e33eba6", 0, "MD5", null, null)); + Mockito.when(dlMock.updateFileInfo(researchObject.getUri(), FILE_PATH, null)).thenReturn( + new ResourceInfo(null, null, "663e9f8d61af863dfb207870ee028041", 0, "MD5", null, null)); Mockito.when(dlMock.fileExists(researchObject.getUri(), FILE_PATH)).thenReturn(true); JobDataMap jobDataMap = new JobDataMap(); jobDataMap.put(ChecksumVerificationJob.RESEARCH_OBJECT_URI, researchObject.getUri()); context = Mockito.mock(JobExecutionContext.class); Mockito.when(context.getMergedJobDataMap()).thenReturn(jobDataMap); resultAnswer = new ResultAnswer(); Mockito.doAnswer(resultAnswer).when(context).setResult(Mockito.any()); fsBuilder = new Builder(builder.getUser(), builder.getDataset(), builder.isUseTransactions(), dlMock); } @Override @After public void tearDown() throws Exception { super.tearDown(); } /** * Test that the job reports no mismatches correctly. * * @throws JobExecutionException * any problem when running the job */ @Test public final void testExecuteWithNoMismatches() throws JobExecutionException { ChecksumVerificationJob job = new ChecksumVerificationJob(); job.setBuilder(fsBuilder); job.execute(context); Assert.assertNotNull(resultAnswer.getResult()); Assert.assertTrue(resultAnswer.getResult().matches()); Assert.assertTrue(resultAnswer.getResult().getMismatches().isEmpty()); } /** * Test that the job reports mismatches correctly. * * @throws JobExecutionException * any problem when running the job */ @Test public final void testExecuteWithMismatches() throws JobExecutionException { Mockito.when(fsBuilder.getDigitalLibrary().getFileContents(researchObject.getUri(), FILE_PATH)).thenReturn( IOUtils.toInputStream("lorem ipsum this is something new")); ChecksumVerificationJob job = new ChecksumVerificationJob(); job.setBuilder(fsBuilder); job.execute(context); Assert.assertNotNull(resultAnswer.getResult()); Assert.assertFalse(resultAnswer.getResult().matches()); Assert.assertEquals(1, resultAnswer.getResult().getMismatches().size()); Mismatch mismatch = resultAnswer.getResult().getMismatches().iterator().next(); Assert.assertEquals(UriBuilder.fromUri(researchObject.getUri()).path(FILE_PATH).build(), mismatch.getResourceUri()); Assert.assertEquals("663e9f8d61af863dfb207870ee028041", mismatch.getCalculatedChecksum().toLowerCase()); Assert.assertEquals("80a751fde577028640c419000e33eba6", mismatch.getExpectedChecksum().toLowerCase()); } }
true
true
public void setUp() throws Exception { super.setUp(); DigitalLibrary dlMock = Mockito.mock(DigitalLibrary.class); Mockito.when(dlMock.getFileContents(researchObject.getUri(), FILE_PATH)).thenReturn( IOUtils.toInputStream("lorem ipsum")); Mockito.when(dlMock.getFileInfo(researchObject.getUri(), FILE_PATH)).thenReturn( new ResourceInfo(null, null, "80a751fde577028640c419000e33eba6", 0, "MD5", null, null)); Mockito.when(dlMock.fileExists(researchObject.getUri(), FILE_PATH)).thenReturn(true); JobDataMap jobDataMap = new JobDataMap(); jobDataMap.put(ChecksumVerificationJob.RESEARCH_OBJECT_URI, researchObject.getUri()); context = Mockito.mock(JobExecutionContext.class); Mockito.when(context.getMergedJobDataMap()).thenReturn(jobDataMap); resultAnswer = new ResultAnswer(); Mockito.doAnswer(resultAnswer).when(context).setResult(Mockito.any()); fsBuilder = new Builder(builder.getUser(), builder.getDataset(), builder.isUseTransactions(), dlMock); }
public void setUp() throws Exception { super.setUp(); DigitalLibrary dlMock = Mockito.mock(DigitalLibrary.class); Mockito.when(dlMock.getFileContents(researchObject.getUri(), FILE_PATH)).thenReturn( IOUtils.toInputStream("lorem ipsum")); Mockito.when(dlMock.getFileInfo(researchObject.getUri(), FILE_PATH)).thenReturn( new ResourceInfo(null, null, "80a751fde577028640c419000e33eba6", 0, "MD5", null, null)); Mockito.when(dlMock.updateFileInfo(researchObject.getUri(), FILE_PATH, null)).thenReturn( new ResourceInfo(null, null, "663e9f8d61af863dfb207870ee028041", 0, "MD5", null, null)); Mockito.when(dlMock.fileExists(researchObject.getUri(), FILE_PATH)).thenReturn(true); JobDataMap jobDataMap = new JobDataMap(); jobDataMap.put(ChecksumVerificationJob.RESEARCH_OBJECT_URI, researchObject.getUri()); context = Mockito.mock(JobExecutionContext.class); Mockito.when(context.getMergedJobDataMap()).thenReturn(jobDataMap); resultAnswer = new ResultAnswer(); Mockito.doAnswer(resultAnswer).when(context).setResult(Mockito.any()); fsBuilder = new Builder(builder.getUser(), builder.getDataset(), builder.isUseTransactions(), dlMock); }
diff --git a/code/mnj/lua/Lua.java b/code/mnj/lua/Lua.java index 84936f0..f4d6bc2 100644 --- a/code/mnj/lua/Lua.java +++ b/code/mnj/lua/Lua.java @@ -1,3953 +1,3951 @@ /* $Header$ * (c) Copyright 2006, Intuwave Ltd. All Rights Reserved. * * Although Intuwave has tested this program and reviewed the documentation, * Intuwave makes no warranty or representation, either expressed or implied, * with respect to this software, its quality, performance, merchantability, * or fitness for a particular purpose. As a result, this software is licensed * "AS-IS", and you are assuming the entire risk as to its quality and * performance. * * You are granted license to use this code as a basis for your own * application(s) under the terms of the separate license between you and * Intuwave. */ package mnj.lua; import java.io.InputStream; import java.io.OutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.Reader; import java.util.Enumeration; import java.util.Stack; import java.util.Vector; /** * <p> * Encapsulates a Lua execution environment. A lot of Jili's public API * manifests as public methods in this class. A key part of the API is * the ability to call Lua functions from Java (ultimately, all Lua code * is executed in this manner). * </p> * * <p> * The Stack * </p> * * <p> * All arguments to Lua functions and all results returned by Lua * functions are placed onto a stack. The stack can be indexed by an * integer in the same way as the PUC-Rio implementation. A positive * index is an absolute index and ranges from 1 (the bottom-most * element) through to <var>n</var> (the top-most element), * where <var>n</var> is the number of elements on the stack. Negative * indexes are relative indexes, -1 is the top-most element, -2 is the * element underneath that, and so on. 0 is not used. * </p> * * <p> * Note that in Jili the stack is used only for passing arguments and * returning results, unlike PUC-Rio. * </p> * * <p> * The protocol for calling a function is described in the {@link Lua#call} * method. In brief: push the function onto the stack, then push the * arguments to the call. * </p> * * <p> * The methods {@link Lua#push}, {@link Lua#pop}, {@link Lua#value}, * {@link Lua#getTop}, {@link Lua#setTop} are used to manipulate the stack. * </p> */ public final class Lua { /** Version string. */ public static final String VERSION = "Lua 5.1 (Jili 0.X.Y)"; /** Table of globals (global variables). This actually shared across * all coroutines (with the same main thread), but kept in each Lua * thread as an optimisation. */ private LuaTable global; /** Reference the main Lua thread. Itself if this is the main Lua * thread. */ private Lua main; /** VM data stack. */ private Vector stack = new Vector(); private int base; // = 0; int nCcalls; // = 0; /** Instruction to resume execution at. Index into code array. */ private int savedpc; // = 0; /** * Vector of CallInfo records. Actually it's a Stack which is a * subclass of Vector, but it mostly the Vector methods that are used. */ private Stack civ = new Stack(); { civ.addElement(new CallInfo()); } /** CallInfo record for currently active function. */ private CallInfo ci() { return (CallInfo)civ.lastElement(); } /** Open Upvalues. All UpVal objects that reference the VM stack. * openupval is a java.util.Vector of UpVal stored in order of stack * slot index: higher stack indexes are stored at higher Vector * positions. */ private Vector openupval = new Vector(); /** Number of list items to accumulate before a SETLIST instruction. */ static final int LFIELDS_PER_FLUSH = 50; /** Limit for table tag-method chains (to avoid loops) */ private static final int MAXTAGLOOP = 100; /** Used to communicate error status (ERRRUN, etc) from point where * error is raised to the code that catches it. */ private int errorStatus; /** * The current error handler (set by {@link Lua#pcall}). A Lua * function to call. */ private Object errfunc; /** * coroutine activation status. */ private int status; /** Nonce object used by pcall and friends (to detect when an * exception is a Lua error). */ private static final String LUA_ERROR = ""; /** Metatable for primitive types. Shared between all coroutines. */ private LuaTable[] metatable; /** * Maximum number of local variables per function. As per * LUAI_MAXVARS from "luaconf.h". Default access so that {@link * FuncState} can see it. */ static final int MAXVARS = 200; static final int MAXSTACK = 250; static final int MAXUPVALUES = 60; /** * Used to construct a Lua thread that shares its global state with * another Lua state. */ private Lua(Lua L) { // Copy the global state, that's shared across all coroutines that // share the same main thread, into the new Lua thread. // Any more than this and the global state should be shunted to a // separate object (as it is in PUC-Rio). this.global = L.global; this.metatable = L.metatable; this.main = L; } ////////////////////////////////////////////////////////////////////// // Public API /** * Creates a fresh Lua state. */ public Lua() { this.global = new LuaTable(); this.metatable = new LuaTable[NUM_TAGS]; this.main = this; } /** * Equivalent of LUA_MULTRET. */ // Required, by vmPoscall, to be negative. public static final int MULTRET = -1; /** * The Lua <code>nil</code> value. */ public static final Object NIL = null; // Lua type tags, from lua.h /** Lua type tag, representing no stack value. */ public static final int TNONE = -1; /** Lua type tag, representing <code>nil</code>. */ public static final int TNIL = 0; /** Lua type tag, representing boolean. */ public static final int TBOOLEAN = 1; // TLIGHTUSERDATA not available. :todo: make available? /** Lua type tag, representing numbers. */ public static final int TNUMBER = 3; /** Lua type tag, representing strings. */ public static final int TSTRING = 4; /** Lua type tag, representing tables. */ public static final int TTABLE = 5; /** Lua type tag, representing functions. */ public static final int TFUNCTION = 6; /** Lua type tag, representing userdata. */ public static final int TUSERDATA = 7; /** Lua type tag, representing threads. */ public static final int TTHREAD = 8; /** Number of type tags. Should correspond to last entry in the list * of tags. */ private static final int NUM_TAGS = 8; /** Names for above type tags, starting from {@link Lua#TNIL}. * Equivalent to luaT_typenames. */ private static final String[] TYPENAME = { "nil", "boolean", "userdata", "number", "string", "table", "function", "userdata", "thread" }; /** * Minimum stack size that Lua Java functions gets. May turn out to * be silly / redundant. */ public static final int MINSTACK = 20; /** Status code, returned from pcall and friends, that indicates the * coroutine has yielded. */ public static final int YIELD = 1; /** Status code, returned from pcall and friends, that indicates * a runtime error. */ public static final int ERRRUN = 2; /** Status code, returned from pcall and friends, that indicates * a syntax error. */ public static final int ERRSYNTAX = 3; /** Status code, returned from pcall and friends, that indicates * a memory allocation error. */ private static final int ERRMEM = 4; /** Status code, returned from pcall and friends, that indicates * an error whilst running the error handler function. */ public static final int ERRERR = 5; /** Status code, returned from loadFile and friends, that indicates * an IO error. */ public static final int ERRFILE = 6; // Enums for gc(). /** Action, passed to {@link Lua#gc}, that requests the GC to stop. */ public static final int GCSTOP = 0; /** Action, passed to {@link Lua#gc}, that requests the GC to restart. */ public static final int GCRESTART = 1; /** Action, passed to {@link Lua#gc}, that requests a full collection. */ public static final int GCCOLLECT = 2; /** Action, passed to {@link Lua#gc}, that returns amount of memory * (in Kibibytes) in use (by the entire Java runtime). */ public static final int GCCOUNT = 3; /** Action, passed to {@link Lua#gc}, that returns the remainder of * dividing the amount of memory in use by 1024. */ public static final int GCCOUNTB = 4; /** Action, passed to {@link Lua#gc}, that requests an incremental * garbage collection be performed. */ public static final int GCSTEP = 5; /** Action, passed to {@link Lua#gc}, that sets a new value for the * <var>pause</var> of the collector. */ public static final int GCSETPAUSE = 6; /** Action, passed to {@link Lua#gc}, that sets a new values for the * <var>step multiplier</var> of the collector. */ public static final int GCSETSTEPMUL = 7; /** * Calls a Lua value. Normally this is called on functions, but the * semantics of Lua permit calls on any value as long as its metatable * permits it. * * In order to call a function, the function must be * pushed onto the stack, then its arguments must be * {@link Lua#push pushed} onto the stack; the first argument is pushed * directly after the function, * then the following arguments are pushed in order (direct * order). The parameter <var>nargs</var> specifies the number of * arguments (which may be 0). * * When the function returns the function value on the stack and all * the arguments are removed from the stack and replaced with the * results of the function, adjusted to the number specified by * <var>nresults</var>. So the first result from the function call will * be at the same index where the function was immediately prior to * calling this method. * * @param nargs The number of arguments in this function call. * @param nresults The number of results required. */ public void call(int nargs, int nresults) { apiChecknelems(nargs+1); int func = stack.size() - (nargs + 1); this.vmCall(func, nresults); } /** * Closes a Lua state. In this implementation, this method does * nothing. */ public void close() { } /** * Concatenate values (usually strings) on the stack. * <var>n</var> values from the top of the stack are concatenated, as * strings, and replaced with the resulting string. * @param n the number of values to concatenate. */ public void concat(int n) { apiChecknelems(n); if (n >= 2) { vmConcat(n, (stack.size() - base) - 1); pop(n-1); } else if (n == 0) // push empty string { push(""); } // else n == 1; nothing to do } /** * Creates a new empty table and returns it. * @param narr number of array elements to pre-allocate. * @param nrec number of non-array elements to pre-allocate. * @return a fresh table. * @see Lua#newTable */ public LuaTable createTable(int narr, int nrec) { return new LuaTable(narr, nrec); } /** * Dumps a function as a binary chunk. * @param function the Lua function to dump. * @param writer the stream that receives the dumped binary. * @throws IOException when writer does. */ public static void dump(Object function, OutputStream writer) throws IOException { if (!(function instanceof LuaFunction)) { throw new IOException("Cannot dump " + typeName(type(function))); } LuaFunction f = (LuaFunction)function; uDump(f.proto(), writer, false); } /** * Tests for equality according to the semantics of Lua's * <code>==</code> operator (so may call metamethods). * @param o1 a Lua value. * @param o2 another Lua value. * @return true when equal. */ public boolean equal(Object o1, Object o2) { return vmEqual(o1, o2); } /** * Generates a Lua error using the error message. * @param message the error message. * @return never. */ public int error(Object message) { return gErrormsg(message); } /** * Control garbage collector. Note that in Jili most of the options * to this function make no sense and they will not do anything. * @param what specifies what GC action to take. * @param data data that may be used by the action. * @return varies. */ public int gc(int what, int data) { Runtime rt; switch (what) { case GCSTOP: return 0; case GCRESTART: case GCCOLLECT: case GCSTEP: System.gc(); return 0; case GCCOUNT: rt = Runtime.getRuntime(); return (int)((rt.totalMemory() - rt.freeMemory()) / 1024); case GCCOUNTB: rt = Runtime.getRuntime(); return (int)((rt.totalMemory() - rt.freeMemory()) % 1024); case GCSETPAUSE: case GCSETSTEPMUL: return 0; } return 0; } /** * Returns the environment table of the Lua value. * @param o the Lua value. * @return its environment table. */ public LuaTable getFenv(Object o) { if (o instanceof LuaFunction) { LuaFunction f = (LuaFunction)o; return f.getEnv(); } if (o instanceof LuaJavaCallback) { LuaJavaCallback f = (LuaJavaCallback)o; // :todo: implement this case. return null; } if (o instanceof LuaUserdata) { LuaUserdata u = (LuaUserdata)o; return u.getEnv(); } if (o instanceof Lua) { Lua l = (Lua)o; return l.global; } return null; } /** * Get a field from a table (or other object). * @param t The object whose field to retrieve. * @param field The name of the field. * @return the Lua value */ public Object getField(Object t, String field) { return vmGettable(t, field); } /** * Get a global variable. * @param name The name of the global variable. * @return The value of the global variable. */ public Object getGlobal(String name) { return vmGettable(global, name); } /** * Gets the global environment. The global environment, where global * variables live, is returned as a <code>LuaTable</code>. Note that * modifying this table has exactly the same effect as creating or * changing global variables from within Lua. * @return The global environment as a table. */ public LuaTable getGlobals() { return global; } /** Get metatable. * @param o the Lua value whose metatable to retrieve. * @return The metatable, or null if there is no metatable. */ public LuaTable getMetatable(Object o) { LuaTable mt; if (o instanceof LuaTable) { LuaTable t = (LuaTable)o; mt = t.getMetatable(); } else if (o instanceof LuaUserdata) { LuaUserdata u = (LuaUserdata)o; mt = u.getMetatable(); } else { mt = metatable[type(o)]; } return mt; } /** * Indexes into a table and returns the value. * @param t the Lua value to index. * @param k the key whose value to return. * @return the value t[k]. */ public Object getTable(Object t, Object k) { return vmGettable(t, k); } /** * Gets the number of elements in the stack. If the stack is not * empty then this is the index of the top-most element. * @return number of stack elements. */ public int getTop() { return stack.size() - base; } /** * Insert Lua value into stack immediately at specified index. Values * in stack at that index and higher get pushed up. * @param o the Lua value to insert into the stack. * @param idx the stack index at which to insert. */ public void insert(Object o, int idx) { idx = absIndex(idx); stack.insertElementAt(o, idx); } /** * Tests that an object is a Lua boolean. * @param o the Object to test. * @return true if and only if the object is a Lua boolean. */ public static boolean isBoolean(Object o) { return o instanceof Boolean; } /** * Tests that an object is a Lua function implementated in Java (a Lua * Java Function). * @param o the Object to test. * @return true if and only if the object is a Lua Java Function. */ public static boolean isJavaFunction(Object o) { return o instanceof LuaJavaCallback; } /** * Tests that an object is a Lua function (implemented in Lua or * Java). * @param o the Object to test. * @return true if and only if the object is a function. */ public static boolean isFunction(Object o) { return o instanceof LuaFunction || o instanceof LuaJavaCallback; } /** * Tests that a Lua thread is the main thread. * @return true if and only if is the main thread. */ public boolean isMain() { return this == main; } /** * Tests that an object is Lua <code>nil</code>. * @param o the Object to test. * @return true if and only if the object is Lua <code>nil</code>. */ public static boolean isNil(Object o) { return null == o; } /** * Tests that an object is a Lua number or a string convertible to a * number. * @param o the Object to test. * @return true if and only if the object is a number or a convertible string. */ public static boolean isNumber(Object o) { return tonumber(o, NUMOP); } /** * Tests that an object is a Lua string or a number (which is always * convertible to a string). * @param o the Object to test. * @return true if and only if object is a string or number. */ public static boolean isString(Object o) { return o instanceof String; } /** * Tests that an object is a Lua table. * @param o the Object to test. * @return <code>true</code> if and only if the object is a Lua table. */ public static boolean isTable(Object o) { return o instanceof LuaTable; } /** * Tests that an object is a Lua thread. * @param o the Object to test. * @return <code>true</code> if and only if the object is a Lua thread. */ public static boolean isThread(Object o) { return o instanceof Lua; } /** * Tests that an object is a Lua userdata. * @param o the Object to test. * @return true if and only if the object is a Lua userdata. */ public static boolean isUserdata(Object o) { return o instanceof LuaUserdata; } /** * <p> * Tests that an object is a Lua value. Returns <code>true</code> for * an argument that is a Jili representation of a Lua value, * <code>false</code> for Java references that are not Lua values. * For example <code>isValue(new LuaTable())</code> is * <code>true</code>, but <code>isValue(new Object[] { })</code> is * <code>false</code> because Java arrays are not a representation of * any Lua value. * </p> * <p> * PUC-Rio Lua provides no * counterpart for this method because in their implementation it is * impossible to get non Lua values on the stack, whereas in Jili it * is common to mix Lua values with ordinary, non Lua, Java objects. * </p> * @param o the Object to test. * @return true if and if it represents a Lua value. */ public static boolean isValue(Object o) { return o == null || o instanceof Boolean || o instanceof String || o instanceof Double || o instanceof LuaFunction || o instanceof LuaJavaCallback || o instanceof LuaTable || o instanceof LuaUserdata; } /** * Compares two Lua values according to the semantics of Lua's * <code>&lt;</code> operator, so may call metamethods. * @param o1 the left-hand operand. * @param o2 the right-hand operand. * @return true when <code>o1 < o2</code>. */ public boolean lessThan(Object o1, Object o2) { return vmLessthan(o1, o2); } /** * <p> * Loads a Lua chunk in binary or source form. * Comparable to C's lua_load. If the chunk is determined to be * binary then it is loaded directly. Otherwise the chunk is assumed * to be a Lua source chunk and compilation is required first; the * <code>InputStream</code> is used to create a <code>Reader</code> * using the UTF-8 encoding * (using a second argument of <code>"UTF-8"</code> to the * {@link java.io.InputStreamReader#InputStreamReader(java.io.InputStream, * java.lang.String)} * constructor) and the Lua source is compiled. * </p> * <p> * If successful, The compiled chunk, a Lua function, is pushed onto * the stack and a zero status code is returned. Otherwise a non-zero * status code is returned to indicate an error and the error message * is pushed onto the stack. * </p> * @param in The binary chunk as an InputStream, for example from * {@link Class#getResourceAsStream}. * @param chunkname The name of the chunk. * @return A status code. */ public int load(InputStream in, String chunkname) { push(new LuaInternal(in, chunkname)); return pcall(0, 1, null); } /** * Loads a Lua chunk in source form. * Comparable to C's lua_load. Since this takes a {@link * java.io.Reader} parameter, * this method is restricted to loading Lua chunks in source form. * In every other respect this method is just like {@link * Lua#load(InputStream, String)}. * @param in The source chunk as a Reader, for example from * <code>java.io.InputStreamReader(Class.getResourceAsStream())</code>. * @param chunkname The name of the chunk. * @return A status code. * @see java.io.InputStreamReader */ public int load(Reader in, String chunkname) { push(new LuaInternal(in, chunkname)); return pcall(0, 1, null); } /** * Slowly get the next key from a table. Unlike most other functions * in the API this one uses the stack. The top-of-stack is popped and * used to find the next key in the table at the position specified by * index. If there is a next key then the key and its value are * pushed onto the stack and <code>true</code> is returned. * Otherwise (the end of the table has been reached) * <code>false</code> is returned. * @param idx stack index of table. * @return true if and only if there are more keys in the table. * @deprecated Use {@link Lua#tableKeys} enumeration protocol instead. */ public boolean next(int idx) { Object o = value(idx); // :todo: api check LuaTable t = (LuaTable)o; Object key = value(-1); pop(1); Enumeration e = t.keys(); if (key == NIL) { if (e.hasMoreElements()) { key = e.nextElement(); push(key); push(t.get(key)); return true; } return false; } while (e.hasMoreElements()) { Object k = e.nextElement(); if (k == key) { if (e.hasMoreElements()) { key = e.nextElement(); push(key); push(t.get(key)); return true; } return false; } } // protocol error which we could potentially diagnose. return false; } /** * Creates a new empty table and returns it. * @return a fresh table. * @see Lua#createTable */ public LuaTable newTable() { return new LuaTable(); } /** * Creates a new Lua thread and returns it. * @return a new Lua thread. */ public Lua newThread() { return new Lua(this); } /** * Wraps an arbitrary Java reference in a Lua userdata and returns it. * @param ref the Java reference to wrap. * @return the new LuaUserdata. */ public LuaUserdata newUserdata(Object ref) { return new LuaUserdata(ref); } /** * Return the <em>length</em> of a Lua value. For strings this is * the string length; for tables, this is result of the <code>#</code> * operator; for other values it is 0. * @param o a Lua value. * @return its length. */ public static int objLen(Object o) { if (o instanceof String) { String s = (String)o; return s.length(); } if (o instanceof LuaTable) { LuaTable t = (LuaTable)o; return t.getn(); } if (o instanceof Double) { return vmTostring(o).length(); } return 0; } /** * <p> * Protected {@link Lua#call}. <var>nargs</var> and * <var>nresults</var> have the same meaning as in {@link Lua#call}. * If there are no errors during the call, this method behaves as * {@link Lua#call}. Any errors are caught, the error object (usually * a message) is pushed onto the stack, and a non-zero error code is * returned. * </p> * <p> * If <var>er</var> is <code>null</code> then the error object that is * on the stack is the original error object. Otherwise * <var>ef</var> specifies an <em>error handling function</em> which * is called when the original error is generated; its return value * becomes the error object left on the stack by <code>pcall</code>. * </p> * @param nargs number of arguments. * @param nresults number of result required. * @param ef error function to call in case of error. * @return 0 if successful, else a non-zero error code. */ public int pcall(int nargs, int nresults, Object ef) { apiChecknelems(nargs+1); int restoreStack = stack.size() - (nargs + 1); // Most of this code comes from luaD_pcall int restoreCi = civ.size(); int oldnCcalls = nCcalls; Object old_errfunc = errfunc; errfunc = ef; // :todo: save and restore allowhooks try { errorStatus = 0; call(nargs, nresults); } catch (RuntimeException e) { if (e.getMessage() == LUA_ERROR) { fClose(restoreStack); // close eventual pending closures dSeterrorobj(errorStatus, restoreStack); nCcalls = oldnCcalls; civ.setSize(restoreCi); CallInfo ci = ci(); base = ci.base(); savedpc = ci.savedpc(); } else { throw e; } } errfunc = old_errfunc; return errorStatus; } /** * Removes (and discards) the top-most <var>n</var> elements from the stack. * @param n the number of elements to remove. */ public void pop(int n) { if (n < 0) { throw new IllegalArgumentException(); } stack.setSize(stack.size() - n); } /** * Pushes a value onto the stack in preparation for calling a * function (or returning from one). See {@link Lua#call} for * the protocol to be used for calling functions. See {@link * Lua#pushNumber} for pushing numbers, and {@link Lua#pushValue} for * pushing a value that is already on the stack. * @param o the Lua value to push. */ public void push(Object o) { stack.addElement(o); } /** * Push boolean onto the stack. * @param b the boolean to push. */ public void pushBoolean(boolean b) { push(valueOfBoolean(b)); } /** * Push literal string onto the stack. * @param s the string to push. */ public void pushLiteral(String s) { push(s); } /** Push nil onto the stack. */ public void pushNil() { push(NIL); } /** * Pushes a number onto the stack. See also {@link Lua#push}. * @param d the number to push. */ public void pushNumber(double d) { push(new Double(d)); } /** * Push string onto the stack. * @param s the string to push. */ public void pushString(String s) { push(s); } /** * Copies a stack element onto the top of the stack. * Equivalent to <code>L.push(L.value(idx))</code>. * @param idx stack index of value to push. */ public void pushValue(int idx) { push(value(idx)); } /** * Implements equality without metamethods. * @param o1 the first Lua value to compare. * @param o2 the other Lua value. * @return true if and only if they compare equal. */ public static boolean rawEqual(Object o1, Object o2) { return oRawequal(o1, o2); } /** * Gets an element from a table, without using metamethods. * @param t The table to access. * @param k The index (key) into the table. * @return The value at the specified index. */ public static Object rawGet(Object t, Object k) { LuaTable table = (LuaTable)t; return table.get(k); } /** * Gets an element from an array, without using metamethods. * @param t the array (table). * @param i the index of the element to retrieve. * @return the value at the specified index. */ public static Object rawGetI(Object t, int i) { LuaTable table = (LuaTable)t; return table.getnum(i); } /** * Sets an element in a table, without using metamethods. * @param t The table to modify. * @param k The index into the table. * @param v The new value to be stored at index <var>k</var>. */ public static void rawSet(Object t, Object k, Object v) { if (k == NIL) { throw new NullPointerException(); } LuaTable table = (LuaTable)t; table.put(k, v); } /** * Sets an element in an array, without using metamethods. * @param t the array (table). * @param i the index of the element to set. * @param v the new value to be stored at index <var>i</var>. */ public void rawSetI(Object t, int i, Object v) { apiCheck(t instanceof LuaTable); LuaTable h = (LuaTable)t; h.putnum(i, v); } /** * Register a {@link LuaJavaCallback} as the new value of the global * <var>name</var>. * @param name the name of the global. * @param f the LuaJavaCallback to register. */ public void register(String name, LuaJavaCallback f) { setGlobal(name, f); } /** * Starts and resumes a coroutine. * @param narg Number of values to pass to coroutine. * @return Lua.YIELD, 0, or an error code. */ public int resume(int narg) { if (status != YIELD) { if (status != 0) return resume_error("cannot resume dead coroutine"); else if (civ.size() != 1) return resume_error("cannot resume non-suspended coroutine"); } // assert errfunc == 0 && nCcalls == 0; protect: try { errorStatus = 0; // This block is equivalent to resume from ldo.c int firstArg = stack.size() - narg; if (status == 0) // start coroutine? { // assert civ.size() == 1 && firstArg > base); if (vmPrecall(firstArg - 1, MULTRET) != PCRLUA) break protect; } else // resuming from previous yield { // assert status == YIELD; status = 0; if (!isLua(ci())) // 'common' yield { // finish interrupted execution of 'OP_CALL' // assert ... if (vmPoscall(firstArg)) // complete it... stack.setSize(ci().top()); // and correct top } else // yielded inside a hook: just continue its execution base = ci().base(); } vmExecute(civ.size() - 1); } catch (RuntimeException e) { if (e.getMessage() == LUA_ERROR) // error? { status = errorStatus; // mark thread as 'dead' dSeterrorobj(errorStatus, stack.size()); ci().setTop(stack.size()); } else { throw e; } } return status; } /** * Set the environment for a function, thread, or userdata. * @param o Object whose environment will be set. * @param table Environment table to use. * @return true if the object had its environment set, false otherwise. */ public boolean setFenv(Object o, Object table) { // :todo: consider implementing common env interface for // LuaFunction, LuaJavaCallback, LuaUserdata, Lua. One cast to an // interface and an interface method call may be shorter // than this mess. LuaTable t = (LuaTable)table; if (o instanceof LuaFunction) { LuaFunction f = (LuaFunction)o; f.setEnv(t); return true; } if (o instanceof LuaJavaCallback) { LuaJavaCallback f = (LuaJavaCallback)o; // :todo: implement this case. return false; } if (o instanceof LuaUserdata) { LuaUserdata u = (LuaUserdata)o; u.setEnv(t); return true; } if (o instanceof Lua) { Lua l = (Lua)o; l.global = t; return true; } return false; } /** * Set a field in a Lua value. * @param t Lua value of which to set a field. * @param name Name of field to set. * @param v new Lua value for field. */ public void setField(Object t, String name, Object v) { vmSettable(t, name, v); } /** * Sets the metatable for a Lua value. * @param o Lua value of which to set metatable. * @param mt The new metatable. */ public void setMetatable(Object o, Object mt) { if (isNil(mt)) { mt = null; } else { apiCheck(mt instanceof LuaTable); } LuaTable mtt = (LuaTable)mt; if (o instanceof LuaTable) { LuaTable t = (LuaTable)o; t.setMetatable(mtt); } else if (o instanceof LuaUserdata) { LuaUserdata u = (LuaUserdata)o; u.setMetatable(mtt); } else { metatable[type(o)] = mtt; } } /** * Set a global variable. * @param name name of the global variable to set. * @param value desired new value for the variable. */ public void setGlobal(String name, Object value) { vmSettable(global, name, value); } /** * Does the equivalent of <code>t[k] = v</code>. * @param t the table to modify. * @param k the index to modify. * @param v the new value at index <var>k</var>. */ public void setTable(Object t, Object k, Object v) { vmSettable(t, k, v); } /** * Set the stack top. * @param n the desired size of the stack (in elements). */ public void setTop(int n) { if (n < 0) { throw new IllegalArgumentException(); } stack.setSize(base+n); } /** * Status of a Lua thread. * @return 0, an error code, or Lua.YIELD. */ public int status() { return status; } /** * Returns an {@link java.util.Enumeration} for the keys of a table. * @param t a Lua table. * @return an Enumeration object. */ public Enumeration tableKeys(Object t) { if (!(t instanceof LuaTable)) { error("table required"); // NOTREACHED } return ((LuaTable)t).keys(); } /** * Convert to boolean. * @param o Lua value to convert. * @return the resulting primitive boolean. */ public boolean toBoolean(Object o) { return !(o == NIL || Boolean.FALSE.equals(o)); } /** * Convert to integer and return it. Returns 0 if cannot be * converted. * @param o Lua value to convert. * @return the resulting int. */ public int toInteger(Object o) { if (tonumber(o, NUMOP)) { return (int)NUMOP[0]; } return 0; } /** * Convert to number and return it. Returns 0 if cannot be * converted. * @param o Lua value to convert. * @return The resulting number. */ public double toNumber(Object o) { if (tonumber(o, NUMOP)) { return NUMOP[0]; } return 0; } /** * Convert to string and return it. If value cannot be converted then * null is returned. Note that unlike <code>lua_tostring</code> this * does not modify the Lua value. * @param o Lua value to convert. * @return The resulting string. */ public String toString(Object o) { return vmTostring(o); } /** * Convert to Lua thread and return it or <code>null</code>. * @param o Lua value to convert. * @return The resulting Lua instance. */ public Lua toThread(Object o) { if (!(o instanceof Lua)) { return null; } return (Lua)o; } /** * Convert to userdata or <code>null</code>. If value is a {@link * LuaUserdata} then it is returned, otherwise, <code>null</code> is * returned. * @param o Lua value. * @return value as userdata or <code>null</code>. */ public LuaUserdata toUserdata(Object o) { if (o instanceof LuaUserdata) { return (LuaUserdata)o; } return null; } /** * Type of the Lua value at the specified stack index. * @param idx stack index to type. * @return the type, or {@link Lua#TNONE} if there is no value at <var>idx</var> */ public int type(int idx) { idx = absIndex(idx); if (idx < 0) { return TNONE; } Object o = stack.elementAt(idx); return type(o); } /** * Type of a Lua value. * @param o the Lua value whose type to return. * @return the Lua type from an enumeration. */ public static int type(Object o) { if (o == NIL) { return TNIL; } else if (o instanceof Double) { return TNUMBER; } else if (o instanceof Boolean) { return TBOOLEAN; } else if (o instanceof String) { return TSTRING; } else if (o instanceof LuaTable) { return TTABLE; } else if (o instanceof LuaFunction || o instanceof LuaJavaCallback) { return TFUNCTION; } else if (o instanceof LuaUserdata) { return TUSERDATA; } else if (o instanceof Lua) { return TTHREAD; } return TNONE; } /** * Name of type. * @param type a Lua type from, for example, {@link Lua#type}. * @return the type's name. */ public static String typeName(int type) { if (TNONE == type) { return "no value"; } return TYPENAME[type]; } /** * Gets a value from the stack. * If <var>idx</var> is positive and exceeds * the size of the stack, {@link Lua#NIL} is returned. * @param idx the stack index of the value to retrieve. * @return the Lua value from the stack. */ public Object value(int idx) { idx = absIndex(idx); if (idx < 0) { return NIL; } return stack.elementAt(idx); } /** * Converts primitive boolean into a Lua value. * @param b the boolean to convert. * @return the resulting Lua value. */ public static Object valueOfBoolean(boolean b) { // If CLDC 1.1 had // <code>java.lang.Boolean.valueOf(boolean);</code> then I probably // wouldn't have written this. This does have a small advantage: // code that uses this method does not need to assume that Lua booleans in // Jili are represented using Java.lang.Boolean. if (b) { return Boolean.TRUE; } else { return Boolean.FALSE; } } /** * Converts primitive number into a Lua value. * @param d the number to convert. * @return the resulting Lua value. */ public static Object valueOfNumber(double d) { // :todo: consider interning "common" numbers, like 0, 1, -1, etc. return new Double(d); } /** * Exchange values between different threads. * @param to destination Lua thread. * @param n numbers of stack items to move. */ public void xmove(Lua to, int n) { if (this == to) { return; } apiChecknelems(n); // L.apiCheck(from.G() == to.G()); for (int i = 0; i < n; ++i) { to.push(value(-n+i)); } pop(n); } /** * Yields a coroutine. Should only be called as the return expression * of a Lua Java function: <code>return L.yield(nresults);</code>. * @param nresults Number of results to return to L.resume. * @return a secret value. */ public int yield(int nresults) { if (nCcalls > 0) gRunerror("attempt to yield across metamethod/Java-call boundary"); base = stack.size() - nresults; // protect stack slots below status = YIELD; return -1; } // Miscellaneous private functions. /** Convert from Java API stack index to absolute index. * @return an index into <code>this.stack</code> or -1 if out of range. */ private int absIndex(int idx) { int s = stack.size(); if (idx == 0) { return -1; } if (idx > 0) { if (idx + base > s) { return -1; } return base + idx - 1; } // idx < 0 if (s + idx < base) { return -1; } return s + idx; } ////////////////////////////////////////////////////////////////////// // Auxiliary API // :todo: consider placing in separate class (or macroised) so that we // can change its definition (to remove the check for example). private void apiCheck(boolean cond) { if (!cond) { throw new IllegalArgumentException(); } } private void apiChecknelems(int n) { apiCheck(n <= stack.size() - base); } /** * Checks a general condition and raises error if false. * @param cond the (evaluated) condition to check. * @param numarg argument index. * @param extramsg extra error message to append. */ public void argCheck(boolean cond, int numarg, String extramsg) { if (cond) { return; } argError(numarg, extramsg); } /** * Raise a general error for an argument. * @param narg argument index. * @param extramsg extra message string to append. * @return never (used idiomatically in <code>return argError(...)</code>) */ public int argError(int narg, String extramsg) { // :todo: use debug API as per PUC-Rio if (true) { return error("bad argument " + narg + " (" + extramsg + ")"); } return 0; } /** * Calls a metamethod. Pushes 1 result onto stack if method called. * @param obj stack index of object whose metamethod to call * @param event metamethod (event) name. * @return true if and only if metamethod was found and called. */ public boolean callMeta(int obj, String event) { Object o = value(obj); Object ev = getMetafield(o, event); if (ev == null) { return false; } push(ev); push(o); call(1, 1); return true; } /** * Checks that an argument is present (can be anything). * Raises error if not. * @param narg argument index. */ public void checkAny(int narg) { if (type(narg) == TNONE) { argError(narg, "value expected"); } } /** * Checks is a number and returns it as an integer. Raises error if * not a number. * @param narg argument index. * @return the argument as an int. */ public int checkInt(int narg) { return (int)checkNumber(narg); } /** * Checks is a number. Raises error if not a number. * @param narg argument index. * @return the argument as a double. */ public double checkNumber(int narg) { Object o = value(narg); double d = toNumber(o); if (d == 0 && !isNumber(o)) { tagError(narg, TNUMBER); } return d; } /** * Checks that an optional string argument is an element from a set of * strings. Raises error if not. * @param narg argument index. * @param def default string to use if argument not present. * @param lst the set of strings to match against. * @return an index into <var>lst</var> specifying the matching string. */ public int checkOption(int narg, String def, String[] lst) { String name; if (def == null) { name = checkString(narg); } else { name = optString(narg, def); } for (int i=0; i<lst.length; ++i) { if (lst[i].equals(name)) { return i; } } return argError(narg, "invalid option '" + name + "'"); } /** * Checks argument is a string and returns it. Raises error if not a * string. * @param narg argument index. * @return the argument as a string. */ public String checkString(int narg) { String s = toString(value(narg)); if (s == null) { tagError(narg, TSTRING); } return s; } /** * Checks the type of an argument, raises error if not matching. * @param narg argument index. * @param t typecode (from {@link Lua#type} for example). */ public void checkType(int narg, int t) { if (type(narg) != t) { tagError(narg, t); } } /** * Loads and runs the given string. * @param s the string to run. * @return a status code, as per {@link Lua#load}. */ public int doString(String s) { int status = load(Lua.stringReader(s), s); if (status == 0) { status = pcall(0, MULTRET, null); } return status; } private int errfile(String what, String fname, Exception e) { push("cannot " + what + " " + fname + ": " + e.toString()); return ERRFILE; } /** * Get a field (event) from an Lua value's metatable. Returns null * if there is no field nor metatable. * @param o Lua value to get metafield for. * @param event name of metafield (event). * @return the field from the metatable, or null. */ public Object getMetafield(Object o, String event) { LuaTable mt = getMetatable(o); if (mt == null) { return null; } return mt.get(event); } boolean isNoneOrNil(int narg) { return type(narg) <= TNIL; } /** * Loads a Lua chunk from a file. The <var>filename</var> argument is * used in a call to {@link Class#getResourceAsStream} where * <code>this</code> is the {@link Lua} instance, thus relative * pathnames will be relative to the location of the * <code>Lua.class</code> file. Pushes compiled chunk, or error * message, onto stack. * @param filename location of file. * @return status code, as per {@link Lua#load}. */ public int loadFile(String filename) { if (filename == null) { throw new NullPointerException(); } InputStream in = getClass().getResourceAsStream(filename); if (in == null) { return errfile("open", filename, new IOException()); } int status = 0; try { in.mark(1); int c = in.read(); if (c == '#') // Unix exec. file? { // :todo: handle this case } in.reset(); status = load(in, "@" + filename); } catch (IOException e) { return errfile("read", filename, e); } return status; } /** * Loads a Lua chunk from a string. Pushes compiled chunk, or error * message, onto stack. * @param s the string to load. * @param chunkname the name of the chunk. * @return status code, as per {@link Lua#load}. */ public int loadString(String s, String chunkname) { return load(stringReader(s), chunkname); } /** * Get optional integer argument. Raises error if non-number * supplied. * @param narg argument index. * @param def default value for integer. * @return an int. */ public int optInt(int narg, int def) { if (isNoneOrNil(narg)) { return def; } return checkInt(narg); } /** * Get optional number argument. Raises error if non-number supplied. * @param narg argument index. * @param def default value for number. * @return a double. */ public double optNumber(int narg, double def) { if (isNoneOrNil(narg)) { return def; } return checkNumber(narg); } /** * Get optional string argument. Raises error if non-string supplied. * @param narg argument index. * @param def default value for string. * @return a string. */ public String optString(int narg, String def) { if (isNoneOrNil(narg)) { return def; } return checkString(narg); } private void tagError(int narg, int tag) { typerror(narg, typeName(tag)); } /** * Name of type of value at <var>idx</var>. * @param idx stack index. * @return the name of the value's type. */ public String typeNameOfIndex(int idx) { return TYPENAME[type(idx)]; } /** * Declare type error in argument. * @param narg Index of argument. * @param tname Name of type expected. */ public void typerror(int narg, String tname) { argError(narg, tname + " expected, got " + typeNameOfIndex(narg)); } /** * Return string identifying current position of the control at level * <var>level</var>. * @param level specifies the call-stack level. * @return a description for that level. */ public String where(int level) { Debug ar = getStack(level); // check function at level if (ar != null) { getInfo("Sl", ar); // get info about it if (ar.currentline() > 0) // is there info? { return ar.shortsrc() + ":" + ar.currentline() + ": "; } } return ""; // else, no information available... } /** * Provide {@link java.io.Reader} interface over a <code>String</code>. * Equivalent of {@link java.io.StringReader#StringReader} from J2SE. * The ability to convert a <code>String</code> to a * <code>Reader</code> is required internally, * to provide the Lua function <code>loadstring</code>; exposed * externally as a convenience. * @param s the string from which to read. * @return a {@link java.io.Reader} that reads successive chars from <var>s</var>. */ public static Reader stringReader(String s) { return new StringReader(s); } ////////////////////////////////////////////////////////////////////// // Debug // Methods equivalent to debug API. In PUC-Rio most of these are in // ldebug.c private boolean getInfo(String what, Debug ar) { Object f = null; CallInfo callinfo = null; // :todo: complete me if (ar.ici() > 0) // no tail call? { callinfo = (CallInfo)civ.elementAt(ar.ici()); f = stack.elementAt(callinfo.function()); // assert isFunction(f); } return auxgetinfo(what, ar, f, callinfo); } /** * Locates function activation at specified call level and returns a * {@link Debug} * record for it, or <code>null</code> if level is too high. * May become public. * @param level the call level. * @return a {@link Debug} instance describing the activation record. */ Debug getStack(int level) { int ici; // Index of CallInfo for (ici=civ.size()-1; level > 0 && ici > 0; --ici) { CallInfo ci = (CallInfo)civ.elementAt(ici); --level; if (isLua(ci)) // Lua function? { level -= ci.tailcalls(); // skip lost tail calls } } if (level == 0 && ici > 0) // level found? { return new Debug(ici); } else if (level < 0) // level is of a lost tail call? { return new Debug(0); } return null; } /** * @return true is okay, false otherwise (for example, error). */ private boolean auxgetinfo(String what, Debug ar, Object f, CallInfo ci) { boolean status = true; if (f == null) { // :todo: implement me return status; } for (int i=0; i<what.length(); ++i) { switch (what.charAt(i)) { case 'S': funcinfo(ar, f); break; case 'l': ar.setCurrentline((ci != null) ? currentline(ci) : -1); break; // :todo: more cases. default: status = false; } } return status; } private int currentline(CallInfo ci) { int pc = currentpc(ci); if (pc < 0) { return -1; // only active Lua functions have current-line info } else { Object faso = stack.elementAt(ci.function()); LuaFunction f = (LuaFunction)faso; return f.proto().getline(pc); } } private int currentpc(CallInfo ci) { if (!isLua(ci)) // function is not a Lua function? { return -1; } if (ci == ci()) { ci.setSavedpc(savedpc); } return pcRel(ci.savedpc()); } private void funcinfo(Debug ar, Object cl) { if (cl instanceof LuaJavaCallback) { ar.setSource("=[Java]"); ar.setLinedefined(-1); ar.setLastlinedefined(-1); ar.setWhat("Java"); } else { Proto p = ((LuaFunction)cl).proto(); ar.setSource(p.source()); ar.setLinedefined(p.linedefined()); ar.setLastlinedefined(p.lastlinedefined()); ar.setWhat(ar.linedefined() == 0 ? "main" : "Lua"); } } /** Equivalent to macro isLua _and_ f_isLua from lstate.h. */ private boolean isLua(CallInfo callinfo) { Object f = stack.elementAt(callinfo.function()); return f instanceof LuaFunction; } private static int pcRel(int pc) { return pc - 1; } ////////////////////////////////////////////////////////////////////// // Do // Methods equivalent to the file ldo.c. Prefixed with d. // Some of these are in vm* instead. /** Equivalent to luaD_seterrorobj. */ private void dSeterrorobj(int errcode, int oldtop) { switch (errcode) { case ERRERR: stack.setElementAt("error in error handling", oldtop); break; case ERRSYNTAX: case ERRRUN: stack.setElementAt(stack.lastElement(), oldtop); break; } stack.setSize(oldtop+1); } void dThrow(int status) { errorStatus = status; throw new RuntimeException(LUA_ERROR); } ////////////////////////////////////////////////////////////////////// // Func // Methods equivalent to the file lfunc.c. Prefixed with f. /** Equivalent of luaF_close. All open upvalues referencing stack * slots level or higher are closed. * @param level Absolute stack index. */ private void fClose(int level) { int i = openupval.size(); while (--i >= 0) { UpVal uv = (UpVal)openupval.elementAt(i); if (uv.offset() < level) { break; } uv.close(); } openupval.setSize(i+1); return; } private UpVal fFindupval(int idx) { /* * We search from the end of the Vector towards the beginning, * looking for an UpVal for the required stack-slot. */ int i = openupval.size(); while (--i >= 0) { UpVal uv = (UpVal)openupval.elementAt(i); if (uv.offset() == idx) { return uv; } if (uv.offset() < idx) { break; } } // i points to be position _after_ which we want to insert a new // UpVal (it's -1 when we want to insert at the beginning). UpVal uv = new UpVal(stack, idx); openupval.insertElementAt(uv, i+1); return uv; } ////////////////////////////////////////////////////////////////////// // Debug // Methods equivalent to the file ldebug.c. Prefixed with g. /** p1 and p2 are absolute stack indexes. Corrupts NUMOP[0]. */ private void gAritherror(int p1, int p2) { if (!tonumber(value(p1), NUMOP)) { p2 = p1; // first operand is wrong } gTypeerror(value(p2), "perform arithmetic on"); } /** p1 and p2 are absolute stack indexes. */ private void gConcaterror(int p1, int p2) { if (stack.elementAt(p1) instanceof String) { p1 = p2; } // assert !(p1 instanceof String); gTypeerror(stack.elementAt(p1), "concatenate"); } boolean gCheckcode(Proto p) { // :todo: implement me. return true ; } private int gErrormsg(Object message) { push(message); if (errfunc != null) // is there an error handling function { if (!isFunction(errfunc)) { dThrow(ERRERR); } insert(errfunc, getTop()); // push function (under error arg) vmCall(stack.size()-2, 1); // call it } dThrow(ERRRUN); // NOTREACHED return 0; } private boolean gOrdererror(Object p1, Object p2) { String t1 = typeName(type(p1)); String t2 = typeName(type(p2)); if (t1.charAt(2) == t2.charAt(2)) { gRunerror("attempt to compare two " + t1 + "values"); } else { gRunerror("attempt to compare " + t1 + " with " + t2); } // NOTREACHED return false; } void gRunerror(String s) { gErrormsg(s); } private void gTypeerror(Object o, String op) { // :todo: PUC-Rio searches the stack to see if the value (which may // be a reference to stack cell) is a local variable. Jili can't do // that so easily. Consider changing interface. String t = typeName(type(o)); gRunerror("attempt to " + op + " a " + t + " value"); } ////////////////////////////////////////////////////////////////////// // Object // Methods equivalent to the file lobject.c. Prefixed with o. private static final int IDSIZE = 60; /** * @return a string no longer than IDSIZE. */ static String oChunkid(String source) { int len = IDSIZE; if (source.startsWith("=")) { if(source.length() < IDSIZE+1) { return source.substring(1); } else { return source.substring(1, 1+len); } } // else "source" or "...source" if (source.startsWith("@")) { len -= " '...' ".length(); int l = source.length(); if (l > len) { return "..." + // get last part of file name source.substring(source.length()-len, source.length()); } return source; } // else [string "string"] int l = source.indexOf('\n'); if (l == -1) { l = source.length(); } len -= " [string \"...\"] ".length(); if (l > len) { l = len; } StringBuffer buf = new StringBuffer(); buf.append("[string \""); buf.append(source.substring(0, l)); if (source.length() > l) // must truncate { buf.append("..."); } buf.append("\"]"); return buf.toString(); } /** Equivalent to luaO_rawequalObj. */ private static boolean oRawequal(Object a, Object b) { // see also vmEqual if (NIL == a) { return NIL == b; } // Now a is not null, so a.equals() is a valid call. // Numbers (Doubles), Booleans, Strings all get compared by value, // as they should; tables, functions, get compared by identity as // they should. return a.equals(b); } /** Equivalent to luaO_str2d. */ private static boolean oStr2d(String s, double[] out) { // :todo: using try/catch may be too slow. In which case we'll have // to recognise the valid formats first. try { out[0] = Double.parseDouble(s); return true; } catch (NumberFormatException e0_) { try { // Attempt hexadecimal conversion. // :todo: using String.trim is not strictly accurate, because it // trims other ASCII control characters as well as whitespace. s = s.trim().toUpperCase(); if (s.startsWith("0X")) { s = s.substring(2); } else if (s.startsWith("-0X")) { s = "-" + s.substring(3); } out[0] = Integer.parseInt(s, 16); return true; } catch (NumberFormatException e1_) { return false; } } } //////////////////////////////////////////////////////////////////////// // VM // Most of the methods in this section are equivalent to the files // lvm.c and ldo.c from PUC-Rio. They're mostly prefixed with vm as // well. private static final int PCRLUA = 0; private static final int PCRJ = 1; private static final int PCRYIELD = 2; // Instruction decomposition. // There follows a series of methods that extract the various fields // from a VM instruction. See lopcodes.h from PUC-Rio. // :todo: Consider replacing with m4 macros (or similar). // A brief overview of the instruction format: // Logically an instruction has an opcode (6 bits), op, and up to // three fields using one of three formats: // A B C (8 bits, 9 bits, 9 bits) // A Bx (8 bits, 18 bits) // A sBx (8 bits, 18 bits signed - excess K) // Some instructions do not use all the fields (EG OP_UNM only uses A // and B). // When packed into a word (an int in Jili) the following layouts are // used: // 31 (MSB) 23 22 14 13 6 5 0 (LSB) // +--------------+--------------+------------+--------+ // | B | C | A | OPCODE | // +--------------+--------------+------------+--------+ // // +--------------+--------------+------------+--------+ // | Bx | A | OPCODE | // +--------------+--------------+------------+--------+ // // +--------------+--------------+------------+--------+ // | sBx | A | OPCODE | // +--------------+--------------+------------+--------+ static final int NO_REG = 0xff; // SIZE_A == 8, (1 << 8)-1 // Hardwired values for speed. /** Equivalent of macro GET_OPCODE */ static int OPCODE(int instruction) { // POS_OP == 0 (shift amount) // SIZE_OP == 6 (opcode width) return instruction & 0x3f; } /** Equivalent of macro GET_OPCODE */ static int SET_OPCODE(int i, int op) { // POS_OP == 0 (shift amount) // SIZE_OP == 6 (opcode width) return (i & ~0x3F) | (op & 0x3F); } /** Equivalent of macro GETARG_A */ static int ARGA(int instruction) { // POS_A == POS_OP + SIZE_OP == 6 (shift amount) // SIZE_A == 8 (operand width) return (instruction >>> 6) & 0xff; } static int SETARG_A(int i, int u) { return (i & ~(0xff << 6)) | ((u & 0xff) << 6); } /** Equivalent of macro GETARG_B */ static int ARGB(int instruction) { // POS_B == POS_OP + SIZE_OP + SIZE_A + SIZE_C == 23 (shift amount) // SIZE_B == 9 (operand width) /* No mask required as field occupies the most significant bits of a * 32-bit int. */ return (instruction >>> 23); } static int SETARG_B(int i, int b) { return (i & ~(0x1ff << 23)) | ((b & 0x1ff) << 23); } /** Equivalent of macro GETARG_C */ static int ARGC(int instruction) { // POS_C == POS_OP + SIZE_OP + SIZE_A == 14 (shift amount) // SIZE_C == 9 (operand width) return (instruction >>> 14) & 0x1ff; } static int SETARG_C(int i, int c) { return (i & ~(0x1ff << 14)) | ((c & 0x1ff) << 14); } /** Equivalent of macro GETARG_Bx */ static int ARGBx(int instruction) { // POS_Bx = POS_C == 14 // SIZE_Bx == SIZE_C + SIZE_B == 18 /* No mask required as field occupies the most significant bits of a * 32 bit int. */ return (instruction >>> 14); } static int SETARG_Bx(int i, int bx) { return (i & 0x3fff) | (bx << 14) ; } /** Equivalent of macro GETARG_sBx */ static int ARGsBx(int instruction) { // As ARGBx but with (2**17-1) subtracted. return (instruction >>> 14) - MAXARG_sBx; } static int SETARG_sBx(int i, int bx) { return (i & 0x3fff) | ((bx+MAXARG_sBx) << 14) ; // CHECK THIS IS RIGHT } static boolean ISK(int field) { // The "is constant" bit position depends on the size of the B and C // fields (required to be the same width). // SIZE_B == 9 return field >= 0x100; } /** * Near equivalent of macros RKB and RKC. Note: non-static as it * requires stack and base instance members. Stands for "Register or * Konstant" by the way, it gets value from either the register file * (stack) or the constant array (k). */ private Object RK(Object[] k, int field) { if (ISK(field)) { return k[field & 0xff]; } return stack.elementAt(base + field); } // CREATE functions are required by FuncState, so default access. static int CREATE_ABC(int o, int a, int b, int c) { // POS_OP == 0 // POS_A == 6 // POS_B == 23 // POS_C == 14 return o | (a << 6) | (b << 23) | (c << 14); } static int CREATE_ABx(int o, int a, int bc) { // POS_OP == 0 // POS_A == 6 // POS_Bx == POS_C == 14 return o | (a << 6) | (bc << 14); } // opcode enumeration. // Generated by a script: // awk -f opcode.awk < lopcodes.h // and then pasted into here. // Made default access so that code generation, in FuncState, can see // the enumeration as well. static final int OP_MOVE = 0; static final int OP_LOADK = 1; static final int OP_LOADBOOL = 2; static final int OP_LOADNIL = 3; static final int OP_GETUPVAL = 4; static final int OP_GETGLOBAL = 5; static final int OP_GETTABLE = 6; static final int OP_SETGLOBAL = 7; static final int OP_SETUPVAL = 8; static final int OP_SETTABLE = 9; static final int OP_NEWTABLE = 10; static final int OP_SELF = 11; static final int OP_ADD = 12; static final int OP_SUB = 13; static final int OP_MUL = 14; static final int OP_DIV = 15; static final int OP_MOD = 16; static final int OP_POW = 17; static final int OP_UNM = 18; static final int OP_NOT = 19; static final int OP_LEN = 20; static final int OP_CONCAT = 21; static final int OP_JMP = 22; static final int OP_EQ = 23; static final int OP_LT = 24; static final int OP_LE = 25; static final int OP_TEST = 26; static final int OP_TESTSET = 27; static final int OP_CALL = 28; static final int OP_TAILCALL = 29; static final int OP_RETURN = 30; static final int OP_FORLOOP = 31; static final int OP_FORPREP = 32; static final int OP_TFORLOOP = 33; static final int OP_SETLIST = 34; static final int OP_CLOSE = 35; static final int OP_CLOSURE = 36; static final int OP_VARARG = 37; // end of instruction decomposition static final int SIZE_C = 9; static final int SIZE_B = 9; static final int SIZE_Bx = SIZE_C + SIZE_B; static final int SIZE_A = 8; static final int SIZE_OP = 6; static final int POS_OP = 0; static final int POS_A = POS_OP + SIZE_OP; static final int POS_C = POS_A + SIZE_A; static final int POS_B = POS_C + SIZE_C; static final int POS_Bx = POS_C; static final int MAXARG_Bx = (1<<SIZE_Bx)-1; static final int MAXARG_sBx = MAXARG_Bx>>1; // `sBx' is signed static final int MAXARG_A = (1<<SIZE_A)-1; static final int MAXARG_B = (1<<SIZE_B)-1; static final int MAXARG_C = (1<<SIZE_C)-1; /* this bit 1 means constant (0 means register) */ static final int BITRK = 1 << (SIZE_B - 1) ; static final int MAXINDEXRK = BITRK - 1 ; /** * Equivalent of luaD_call. * @param func absolute stack index of function to call. * @param r number of required results. */ private void vmCall(int func, int r) { ++nCcalls; if (vmPrecall(func, r) == PCRLUA) { vmExecute(1); } --nCcalls; } /** Equivalent of luaV_concat. */ private void vmConcat(int total, int last) { do { int top = base + last + 1; int n = 2; // number of elements handled in this pass (at least 2) if (!tostring(top-2)|| !tostring(top-1)) { if (!call_binTM(top-2, top-1, top-2, "__concat")) { gConcaterror(top-2, top-1); } } else if (((String)stack.elementAt(top-1)).length() > 0) { int tl = ((String)stack.elementAt(top-1)).length(); for (n = 1; n < total && tostring(top-n-1); ++n) { tl += ((String)stack.elementAt(top-n-1)).length(); if (tl < 0) { gRunerror("string length overflow"); } } StringBuffer buffer = new StringBuffer(tl); for (int i=n; i>0; i--) // concat all strings { buffer.append(stack.elementAt(top-i)); } stack.setElementAt(buffer.toString(), top-n); } total -= n-1; // got n strings to create 1 new last -= n-1; } while (total > 1); // repeat until only 1 result left } /** * Primitive for testing Lua equality of two values. Equivalent of * PUC-Rio's <code>equalobj</code> macro. Note that using null to * model nil complicates this test, maybe we should use a nonce object. * In the loosest sense, this is the equivalent of * <code>luaV_equalval</code>. */ private boolean vmEqual(Object a, Object b) { // :todo: consider if (a == b) return true; if (NIL == a) { return NIL == b; } // Now a is not null, so a.equals() is a valid call. if (a.equals(b)) { return true; } if (NIL == b) { return false; } // Now b is not null, so b.getClass() is a valid call. if (a.getClass() != b.getClass()) { return false; } // Same class, but different objects. if (a instanceof LuaJavaCallback || a instanceof LuaTable) { // Resort to metamethods. Object tm = get_compTM(getMetatable(a), getMetatable(b), "__eq"); if (null == tm) // no TM? { return false; } Object res = callTMres(tm, a, b); // call TM return !isFalse(res); } return false; } /** * Array of numeric operands. Used when converting strings to numbers * by an arithmetic opcode (ADD, SUB, MUL, DIV, MOD, POW, UNM). */ private static final double[] NUMOP = new double[2]; /** The core VM execution engine. */ private void vmExecute(int nexeccalls) { // This labelled while loop is used to simulate the effect of C's // goto. The end of the while loop is never reached. The beginning // of the while loop is branched to using a "continue reentry;" // statement (when a Lua function is called or returns). reentry: while (true) { // assert stack.elementAt[ci.function()] instanceof LuaFunction; LuaFunction function = (LuaFunction)stack.elementAt(ci().function()); Proto proto = function.proto(); int[] code = proto.code(); Object[] k = proto.constant(); int pc = savedpc; while (true) // main loop of interpreter { // Where the PUC-Rio code used the Protect macro, this has been // replaced with "savedpc = pc" and a "// Protect" comment. // Where the PUC-Rio code used the dojump macro, this has been // replaced with the equivalent increment of the pc and a // "//dojump" comment. int i = code[pc++]; // VM instruction. // :todo: count and line hook int a = ARGA(i); // its A field. Object rb; Object rc; switch (OPCODE(i)) { case OP_MOVE: stack.setElementAt(stack.elementAt(base+ARGB(i)), base+a); continue; case OP_LOADK: stack.setElementAt(k[ARGBx(i)], base+a); continue; case OP_LOADBOOL: stack.setElementAt(valueOfBoolean(ARGB(i) != 0), base+a); if (ARGC(i) != 0) { ++pc; } continue; case OP_LOADNIL: { int b = base + ARGB(i); do { stack.setElementAt(NIL, b--); } while (b >= base + a); continue; } case OP_GETUPVAL: { int b = ARGB(i); stack.setElementAt(function.upVal(b).getValue(), base+a); continue; } case OP_GETGLOBAL: rb = k[ARGBx(i)]; // assert rb instance of String; savedpc = pc; // Protect stack.setElementAt(vmGettable(function.getEnv(), rb), base+a); continue; case OP_GETTABLE: { savedpc = pc; // Protect Object t = stack.elementAt(base+ARGB(i)); stack.setElementAt(vmGettable(t, RK(k, ARGC(i))), base+a); continue; } case OP_SETUPVAL: { UpVal uv = function.upVal(ARGB(i)); uv.setValue(stack.elementAt(base+a)); continue; } case OP_SETGLOBAL: savedpc = pc; // Protect vmSettable(function.getEnv(), k[ARGBx(i)], stack.elementAt(base+a)); continue; case OP_SETTABLE: { savedpc = pc; // Protect Object t = stack.elementAt(base+a); vmSettable(t, RK(k, ARGB(i)), RK(k, ARGC(i))); continue; } case OP_NEWTABLE: { // :todo: use the b and c hints, currently ignored. int b = ARGB(i); int c = ARGC(i); stack.setElementAt(new LuaTable(), base+a); continue; } case OP_SELF: { int b = ARGB(i); rb = stack.elementAt(base+b); stack.setElementAt(rb, base+a+1); savedpc = pc; // Protect stack.setElementAt(vmGettable(rb, RK(k, ARGC(i))), base+a); continue; } case OP_ADD: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double sum = ((Double)rb).doubleValue() + ((Double)rc).doubleValue(); stack.setElementAt(valueOfNumber(sum), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double sum = NUMOP[0] + NUMOP[1]; stack.setElementAt(valueOfNumber(sum), base+a); } else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a, "__add")) { gAritherror(base+ARGB(i), base+ARGC(i)); } continue; case OP_SUB: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double difference = ((Double)rb).doubleValue() - ((Double)rc).doubleValue(); stack.setElementAt(valueOfNumber(difference), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double difference = NUMOP[0] - NUMOP[1]; stack.setElementAt(valueOfNumber(difference), base+a); } else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a, "__sub")) { gAritherror(base+ARGB(i), base+ARGC(i)); } continue; case OP_MUL: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double product = ((Double)rb).doubleValue() * ((Double)rc).doubleValue(); stack.setElementAt(valueOfNumber(product), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double product = NUMOP[0] * NUMOP[1]; stack.setElementAt(valueOfNumber(product), base+a); } else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a, "__mul")) { gAritherror(base+ARGB(i), base+ARGC(i)); } continue; case OP_DIV: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double quotient = ((Double)rb).doubleValue() / ((Double)rc).doubleValue(); stack.setElementAt(valueOfNumber(quotient), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double quotient = NUMOP[0] / NUMOP[1]; stack.setElementAt(valueOfNumber(quotient), base+a); } else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a, "__div")) { gAritherror(base+ARGB(i), base+ARGC(i)); } continue; case OP_MOD: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double db = ((Double)rb).doubleValue(); double dc = ((Double)rc).doubleValue(); double modulus = modulus(db, dc); stack.setElementAt(valueOfNumber(modulus), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double modulus = modulus(NUMOP[0], NUMOP[1]); stack.setElementAt(valueOfNumber(modulus), base+a); } else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a, "__mod")) { gAritherror(base+ARGB(i), base+ARGC(i)); } continue; case OP_POW: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double result = iNumpow(((Double)rb).doubleValue(), ((Double)rc).doubleValue()); stack.setElementAt(valueOfNumber(result), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double result = iNumpow(NUMOP[0], NUMOP[1]); stack.setElementAt(valueOfNumber(result), base+a); } else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a, "__pow")) { gAritherror(base+ARGB(i), base+ARGC(i)); } continue; case OP_UNM: { rb = stack.elementAt(base+ARGB(i)); if (rb instanceof Double) { double db = ((Double)rb).doubleValue(); stack.setElementAt(valueOfNumber(-db), base+a); } else if (tonumber(rb, NUMOP)) { stack.setElementAt(valueOfNumber(-NUMOP[0]), base+a); } else if (!call_binTM(base+ARGB(i), base+ARGB(i), base+a, "__unm")) { gAritherror(base+ARGB(i), base+ARGB(i)); } continue; } case OP_NOT: { Object ra = stack.elementAt(base+ARGB(i)); stack.setElementAt(valueOfBoolean(isFalse(ra)), base+a); continue; } case OP_LEN: rb = stack.elementAt(base+ARGB(i)); if (rb instanceof LuaTable) { LuaTable t = (LuaTable)rb; stack.setElementAt(new Double(t.getn()), base+a); continue; } else if (rb instanceof String) { String s = (String)rb; stack.setElementAt(new Double(s.length()), base+a); continue; } savedpc = pc; // Protect if (!call_binTM(base+ARGB(i), base+ARGB(i), base+a, "__len")) { gTypeerror(rb, "get length of"); } continue; case OP_CONCAT: { int b = ARGB(i); int c = ARGC(i); savedpc = pc; // Protect // :todo: The compiler assumes that all // stack locations _above_ b end up with junk in them. In // which case we can improve the speed of vmConcat (by not // converting each stack slot, but simply using // StringBuffer.append on whatever is there). vmConcat(c - b + 1, c); stack.setElementAt(stack.elementAt(base+b), base+a); continue; } case OP_JMP: // dojump pc += ARGsBx(i); continue; case OP_EQ: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (vmEqual(rb, rc) == (a != 0)) { // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_LT: savedpc = pc; // Protect if (vmLessthan(RK(k, ARGB(i)), RK(k, ARGC(i))) == (a != 0)) { // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_LE: savedpc = pc; // Protect if (vmLessequal(RK(k, ARGB(i)), RK(k, ARGC(i))) == (a != 0)) { // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_TEST: if (isFalse(stack.elementAt(base+a)) != (ARGC(i) != 0)) { // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_TESTSET: rb = stack.elementAt(base+ARGB(i)); if (isFalse(rb) != (ARGC(i) != 0)) { stack.setElementAt(rb, base+a); // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_CALL: { int b = ARGB(i); int nresults = ARGC(i) - 1; if (b != 0) { stack.setSize(base+a+b); } savedpc = pc; switch (vmPrecall(base+a, nresults)) { case PCRLUA: nexeccalls++; continue reentry; case PCRJ: // Was Java function called by precall, adjust result if (nresults >= 0) { stack.setSize(ci().top()); } continue; default: return; // yield } } case OP_TAILCALL: { int b = ARGB(i); if (b != 0) { stack.setSize(base+a+b); } savedpc = pc; // assert ARGC(i) - 1 == MULTRET switch (vmPrecall(base+a, MULTRET)) { case PCRLUA: { // tail call: put new frame in place of previous one. CallInfo ci = (CallInfo)civ.elementAt(civ.size()-2); int func = ci.function(); CallInfo fci = ci(); // Fresh CallInfo int pfunc = fci.function(); fClose(ci.base()); base = func + (fci.base() - pfunc); int aux; // loop index is used after loop ends for (aux=0; pfunc+aux < stack.size(); ++aux) { // move frame down stack.setElementAt(stack.elementAt(pfunc+aux), func+aux); } stack.setSize(func+aux); // correct top // assert stack.size() == base + ((LuaFunction)stack.elementAt(func)).proto().maxstacksize(); ci.tailcall(base, stack.size()); dec_ci(); // remove new frame. continue reentry; } case PCRJ: // It was a Java function { continue; } default: { return; // yield } } } case OP_RETURN: { fClose(base); int b = ARGB(i); if (b != 0) { int top = a + b - 1; stack.setSize(base + top); } savedpc = pc; // 'adjust' replaces aliased 'b' in PUC-Rio code. boolean adjust = vmPoscall(base+a); if (--nexeccalls == 0) { return; } if (adjust) { stack.setSize(ci().top()); } continue reentry; } case OP_FORLOOP: { double step = ((Double)stack.elementAt(base+a+2)).doubleValue(); double idx = ((Double)stack.elementAt(base+a)).doubleValue() + step; double limit = ((Double)stack.elementAt(base+a+1)).doubleValue(); if ((0 < step && idx <= limit) || (step <= 0 && limit <= idx)) { // dojump pc += ARGsBx(i); Object d = valueOfNumber(idx); stack.setElementAt(d, base+a); // internal index stack.setElementAt(d, base+a+3); // external index } continue; } case OP_FORPREP: { int init = base+a; int plimit = base+a+1; int pstep = base+a+2; savedpc = pc; // next steps may throw errors if (!tonumber(init)) { gRunerror("'for' initial value must be a number"); } else if (!tonumber(plimit)) { gRunerror("'for' limit must be a number"); } else if (!tonumber(pstep)) { gRunerror("'for' step must be a number"); } double step = ((Double)stack.elementAt(pstep)).doubleValue(); double idx = ((Double)stack.elementAt(init)).doubleValue() - step; stack.setElementAt(new Double(idx), init); // dojump pc += ARGsBx(i); continue; } case OP_TFORLOOP: { int cb = base+a+3; // call base stack.setElementAt(stack.elementAt(base+a+2), cb+2); stack.setElementAt(stack.elementAt(base+a+1), cb+1); stack.setElementAt(stack.elementAt(base+a), cb); stack.setSize(cb+3); savedpc = pc; // Protect vmCall(cb, ARGC(i)); stack.setSize(ci().top()); if (NIL != stack.elementAt(cb)) // continue loop { stack.setElementAt(stack.elementAt(cb), cb-1); // dojump pc += ARGsBx(code[pc]); } ++pc; continue; } case OP_SETLIST: { int n = ARGB(i); int c = ARGC(i); - int last; - LuaTable t; if (0 == n) { - n = (stack.size() - a) - 1; + n = (stack.size() - (base + a)) - 1; stack.setSize(ci().top()); } if (0 == c) { c = code[pc++]; } - t = (LuaTable)stack.elementAt(base+a); - last = ((c-1)*LFIELDS_PER_FLUSH) + n; + LuaTable t = (LuaTable)stack.elementAt(base+a); + int last = ((c-1)*LFIELDS_PER_FLUSH) + n; // :todo: consider expanding space in table for (; n > 0; n--) { Object val = stack.elementAt(base+a+n); t.putnum(last--, val); } continue; } case OP_CLOSE: fClose(base+a); continue; case OP_CLOSURE: { Proto p = function.proto().proto()[ARGBx(i)]; int nup = p.nups(); UpVal[] up = new UpVal[nup]; for (int j=0; j<nup; j++, pc++) { int in = code[pc]; if (OPCODE(in) == OP_GETUPVAL) { up[j] = function.upVal(ARGB(in)); } else { // assert OPCODE(in) == OP_MOVE; up[j] = fFindupval(base + ARGB(in)); } } LuaFunction nf = new LuaFunction(p, up, function.getEnv()); stack.setElementAt(nf, base+a); continue; } case OP_VARARG: { int b = ARGB(i)-1; int n = (base - ci().function()) - function.proto().numparams() - 1; if (b == MULTRET) { // :todo: Protect // :todo: check stack b = n; stack.setSize(base+a+n); } for (int j=0; j<b; ++j) { if (j < n) { Object src = stack.elementAt(base - n + j); stack.setElementAt(src, base+a+j); } else { stack.setElementAt(NIL, base+a+j); } } continue; } } /* switch */ } /* while */ } /* reentry: while */ } double iNumpow(double a, double b) { // :todo: this needs proper checking for boundary cases // EG, is currently wrong for (-0)^2. boolean invert = b < 0.0 ; if (invert) b = -b ; if (a == 0.0) return invert ? Double.NaN : a ; double result = 1.0 ; int ipow = (int) b ; b -= ipow ; double t = a ; while (ipow > 0) { if ((ipow & 1) != 0) result *= t ; ipow >>= 1 ; t = t*t ; } if (b != 0.0) // integer only case, save doing unnecessary work { if (a < 0.0) // doesn't work if a negative (complex result!) return Double.NaN ; t = Math.sqrt(a) ; double half = 0.5 ; while (b > 0.0) { if (b >= half) { result = result * t ; b -= half ; } b = b+b ; t = Math.sqrt(t) ; if (t == 1.0) break ; } } return invert ? 1.0 / result : result ; } /** Equivalent of luaV_gettable. */ private Object vmGettable(Object t, Object key) { Object tm; for (int loop = 0; loop < MAXTAGLOOP; ++loop) { if (t instanceof LuaTable) // 't' is a table? { LuaTable h = (LuaTable)t; Object res = h.get(key); if (!isNil(res)) return res; tm = tagmethod(h, "__index"); if (tm == null) return res; // else will try the tag method } else { tm = tagmethod(t, "__index"); if (tm == null) gTypeerror(t, "index"); } if (isFunction(tm)) return callTMres(tm, t, key); t = tm; // else repeat with 'tm' } gRunerror("loop in gettable"); // NOTREACHED return null; } /** Equivalent of luaV_lessthan. */ private boolean vmLessthan(Object l, Object r) { // :todo: currently goes wrong when comparing nil. Fix it. if (l.getClass() != r.getClass()) { // :todo: Make Lua error throw new IllegalArgumentException(); } else if (l instanceof Double) { return ((Double)l).doubleValue() < ((Double)r).doubleValue(); } else if (l instanceof String) { // :todo: PUC-Rio use strcoll, maybe we should use something // equivalent. return ((String)l).compareTo((String)r) < 0; } int res = call_orderTM(l, r, "__lt"); if (res >= 0) { return res != 0; } return gOrdererror(l, r); } /** Equivalent of luaV_lessequal. */ private boolean vmLessequal(Object l, Object r) { // :todo: currently goes wrong when comparing nil. Fix it. if (l.getClass() != r.getClass()) { // :todo: Make Lua error throw new IllegalArgumentException(); } else if (l instanceof Double) { return ((Double)l).doubleValue() <= ((Double)r).doubleValue(); } else if (l instanceof String) { return ((String)l).compareTo((String)r) <= 0; } int res = call_orderTM(l, r, "__le"); // first try 'le' if (res >= 0) { return res != 0; } res = call_orderTM(r, l, "__lt"); // else try 'lt' if (res >= 0) { return res == 0; } return gOrdererror(l, r); } /** * Equivalent of luaD_poscall. * @param firstResult stack index (absolute) of the first result */ private boolean vmPoscall(int firstResult) { // :todo: call hook CallInfo lci; // local copy, for faster access lci = dec_ci(); // Now (as a result of the dec_ci call), lci is the CallInfo record // for the current function (the function executing an OP_RETURN // instruction), and this.ci is the CallInfo record for the function // we are returning to. int res = lci.res(); int wanted = lci.nresults(); // Caution: wanted could be == MULTRET CallInfo cci = ci(); // Continuation CallInfo base = cci.base(); savedpc = cci.savedpc(); // Move results (and pad with nils to required number if necessary) int i = wanted; int top = stack.size(); // The movement is always downwards, so copying from the top-most // result first is always correct. while (i != 0 && firstResult < top) { stack.setElementAt(stack.elementAt(firstResult++), res++); i--; } if (i > 0) { stack.setSize(res+i); } // :todo: consider using two stack.setSize calls to nil out // remaining required results. // This trick only works if Lua.NIL == null, whereas the current // code works regardless of what Lua.NIL is. while (i-- > 0) { stack.setElementAt(NIL, res++); } stack.setSize(res); return wanted != MULTRET; } /** * Equivalent of LuaD_precall. This method expects that the arguments * to the function are placed above the function on the stack. * @param func absolute stack index of the function to call. * @param r number of results expected. */ private int vmPrecall(int func, int r) { Object faso; // Function AS Object faso = stack.elementAt(func); if (!isFunction(faso)) { faso = tryfuncTM(func); } ci().setSavedpc(savedpc); if (faso instanceof LuaFunction) { LuaFunction f = (LuaFunction)faso; Proto p = f.proto(); // :todo: ensure enough stack if (!p.isVararg()) { base = func + 1; if (stack.size() > base + p.numparams()) { // trim stack to the argument list stack.setSize(base + p.numparams()); } } else { int nargs = (stack.size() - func) - 1; base = adjust_varargs(p, nargs); } int top = base + p.maxstacksize(); inc_ci(func, base, top, r); savedpc = 0; // expand stack to the function's max stack size. stack.setSize(top); // :todo: implement call hook. return PCRLUA; } else if (faso instanceof LuaJavaCallback) { LuaJavaCallback fj = (LuaJavaCallback)faso; // :todo: checkstack (not sure it's necessary) base = func + 1; inc_ci(func, base, stack.size()+MINSTACK, r); // :todo: call hook int n = fj.luaFunction(this); if (n < 0) // yielding? { return PCRYIELD; } else { vmPoscall(stack.size() - n); return PCRJ; } } throw new IllegalArgumentException(); } /** Equivalent of luaV_settable. */ private void vmSettable(Object t, Object key, Object val) { for (int loop = 0; loop < MAXTAGLOOP; ++loop) { Object tm; if (t instanceof LuaTable) // 't' is a table { LuaTable h = (LuaTable)t; Object o = h.get(key); if (o != NIL) // result is not nil? { h.put(key, val); return; } tm = tagmethod(h, "__newindex"); if (tm == null) // or no TM? { h.put(key, val); return; } // else will try the tag method } else { tm = tagmethod(t, "__newindex"); if (tm == null) gTypeerror(t, "index"); } if (isFunction(tm)) { callTM(tm, t, key, val); return; } t = tm; // else repeat with 'tm' } gRunerror("loop in settable"); } private static String vmTostring(Object o) { if (o instanceof String) { return (String)o; } if (!(o instanceof Double)) { return null; } // Convert number to string. PUC-Rio abstracts this operation into // a macro, lua_number2str. The macro is only invoked from their // equivalent of this code. Double d = (Double)o; String repr = d.toString(); // Note: A naive conversion results in 3..4 == "3.04.0" which isn't // good. We special case the integers. if (repr.endsWith(".0")) { repr = repr.substring(0, repr.length()-2); } return repr; } /** Equivalent of adjust_varargs in "ldo.c". */ private int adjust_varargs(Proto p, int actual) { int nfixargs = p.numparams(); for (; actual < nfixargs; ++actual) { stack.addElement(NIL); } // PUC-Rio's LUA_COMPAT_VARARG is not supported here. // Move fixed parameters to final position int fixed = stack.size() - actual; // first fixed argument int newbase = stack.size(); // final position of first argument for (int i=0; i<nfixargs; ++i) { stack.addElement(stack.elementAt(fixed+i)); stack.setElementAt(NIL, fixed+i); } return newbase; } /** * @param p1 left hand operand. Absolute stack index. * @param p2 right hand operand. Absolute stack index. * @param res absolute stack index of result. * @return false if no tagmethod, true otherwise */ private boolean call_binTM(int p1, int p2, int res, String event) { Object tm = tagmethod(value(p1), event); // try first operand if (isNil(tm)) { tm = tagmethod(value(p2), event); // try second operand } if (!isFunction(tm)) { return false; } stack.setElementAt(callTMres(tm, value(p1), value(p2)), res); return true; } /** * @return -1 if no tagmethod, 0 false, 1 true */ private int call_orderTM(Object p1, Object p2, String event) { Object tm1 = tagmethod(p1, event); if (tm1 == NIL) // not metamethod { return -1; } Object tm2 = tagmethod(p2, event); if (!oRawequal(tm1, tm2)) // different metamethods? { return -1; } return isFalse(callTMres(tm1, p1, p2)) ? 0 : 1; } private void callTM(Object f, Object p1, Object p2, Object p3) { push(f); push(p1); push(p2); push(p3); vmCall(stack.size()-4, 0); } private Object callTMres(Object f, Object p1, Object p2) { push(f); push(p1); push(p2); vmCall(stack.size()-3, 1); Object res = stack.lastElement(); pop(1); return res; } private Object get_compTM(LuaTable mt1, LuaTable mt2, String event) { if (mt1 == null) { return null; } Object tm1 = mt1.get(event); if (isNil(tm1)) { return null; // no metamethod } if (mt1 == mt2) { return tm1; // same metatables => same metamethods } if (mt2 == null) { return null; } Object tm2 = mt2.get(event); if (isNil(tm2)) { return null; // no metamethod } if (oRawequal(tm1, tm2)) // same metamethods? { return tm1; } return null; } /** * Gets tagmethod for object. */ private Object tagmethod(Object o, String event) { LuaTable mt; mt = getMetatable(o); if (mt == null) { return null; } return mt.get(event); } /** * Computes the result of Lua's modules operator (%). Note that this * modulus operator does not match Java's %. */ private static double modulus(double x, double y) { return x - Math.floor(x/y)*y; } /** * Convert to number. Returns true if the argument o was converted to * a number. Converted number is placed in <var>out[0]</var>. Returns * false if the argument <var>o</var> could not be converted to a number. * Overloaded. */ private static boolean tonumber(Object o, double[] out) { if (o instanceof Double) { out[0] = ((Double)o).doubleValue(); return true; } if (!(o instanceof String)) { return false; } if (oStr2d((String)o, out)) { return true; } return false; } /** * Converts a stack slot to number. Returns true if the element at * the specified stack slot was converted to a number. False * otherwise. Note that this actually modifies the element stored at * <var>idx</var> in the stack (in faithful emulation of the PUC-Rio * code). Corrupts <code>NUMOP[0]</code>. Overloaded. * @param idx absolute stack slot. */ private boolean tonumber(int idx) { if (tonumber(stack.elementAt(idx), NUMOP)) { stack.setElementAt(new Double(NUMOP[0]), idx); return true; } return false; } /** * Convert a pair of operands for an arithmetic opcode. Stores * converted results in <code>out[0]</code> and <code>out[1]</code>. * @return true if and only if both values converted to number. */ private static boolean toNumberPair(Object x, Object y, double[] out) { if (tonumber(y, out)) { out[1] = out[0]; if (tonumber(x, out)) { return true; } } return false; } /** * Convert to string. Returns true if element was number or string * (the number will have been converted to a string), false otherwise. * Note this actually modifies the element stored at <var>idx</var> in * the stack (in faithful emulation of the PUC-Rio code). */ private boolean tostring(int idx) { Object o = stack.elementAt(idx); String s = vmTostring(o); if (s == null) { return false; } stack.setElementAt(s, idx); return true; } /** * @param func absolute stack index of the function object. */ private Object tryfuncTM(int func) { Object tm = tagmethod(stack.elementAt(func), "__call"); if (!isFunction(tm)) { gTypeerror(stack.elementAt(func), "call"); } insert(tm, func); return tm; } /** Lua's is False predicate. */ private boolean isFalse(Object o) { return o == NIL || Boolean.FALSE.equals(o); } /** Make new CallInfo record. */ private CallInfo inc_ci(int func, int baseArg, int top, int nresults) { CallInfo ci = new CallInfo(func, baseArg, top, nresults); civ.addElement(ci); return ci; } /** Pop topmost CallInfo record and return it. */ private CallInfo dec_ci() { CallInfo ci = (CallInfo)civ.pop(); return ci; } /** Equivalent to resume_error from ldo.c */ private int resume_error(String msg) { stack.setSize(ci().base()); stack.addElement(msg); return ERRRUN; } /** * Corresponds to ldump's luaU_dump method, but with data gone and writer * replaced by OutputStream. */ static int uDump(Proto f, OutputStream writer, boolean strip) throws IOException { DumpState d = new DumpState(new DataOutputStream(writer), strip) ; d.DumpHeader(); d.DumpFunction(f, null); d.writer.flush(); return 0; // Any errors result in thrown exceptions. } } final class DumpState { DataOutputStream writer; boolean strip; DumpState(DataOutputStream writer, boolean strip) { this.writer = writer ; this.strip = strip ; } //////////////// dumper //////////////////// void DumpHeader() throws IOException { /* * In order to make the code more compact the dumper re-uses the * header defined in Loader.java. It has to fix the endianness byte * first. */ Loader.HEADER[6] = 0; writer.write(Loader.HEADER) ; } private void DumpInt(int i) throws IOException { writer.writeInt(i) ; // big-endian } private void DumpNumber(double d) throws IOException { writer.writeDouble(d) ; // big-endian } void DumpFunction(Proto f, String p) throws IOException { DumpString((f.source == p || strip) ? null : f.source); DumpInt(f.linedefined); DumpInt(f.lastlinedefined); writer.writeByte(f.nups); writer.writeByte(f.numparams); writer.writeBoolean(f.isVararg()); writer.writeByte(f.maxstacksize); DumpCode(f); DumpConstants(f); DumpDebug(f); } private void DumpCode(Proto f) throws IOException { int n = f.sizecode ; int [] code = f.code ; DumpInt(n); for (int i = 0 ; i < n ; i++) DumpInt(code[i]) ; } private void DumpConstants(Proto f) throws IOException { int n = f.sizek; Object [] k = f.k ; DumpInt(n) ; for (int i = 0 ; i < n ; i++) { Object o = k[i] ; if (o == null) { writer.writeByte(Lua.TNIL) ; } else if (o instanceof Boolean) { writer.writeByte(Lua.TBOOLEAN) ; writer.writeBoolean(((Boolean)o).booleanValue()) ; } else if (o instanceof Double) { writer.writeByte(Lua.TNUMBER) ; DumpNumber(((Double)o).doubleValue()) ; } else if (o instanceof String) { writer.writeByte(Lua.TSTRING) ; DumpString((String)o) ; } else { //lua_assert(false); /* cannot happen */ } } n = f.sizep ; DumpInt(n) ; for (int i = 0 ; i < n ; i++) { Proto subfunc = f.p[i] ; DumpFunction(subfunc, f.source) ; } } private void DumpString(String s) throws IOException { if (s == null) { DumpInt(0); } else { /* * Strings are dumped by converting to UTF-8 encoding. The MIDP * 2.0 spec guarantees that this encoding will be supported (see * page 9 of midp-2_0-fr-spec.pdf). Nonetheless, any * possible UnsupportedEncodingException is left to be thrown * (it's a subclass of IOException which is declared to be thrown). */ byte [] contents = s.getBytes("UTF-8") ; int size = contents.length ; DumpInt(size+1) ; writer.write(contents, 0, size) ; writer.writeByte(0) ; } } private void DumpDebug(Proto f) throws IOException { if (strip) { DumpInt(0) ; DumpInt(0) ; DumpInt(0) ; return ; } int n = f.sizelineinfo; DumpInt(n); for (int i=0; i<n; i++) DumpInt(f.lineinfo[i]) ; n = f.sizelocvars; DumpInt(n); for (int i=0; i<n; i++) { LocVar locvar = f.locvars[i] ; DumpString(locvar.varname); DumpInt(locvar.startpc); DumpInt(locvar.endpc); } n = f.sizeupvalues; DumpInt(n); for (int i=0; i<n; i++) DumpString(f.upvalues[i]); } }
false
true
private void vmExecute(int nexeccalls) { // This labelled while loop is used to simulate the effect of C's // goto. The end of the while loop is never reached. The beginning // of the while loop is branched to using a "continue reentry;" // statement (when a Lua function is called or returns). reentry: while (true) { // assert stack.elementAt[ci.function()] instanceof LuaFunction; LuaFunction function = (LuaFunction)stack.elementAt(ci().function()); Proto proto = function.proto(); int[] code = proto.code(); Object[] k = proto.constant(); int pc = savedpc; while (true) // main loop of interpreter { // Where the PUC-Rio code used the Protect macro, this has been // replaced with "savedpc = pc" and a "// Protect" comment. // Where the PUC-Rio code used the dojump macro, this has been // replaced with the equivalent increment of the pc and a // "//dojump" comment. int i = code[pc++]; // VM instruction. // :todo: count and line hook int a = ARGA(i); // its A field. Object rb; Object rc; switch (OPCODE(i)) { case OP_MOVE: stack.setElementAt(stack.elementAt(base+ARGB(i)), base+a); continue; case OP_LOADK: stack.setElementAt(k[ARGBx(i)], base+a); continue; case OP_LOADBOOL: stack.setElementAt(valueOfBoolean(ARGB(i) != 0), base+a); if (ARGC(i) != 0) { ++pc; } continue; case OP_LOADNIL: { int b = base + ARGB(i); do { stack.setElementAt(NIL, b--); } while (b >= base + a); continue; } case OP_GETUPVAL: { int b = ARGB(i); stack.setElementAt(function.upVal(b).getValue(), base+a); continue; } case OP_GETGLOBAL: rb = k[ARGBx(i)]; // assert rb instance of String; savedpc = pc; // Protect stack.setElementAt(vmGettable(function.getEnv(), rb), base+a); continue; case OP_GETTABLE: { savedpc = pc; // Protect Object t = stack.elementAt(base+ARGB(i)); stack.setElementAt(vmGettable(t, RK(k, ARGC(i))), base+a); continue; } case OP_SETUPVAL: { UpVal uv = function.upVal(ARGB(i)); uv.setValue(stack.elementAt(base+a)); continue; } case OP_SETGLOBAL: savedpc = pc; // Protect vmSettable(function.getEnv(), k[ARGBx(i)], stack.elementAt(base+a)); continue; case OP_SETTABLE: { savedpc = pc; // Protect Object t = stack.elementAt(base+a); vmSettable(t, RK(k, ARGB(i)), RK(k, ARGC(i))); continue; } case OP_NEWTABLE: { // :todo: use the b and c hints, currently ignored. int b = ARGB(i); int c = ARGC(i); stack.setElementAt(new LuaTable(), base+a); continue; } case OP_SELF: { int b = ARGB(i); rb = stack.elementAt(base+b); stack.setElementAt(rb, base+a+1); savedpc = pc; // Protect stack.setElementAt(vmGettable(rb, RK(k, ARGC(i))), base+a); continue; } case OP_ADD: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double sum = ((Double)rb).doubleValue() + ((Double)rc).doubleValue(); stack.setElementAt(valueOfNumber(sum), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double sum = NUMOP[0] + NUMOP[1]; stack.setElementAt(valueOfNumber(sum), base+a); } else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a, "__add")) { gAritherror(base+ARGB(i), base+ARGC(i)); } continue; case OP_SUB: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double difference = ((Double)rb).doubleValue() - ((Double)rc).doubleValue(); stack.setElementAt(valueOfNumber(difference), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double difference = NUMOP[0] - NUMOP[1]; stack.setElementAt(valueOfNumber(difference), base+a); } else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a, "__sub")) { gAritherror(base+ARGB(i), base+ARGC(i)); } continue; case OP_MUL: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double product = ((Double)rb).doubleValue() * ((Double)rc).doubleValue(); stack.setElementAt(valueOfNumber(product), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double product = NUMOP[0] * NUMOP[1]; stack.setElementAt(valueOfNumber(product), base+a); } else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a, "__mul")) { gAritherror(base+ARGB(i), base+ARGC(i)); } continue; case OP_DIV: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double quotient = ((Double)rb).doubleValue() / ((Double)rc).doubleValue(); stack.setElementAt(valueOfNumber(quotient), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double quotient = NUMOP[0] / NUMOP[1]; stack.setElementAt(valueOfNumber(quotient), base+a); } else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a, "__div")) { gAritherror(base+ARGB(i), base+ARGC(i)); } continue; case OP_MOD: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double db = ((Double)rb).doubleValue(); double dc = ((Double)rc).doubleValue(); double modulus = modulus(db, dc); stack.setElementAt(valueOfNumber(modulus), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double modulus = modulus(NUMOP[0], NUMOP[1]); stack.setElementAt(valueOfNumber(modulus), base+a); } else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a, "__mod")) { gAritherror(base+ARGB(i), base+ARGC(i)); } continue; case OP_POW: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double result = iNumpow(((Double)rb).doubleValue(), ((Double)rc).doubleValue()); stack.setElementAt(valueOfNumber(result), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double result = iNumpow(NUMOP[0], NUMOP[1]); stack.setElementAt(valueOfNumber(result), base+a); } else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a, "__pow")) { gAritherror(base+ARGB(i), base+ARGC(i)); } continue; case OP_UNM: { rb = stack.elementAt(base+ARGB(i)); if (rb instanceof Double) { double db = ((Double)rb).doubleValue(); stack.setElementAt(valueOfNumber(-db), base+a); } else if (tonumber(rb, NUMOP)) { stack.setElementAt(valueOfNumber(-NUMOP[0]), base+a); } else if (!call_binTM(base+ARGB(i), base+ARGB(i), base+a, "__unm")) { gAritherror(base+ARGB(i), base+ARGB(i)); } continue; } case OP_NOT: { Object ra = stack.elementAt(base+ARGB(i)); stack.setElementAt(valueOfBoolean(isFalse(ra)), base+a); continue; } case OP_LEN: rb = stack.elementAt(base+ARGB(i)); if (rb instanceof LuaTable) { LuaTable t = (LuaTable)rb; stack.setElementAt(new Double(t.getn()), base+a); continue; } else if (rb instanceof String) { String s = (String)rb; stack.setElementAt(new Double(s.length()), base+a); continue; } savedpc = pc; // Protect if (!call_binTM(base+ARGB(i), base+ARGB(i), base+a, "__len")) { gTypeerror(rb, "get length of"); } continue; case OP_CONCAT: { int b = ARGB(i); int c = ARGC(i); savedpc = pc; // Protect // :todo: The compiler assumes that all // stack locations _above_ b end up with junk in them. In // which case we can improve the speed of vmConcat (by not // converting each stack slot, but simply using // StringBuffer.append on whatever is there). vmConcat(c - b + 1, c); stack.setElementAt(stack.elementAt(base+b), base+a); continue; } case OP_JMP: // dojump pc += ARGsBx(i); continue; case OP_EQ: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (vmEqual(rb, rc) == (a != 0)) { // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_LT: savedpc = pc; // Protect if (vmLessthan(RK(k, ARGB(i)), RK(k, ARGC(i))) == (a != 0)) { // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_LE: savedpc = pc; // Protect if (vmLessequal(RK(k, ARGB(i)), RK(k, ARGC(i))) == (a != 0)) { // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_TEST: if (isFalse(stack.elementAt(base+a)) != (ARGC(i) != 0)) { // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_TESTSET: rb = stack.elementAt(base+ARGB(i)); if (isFalse(rb) != (ARGC(i) != 0)) { stack.setElementAt(rb, base+a); // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_CALL: { int b = ARGB(i); int nresults = ARGC(i) - 1; if (b != 0) { stack.setSize(base+a+b); } savedpc = pc; switch (vmPrecall(base+a, nresults)) { case PCRLUA: nexeccalls++; continue reentry; case PCRJ: // Was Java function called by precall, adjust result if (nresults >= 0) { stack.setSize(ci().top()); } continue; default: return; // yield } } case OP_TAILCALL: { int b = ARGB(i); if (b != 0) { stack.setSize(base+a+b); } savedpc = pc; // assert ARGC(i) - 1 == MULTRET switch (vmPrecall(base+a, MULTRET)) { case PCRLUA: { // tail call: put new frame in place of previous one. CallInfo ci = (CallInfo)civ.elementAt(civ.size()-2); int func = ci.function(); CallInfo fci = ci(); // Fresh CallInfo int pfunc = fci.function(); fClose(ci.base()); base = func + (fci.base() - pfunc); int aux; // loop index is used after loop ends for (aux=0; pfunc+aux < stack.size(); ++aux) { // move frame down stack.setElementAt(stack.elementAt(pfunc+aux), func+aux); } stack.setSize(func+aux); // correct top // assert stack.size() == base + ((LuaFunction)stack.elementAt(func)).proto().maxstacksize(); ci.tailcall(base, stack.size()); dec_ci(); // remove new frame. continue reentry; } case PCRJ: // It was a Java function { continue; } default: { return; // yield } } } case OP_RETURN: { fClose(base); int b = ARGB(i); if (b != 0) { int top = a + b - 1; stack.setSize(base + top); } savedpc = pc; // 'adjust' replaces aliased 'b' in PUC-Rio code. boolean adjust = vmPoscall(base+a); if (--nexeccalls == 0) { return; } if (adjust) { stack.setSize(ci().top()); } continue reentry; } case OP_FORLOOP: { double step = ((Double)stack.elementAt(base+a+2)).doubleValue(); double idx = ((Double)stack.elementAt(base+a)).doubleValue() + step; double limit = ((Double)stack.elementAt(base+a+1)).doubleValue(); if ((0 < step && idx <= limit) || (step <= 0 && limit <= idx)) { // dojump pc += ARGsBx(i); Object d = valueOfNumber(idx); stack.setElementAt(d, base+a); // internal index stack.setElementAt(d, base+a+3); // external index } continue; } case OP_FORPREP: { int init = base+a; int plimit = base+a+1; int pstep = base+a+2; savedpc = pc; // next steps may throw errors if (!tonumber(init)) { gRunerror("'for' initial value must be a number"); } else if (!tonumber(plimit)) { gRunerror("'for' limit must be a number"); } else if (!tonumber(pstep)) { gRunerror("'for' step must be a number"); } double step = ((Double)stack.elementAt(pstep)).doubleValue(); double idx = ((Double)stack.elementAt(init)).doubleValue() - step; stack.setElementAt(new Double(idx), init); // dojump pc += ARGsBx(i); continue; } case OP_TFORLOOP: { int cb = base+a+3; // call base stack.setElementAt(stack.elementAt(base+a+2), cb+2); stack.setElementAt(stack.elementAt(base+a+1), cb+1); stack.setElementAt(stack.elementAt(base+a), cb); stack.setSize(cb+3); savedpc = pc; // Protect vmCall(cb, ARGC(i)); stack.setSize(ci().top()); if (NIL != stack.elementAt(cb)) // continue loop { stack.setElementAt(stack.elementAt(cb), cb-1); // dojump pc += ARGsBx(code[pc]); } ++pc; continue; } case OP_SETLIST: { int n = ARGB(i); int c = ARGC(i); int last; LuaTable t; if (0 == n) { n = (stack.size() - a) - 1; stack.setSize(ci().top()); } if (0 == c) { c = code[pc++]; } t = (LuaTable)stack.elementAt(base+a); last = ((c-1)*LFIELDS_PER_FLUSH) + n; // :todo: consider expanding space in table for (; n > 0; n--) { Object val = stack.elementAt(base+a+n); t.putnum(last--, val); } continue; } case OP_CLOSE: fClose(base+a); continue; case OP_CLOSURE: { Proto p = function.proto().proto()[ARGBx(i)]; int nup = p.nups(); UpVal[] up = new UpVal[nup]; for (int j=0; j<nup; j++, pc++) { int in = code[pc]; if (OPCODE(in) == OP_GETUPVAL) { up[j] = function.upVal(ARGB(in)); } else { // assert OPCODE(in) == OP_MOVE; up[j] = fFindupval(base + ARGB(in)); } } LuaFunction nf = new LuaFunction(p, up, function.getEnv()); stack.setElementAt(nf, base+a); continue; } case OP_VARARG: { int b = ARGB(i)-1; int n = (base - ci().function()) - function.proto().numparams() - 1; if (b == MULTRET) { // :todo: Protect // :todo: check stack b = n; stack.setSize(base+a+n); } for (int j=0; j<b; ++j) { if (j < n) { Object src = stack.elementAt(base - n + j); stack.setElementAt(src, base+a+j); } else { stack.setElementAt(NIL, base+a+j); } } continue; } } /* switch */ } /* while */ } /* reentry: while */ }
private void vmExecute(int nexeccalls) { // This labelled while loop is used to simulate the effect of C's // goto. The end of the while loop is never reached. The beginning // of the while loop is branched to using a "continue reentry;" // statement (when a Lua function is called or returns). reentry: while (true) { // assert stack.elementAt[ci.function()] instanceof LuaFunction; LuaFunction function = (LuaFunction)stack.elementAt(ci().function()); Proto proto = function.proto(); int[] code = proto.code(); Object[] k = proto.constant(); int pc = savedpc; while (true) // main loop of interpreter { // Where the PUC-Rio code used the Protect macro, this has been // replaced with "savedpc = pc" and a "// Protect" comment. // Where the PUC-Rio code used the dojump macro, this has been // replaced with the equivalent increment of the pc and a // "//dojump" comment. int i = code[pc++]; // VM instruction. // :todo: count and line hook int a = ARGA(i); // its A field. Object rb; Object rc; switch (OPCODE(i)) { case OP_MOVE: stack.setElementAt(stack.elementAt(base+ARGB(i)), base+a); continue; case OP_LOADK: stack.setElementAt(k[ARGBx(i)], base+a); continue; case OP_LOADBOOL: stack.setElementAt(valueOfBoolean(ARGB(i) != 0), base+a); if (ARGC(i) != 0) { ++pc; } continue; case OP_LOADNIL: { int b = base + ARGB(i); do { stack.setElementAt(NIL, b--); } while (b >= base + a); continue; } case OP_GETUPVAL: { int b = ARGB(i); stack.setElementAt(function.upVal(b).getValue(), base+a); continue; } case OP_GETGLOBAL: rb = k[ARGBx(i)]; // assert rb instance of String; savedpc = pc; // Protect stack.setElementAt(vmGettable(function.getEnv(), rb), base+a); continue; case OP_GETTABLE: { savedpc = pc; // Protect Object t = stack.elementAt(base+ARGB(i)); stack.setElementAt(vmGettable(t, RK(k, ARGC(i))), base+a); continue; } case OP_SETUPVAL: { UpVal uv = function.upVal(ARGB(i)); uv.setValue(stack.elementAt(base+a)); continue; } case OP_SETGLOBAL: savedpc = pc; // Protect vmSettable(function.getEnv(), k[ARGBx(i)], stack.elementAt(base+a)); continue; case OP_SETTABLE: { savedpc = pc; // Protect Object t = stack.elementAt(base+a); vmSettable(t, RK(k, ARGB(i)), RK(k, ARGC(i))); continue; } case OP_NEWTABLE: { // :todo: use the b and c hints, currently ignored. int b = ARGB(i); int c = ARGC(i); stack.setElementAt(new LuaTable(), base+a); continue; } case OP_SELF: { int b = ARGB(i); rb = stack.elementAt(base+b); stack.setElementAt(rb, base+a+1); savedpc = pc; // Protect stack.setElementAt(vmGettable(rb, RK(k, ARGC(i))), base+a); continue; } case OP_ADD: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double sum = ((Double)rb).doubleValue() + ((Double)rc).doubleValue(); stack.setElementAt(valueOfNumber(sum), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double sum = NUMOP[0] + NUMOP[1]; stack.setElementAt(valueOfNumber(sum), base+a); } else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a, "__add")) { gAritherror(base+ARGB(i), base+ARGC(i)); } continue; case OP_SUB: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double difference = ((Double)rb).doubleValue() - ((Double)rc).doubleValue(); stack.setElementAt(valueOfNumber(difference), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double difference = NUMOP[0] - NUMOP[1]; stack.setElementAt(valueOfNumber(difference), base+a); } else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a, "__sub")) { gAritherror(base+ARGB(i), base+ARGC(i)); } continue; case OP_MUL: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double product = ((Double)rb).doubleValue() * ((Double)rc).doubleValue(); stack.setElementAt(valueOfNumber(product), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double product = NUMOP[0] * NUMOP[1]; stack.setElementAt(valueOfNumber(product), base+a); } else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a, "__mul")) { gAritherror(base+ARGB(i), base+ARGC(i)); } continue; case OP_DIV: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double quotient = ((Double)rb).doubleValue() / ((Double)rc).doubleValue(); stack.setElementAt(valueOfNumber(quotient), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double quotient = NUMOP[0] / NUMOP[1]; stack.setElementAt(valueOfNumber(quotient), base+a); } else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a, "__div")) { gAritherror(base+ARGB(i), base+ARGC(i)); } continue; case OP_MOD: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double db = ((Double)rb).doubleValue(); double dc = ((Double)rc).doubleValue(); double modulus = modulus(db, dc); stack.setElementAt(valueOfNumber(modulus), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double modulus = modulus(NUMOP[0], NUMOP[1]); stack.setElementAt(valueOfNumber(modulus), base+a); } else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a, "__mod")) { gAritherror(base+ARGB(i), base+ARGC(i)); } continue; case OP_POW: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double result = iNumpow(((Double)rb).doubleValue(), ((Double)rc).doubleValue()); stack.setElementAt(valueOfNumber(result), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double result = iNumpow(NUMOP[0], NUMOP[1]); stack.setElementAt(valueOfNumber(result), base+a); } else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a, "__pow")) { gAritherror(base+ARGB(i), base+ARGC(i)); } continue; case OP_UNM: { rb = stack.elementAt(base+ARGB(i)); if (rb instanceof Double) { double db = ((Double)rb).doubleValue(); stack.setElementAt(valueOfNumber(-db), base+a); } else if (tonumber(rb, NUMOP)) { stack.setElementAt(valueOfNumber(-NUMOP[0]), base+a); } else if (!call_binTM(base+ARGB(i), base+ARGB(i), base+a, "__unm")) { gAritherror(base+ARGB(i), base+ARGB(i)); } continue; } case OP_NOT: { Object ra = stack.elementAt(base+ARGB(i)); stack.setElementAt(valueOfBoolean(isFalse(ra)), base+a); continue; } case OP_LEN: rb = stack.elementAt(base+ARGB(i)); if (rb instanceof LuaTable) { LuaTable t = (LuaTable)rb; stack.setElementAt(new Double(t.getn()), base+a); continue; } else if (rb instanceof String) { String s = (String)rb; stack.setElementAt(new Double(s.length()), base+a); continue; } savedpc = pc; // Protect if (!call_binTM(base+ARGB(i), base+ARGB(i), base+a, "__len")) { gTypeerror(rb, "get length of"); } continue; case OP_CONCAT: { int b = ARGB(i); int c = ARGC(i); savedpc = pc; // Protect // :todo: The compiler assumes that all // stack locations _above_ b end up with junk in them. In // which case we can improve the speed of vmConcat (by not // converting each stack slot, but simply using // StringBuffer.append on whatever is there). vmConcat(c - b + 1, c); stack.setElementAt(stack.elementAt(base+b), base+a); continue; } case OP_JMP: // dojump pc += ARGsBx(i); continue; case OP_EQ: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (vmEqual(rb, rc) == (a != 0)) { // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_LT: savedpc = pc; // Protect if (vmLessthan(RK(k, ARGB(i)), RK(k, ARGC(i))) == (a != 0)) { // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_LE: savedpc = pc; // Protect if (vmLessequal(RK(k, ARGB(i)), RK(k, ARGC(i))) == (a != 0)) { // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_TEST: if (isFalse(stack.elementAt(base+a)) != (ARGC(i) != 0)) { // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_TESTSET: rb = stack.elementAt(base+ARGB(i)); if (isFalse(rb) != (ARGC(i) != 0)) { stack.setElementAt(rb, base+a); // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_CALL: { int b = ARGB(i); int nresults = ARGC(i) - 1; if (b != 0) { stack.setSize(base+a+b); } savedpc = pc; switch (vmPrecall(base+a, nresults)) { case PCRLUA: nexeccalls++; continue reentry; case PCRJ: // Was Java function called by precall, adjust result if (nresults >= 0) { stack.setSize(ci().top()); } continue; default: return; // yield } } case OP_TAILCALL: { int b = ARGB(i); if (b != 0) { stack.setSize(base+a+b); } savedpc = pc; // assert ARGC(i) - 1 == MULTRET switch (vmPrecall(base+a, MULTRET)) { case PCRLUA: { // tail call: put new frame in place of previous one. CallInfo ci = (CallInfo)civ.elementAt(civ.size()-2); int func = ci.function(); CallInfo fci = ci(); // Fresh CallInfo int pfunc = fci.function(); fClose(ci.base()); base = func + (fci.base() - pfunc); int aux; // loop index is used after loop ends for (aux=0; pfunc+aux < stack.size(); ++aux) { // move frame down stack.setElementAt(stack.elementAt(pfunc+aux), func+aux); } stack.setSize(func+aux); // correct top // assert stack.size() == base + ((LuaFunction)stack.elementAt(func)).proto().maxstacksize(); ci.tailcall(base, stack.size()); dec_ci(); // remove new frame. continue reentry; } case PCRJ: // It was a Java function { continue; } default: { return; // yield } } } case OP_RETURN: { fClose(base); int b = ARGB(i); if (b != 0) { int top = a + b - 1; stack.setSize(base + top); } savedpc = pc; // 'adjust' replaces aliased 'b' in PUC-Rio code. boolean adjust = vmPoscall(base+a); if (--nexeccalls == 0) { return; } if (adjust) { stack.setSize(ci().top()); } continue reentry; } case OP_FORLOOP: { double step = ((Double)stack.elementAt(base+a+2)).doubleValue(); double idx = ((Double)stack.elementAt(base+a)).doubleValue() + step; double limit = ((Double)stack.elementAt(base+a+1)).doubleValue(); if ((0 < step && idx <= limit) || (step <= 0 && limit <= idx)) { // dojump pc += ARGsBx(i); Object d = valueOfNumber(idx); stack.setElementAt(d, base+a); // internal index stack.setElementAt(d, base+a+3); // external index } continue; } case OP_FORPREP: { int init = base+a; int plimit = base+a+1; int pstep = base+a+2; savedpc = pc; // next steps may throw errors if (!tonumber(init)) { gRunerror("'for' initial value must be a number"); } else if (!tonumber(plimit)) { gRunerror("'for' limit must be a number"); } else if (!tonumber(pstep)) { gRunerror("'for' step must be a number"); } double step = ((Double)stack.elementAt(pstep)).doubleValue(); double idx = ((Double)stack.elementAt(init)).doubleValue() - step; stack.setElementAt(new Double(idx), init); // dojump pc += ARGsBx(i); continue; } case OP_TFORLOOP: { int cb = base+a+3; // call base stack.setElementAt(stack.elementAt(base+a+2), cb+2); stack.setElementAt(stack.elementAt(base+a+1), cb+1); stack.setElementAt(stack.elementAt(base+a), cb); stack.setSize(cb+3); savedpc = pc; // Protect vmCall(cb, ARGC(i)); stack.setSize(ci().top()); if (NIL != stack.elementAt(cb)) // continue loop { stack.setElementAt(stack.elementAt(cb), cb-1); // dojump pc += ARGsBx(code[pc]); } ++pc; continue; } case OP_SETLIST: { int n = ARGB(i); int c = ARGC(i); if (0 == n) { n = (stack.size() - (base + a)) - 1; stack.setSize(ci().top()); } if (0 == c) { c = code[pc++]; } LuaTable t = (LuaTable)stack.elementAt(base+a); int last = ((c-1)*LFIELDS_PER_FLUSH) + n; // :todo: consider expanding space in table for (; n > 0; n--) { Object val = stack.elementAt(base+a+n); t.putnum(last--, val); } continue; } case OP_CLOSE: fClose(base+a); continue; case OP_CLOSURE: { Proto p = function.proto().proto()[ARGBx(i)]; int nup = p.nups(); UpVal[] up = new UpVal[nup]; for (int j=0; j<nup; j++, pc++) { int in = code[pc]; if (OPCODE(in) == OP_GETUPVAL) { up[j] = function.upVal(ARGB(in)); } else { // assert OPCODE(in) == OP_MOVE; up[j] = fFindupval(base + ARGB(in)); } } LuaFunction nf = new LuaFunction(p, up, function.getEnv()); stack.setElementAt(nf, base+a); continue; } case OP_VARARG: { int b = ARGB(i)-1; int n = (base - ci().function()) - function.proto().numparams() - 1; if (b == MULTRET) { // :todo: Protect // :todo: check stack b = n; stack.setSize(base+a+n); } for (int j=0; j<b; ++j) { if (j < n) { Object src = stack.elementAt(base - n + j); stack.setElementAt(src, base+a+j); } else { stack.setElementAt(NIL, base+a+j); } } continue; } } /* switch */ } /* while */ } /* reentry: while */ }