answer
stringlengths
17
10.2M
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.presents.server; import java.util.ArrayList; import java.util.HashMap; import com.google.inject.Inject; import com.google.inject.Singleton; import com.samskivert.util.ObserverList; import com.samskivert.util.RunQueue; import com.threerings.presents.annotation.EventQueue; import static com.threerings.presents.Log.log; /** * Handles the orderly shutdown of all server services. */ @Singleton public class ShutdownManager { /** Implementers of this interface will be notified when the server is shutting down. */ public static interface Shutdowner { /** * Called when the server is shutting down. */ public void shutdown (); } public static enum Constraint { RUNS_BEFORE, RUNS_AFTER }; @Inject ShutdownManager (@EventQueue RunQueue dobjq) { _dobjq = dobjq; } /** * Registers an entity that will be notified when the server is shutting down. */ public void registerShutdowner (Shutdowner downer) { _downers.add(downer); } /** * Unregisters the shutdowner from hearing when the server is shutdown. */ public void unregisterShutdowner (Shutdowner downer) { _downers.remove(downer); } /** * Adds a constraint that a certain shutdowner must be run before another. */ public void addConstraint (Shutdowner lhs, Constraint constraint, Shutdowner rhs) throws IllegalArgumentException { if (lhs == null || rhs == null) { throw new IllegalArgumentException("Cannot add constraint about null shutdowner."); } Shutdowner before = (constraint == Constraint.RUNS_BEFORE) ? lhs : rhs; Shutdowner after = (constraint == Constraint.RUNS_BEFORE) ? rhs : lhs; _downers.addDependency(after, before); } /** * Queues up a request to shutdown on the dobjmgr thread. This method may be safely called from * any thread. */ public void queueShutdown () { _dobjq.postRunnable(new Runnable() { public void run () { shutdown(); } }); } /** * Shuts down all shutdowners immediately on the caller's thread. */ public void shutdown () { if (_downers == null) { log.warning("Refusing repeat shutdown request."); return; } ObserverList<Shutdowner> downers = ObserverList.newSafeInOrder(); while (!_downers.isEmpty()) { downers.add(_downers.removeAvailableElement()); } _downers = null; // shut down all shutdown participants downers.apply(new ObserverList.ObserverOp<Shutdowner>() { public boolean apply (Shutdowner downer) { downer.shutdown(); return true; } }); } /** * We maintain a bidirectional graph to manage the order that the items are removed. Children * must wait until their parents are accessed - thus removing an available element means that * a node without parents (an orphan) is removed and returned. * @param <T> */ protected class DependencyGraph<T> { /** * Adds an element with no initial dependencies from the graph. */ public void add (T element) { DependencyNode<T> node = new DependencyNode<T>(element); _nodes.put(element, node); _orphans.add(element); } /** * Removes an element and its dependencies from the graph. */ public void remove (T element) { DependencyNode<T> node = _nodes.remove(element); _orphans.remove(element); // Remove ourselves as a child of our parents. for (DependencyNode<T> parent : node.parents) { parent.children.remove(node); } // Remove ourselves as a parent of our children, possibly orphaning them. for (DependencyNode<T> child : node.children) { child.parents.remove(node); if (child.parents.isEmpty()) { _orphans.add(child.content); } } } /** * Removes and returns an element which is available, meaning not dependent upon any other * still in the graph. */ public T removeAvailableElement () { T elem = _orphans.get(0); DependencyNode<T> node = _nodes.get(elem); remove(elem); return elem; } /** * Returns the number of elements in the graph. */ public int size () { return _nodes.size(); } /** * Returns whether there are no more elements in the graph. */ public boolean isEmpty () { return size() == 0; } /** * Records a new dependency of the dependant upon the dependee. */ public void addDependency (T dependant, T dependee) throws IllegalArgumentException { _orphans.remove(dependant); DependencyNode<T> dependantNode = _nodes.get(dependant); DependencyNode<T> dependeeNode = _nodes.get(dependee); if (dependsOn(dependee, dependant)) { throw new IllegalArgumentException("Refusing to create circular dependency."); } dependantNode.parents.add(dependeeNode); dependeeNode.children.add(dependantNode); } /** * Returns whether elem1 is designated to depend on elem2. */ public boolean dependsOn (T elem1, T elem2) { DependencyNode<T> node1 = _nodes.get(elem1); DependencyNode<T> node2 = _nodes.get(elem2); ArrayList<DependencyNode<T>> nodesToCheck = new ArrayList<DependencyNode<T>>(); ArrayList<DependencyNode<T>> nodesAlreadyChecked = new ArrayList<DependencyNode<T>>(); nodesToCheck.addAll(node1.parents); // We prevent circular dependencies when we add dependencies. Otherwise, this'd be // potentially non-terminating. while (!nodesToCheck.isEmpty()) { // We take it off the end since we don't care about order and this is faster. DependencyNode<T> checkNode = nodesToCheck.remove(nodesToCheck.size() - 1); if (nodesAlreadyChecked.contains(checkNode)) { // We've seen him before, no need to check again. continue; } else if (checkNode == node2) { // We've found our dependency return true; } else { nodesAlreadyChecked.add(checkNode); nodesToCheck.addAll(checkNode.parents); } } return false; } /** All the nodes included in the graph. */ protected HashMap<T, DependencyNode<T>> _nodes = new HashMap<T, DependencyNode<T>>(); /** Nodes in the graph with no parents/dependencies. */ protected ArrayList<T> _orphans = new ArrayList<T>(); protected class DependencyNode<T> { public T content; public ArrayList<DependencyNode<T>> parents; public ArrayList<DependencyNode<T>> children; public DependencyNode (T contents) { this.content = contents; this.parents = new ArrayList<DependencyNode<T>>(); this.children = new ArrayList<DependencyNode<T>>(); } } } /** All of the registered shutdowners along with related constraints. */ protected DependencyGraph<Shutdowner> _downers = new DependencyGraph<Shutdowner>(); /** The queue we'll use to get onto the dobjmgr thread before shutting down. */ protected RunQueue _dobjq; }
package afc.ant.modular; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedHashSet; public class SerialDependencyResolver implements DependencyResolver { private HashSet<Node> nodes; public void init(final Collection<ModuleInfo> modules) throws CyclicDependenciesDetectedException { if (modules == null) { throw new NullPointerException("modules"); } ensureNoLoops(modules); nodes = buildNodeGraph(modules); } private static Node resolveNode(final ModuleInfo module, final IdentityHashMap<ModuleInfo, Node> registry) { Node node = registry.get(module); if (node == null) { node = new Node(module); registry.put(module, node); } return node; } // TODO prevent repeated calls of #getFreeModule without calling moduleProcessed // returns a module that does not have dependencies public ModuleInfo getFreeModule() { if (nodes.isEmpty()) { return null; } for (final Node node : nodes) { if (node.dependencies.size() == 0) { return node.module; } } throw new IllegalStateException(); // cyclic dependency detection does not work properly. } public void moduleProcessed(final ModuleInfo module) { if (module == null) { throw new NullPointerException("module"); } // TODO improve performance for (final Node node : nodes) { if (node.module == module) { for (final Node depOf : node.dependencyOf) { depOf.dependencies.remove(node); } nodes.remove(node); return; } } throw new IllegalArgumentException("Alien module is passed."); } private static class Node { private Node(final ModuleInfo module) { this.module = module; dependencies = new HashSet<Node>(); dependencyOf = new HashSet<Node>(); } private final ModuleInfo module; private final HashSet<Node> dependencies; private final HashSet<Node> dependencyOf; } private static HashSet<Node> buildNodeGraph(final Collection<ModuleInfo> modules) { final IdentityHashMap<ModuleInfo, Node> registry = new IdentityHashMap<ModuleInfo, Node>(); final HashSet<Node> nodeGraph = new HashSet<Node>(); // TODO check that there are no missing and/or duplicate modules and all nodes are initialised fully for (final ModuleInfo module : modules) { if (module == null) { throw new NullPointerException("modules contains null elements."); } final Node node = resolveNode(module, registry); // linking nodes in the same way as modules are linked for (final ModuleInfo dep : module.getDependencies()) { final Node depNode = resolveNode(dep, registry); node.dependencies.add(depNode); depNode.dependencyOf.add(node); } nodeGraph.add(node); } return nodeGraph; } private static void ensureNoLoops(final Collection<ModuleInfo> modules) throws CyclicDependenciesDetectedException { final HashSet<Node> graph = buildNodeGraph(modules); /* Remove nodes without dependencies from the graph while this is possible. Non-empty resulting graph means there are loops in there. */ boolean stuck; do { stuck = true; for (final Iterator<Node> i = graph.iterator(); i.hasNext();) { final Node node = i.next(); if (node.dependencies.size() == 0) { for (final Node depOf : node.dependencyOf) { depOf.dependencies.remove(node); } i.remove(); // means graph.remove(node); stuck = false; } } } while (!stuck); if (graph.isEmpty()) { return; } /* There are cycling dependencies detected. Obtaining here a single loop to report to the invoker. * * The following holds: * - each node has at least a single dependency * - walking in any direction from any starting node within the graph will lead to a loop detected * - the loop detected does not necessarily end with the starting node, some leading nodes could be truncated */ final LinkedHashSet<Node> path = new LinkedHashSet<Node>(); for (Node node = anyNode(graph);; node = anyNode(node.dependencies)) { if (!path.add(node)) { // the node is already visited so the loop is detected int loopSize = path.size(); final Iterator<Node> it = path.iterator(); while (it.next() != node) { // skipping all leading nodes that are outside the loop --loopSize; } final ArrayList<ModuleInfo> loop = new ArrayList<ModuleInfo>(loopSize); loop.add(node.module); while (it.hasNext()) { loop.add(it.next().module); } assert loopSize == loop.size(); throw new CyclicDependenciesDetectedException(loop); } } } private static Node anyNode(final HashSet<Node> nodes) { return nodes.iterator().next(); } }
package gov.nih.nci.cadsr.cadsrpasswordchange.core; import java.security.GeneralSecurityException; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import javax.sql.DataSource; import org.apache.log4j.Logger; public class DAO implements AbstractDao { public static int MAX_ANSWER_LENGTH = 500; private static OracleObfuscation x; static { try { x = new OracleObfuscation("$_12345&"); } catch (GeneralSecurityException e) { e.printStackTrace(); } } public static String _jndiUser = "java:/jdbc/caDSR"; public static String _jndiSystem = "java:/jdbc/caDSRPasswordChange"; private Connection conn; private DataSource datasource; private static final String QUESTION_TABLE_NAME = "SBREXT.USER_SECURITY_QUESTIONS"; protected static final String SELECT_COLUMNS = "ua_name, question1, answer1, question2, answer2, question3, answer3, date_modified"; protected static final String PK_CONDITION = "ua_name=?"; private static final String SQL_INSERT = "INSERT INTO " + QUESTION_TABLE_NAME + " (ua_name,question1,answer1,question2,answer2,question3,answer3,date_modified) VALUES (?,?,?,?,?,?,?,?)"; private Logger logger = Logger.getLogger(DAO.class); public DAO(DataSource datasource) { this.datasource = datasource; } public DAO(Connection conn) { this.conn = conn; } public boolean checkValidUser(String username) throws Exception { boolean retVal = false; logger.info ("1 checkValidUser user: " + username); Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { if(conn == null) { DataSource ds = ConnectionUtil.getDS(DAO._jndiSystem); logger.debug("got DataSource for " + _jndiSystem); conn = ds.getConnection(); } logger.debug("connected"); stmt = conn.prepareStatement("select * from SBR.USER_ACCOUNTS_VIEW where UA_NAME = ?"); stmt.setString(1, username); rs = stmt.executeQuery(); if(rs.next()) { //assuming all user Ids are unique/no duplicate retVal = true; logger.info ("5 checkValidUser user: " + username); } } catch (Exception e) { e.printStackTrace(); logger.debug(e.getMessage()); } finally { if (rs != null) try { rs.close(); } catch (SQLException e) { logger.error(e.getMessage()); } if (stmt != null) try { stmt.close(); } catch (SQLException e) { logger.error(e.getMessage()); } if (conn != null) try { conn.close(); conn = null; } catch (SQLException e) { logger.error(e.getMessage()); } } logger.info("checkValidUser(): " + retVal); return retVal; } public UserBean checkValidUser(String username, String password) throws Exception { if(datasource == null) { throw new Exception("DataSource is empty or NULL."); } logger.info ("checkValidUser(username, password) user: " + username); UserBean userBean = new UserBean(username); Connection conn = null; try { conn = datasource.getConnection(username, password); logger.debug("connected"); userBean.setLoggedIn(true); userBean.setResult(new Result(ResultCode.NOT_EXPIRED)); } catch (Exception ex) { logger.debug(ex.getMessage()); Result result = ConnectionUtil.decode(ex); // expired passwords are acceptable as logins if (result.getResultCode() == ResultCode.EXPIRED) { userBean.setLoggedIn(true); logger.debug("considering expired password acceptable login"); } userBean.setResult(result); } finally { if (conn != null) { try { conn.close(); } catch (Exception ex) { logger.error(ex.getMessage()); } } } logger.info("returning isLoggedIn " + userBean.isLoggedIn()); return userBean; } public Result changePassword(String user, String password, String newPassword) { logger.info("changePassword user " + user ); Result result = new Result(ResultCode.UNKNOWN_ERROR); // (should get replaced) PreparedStatement stmt = null; boolean isConnectionException = true; // use to modify returned messages when exceptions are system issues instead of password change issues try { if(conn == null) { DataSource ds = ConnectionUtil.getDS(DAO._jndiSystem); logger.debug("got DataSource for " + _jndiSystem); conn = ds.getConnection(); } logger.debug("connected"); isConnectionException = false; // can't use parameters with PreparedStatement and "alter user", create a single string // (must quote password to retain capitalization for verification function) //String alterUser = "alter user ? identified by \"?\" replace \"?\"; String alterUser = "alter user " + user + " identified by \"" + newPassword + "\" replace " + "\"" + password + "\""; stmt = conn.prepareStatement(alterUser); //stmt.setString(1, user); //this is not an oversight, it just didn't work for some reason at runtime (missing user or role or invalid column index) //stmt.setString(2, password); //stmt.setString(3, newPassword); logger.debug("attempted to alter user " + user); stmt.execute(); result = new Result(ResultCode.PASSWORD_CHANGED); } catch (Exception ex) { logger.debug(ex.getMessage()); if (isConnectionException) result = new Result(ResultCode.UNKNOWN_ERROR); // error not related to user, provide a generic error else result = ConnectionUtil.decode(ex); } finally { if (stmt != null) try { stmt.close(); } catch (SQLException e) { logger.error(e.getMessage()); } if (conn != null) try { conn.close(); conn = null; } catch (SQLException e) { logger.error(e.getMessage()); } } logger.info("returning ResultCode " + result.getResultCode().toString()); return result; } private void params( PreparedStatement pstmt, Object[] params) throws SQLException { int i = 1; for (Object param : params) { if (param != null) { pstmt.setObject( i++, param ); } } } public UserSecurityQuestion findByPrimaryKey( String uaName ) throws Exception { Statement stmt = null; String sql = null; ResultSet rs = null; UserSecurityQuestion q = null; try { sql = "select * from " + QUESTION_TABLE_NAME + " where ua_name = ?"; logger.debug("findByPrimaryKey sql : " + sql); if(conn == null) { DataSource ds = ConnectionUtil.getDS(DAO._jndiSystem); logger.debug("got DataSource for " + _jndiSystem); conn = ds.getConnection(); } PreparedStatement pstmt = conn.prepareStatement( sql ); pstmt.setString(1, uaName); rs = pstmt.executeQuery(); int count = 0; logger.debug("findByPrimaryKey: " + count); if(rs.next()) { q = new UserSecurityQuestion(); q.setUaName(rs.getString("ua_name")); q.setQuestion1(rs.getString("question1")); q.setAnswer1(decode(rs.getString("answer1"))); q.setQuestion2(rs.getString("question2")); q.setAnswer2(decode(rs.getString("answer2"))); q.setQuestion3(rs.getString("question3")); q.setAnswer3(decode(rs.getString("answer3"))); q.setDateModified(rs.getDate("date_modified")); } logger.debug("findByPrimaryKey: " + count + " q " + q); } catch (SQLException e) { throw new Exception( e ); } finally { if (rs != null) try { rs.close(); } catch (SQLException e) { logger.error(e.getMessage()); } if (stmt != null) try { stmt.close(); } catch (SQLException e) { logger.error(e.getMessage()); } if (conn != null) try { conn.close(); conn = null; } catch (SQLException e) { logger.error(e.getMessage()); } } return q; } public UserSecurityQuestion findByUaName( String uaName ) throws Exception { return findByPrimaryKey( uaName ); } public UserSecurityQuestion[] findAll( ) throws Exception { Statement stmt = null; ResultSet rs = null; String sql = null; ArrayList<UserSecurityQuestion> qList = new ArrayList<UserSecurityQuestion>(); try { sql = "select * from " + QUESTION_TABLE_NAME; if(conn == null) { DataSource ds = ConnectionUtil.getDS(DAO._jndiSystem); logger.debug("got DataSource for " + _jndiSystem); conn = ds.getConnection(); } PreparedStatement pstmt = conn.prepareStatement( sql ); rs = pstmt.executeQuery(); UserSecurityQuestion q = null; while(rs.next()) { q = new UserSecurityQuestion(); q.setUaName(rs.getString("ua_name")); q.setQuestion1(rs.getString("question1")); q.setAnswer1(decode(rs.getString("answer1"))); q.setQuestion2(rs.getString("question2")); q.setAnswer2(decode(rs.getString("answer2"))); q.setQuestion3(rs.getString("question3")); q.setAnswer3(decode(rs.getString("answer3"))); q.setDateModified(rs.getDate("date_modified")); qList.add(q); } } catch (SQLException e) { throw new Exception( e ); } finally { if (rs != null) try { rs.close(); } catch (SQLException e) {} if (stmt != null) try { stmt.close(); } catch (SQLException e) {} if (conn != null) try { conn.close(); conn = null; } catch (SQLException e) { logger.error(e.getMessage()); } } return toArray(qList); } public boolean deleteByPrimaryKey( String uaName ) throws Exception { //no requirement to delete anything return false; } private void checkMaxLength( String name, String value, int maxLength) throws Exception { if ( value != null && value.length() > maxLength ) { throw new Exception("Value of column '" + name + "' cannot have more than " + maxLength + " chars"); } } public void insert( UserSecurityQuestion dto ) throws Exception { PreparedStatement stmt = null; try { if(conn == null) { DataSource ds = ConnectionUtil.getDS(DAO._jndiSystem); logger.debug("got DataSource for " + _jndiSystem); conn = ds.getConnection(); } stmt = conn.prepareStatement( SQL_INSERT ); if ( dto.getUaName() == null ) { throw new Exception("Value of column 'ua_name' cannot be null"); } checkMaxLength( "ua_name", dto.getUaName(), 30 ); stmt.setString( 1, dto.getUaName() ); if ( dto.getQuestion1() == null ) { throw new Exception("Value of column 'question1' cannot be null"); } checkMaxLength( "question1", dto.getQuestion1(), 500 ); stmt.setString( 2, dto.getQuestion1() ); if ( dto.getAnswer1() == null ) { throw new Exception("Value of column 'answer1' cannot be null"); } // checkMaxLength( "answer1", dto.getAnswer1(), 500 ); stmt.setString( 3, dto.getAnswer1() ); if ( dto.getQuestion2() == null ) { throw new Exception("Value of column 'question2' cannot be null"); } checkMaxLength( "question2", dto.getQuestion2(), 500 ); stmt.setString( 4, dto.getQuestion2() ); if ( dto.getAnswer2() == null ) { throw new Exception("Value of column 'answer2' cannot be null"); } // checkMaxLength( "answer2", dto.getAnswer2(), 500 ); stmt.setString( 5, dto.getAnswer2() ); if ( dto.getQuestion3() == null ) { throw new Exception("Value of column 'question3' cannot be null"); } checkMaxLength( "question3", dto.getQuestion3(), 500 ); stmt.setString( 6, dto.getQuestion3() ); if ( dto.getAnswer3() == null ) { throw new Exception("Value of column 'answer3' cannot be null"); } // checkMaxLength( "answer3", dto.getAnswer3(), 500 ); stmt.setString( 7, dto.getAnswer3() ); if ( dto.getDateModified() == null ) { dto.setDateModified( new Date( System.currentTimeMillis())); } stmt.setDate( 8, dto.getDateModified() ); int n = stmt.executeUpdate(); } catch (SQLException e) { throw new Exception( e ); } finally { if (stmt != null) try { stmt.close(); } catch (SQLException e) {} if (conn != null) try { conn.close(); conn = null; } catch (SQLException e) { logger.error(e.getMessage()); } } } public boolean update( String uaName, UserSecurityQuestion dto ) throws Exception { StringBuffer sb = new StringBuffer(); ArrayList<Object> params = new ArrayList<Object>(); if ( dto.getUaName() != null ) { checkMaxLength( "ua_name", dto.getUaName(), 30 ); sb.append( "ua_name=?" ); params.add( dto.getUaName()); } if ( dto.getQuestion1() != null ) { if (sb.length() > 0) { sb.append( ", " ); } checkMaxLength( "question1", dto.getQuestion1(), 500 ); sb.append( "question1=?" ); params.add( dto.getQuestion1()); } if ( dto.getAnswer1() != null ) { if (sb.length() > 0) { sb.append( ", " ); } // checkMaxLength( "answer1", dto.getAnswer1(), 500 ); sb.append( "answer1=?" ); params.add( dto.getAnswer1()); } if ( dto.getQuestion2() != null ) { if (sb.length() > 0) { sb.append( ", " ); } checkMaxLength( "question2", dto.getQuestion2(), 500 ); sb.append( "question2=?" ); params.add( dto.getQuestion2()); } if ( dto.getAnswer2() != null ) { if (sb.length() > 0) { sb.append( ", " ); } // checkMaxLength( "answer2", dto.getAnswer2(), 500 ); sb.append( "answer2=?" ); params.add( dto.getAnswer2()); } if ( dto.getQuestion3() != null ) { if (sb.length() > 0) { sb.append( ", " ); } checkMaxLength( "question3", dto.getQuestion3(), 500 ); sb.append( "question3=?" ); params.add( dto.getQuestion3()); } if ( dto.getAnswer3() != null ) { if (sb.length() > 0) { sb.append( ", " ); } // checkMaxLength( "answer3", dto.getAnswer3(), 500 ); sb.append( "answer3=?" ); params.add( dto.getAnswer3()); } if (sb.length() == 0) { return false; } params.add( uaName ); Object[] oparams = new Object[ params.size() ]; return updateOne( sb.toString(), PK_CONDITION, params.toArray( oparams )); } private boolean updateOne( String setstring, String cond, Object... params) throws Exception { int ret = executeUpdate( getUpdateSql( setstring, cond ), params ); if (ret > 1) { throw new Exception("More than one record updated"); } return ret == 1; } private int executeUpdate( String sql, Object... params) throws Exception { Statement stmt = null; try { if (params != null && params.length > 0) { if(conn == null) { DataSource ds = ConnectionUtil.getDS(DAO._jndiSystem); logger.debug("got DataSource for " + _jndiSystem); conn = ds.getConnection(); } PreparedStatement pstmt = conn.prepareStatement( sql ); stmt = pstmt; params( pstmt, params); return pstmt.executeUpdate(); } else { stmt = conn.createStatement(); return stmt.executeUpdate( sql ); } } catch (SQLException e) { throw new Exception( e ); } finally { if (stmt != null) try { stmt.close(); } catch (SQLException e) {} if (conn != null) try { conn.close(); conn = null; } catch (SQLException e) { logger.error(e.getMessage()); } } } private String getUpdateSql(String setstring, String cond) { return getUpdateSql(setstring) + getSqlCondition( cond ); } /** * Returns the condition starting with " WHERE " or an empty string. */ private String getSqlCondition(String cond) { return cond != null && cond.length() > 0 ? (" WHERE " + cond) : ""; } private String getUpdateSql(String setstring) { return "UPDATE " + QUESTION_TABLE_NAME + " SET " + setstring; } private String encode(String text) { return text; } private String decode(String text) { return text; } private UserSecurityQuestion fetch( ResultSet rs ) throws Exception { UserSecurityQuestion dto = new UserSecurityQuestion(); dto.setUaName( rs.getString( 1 )); dto.setQuestion1( rs.getString( 2 )); dto.setAnswer1( decode(rs.getString( 3 ))); dto.setQuestion2( rs.getString( 4 )); dto.setAnswer2( decode(rs.getString( 5 ))); dto.setQuestion3( rs.getString( 6 )); dto.setAnswer3( decode(rs.getString( 7 ))); dto.setDateModified( rs.getDate( 8 )); return dto; } private UserSecurityQuestion[] toArray(ArrayList<UserSecurityQuestion> list ) { UserSecurityQuestion[] ret = new UserSecurityQuestion[ list.size() ]; return list.toArray( ret ); } public Result resetPassword(String user, String newPassword) { logger.info("resetPassword user " + user ); Result result = new Result(ResultCode.UNKNOWN_ERROR); // (should get replaced) PreparedStatement stmt = null; boolean isConnectionException = true; // use to modify returned messages when exceptions are system issues instead of password change issues try { if(conn == null) { DataSource ds = ConnectionUtil.getDS(DAO._jndiSystem); logger.debug("got DataSource for " + _jndiSystem); conn = ds.getConnection(); } logger.debug("connected"); isConnectionException = false; // can't use parameters with PreparedStatement and "alter user", create a single string // (must quote password to retain capitalization for verification function) String alterUser = "alter user " + user + " identified by \"" + newPassword + "\" account unlock"; stmt = conn.prepareStatement(alterUser); logger.debug("attempted to alter user " + user); stmt.execute(); result = new Result(ResultCode.PASSWORD_CHANGED); } catch (Exception ex) { ex.printStackTrace(); logger.debug(ex.getMessage()); if (isConnectionException) result = new Result(ResultCode.UNKNOWN_ERROR); // error not related to user, provide a generic error else result = ConnectionUtil.decode(ex); } finally { if (stmt != null) try { stmt.close(); } catch (SQLException e) { logger.error(e.getMessage()); } if (conn != null) try { conn.close(); conn = null; } catch (SQLException e) { logger.error(e.getMessage()); } } return result; } /** * This should be moved into a common utility class. * @param toolName * @param property * @return */ public String getToolProperty(String toolName, String property) { logger.info("accessing sbrext.tool_options_view_ext table, toolName '" + toolName + "', property '" + property + "'"); PreparedStatement stmt = null; ResultSet rs = null; String value = null; try { if(conn == null) { DataSource ds = ConnectionUtil.getDS(DAO._jndiSystem); logger.debug("got DataSource for " + _jndiSystem); conn = ds.getConnection(); } logger.debug("connected"); stmt = conn.prepareStatement("select value from sbrext.tool_options_view_ext where Tool_name = ? and Property = ?"); stmt.setString(1, toolName); stmt.setString(2, property); rs = stmt.executeQuery(); if(rs.next()) { //assuming all user Ids are unique/no duplicate value = rs.getString("value"); logger.info ("getToolProperty: toolName '" + toolName + "', property '" + property + "' value '" + value + "'"); } } catch (Exception ex) { ex.printStackTrace(); logger.debug(ex.getMessage()); } finally { if (rs != null) try { rs.close(); } catch (SQLException e) { logger.error(e.getMessage()); } if (stmt != null) try { stmt.close(); } catch (SQLException e) { logger.error(e.getMessage()); } if (conn != null) try { conn.close(); conn = null; } catch (SQLException e) { logger.error(e.getMessage()); } } return value; } }
package gov.nih.nci.cadsr.cadsrpasswordchange.core; import java.security.GeneralSecurityException; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; import org.apache.log4j.Logger; public class DAO implements AbstractDao { // public static String SECRET_WORD = "$_12345&"; // private static OracleObfuscation x; // static { // try { // x = new OracleObfuscation(SECRET_WORD); // } catch (GeneralSecurityException e) { // e.printStackTrace(); public static String _jndiUser = "java:/jdbc/caDSR"; public static String _jndiSystem = "java:/jdbc/caDSRPasswordChange"; private Connection conn; private DataSource datasource; private static final String QUESTION_TABLE_NAME = "SBREXT.USER_SECURITY_QUESTIONS"; protected static final String SELECT_COLUMNS = "ua_name, question1, answer1, question2, answer2, question3, answer3, date_modified"; protected static final String PK_CONDITION = "ua_name=?"; private static final String SQL_INSERT = "INSERT INTO " + QUESTION_TABLE_NAME + " (ua_name,question1,answer1,question2,answer2,question3,answer3,date_modified) VALUES (?,?,?,?,?,?,?,?)"; private Logger logger = Logger.getLogger(DAO.class); public DAO(DataSource datasource) { this.datasource = datasource; } public DAO(Connection conn) { this.conn = conn; } public boolean checkValidUser(String username) throws Exception { boolean retVal = false; logger.info ("1 checkValidUser user: " + username); Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { if(conn == null) { DataSource ds = ConnectionUtil.getDS(DAO._jndiSystem); logger.debug("got DataSource for " + _jndiSystem); conn = ds.getConnection(); } logger.debug("connected"); stmt = conn.prepareStatement("select * from SBR.USER_ACCOUNTS_VIEW where UA_NAME = ?"); stmt.setString(1, username); rs = stmt.executeQuery(); if(rs.next()) { //assuming all user Ids are unique/no duplicate retVal = true; logger.info ("5 checkValidUser user: " + username); } } catch (Exception e) { e.printStackTrace(); logger.debug(e.getMessage()); } finally { if (rs != null) try { rs.close(); } catch (SQLException e) { logger.error(e.getMessage()); } if (stmt != null) try { stmt.close(); } catch (SQLException e) { logger.error(e.getMessage()); } if (conn != null) try { conn.close(); conn = null; } catch (SQLException e) { logger.error(e.getMessage()); } } logger.info("checkValidUser(): " + retVal); return retVal; } public UserBean checkValidUser(String username, String password) throws Exception { if(datasource == null) { throw new Exception("DataSource is empty or NULL."); } logger.info ("checkValidUser(username, password) user: " + username); UserBean userBean = new UserBean(username); Connection conn = null; try { conn = datasource.getConnection(username, password); logger.debug("connected"); userBean.setLoggedIn(true); userBean.setResult(new Result(ResultCode.NOT_EXPIRED)); } catch (Exception ex) { logger.debug(ex.getMessage()); Result result = ConnectionUtil.decode(ex); // expired passwords are acceptable as logins if (result.getResultCode() == ResultCode.EXPIRED) { userBean.setLoggedIn(true); logger.debug("considering expired password acceptable login"); } userBean.setResult(result); } finally { if (conn != null) { try { conn.close(); } catch (Exception ex) { logger.error(ex.getMessage()); } } } logger.info("returning isLoggedIn " + userBean.isLoggedIn()); return userBean; } public Result changePassword(String user, String password, String newPassword) { logger.info("changePassword user " + user ); Result result = new Result(ResultCode.UNKNOWN_ERROR); // (should get replaced) PreparedStatement stmt = null; boolean isConnectionException = true; // use to modify returned messages when exceptions are system issues instead of password change issues try { if(conn == null) { DataSource ds = ConnectionUtil.getDS(DAO._jndiSystem); logger.debug("got DataSource for " + _jndiSystem); conn = ds.getConnection(); } logger.debug("connected"); isConnectionException = false; // can't use parameters with PreparedStatement and "alter user", create a single string // (must quote password to retain capitalization for verification function) //String alterUser = "alter user ? identified by \"?\" replace \"?\"; String alterUser = "alter user " + user + " identified by \"" + newPassword.trim() + "\" replace " + "\"" + password.trim() + "\""; stmt = conn.prepareStatement(alterUser); //stmt.setString(1, user); //this is not an oversight, it just didn't work for some reason at runtime (missing user or role or invalid column index) //stmt.setString(2, password); //stmt.setString(3, newPassword); logger.debug("attempted to alter user " + user); stmt.execute(); result = new Result(ResultCode.PASSWORD_CHANGED); } catch (Exception ex) { logger.debug(ex.getMessage()); if (isConnectionException) result = new Result(ResultCode.UNKNOWN_ERROR); // error not related to user, provide a generic error else result = ConnectionUtil.decode(ex); } finally { if (stmt != null) try { stmt.close(); } catch (SQLException e) { logger.error(e.getMessage()); } if (conn != null) try { conn.close(); conn = null; } catch (SQLException e) { logger.error(e.getMessage()); } } logger.info("returning ResultCode " + result.getResultCode().toString()); return result; } private void params( PreparedStatement pstmt, Object[] params) throws SQLException { int i = 1; for (Object param : params) { if (param != null) { pstmt.setObject( i++, param ); } } } public UserSecurityQuestion findByPrimaryKey( String uaName ) throws Exception { Statement stmt = null; String sql = null; ResultSet rs = null; UserSecurityQuestion q = null; try { sql = "select * from " + QUESTION_TABLE_NAME + " where ua_name = ?"; logger.debug("findByPrimaryKey sql : " + sql); if(conn == null) { DataSource ds = ConnectionUtil.getDS(DAO._jndiSystem); logger.debug("got DataSource for " + _jndiSystem); conn = ds.getConnection(); } PreparedStatement pstmt = conn.prepareStatement( sql ); pstmt.setString(1, uaName); rs = pstmt.executeQuery(); int count = 0; logger.debug("findByPrimaryKey: " + count); if(rs.next()) { q = new UserSecurityQuestion(); q.setUaName(rs.getString("ua_name")); q.setQuestion1(rs.getString("question1")); q.setAnswer1(decode(rs.getString("answer1"))); q.setQuestion2(rs.getString("question2")); q.setAnswer2(decode(rs.getString("answer2"))); q.setQuestion3(rs.getString("question3")); q.setAnswer3(decode(rs.getString("answer3"))); q.setDateModified(rs.getDate("date_modified")); } logger.debug("findByPrimaryKey: " + count + " q " + q); } catch (SQLException e) { throw new Exception( e ); } finally { if (rs != null) try { rs.close(); } catch (SQLException e) { logger.error(e.getMessage()); } if (stmt != null) try { stmt.close(); } catch (SQLException e) { logger.error(e.getMessage()); } if (conn != null) try { conn.close(); conn = null; } catch (SQLException e) { logger.error(e.getMessage()); } } return q; } public UserSecurityQuestion findByUaName( String uaName ) throws Exception { return findByPrimaryKey( uaName ); } public UserSecurityQuestion[] findAll( ) throws Exception { Statement stmt = null; ResultSet rs = null; String sql = null; ArrayList<UserSecurityQuestion> qList = new ArrayList<UserSecurityQuestion>(); try { sql = "select * from " + QUESTION_TABLE_NAME; if(conn == null) { DataSource ds = ConnectionUtil.getDS(DAO._jndiSystem); logger.debug("got DataSource for " + _jndiSystem); conn = ds.getConnection(); } PreparedStatement pstmt = conn.prepareStatement( sql ); rs = pstmt.executeQuery(); UserSecurityQuestion q = null; while(rs.next()) { q = new UserSecurityQuestion(); q.setUaName(rs.getString("ua_name")); q.setQuestion1(rs.getString("question1")); q.setAnswer1(decode(rs.getString("answer1"))); q.setQuestion2(rs.getString("question2")); q.setAnswer2(decode(rs.getString("answer2"))); q.setQuestion3(rs.getString("question3")); q.setAnswer3(decode(rs.getString("answer3"))); q.setDateModified(rs.getDate("date_modified")); qList.add(q); } } catch (SQLException e) { throw new Exception( e ); } finally { if (rs != null) try { rs.close(); } catch (SQLException e) {} if (stmt != null) try { stmt.close(); } catch (SQLException e) {} if (conn != null) try { conn.close(); conn = null; } catch (SQLException e) { logger.error(e.getMessage()); } } return toArray(qList); } public boolean deleteByPrimaryKey( String uaName ) throws Exception { //no requirement to delete anything return false; } private void checkMaxLength( String name, String value, int maxLength) throws Exception { if ( value != null && value.length() > maxLength ) { throw new Exception("Value of column '" + name + "' cannot have more than " + maxLength + " chars"); } } public void insert( UserSecurityQuestion dto ) throws Exception { PreparedStatement stmt = null; try { if(conn == null) { DataSource ds = ConnectionUtil.getDS(DAO._jndiSystem); logger.debug("got DataSource for " + _jndiSystem); conn = ds.getConnection(); } stmt = conn.prepareStatement( SQL_INSERT ); if ( dto.getUaName() == null ) { throw new Exception("Value of column 'ua_name' cannot be null"); } checkMaxLength( "ua_name", dto.getUaName(), 30 ); stmt.setString( 1, dto.getUaName() ); if ( dto.getQuestion1() == null ) { throw new Exception("Value of column 'question1' cannot be null"); } checkMaxLength( "question1", dto.getQuestion1(), 500 ); stmt.setString( 2, dto.getQuestion1() ); if ( dto.getAnswer1() == null ) { throw new Exception("Value of column 'answer1' cannot be null"); } // checkMaxLength( "answer1", dto.getAnswer1(), 500 ); stmt.setString( 3, dto.getAnswer1() ); if ( dto.getQuestion2() == null ) { throw new Exception("Value of column 'question2' cannot be null"); } checkMaxLength( "question2", dto.getQuestion2(), 500 ); stmt.setString( 4, dto.getQuestion2() ); if ( dto.getAnswer2() == null ) { throw new Exception("Value of column 'answer2' cannot be null"); } // checkMaxLength( "answer2", dto.getAnswer2(), 500 ); stmt.setString( 5, dto.getAnswer2() ); if ( dto.getQuestion3() == null ) { throw new Exception("Value of column 'question3' cannot be null"); } checkMaxLength( "question3", dto.getQuestion3(), 500 ); stmt.setString( 6, dto.getQuestion3() ); if ( dto.getAnswer3() == null ) { throw new Exception("Value of column 'answer3' cannot be null"); } // checkMaxLength( "answer3", dto.getAnswer3(), 500 ); stmt.setString( 7, dto.getAnswer3() ); if ( dto.getDateModified() == null ) { dto.setDateModified( new Date( System.currentTimeMillis())); } stmt.setDate( 8, dto.getDateModified() ); int n = stmt.executeUpdate(); } catch (SQLException e) { throw new Exception( e ); } finally { if (stmt != null) try { stmt.close(); } catch (SQLException e) {} if (conn != null) try { conn.close(); conn = null; } catch (SQLException e) { logger.error(e.getMessage()); } } } public boolean update( String uaName, UserSecurityQuestion dto ) throws Exception { StringBuffer sb = new StringBuffer(); ArrayList<Object> params = new ArrayList<Object>(); if ( dto.getUaName() != null ) { checkMaxLength( "ua_name", dto.getUaName(), 30 ); sb.append( "ua_name=?" ); params.add( dto.getUaName()); } if ( dto.getQuestion1() != null ) { if (sb.length() > 0) { sb.append( ", " ); } checkMaxLength( "question1", dto.getQuestion1(), 500 ); sb.append( "question1=?" ); params.add( dto.getQuestion1()); } if ( dto.getAnswer1() != null ) { if (sb.length() > 0) { sb.append( ", " ); } // checkMaxLength( "answer1", dto.getAnswer1(), 500 ); sb.append( "answer1=?" ); params.add( dto.getAnswer1()); } if ( dto.getQuestion2() != null ) { if (sb.length() > 0) { sb.append( ", " ); } checkMaxLength( "question2", dto.getQuestion2(), 500 ); sb.append( "question2=?" ); params.add( dto.getQuestion2()); } if ( dto.getAnswer2() != null ) { if (sb.length() > 0) { sb.append( ", " ); } // checkMaxLength( "answer2", dto.getAnswer2(), 500 ); sb.append( "answer2=?" ); params.add( dto.getAnswer2()); } if ( dto.getQuestion3() != null ) { if (sb.length() > 0) { sb.append( ", " ); } checkMaxLength( "question3", dto.getQuestion3(), 500 ); sb.append( "question3=?" ); params.add( dto.getQuestion3()); } if ( dto.getAnswer3() != null ) { if (sb.length() > 0) { sb.append( ", " ); } // checkMaxLength( "answer3", dto.getAnswer3(), 500 ); sb.append( "answer3=?" ); params.add( dto.getAnswer3()); } if (sb.length() == 0) { return false; } params.add( uaName ); Object[] oparams = new Object[ params.size() ]; return updateOne( sb.toString(), PK_CONDITION, params.toArray( oparams )); } private boolean updateOne( String setstring, String cond, Object... params) throws Exception { int ret = executeUpdate( getUpdateSql( setstring, cond ), params ); if (ret > 1) { throw new Exception("More than one record updated"); } return ret == 1; } private int executeUpdate( String sql, Object... params) throws Exception { Statement stmt = null; try { if (params != null && params.length > 0) { if(conn == null) { DataSource ds = ConnectionUtil.getDS(DAO._jndiSystem); logger.debug("got DataSource for " + _jndiSystem); conn = ds.getConnection(); } PreparedStatement pstmt = conn.prepareStatement( sql ); stmt = pstmt; params( pstmt, params); return pstmt.executeUpdate(); } else { stmt = conn.createStatement(); return stmt.executeUpdate( sql ); } } catch (SQLException e) { throw new Exception( e ); } finally { if (stmt != null) try { stmt.close(); } catch (SQLException e) {} if (conn != null) try { conn.close(); conn = null; } catch (SQLException e) { logger.error(e.getMessage()); } } } private String getUpdateSql(String setstring, String cond) { return getUpdateSql(setstring) + getSqlCondition( cond ); } /** * Returns the condition starting with " WHERE " or an empty string. */ private String getSqlCondition(String cond) { return cond != null && cond.length() > 0 ? (" WHERE " + cond) : ""; } private String getUpdateSql(String setstring) { return "UPDATE " + QUESTION_TABLE_NAME + " SET " + setstring; } private String encode(String text) { return text; } private String decode(String text) { return text; } private UserSecurityQuestion fetch( ResultSet rs ) throws Exception { UserSecurityQuestion dto = new UserSecurityQuestion(); dto.setUaName( rs.getString( 1 )); dto.setQuestion1( rs.getString( 2 )); dto.setAnswer1( decode(rs.getString( 3 ))); dto.setQuestion2( rs.getString( 4 )); dto.setAnswer2( decode(rs.getString( 5 ))); dto.setQuestion3( rs.getString( 6 )); dto.setAnswer3( decode(rs.getString( 7 ))); dto.setDateModified( rs.getDate( 8 )); return dto; } private UserSecurityQuestion[] toArray(ArrayList<UserSecurityQuestion> list ) { UserSecurityQuestion[] ret = new UserSecurityQuestion[ list.size() ]; return list.toArray( ret ); } public Result resetPassword(String user, String newPassword) { logger.info("resetPassword user " + user ); Result result = new Result(ResultCode.UNKNOWN_ERROR); // (should get replaced) PreparedStatement stmt = null; boolean isConnectionException = true; // use to modify returned messages when exceptions are system issues instead of password change issues try { if(conn == null) { DataSource ds = ConnectionUtil.getDS(DAO._jndiSystem); logger.debug("got DataSource for " + _jndiSystem); conn = ds.getConnection(); } logger.debug("connected"); isConnectionException = false; // can't use parameters with PreparedStatement and "alter user", create a single string // (must quote password to retain capitalization for verification function) String alterUser = "alter user " + user + " identified by \"" + newPassword.trim() + "\" account unlock"; stmt = conn.prepareStatement(alterUser); logger.debug("attempted to alter user " + user); stmt.execute(); result = new Result(ResultCode.PASSWORD_CHANGED); } catch (Exception ex) { ex.printStackTrace(); logger.debug(ex.getMessage()); if (isConnectionException) result = new Result(ResultCode.UNKNOWN_ERROR); // error not related to user, provide a generic error else result = ConnectionUtil.decode(ex); } finally { if (stmt != null) try { stmt.close(); } catch (SQLException e) { logger.error(e.getMessage()); } if (conn != null) try { conn.close(); conn = null; } catch (SQLException e) { logger.error(e.getMessage()); } } return result; } /** * This should be moved into a common utility class. * @param toolName * @param property * @return */ public String getToolProperty(String toolName, String property) { logger.info("accessing sbrext.tool_options_view_ext table, toolName '" + toolName + "', property '" + property + "'"); PreparedStatement stmt = null; ResultSet rs = null; String value = null; try { if(conn == null) { DataSource ds = ConnectionUtil.getDS(DAO._jndiSystem); logger.debug("got DataSource for " + _jndiSystem); conn = ds.getConnection(); } logger.debug("connected"); stmt = conn.prepareStatement("select value from sbrext.tool_options_view_ext where Tool_name = ? and Property = ?"); stmt.setString(1, toolName); stmt.setString(2, property); rs = stmt.executeQuery(); if(rs.next()) { //assuming all user Ids are unique/no duplicate value = rs.getString("value"); logger.info ("getToolProperty: toolName '" + toolName + "', property '" + property + "' value '" + value + "'"); } } catch (Exception ex) { ex.printStackTrace(); logger.debug(ex.getMessage()); } finally { if (rs != null) try { rs.close(); } catch (SQLException e) { logger.error(e.getMessage()); } if (stmt != null) try { stmt.close(); } catch (SQLException e) { logger.error(e.getMessage()); } if (conn != null) try { conn.close(); conn = null; } catch (SQLException e) { logger.error(e.getMessage()); } } return value; } /** * Method to retrieve all the user's with password which are expiring within the days specified in the passed in number. * @param withinDays * @return */ public List<User> getPasswordExpiringList(int withinDays) { logger.info("getRecipientList entered"); PreparedStatement stmt = null; ResultSet rs = null; String value = null; List arr = new ArrayList(); try { if(conn == null) { DataSource ds = ConnectionUtil.getDS(DAO._jndiSystem); logger.debug("got DataSource for " + _jndiSystem); conn = ds.getConnection(); } logger.debug("connected"); // stmt = conn.prepareStatement("SELECT electronic_mail_address, username, account_status, expiry_date, lock_date FROM dba_users a, sbr.user_accounts_view b WHERE a.username = b.ua_name and EXPIRY_DATE BETWEEN SYSDATE AND SYSDATE+?"); stmt = conn.prepareStatement("SELECT username, account_status, expiry_date, lock_date FROM dba_users where EXPIRY_DATE BETWEEN SYSDATE AND SYSDATE+?"); // stmt = conn.prepareStatement("SELECT electronic_mail_address FROM sbr.user_accounts_view"); stmt.setInt(1, withinDays); rs = stmt.executeQuery(); if(rs.next()) { User user = new User(); // user.setElectronic_mail_address(rs.getString("electronic_mail_address")); // user.setUsername(rs.getString("username")); // user.setAccount_status(rs.getString("account_status")); // user.setExpiry_date(rs.getString("expiry_date")); // user.setLock_date(rs.getString("lock_date")); logger.info ("getRecipientList: mail_address '" + user.getElectronic_mail_address() + "', username '" + user.getUsername() + "' expiry_date '" + user.getExpiry_date() + "'"); arr.add(user); } } catch (Exception ex) { ex.printStackTrace(); logger.debug(ex.getMessage()); } finally { if (rs != null) try { rs.close(); } catch (SQLException e) { logger.error(e.getMessage()); } if (stmt != null) try { stmt.close(); } catch (SQLException e) { logger.error(e.getMessage()); } if (conn != null) try { conn.close(); conn = null; } catch (SQLException e) { logger.error(e.getMessage()); } } return arr; } }
// $Id: ColorPository.java,v 1.2 2003/03/29 02:30:14 mdb Exp $ package com.threerings.media.image; import java.awt.Color; import java.util.ArrayList; import java.util.Iterator; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import com.samskivert.util.HashIntMap; import com.samskivert.util.StringUtil; import com.threerings.media.Log; import com.threerings.resource.ResourceManager; import com.threerings.util.CompiledConfig; import com.threerings.util.RandomUtil; /** * A repository of image recoloration information. It was called the * recolor repository but the re-s cancelled one another out. */ public class ColorPository implements Serializable { /** * Used to store information on a class of colors. These are public to * simplify the XML parsing process, so pay them no mind. */ public static class ClassRecord implements Serializable { /** An integer identifier for this class. */ public int classId; /** The name of the color class. */ public String name; /** The source color to use when recoloring colors in this class. */ public Color source; /** Data identifying the range of colors around the source color * that will be recolored when recoloring using this class. */ public float[] range; public boolean starter; /** A table of target colors included in this class. */ public HashIntMap colors = new HashIntMap(); /** Used when parsing the color definitions. */ public void addColor (ColorRecord record) { // validate the color id if (record.colorId > 255) { Log.warning("Refusing to add color record; colorId > 255 " + "[class=" + this + ", record=" + record + "]."); } else { record.cclass = this; colors.put(record.colorId, record); } } /** Returns a random starting id from the entries in this * class. */ public ColorRecord randomStartingColor () { // figure out our starter ids if we haven't already if (_starters == null) { ArrayList list = new ArrayList(); Iterator iter = colors.values().iterator(); while (iter.hasNext()) { ColorRecord color = (ColorRecord)iter.next(); if (color.starter) { list.add(color); } } _starters = (ColorRecord[]) list.toArray(new ColorRecord[list.size()]); } // return a random entry from the array return _starters[RandomUtil.getInt(_starters.length)]; } /** * Returns a string representation of this instance. */ public String toString () { return "[id=" + classId + ", name=" + name + ", source= Integer.toString(source.getRGB() & 0xFFFFFF, 16) + ", range=" + StringUtil.toString(range) + ", starter=" + starter + ", colors=" + StringUtil.toString(colors.values().iterator()) + "]"; } protected transient ColorRecord[] _starters; /** Increase this value when object's serialized state is impacted * by a class change (modification of fields, inheritance). */ private static final long serialVersionUID = 2; } /** * Used to store information on a particular color. These are public * to simplify the XML parsing process, so pay them no mind. */ public static class ColorRecord implements Serializable { /** The colorization class to which we belong. */ public ClassRecord cclass; /** A unique colorization identifier (used in fingerprints). */ public int colorId; /** The name of the target color. */ public String name; /** Data indicating the offset (in HSV color space) from the * source color to recolor to this color. */ public float[] offsets; public boolean starter; /** * Returns a value that is the composite of our class id and color * id which can be used to identify a colorization record. This * value will always be a positive integer that fits into 16 bits. */ public int getColorPrint () { return ((cclass.classId << 8) | colorId); } /** * Returns the data in this record configured as a colorization * instance. */ public Colorization getColorization () { return new Colorization(getColorPrint(), cclass.source, cclass.range, offsets); } /** * Returns a string representation of this instance. */ public String toString () { return "[id=" + colorId + ", name=" + name + ", offsets=" + StringUtil.toString(offsets) + ", starter=" + starter + "]"; } /** Increase this value when object's serialized state is impacted * by a class change (modification of fields, inheritance). */ private static final long serialVersionUID = 2; } /** * Returns an iterator over all color classes in this pository. */ public Iterator enumerateClasses () { return _classes.values().iterator(); } /** * Returns an array containing the records for the colors in the * specified class. */ public ColorRecord[] enumerateColors (String className) { // make sure the class exists ClassRecord record = getClassRecord(className); if (record == null) { return null; } // create the array ColorRecord[] crecs = new ColorRecord[record.colors.size()]; Iterator iter = record.colors.values().iterator(); for (int i = 0; iter.hasNext(); i++) { crecs[i] = ((ColorRecord)iter.next()); } return crecs; } /** * Returns an array containing the ids of the colors in the specified * class. */ public int[] enumerateColorIds (String className) { // make sure the class exists ClassRecord record = getClassRecord(className); if (record == null) { return null; } int[] cids = new int[record.colors.size()]; Iterator crecs = record.colors.values().iterator(); for (int i = 0; crecs.hasNext(); i++) { cids[i] = ((ColorRecord)crecs.next()).colorId; } return cids; } public boolean isLegalStartColor (int classId, int colorId) { ColorRecord color = getColorRecord(classId, colorId); return (color == null) ? false : color.starter; } /** * Returns a random starting color from the specified color class. */ public ColorRecord getRandomStartingColor (String className) { // make sure the class exists ClassRecord record = getClassRecord(className); return (record == null) ? null : record.randomStartingColor(); } /** * Looks up a colorization by id. */ public Colorization getColorization (int classId, int colorId) { ColorRecord color = getColorRecord(classId, colorId); return (color == null) ? null : color.getColorization(); } /** * Looks up a colorization by color print. */ public Colorization getColorization (int colorPrint) { return getColorization(colorPrint >> 8, colorPrint & 0xFF); } /** * Looks up a colorization by name. */ public Colorization getColorization (String className, int colorId) { ClassRecord crec = getClassRecord(className); if (crec != null) { ColorRecord color = (ColorRecord)crec.colors.get(colorId); if (color != null) { return color.getColorization(); } } return null; } /** * Loads up a colorization class by name and logs a warning if it * doesn't exist. */ public ClassRecord getClassRecord (String className) { Iterator iter = _classes.values().iterator(); while (iter.hasNext()) { ClassRecord crec = (ClassRecord)iter.next(); if (crec.name.equals(className)) { return crec; } } Log.warning("No such color class [class=" + className + "]."); Thread.dumpStack(); return null; } /** * Looks up the requested color record. */ protected ColorRecord getColorRecord (int classId, int colorId) { ClassRecord record = (ClassRecord)_classes.get(classId); if (record == null) { // if they request color class zero, we assume they're just // decoding a blank colorprint, otherwise we complain if (classId != 0) { Log.warning("Requested unknown color class " + "[classId=" + classId + ", colorId=" + colorId + "]."); Thread.dumpStack(); } return null; } return (ColorRecord)record.colors.get(colorId); } /** * Adds a fully configured color class record to the pository. This is * only called by the XML parsing code, so pay it no mind. */ public void addClass (ClassRecord record) { // validate the class id if (record.classId > 255) { Log.warning("Refusing to add class; classId > 255 " + record + "."); } else { _classes.put(record.classId, record); } } /** * Loads up a serialized color pository from the supplied resource * manager. */ public static ColorPository loadColorPository (ResourceManager rmgr) { try { return loadColorPository(rmgr.getResource(CONFIG_PATH)); } catch (IOException ioe) { Log.warning("Failure loading color pository [path=" + CONFIG_PATH + ", error=" + ioe + "]."); return new ColorPository(); } } /** * Loads up a serialized color pository from the supplied resource * manager. */ public static ColorPository loadColorPository (InputStream source) { try { return (ColorPository)CompiledConfig.loadConfig(source); } catch (IOException ioe) { Log.warning("Failure loading color pository: " + ioe + "."); return new ColorPository(); } } /** * Serializes and saves color pository to the supplied file. */ public static void saveColorPository (ColorPository posit, File root) { File path = new File(root, CONFIG_PATH); try { CompiledConfig.saveConfig(path, posit); } catch (IOException ioe) { Log.warning("Failure saving color pository " + "[path=" + path + ", error=" + ioe + "]."); } } /** Our mapping from class names to class records. */ protected HashIntMap _classes = new HashIntMap(); /** Increase this value when object's serialized state is impacted by * a class change (modification of fields, inheritance). */ private static final long serialVersionUID = 1; /** * The path (relative to the resource directory) at which the * serialized recolorization repository should be loaded and stored. */ protected static final String CONFIG_PATH = "config/media/colordefs.dat"; }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.presents.data; import com.threerings.io.SimpleStreamableObject; /** * Used to track and report stats on the connection manager. */ public class ConMgrStats extends SimpleStreamableObject { /** The current index into the history arrays. */ public int current; /** The size of the queue of waiting to auth sockets. */ public int[] authQueueSize; /** The size of the queue of waiting to die sockets. */ public int[] deathQueueSize; /** The outgoing queue size. */ public int[] outQueueSize; /** The overflow queue size. */ public int[] overQueueSize; /** The number of bytes read. */ public int[] bytesIn; /** The number of bytes written. */ public int[] bytesOut; /** The number of messages read. */ public int[] msgsIn; /** The number of messages written. */ public int[] msgsOut; /** Creates our historical arrays. */ public void init () { authQueueSize = new int[60]; deathQueueSize = new int[60]; outQueueSize = new int[60]; overQueueSize = new int[60]; bytesIn = new int[60]; bytesOut = new int[60]; msgsIn = new int[60]; msgsOut = new int[60]; } /** Advances the currently accumulating bucket and clears its * previous contents. */ public void increment () { current = (current + 1) % authQueueSize.length; authQueueSize[current] = 0; deathQueueSize[current] = 0; outQueueSize[current] = 0; overQueueSize[current] = 0; bytesIn[current] = 0; bytesOut[current] = 0; msgsIn[current] = 0; msgsOut[current] = 0; } }
package com.weblyzard.api.document; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlValue; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.eclipse.persistence.oxm.annotations.XmlCDATA; import com.fasterxml.jackson.annotation.JsonProperty; import com.weblyzard.api.datatype.MD5Digest; import com.weblyzard.api.document.serialize.xml.BooleanAdapter; /** * * webLyzard Sentence class * @author weichselbraun@weblyzard.com * **/ @XmlAccessorType(XmlAccessType.FIELD) public class Sentence implements Serializable { private static final long serialVersionUID = 1L; @JsonProperty("md5sum") @XmlAttribute(name="id", namespace=Document.NS_WEBLYZARD) @XmlJavaTypeAdapter(MD5Digest.class) private MD5Digest id; /** * The POS dependency tree of the given sentence. */ @XmlAttribute(name="pos", namespace=Document.NS_WEBLYZARD) private String pos; @XmlAttribute(name="dependency", namespace=Document.NS_WEBLYZARD) private String dependency; @XmlAttribute(name="token", namespace=Document.NS_WEBLYZARD) private String token; @JsonProperty("is_title") @XmlAttribute(name="is_title", namespace=Document.NS_WEBLYZARD) @XmlJavaTypeAdapter(BooleanAdapter.class) private Boolean isTitle; @JsonProperty("text") @XmlValue @XmlCDATA private String text; // additional attributes defined in the weblyzard XML format @JsonProperty("sem_orient") @XmlAttribute(name="sem_orient", namespace=Document.NS_WEBLYZARD) private double semOrient; @XmlAttribute(name="significance", namespace=Document.NS_WEBLYZARD) private double significance; // required by JAXB public Sentence() {} public Sentence(String text) { this.text = text; id = MD5Digest.fromText(text); } public Sentence (String text, String token, String pos) { this(text); this.token = token; this.pos = pos; } public Sentence(String text, String token, String pos, String dependency) { this(text, token, pos); this.dependency = dependency; } public String getText() { return text.replace("&quot;", "\""); } public Sentence setText(String text) { // required to allow marshalling of the XML document (!) this.text = text.replace("\"", "&quot;"); return this; } public Sentence setPos(String pos) { // required for handling double quotes in POS tags. this.pos = pos.replace("\"", "&quot;"); return this; } public String getPos() { if (pos!=null) { return pos.replace("&quot;", "\""); } return pos; } public String getToken() { return token; } public String toString() { return text; } public MD5Digest getId() { return id; } public Sentence setId(MD5Digest id) { this.id = id; return this; } public Boolean getIsTitle() { return Boolean.TRUE.equals(isTitle); } public Sentence setIsTitle(Boolean isTitle) { this.isTitle = isTitle; return this; } public double getSem_orient() { return semOrient; } public Sentence setSem_orient(double sem_orient) { this.semOrient = sem_orient; return this; } public double getSignificance() { return significance; } public Sentence setSignificance(double significance) { this.significance = significance; return this; } public String getDependency() { return dependency; } public Sentence setDependency(String dependency) { this.dependency = dependency; return this; } public Sentence setToken(String token) { this.token = token; return this; } }
package org.jaxen.function; import java.util.List; import org.jaxen.Context; import org.jaxen.Function; import org.jaxen.FunctionCallException; public class PositionFunction implements Function { /** * Returns the position of the context node in the context node-set. * * @param context the context at the point in the * expression where the function is called * @param args an empty list * * @return a <code>Double</code> containing the context position * * @throws FunctionCallException if <code>args</code> is not empty * * @see Context#getSize() */ public Object call(Context context, List args) throws FunctionCallException { if ( args.size() == 0 ) { return evaluate( context ); } throw new FunctionCallException( "position() requires no arguments." ); } /** * * Returns the position of the context node in the context node-set. * * @param context the context at the point in the * expression where the function is called * * @return a <code>Double</code> containing the context position * * @see Context#getPosition() */ public static Double evaluate(Context context) { return new Double( context.getPosition() ); } }
package org.apache.commons.dbcp; import java.util.Hashtable; import javax.naming.Context; import javax.naming.Name; import javax.naming.NamingException; import javax.naming.Reference; import javax.naming.RefAddr; import javax.naming.spi.ObjectFactory; public class BasicDataSourceFactory implements ObjectFactory { /** * <p>Create and return a new <code>BasicDataSource</code> instance. If no * instance can be created, return <code>null</code> instead.</p> * * @param obj The possibly null object containing location or * reference information that can be used in creating an object * @param name The name of this object relative to <code>nameCtx</code> * @param nameCts The context relative to which the <code>name</code> * parameter is specified, or <code>null</code> if <code>name</code> * is relative to the default initial context * @param environment The possibly null environment that is used in * creating this object * * @exception Exception if an exception occurs creating the instance */ public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception { // We only know how to deal with <code>javax.naming.Reference</code>s // that specify a class name of "javax.sql.DataSource" if ((obj == null) || !(obj instanceof Reference)) { return (null); } Reference ref = (Reference) obj; if (!"javax.sql.DataSource".equals(ref.getClassName())) { return (null); } // Create and configure a BasicDataSource instance based on the // RefAddr values associated with this Reference BasicDataSource dataSource = new BasicDataSource(); RefAddr ra = null; ra = ref.get("defaultAutoCommit"); if (ra != null) { dataSource.setDefaultAutoCommit (Boolean.valueOf(ra.getContent().toString()).booleanValue()); } ra = ref.get("defaultReadOnly"); if (ra != null) { dataSource.setDefaultReadOnly (Boolean.valueOf(ra.getContent().toString()).booleanValue()); } ra = ref.get("driverClassName"); if (ra != null) { dataSource.setDriverClassName(ra.getContent().toString()); } ra = ref.get("maxActive"); if (ra != null) { dataSource.setMaxActive (Integer.parseInt(ra.getContent().toString())); } ra = ref.get("maxIdle"); if (ra != null) { dataSource.setMaxIdle (Integer.parseInt(ra.getContent().toString())); } ra = ref.get("maxWait"); if (ra != null) { dataSource.setMaxWait (Long.parseLong(ra.getContent().toString())); } ra = ref.get("password"); if (ra != null) { dataSource.setPassword(ra.getContent().toString()); } ra = ref.get("url"); if (ra != null) { dataSource.setUrl(ra.getContent().toString()); } ra = ref.get("username"); if (ra != null) { dataSource.setUsername(ra.getContent().toString()); } ra = ref.get("validationQuery"); if (ra != null) { dataSource.setValidationQuery(ra.getContent().toString()); } ra = ref.get("removeAbandoned"); if (ra != null) { dataSource.setRemoveAbandoned (Boolean.valueOf(ra.getContent().toString()).booleanValue()); } ra = ref.get("removeAbandonedTimeout"); if (ra != null) { dataSource.setRemoveAbandonedTimeout (Integer.parseInt(ra.getContent().toString())); } ra = ref.get("logAbandoned"); if (ra != null) { dataSource.setLogAbandoned (Boolean.valueOf(ra.getContent().toString()).booleanValue()); } // Return the configured data source instance return (dataSource); } }
package org.apache.fop.render.bitmap; import java.awt.image.RenderedImage; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.batik.ext.awt.image.codec.PNGEncodeParam; import org.apache.batik.ext.awt.image.codec.PNGImageEncoder; import org.apache.fop.apps.FOPException; import org.apache.fop.area.PageViewport; import org.apache.fop.render.java2d.Java2DRenderer; /** * PNG Renderer This class actually does not render itself, instead it extends * <code>org.apache.fop.render.java2D.Java2DRenderer</code> and just encode * rendering results into PNG format using Batik's image codec */ public class PNGRenderer extends Java2DRenderer { /** The MIME type for png-Rendering */ public static final String MIME_TYPE = "image/png"; /** The file syntax prefix, eg. "page" will output "page1.png" etc */ private String filePrefix; /** The output directory where images are to be written */ private File outputDir; /** The PNGEncodeParam for the image */ private PNGEncodeParam renderParams; /** The OutputStream for the first Image */ private OutputStream firstOutputStream; /** @see org.apache.fop.render.AbstractRenderer */ public String getMimeType() { return MIME_TYPE; } /** default constructor */ public PNGRenderer() {} /** @see org.apache.fop.render.Renderer#startRenderer(java.io.OutputStream) */ public void startRenderer(OutputStream outputStream) throws IOException { getLogger().info("rendering areas to PNG"); setOutputDirectory(); this.firstOutputStream = outputStream; } /** * Sets the output directory, either from the outfile specified on the * command line, or from the directory specified in configuration file. Also * sets the file name syntax, eg. "page" */ private void setOutputDirectory() { // the file provided on the command line File f = getUserAgent().getOutputFile(); if (f == null) { //No filename information available. Only the first page will be rendered. outputDir = null; filePrefix = null; } else { outputDir = f.getParentFile(); // extracting file name syntax String s = f.getName(); int i = s.lastIndexOf("."); if (s.charAt(i - 1) == '1') { i--; // getting rid of the "1" } filePrefix = s.substring(0, i); } } public void stopRenderer() throws IOException { super.stopRenderer(); for (int i = 0; i < pageViewportList.size(); i++) { OutputStream os = getCurrentOutputStream(i); if (os == null) { getLogger().warn("No filename information available." + " Stopping early after the first page."); break; } // Do the rendering: get the image for this page RenderedImage image = (RenderedImage) getPageImage((PageViewport) pageViewportList .get(i)); // Encode this image getLogger().debug("Encoding page " + (i + 1)); renderParams = PNGEncodeParam.getDefaultEncodeParam(image); // Set resolution float pixSzMM = userAgent.getPixelUnitToMillimeter(); // num Pixs in 1 Meter int numPix = (int)((1000 / pixSzMM) + 0.5); renderParams.setPhysicalDimension(numPix, numPix, 1); // 1 means 'pix/meter' // Encode PNG image PNGImageEncoder encoder = new PNGImageEncoder(os, renderParams); encoder.encode(image); os.flush(); } } /** * Builds the OutputStream corresponding to this page * @param 0-based pageNumber * @return the corresponding OutputStream */ private OutputStream getCurrentOutputStream(int pageNumber) { if (pageNumber == 0) { return firstOutputStream; } if (filePrefix == null) { return null; } else { File f = new File(outputDir + File.separator + filePrefix + (pageNumber + 1) + ".png"); try { OutputStream os = new BufferedOutputStream(new FileOutputStream(f)); return os; } catch (FileNotFoundException e) { new FOPException("Can't build the OutputStream\n" + e); return null; } } } }
package org.jdesktop.swingx.painter; //import org.jdesktop.swingx.editors.PainterUtil; import org.jdesktop.swingx.painter.effects.AreaEffect; import javax.imageio.ImageIO; import java.awt.*; import java.awt.geom.Area; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import java.util.logging.Logger; public class ImagePainter<T> extends AbstractAreaPainter<T> { /** * Logger to use */ private static final Logger LOG = Logger.getLogger(ImagePainter.class.getName()); /** * The image to draw */ private transient BufferedImage img; private URL imageURL; private boolean horizontalRepeat; private boolean verticalRepeat; private boolean scaleToFit = false; private ScaleType scaleType = ScaleType.InsideFit; public enum ScaleType { InsideFit, OutsideFit, Distort } /** * Create a new ImagePainter. By default there is no image, and the alignment * is centered. */ public ImagePainter() { this(null); } /** * Create a new ImagePainter with the specified image and the Style * Style.CENTERED * * @param image the image to be painted */ public ImagePainter(BufferedImage image) { this(image,HorizontalAlignment.CENTER, VerticalAlignment.CENTER); } /** * Create a new ImagePainter with the specified image and alignment. * @param horizontal the horizontal alignment * @param vertical the vertical alignment * @param image the image to be painted */ public ImagePainter(BufferedImage image, HorizontalAlignment horizontal, VerticalAlignment vertical) { super(); this.img = image; this.setVerticalAlignment(vertical); this.setHorizontalAlignment(horizontal); this.setFillPaint(null); this.setBorderPaint(null); } /** * Sets the image to paint with. * @param image if null, clears the image. Otherwise, this will set the * image to be painted. */ public void setImage(BufferedImage image) { if (image != img) { Image oldImage = img; img = image; firePropertyChange("image", oldImage, img); } } /** * Gets the current image used for painting. * @return the image used for painting */ public BufferedImage getImage() { if(img == null && imageURL != null) { loadImage(); } return img; } /** * @inheritDoc */ public void doPaint(Graphics2D g, T component, int width, int height) { if (img == null && imageURL != null) { loadImage(); } Shape shape = provideShape(g, component,width,height); switch (getStyle()) { case BOTH: drawBackground(g,shape,width,height); drawBorder(g,shape,width,height); break; case FILLED: drawBackground(g,shape,width,height); break; case OUTLINE: drawBorder(g,shape,width,height); break; case NONE: break; } } private void drawBackground(Graphics2D g, Shape shape, int width, int height) { Paint p = getFillPaint(); if(p != null) { if(isPaintStretched()) { p = calculateSnappedPaint(p, width, height); } g.setPaint(p); g.fill(shape); } if(getAreaEffects() != null) { for(AreaEffect ef : getAreaEffects()) { ef.apply(g, shape, width, height); } } if (img != null) { int imgWidth = img.getWidth(null); int imgHeight = img.getHeight(null); if (imgWidth == -1 || imgHeight == -1) { //image hasn't completed loading, do nothing } else { Rectangle rect = calculateLayout(imgWidth, imgHeight, width, height); if(verticalRepeat || horizontalRepeat) { Shape oldClip = g.getClip(); Shape clip = g.getClip(); if(clip == null) { clip = new Rectangle(0,0,width,height); } Area area = new Area(clip); TexturePaint tp = new TexturePaint(img,rect); if(verticalRepeat && horizontalRepeat) { area.intersect(new Area(new Rectangle(0,0,width,height))); g.setClip(area); } else if (verticalRepeat) { area.intersect(new Area(new Rectangle(rect.x,0,rect.width,height))); g.setClip(area); } else { area.intersect(new Area(new Rectangle(0,rect.y,width,rect.height))); g.setClip(area); } g.setPaint(tp); g.fillRect(0,0,width,height); g.setClip(oldClip); } else { if(scaleToFit) { int sw = imgWidth; int sh = imgHeight; if(scaleType == scaleType.InsideFit) { if(sw > width) { float scale = (float)width/(float)sw; sw = (int)(sw * scale); sh = (int)(sh * scale); } if(sh > height) { float scale = (float)height/(float)sh; sw = (int)(sw * scale); sh = (int)(sh * scale); } } if(scaleType == ScaleType.OutsideFit) { if(sw > width) { float scale = (float)width/(float)sw; sw = (int)(sw * scale); sh = (int)(sh * scale); } if(sh < height) { float scale = (float)height/(float)sh; sw = (int)(sw * scale); sh = (int)(sh * scale); } } g.drawImage(img, 0, 0, sw, sh, null); } else { g.drawImage(img, rect.x, rect.y, rect.width, rect.height, null); } } } } } private void drawBorder(Graphics2D g, Shape shape, int width, int height) { if(getBorderPaint() != null) { g.setPaint(getBorderPaint()); g.setStroke(new BasicStroke(getBorderWidth())); g.draw(shape); } } public void setScaleToFit(boolean scaleToFit) { this.scaleToFit = scaleToFit; } private double imageScale = 1.0; /** * Sets the scaling factor used when drawing the image * @param imageScale the new image scaling factor */ public void setImageScale(double imageScale) { double old = getImageScale(); this.imageScale = imageScale; firePropertyChange("imageScale",old,this.imageScale); } /** * Gets the current scaling factor used when drawing an image. * @return the current scaling factor */ public double getImageScale() { return imageScale; } private void loadImage() { try { String img = getImageString(); // use the resolver if it's there if(img != null) { URL url = new URL(img); setImage(ImageIO.read(url)); } } catch (IOException ex) { System.out.println("ex: " + ex.getMessage()); ex.printStackTrace(); } } private String imageString; /** * Used by the persistence mechanism. */ public String getImageString() { return imageString; } /** * Used by the persistence mechanism. */ public void setImageString(String imageString) { System.out.println("setting image string to: " + imageString); String old = this.getImageString(); this.imageString = imageString; loadImage(); firePropertyChange("imageString",old,imageString); } /* public String getBaseURL() { return baseURL; } private String baseURL; public void setBaseURL(String baseURL) { this.baseURL = baseURL; }*/ /** * Indicates if the image will be repeated horizontally. * @return if the image will be repeated horizontally */ public boolean isHorizontalRepeat() { return horizontalRepeat; } /** * Sets if the image should be repeated horizontally. * @param horizontalRepeat the new horizontal repeat value */ public void setHorizontalRepeat(boolean horizontalRepeat) { boolean old = this.isHorizontalRepeat(); this.horizontalRepeat = horizontalRepeat; firePropertyChange("horizontalRepeat",old,this.horizontalRepeat); } /** * Indicates if the image will be repeated vertically. * @return if the image will be repeated vertically */ public boolean isVerticalRepeat() { return verticalRepeat; } /** * Sets if the image should be repeated vertically. * @param verticalRepeat new value for the vertical repeat */ public void setVerticalRepeat(boolean verticalRepeat) { boolean old = this.isVerticalRepeat(); this.verticalRepeat = verticalRepeat; firePropertyChange("verticalRepeat",old,this.verticalRepeat); } public Shape provideShape(Graphics2D g, T comp, int width, int height) { if(getImage() != null) { BufferedImage img = getImage(); int imgWidth = img.getWidth(); int imgHeight = img.getHeight(); return calculateLayout(imgWidth, imgHeight, width, height); } return new Rectangle(0,0,0,0); } public ScaleType getScaleType() { return scaleType; } public void setScaleType(ScaleType scaleType) { this.scaleType = scaleType; } }
/** * VelocimacroManager.java * * manages VMs in namespaces. Currently, there are two namespace modes * supported : * <ul> * <li> flat namespace : all allowable VMs are in the global namespace * <li> local namespace : inline VMs are added to it's own template namespace * </ul> * * Thanks to <a href="mailto:JFernandez@viquity.com">Jose Alberto Fernandez</a> * for some ideas incorporated here. * * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a> * @author <a href="mailto:JFernandez@viquity.com">Jose Alberto Fernandez</a> * @version $Id: VelocimacroManager.java,v 1.4 2000/12/12 02:04:36 geirm Exp $ */ package org.apache.velocity.runtime; import java.util.Hashtable; import java.util.TreeMap; import org.apache.velocity.runtime.directive.Directive; import org.apache.velocity.runtime.directive.VelocimacroProxy; import org.apache.velocity.Template; public class VelocimacroManager { private static String GLOBAL_NAMESPACE = ""; /* hash of namespace hashes */ private Hashtable namespaceHash = new Hashtable(); /* big switch for namespaces. If true, then properties control usage. If false, no. */ private boolean namespacesOn = true; private boolean inlineLocalMode = false; /** * not much to do but add the global namespace to the hash */ VelocimacroManager() { /* * add the global namespace to the namespace hash. We always have that. */ addNamespace( GLOBAL_NAMESPACE ); } /** * adds a VM definition to the cache * @return boolean if all went ok */ public boolean addVM(String vmName, String macroBody, String argArray[],String macroArray[], TreeMap argIndexMap, String namespace ) { MacroEntry me = new MacroEntry( vmName, macroBody, argArray, macroArray, argIndexMap, namespace ); if ( usingNamespaces( namespace ) ) { /* * first, do we have a namespace hash already for this namespace? * if not, add it to the namespaces, and add the VM */ Hashtable local = getNamespace( namespace, true ); local.put( (String) vmName, me ); return true; } else { /* * otherwise, add to global template */ (getNamespace( GLOBAL_NAMESPACE )).put( vmName, me ); return true; } } /** * gets a new living VelocimacroProxy object by the name / source template duple */ public VelocimacroProxy get( String vmName, String namespace ) { if ( usingNamespaces( namespace ) ) { Hashtable local = getNamespace( namespace, false ); /* * if we have macros defined for this template */ if ( local != null) { MacroEntry me = (MacroEntry) local.get( vmName ); if (me != null) return me.createVelocimacro(); } } /* * if we didn't return from there, we need to simply see if it's in the global namespace */ MacroEntry me = (MacroEntry) (getNamespace( GLOBAL_NAMESPACE )).get( vmName ); if (me != null) return me.createVelocimacro(); return null; } /** * removes the VMs and the namespace from the manager. Used when a template is reloaded * to avoid accumulating drek * * @param namespace namespace to dump * @return boolean representing success */ public boolean dumpNamespace( String namespace ) { synchronized( this ) { if (usingNamespaces( namespace ) ) { Hashtable h = (Hashtable) namespaceHash.remove( namespace ); if ( h == null ) return false; h.clear(); return true; } return false; } } /** * public switch to let external user of manager to control namespace * usage indep of properties. That way, for example, at startup the * library files are loaded into global namespace */ public void setNamespaceUsage( boolean b ) { namespacesOn = b; return; } public void setTemplateLocalInlineVM( boolean b ) { inlineLocalMode = b; } /** * returns the hash for the specified namespace. Will not create a new one * if it doesn't exist * * @param namespace name of the namespace :) * @return namespace Hashtable of VMs or null if doesn't exist */ private Hashtable getNamespace( String namespace ) { return getNamespace( namespace, false ); } /** * returns the hash for the specified namespace, and if it doesn't exist * will create a new one and add it to the namespaces * * @param namespace name of the namespace :) * @param addIfNew flag to add a new namespace if it doesn't exist * @return namespace Hashtable of VMs or null if doesn't exist */ private Hashtable getNamespace( String namespace, boolean addIfNew ) { Hashtable h = (Hashtable) namespaceHash.get( namespace ); if (h == null && addIfNew) h = addNamespace( namespace ); return h; } /** * adds a namespace to the namespaces * * @param namespace name of namespace to add * @return Hash added to namespaces, ready for use */ private Hashtable addNamespace( String namespace ) { Hashtable h = new Hashtable(); Object oh; if ((oh = namespaceHash.put( namespace, h )) != null) { /* * There was already an entry on the table, restore it! * This condition should never occur, given the code * and the fact that this method is private. * But just in case, this way of testing for it is much * more efficient than testing before hand using get(). */ namespaceHash.put( namespace, oh ); /* * Should't we be returning the old entry (oh)? * The previous code was just returning null in this case. */ return null; } return h; } /** * determines if currently using namespaces. * * @param namespace currently ignored * @return true if using namespaces, false if not */ private boolean usingNamespaces( String namespace ) { /* * if the big switch turns of namespaces, then ignore the rules */ if ( !namespacesOn ) return false; /* * currently, we only support the local template namespace idea */ if ( inlineLocalMode ) return true; return false; } /** * wrapper class for holding VM information */ protected class MacroEntry { String macroname; String[] argarray; String[] macroarray; TreeMap indexmap; String macrobody; String sourcetemplate; MacroEntry(String vmName, String macroBody, String argArray[], String macroArray[], TreeMap argIndexMap, String sourceTemplate) { this.macroname = vmName; this.argarray = argArray; this.macroarray = macroArray; this.indexmap = argIndexMap; this.macrobody = macroBody; this.sourcetemplate = sourceTemplate; } VelocimacroProxy createVelocimacro() { VelocimacroProxy vp = new VelocimacroProxy(); vp.setName( this.macroname ); vp.setArgArray( this.argarray ); vp.setMacroArray( this.macroarray ); vp.setArgIndexMap( this.indexmap ); vp.setMacrobody( this.macrobody ); return vp; } } }
package org.concord.otrunk.view.document; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.concord.framework.otrunk.OTID; import org.concord.framework.otrunk.OTObject; import org.concord.framework.otrunk.OTObjectList; import org.concord.framework.otrunk.OTObjectService; import org.concord.framework.otrunk.OTXMLString; import org.concord.otrunk.view.OTFolderObject; /** * @author scott * * TODO To change the template for this generated type comment go to Window - * Preferences - Java - Code Generation - Code and Comments */ public class OTCompoundDoc extends OTFolderObject implements OTDocument { public static interface ResourceSchema extends OTFolderObject.ResourceSchema { public OTXMLString getBodyText(); public void setBodyText(OTXMLString text); public static boolean DEFAULT_input = true; public boolean getInput(); public void setInput(boolean flag); public OTObjectList getDocumentRefs(); public void setDocumentRefs(OTObjectList list); public String getMarkupLanguage(); public void setMarkupLanguage(String lang); } private ResourceSchema resources; public OTCompoundDoc(ResourceSchema resources) { super(resources); this.resources = resources; } /* * (non-Javadoc) * * @see org.concord.portfolio.PortfolioObject#getBodyText() */ public String getBodyText() { OTXMLString xmlString = resources.getBodyText(); if (xmlString == null) { return null; } return xmlString.getContent(); } public boolean getInput() { // How do we set default values for primitives... return resources.getInput(); } public void setInput(boolean flag) { resources.setInput(flag); } public void addDocumentReference(OTObject pfObject) { OTObjectList embedded = resources.getDocumentRefs(); embedded.add(pfObject); } public void addDocumentReference(OTID embeddedId) { OTObjectList embedded = resources.getDocumentRefs(); embedded.add(embeddedId); } /** * Returns the list of objects that are actually referenced in the body * text. Not to be confused with getDocumentRefs() in the resource schema. * * If it finds a referenced object that was not already specified in the * DocumentRefs, it adds it to the list. * * TODO: This method should be renamed to getReferencedObjects() or * something like that * * @return */ public Vector getDocumentRefs() { String bodyText = getBodyText(); if (bodyText != null) { Pattern p = Pattern.compile("<object refid=\"([^\"]*)\"[^>]*>"); Matcher m = p.matcher(bodyText); while (m.find()) { String idStr = m.group(1); OTID id = getReferencedId(idStr); OTObject obj = getReferencedObject(id); if (obj != null) addDocumentReference(obj); } p = Pattern.compile("<a href=\"([^\"]*)\"[^>]*>"); m = p.matcher(bodyText); while (m.find()) { String idStr = m.group(1); if (!(idStr.startsWith("http:") || idStr.startsWith("file:") || idStr .startsWith("https:"))) { OTID id = getReferencedId(idStr); OTObject obj = getReferencedObject(id); if (obj != null) addDocumentReference(obj); } } } return resources.getDocumentRefs().getVector(); } public OTObjectList getDocumentRefsAsObjectList(){ return resources.getDocumentRefs(); } public void removeAllDocumentReference() { OTObjectList embedded = resources.getDocumentRefs(); embedded.removeAll(); } public String getDocumentText() { return getBodyText(); } public void setDocumentText(String text) { setBodyText(text); } /* * (non-Javadoc) * * @see org.concord.portfolio.objects.PfTextObject#setBodyText(java.lang.String) */ public void setBodyText(String bodyText) { OTXMLString xmlString = new OTXMLString(bodyText); resources.setBodyText(xmlString); removeAllDocumentReference(); // pattern to match the whole body of a resource file. // this should match the object tag not the format of the // reference, but currently objects can be referenced in links // and in objects. And there can be viewEntry references // So this pattern will match any uuid that starts with quotes // and then grab everything after that to the end quote Pattern p = Pattern .compile("\"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}[^\"]*)\""); Matcher m = p.matcher(bodyText); while (m.find()) { String idStr = m.group(1); OTID id = getReferencedId(idStr); addDocumentReference(id); } } public void setMarkupLanguage(String lang) { resources.setMarkupLanguage(lang); } public String getMarkupLanguage() { return resources.getMarkupLanguage(); } public OTObjectService getOTObjectService() { return resources.getOTObjectService(); } }
package org.jivesoftware.wildfire.spi; import org.jivesoftware.wildfire.*; import org.jivesoftware.wildfire.component.InternalComponentManager; import org.jivesoftware.wildfire.container.BasicModule; import org.jivesoftware.wildfire.server.OutgoingSessionPromise; import org.jivesoftware.util.Log; import org.xmpp.packet.JID; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * <p>Uses simple hashtables for table storage.</p> * <p>Leaves in the tree are indicated by a PacketHandler, while branches are stored in hashtables. * Traverse the tree according to an XMPPAddress' fields (host -> name -> resource) and when you * hit a PacketHandler, you have found the handler for that node and all sub-nodes. </p> * * @author Iain Shigeoka */ public class RoutingTableImpl extends BasicModule implements RoutingTable { /** * We need a three level tree built of hashtables: host -> name -> resource */ private Map routes = new ConcurrentHashMap(); /** * locks access to the routing tale */ private ReadWriteLock routeLock = new ReentrantReadWriteLock(); private String serverName; private InternalComponentManager componentManager; public RoutingTableImpl() { super("Routing table"); componentManager = InternalComponentManager.getInstance(); } public void addRoute(JID node, RoutableChannelHandler destination) { String nodeJID = node.getNode() == null ? "" : node.getNode(); String resourceJID = node.getResource() == null ? "" : node.getResource(); routeLock.writeLock().lock(); try { if (destination instanceof ClientSession) { Object nameRoutes = routes.get(node.getDomain()); if (nameRoutes == null) { nameRoutes = new Hashtable(); routes.put(node.getDomain(), nameRoutes); } Object resourceRoutes = ((Hashtable)nameRoutes).get(nodeJID); if (resourceRoutes == null) { resourceRoutes = new Hashtable(); ((Hashtable)nameRoutes).put(nodeJID, resourceRoutes); } ((Hashtable)resourceRoutes).put(resourceJID, destination); } else { routes.put(node.getDomain(), destination); } } finally { routeLock.writeLock().unlock(); } } public RoutableChannelHandler getRoute(JID node) { if (node == null) { return null; } return getRoute(node.toString(), node.getNode() == null ? "" : node.getNode(), node.getDomain(), node.getResource() == null ? "" : node.getResource()); } private RoutableChannelHandler getRoute(String jid, String node, String domain, String resource) { RoutableChannelHandler route = null; // Check if the address belongs to a remote server if (!serverName.equals(domain) && routes.get(domain) == null && componentManager.getComponent(domain) == null) { // Return a promise of a remote session. This object will queue packets pending // to be sent to remote servers return OutgoingSessionPromise.getInstance(); } routeLock.readLock().lock(); try { Object nameRoutes = routes.get(domain); if (nameRoutes instanceof ChannelHandler) { route = (RoutableChannelHandler)nameRoutes; } else if (nameRoutes != null) { Object resourceRoutes = ((Hashtable)nameRoutes).get(node); if (resourceRoutes instanceof ChannelHandler) { route = (RoutableChannelHandler)resourceRoutes; } else if (resourceRoutes != null) { route = (RoutableChannelHandler) ((Hashtable)resourceRoutes).get(resource); } else { route = null; } } } catch (Exception e) { if (Log.isDebugEnabled()) { Log.debug("Route not found for JID: "+ jid, e); } } finally { routeLock.readLock().unlock(); } return route; } public Iterator getRoutes(JID node) { // Check if the address belongs to a remote server if (!serverName.equals(node.getDomain()) && routes.get(node.getDomain()) == null && componentManager.getComponent(node.getDomain()) == null) { // Return a promise of a remote session. This object will queue packets pending // to be sent to remote servers return Arrays.asList(OutgoingSessionPromise.getInstance()).iterator(); } LinkedList list = null; routeLock.readLock().lock(); try { if (node == null || node.getDomain() == null) { list = new LinkedList(); getRoutes(list, routes); } else { Object nameRoutes = routes.get(node.getDomain()); if (nameRoutes != null) { if (nameRoutes instanceof ChannelHandler) { list = new LinkedList(); list.add(nameRoutes); } else if (node.getNode() == null) { list = new LinkedList(); getRoutes(list, (Hashtable)nameRoutes); } else { Object resourceRoutes = ((Hashtable)nameRoutes).get(node.getNode()); if (resourceRoutes != null) { if (resourceRoutes instanceof ChannelHandler) { list = new LinkedList(); list.add(resourceRoutes); } else if (node.getResource() == null || node.getResource().length() == 0) { list = new LinkedList(); getRoutes(list, (Hashtable)resourceRoutes); } else { Object entry = ((Hashtable)resourceRoutes).get(node.getResource()); if (entry != null) { list = new LinkedList(); list.add(entry); } } } } } } } finally { routeLock.readLock().unlock(); } if (list == null) { return Collections.EMPTY_LIST.iterator(); } else { return list.iterator(); } } /** * <p>Recursive method to iterate through the given table (and any embedded tables) * and stuff non-Hashtable values into the given list.</p> * <p>There should be no recursion problems since * the routing table is at most 3 levels deep.</p> * * @param list The list to stuff entries into * @param table The hashtable who's values should be entered into the list */ private void getRoutes(LinkedList list, Map table) { Iterator entryIter = table.values().iterator(); while (entryIter.hasNext()) { Object entry = entryIter.next(); if (entry instanceof Hashtable) { getRoutes(list, (Hashtable)entry); } else { // Do not include the same entry many times. This could be the case when the same // session is associated with the bareJID and with a given resource if (!list.contains(entry)) { list.add(entry); } } } } public ChannelHandler getBestRoute(JID node) { ChannelHandler route = route = getRoute(node); if (route == null) { // Try looking for a route based on the bare JID String nodeJID = node.getNode() == null ? "" : node.getNode(); route = getRoute(node.toBareJID(), nodeJID, node.getDomain(), ""); } return route; } public ChannelHandler removeRoute(JID node) { ChannelHandler route = null; String nodeJID = node.getNode() == null ? "" : node.getNode(); String resourceJID = node.getResource() == null ? "" : node.getResource(); routeLock.writeLock().lock(); try { Object nameRoutes = routes.get(node.getDomain()); if (nameRoutes instanceof Hashtable) { Object resourceRoutes = ((Hashtable)nameRoutes).get(nodeJID); if (resourceRoutes instanceof Hashtable) { // Remove the requested resource for this user route = (ChannelHandler) ((Hashtable)resourceRoutes).remove(resourceJID); if (((Hashtable)resourceRoutes).isEmpty()) { ((Hashtable)nameRoutes).remove(nodeJID); if (((Hashtable)nameRoutes).isEmpty()) { routes.remove(node.getDomain()); } } } else { // Remove the unique route to this node ((Hashtable)nameRoutes).remove(nodeJID); } } else if (nameRoutes != null) { // The retrieved route points to a RoutableChannelHandler if (("".equals(nodeJID) && "".equals(resourceJID)) || ((RoutableChannelHandler) nameRoutes).getAddress().equals(node)) { // Remove the route to this domain routes.remove(node.getDomain()); } } } catch (Exception e) { Log.error("Error removing route", e); } finally { routeLock.writeLock().unlock(); } return route; } public void initialize(XMPPServer server) { super.initialize(server); serverName = server.getServerInfo().getName(); } }
package org.orbeon.oxf.xforms.processor; import org.dom4j.QName; import org.orbeon.oxf.xforms.StaticStateGlobalOps; import org.orbeon.oxf.xforms.XFormsConstants; import java.util.ArrayList; import java.util.List; public class XFormsFeatures { private static final ResourceConfig[] stylesheets = { // Standard CSS new ResourceConfig("/ops/yui/container/assets/skins/sam/container.css", null), new ResourceConfig("/ops/yui/progressbar/assets/skins/sam/progressbar.css", null), // Calendar CSS new ResourceConfig("/ops/yui/calendar/assets/skins/sam/calendar.css", null), // Yahoo! UI Library new ResourceConfig("/ops/yui/treeview/assets/skins/sam/treeview.css", null) { public boolean isInUse(StaticStateGlobalOps staticStateGlobalOps) { return isTreeInUse(staticStateGlobalOps); } }, new ResourceConfig("/ops/yui/examples/treeview/assets/css/check/tree.css", null) { public boolean isInUse(StaticStateGlobalOps staticStateGlobalOps) { return isTreeInUse(staticStateGlobalOps); } }, new ResourceConfig("/ops/yui/menu/assets/skins/sam/menu.css", null) { public boolean isInUse(StaticStateGlobalOps staticStateGlobalOps) { return isMenuInUse(staticStateGlobalOps) || isYUIRTEInUse(staticStateGlobalOps); } }, // HTML area new ResourceConfig("/ops/yui/editor/assets/skins/sam/editor.css", null) { public boolean isInUse(StaticStateGlobalOps staticStateGlobalOps) { return isYUIRTEInUse(staticStateGlobalOps); } }, new ResourceConfig("/ops/yui/button/assets/skins/sam/button.css", null) { public boolean isInUse(StaticStateGlobalOps staticStateGlobalOps) { return isYUIRTEInUse(staticStateGlobalOps); } }, // Other standard stylesheets new ResourceConfig("/config/theme/xforms.css", null), new ResourceConfig("/config/theme/error.css", null) }; private static final ResourceConfig[] scripts = { // Yahoo UI Library new ResourceConfig("/ops/yui/yahoo/yahoo.js", "/ops/yui/yahoo/yahoo-min.js"), new ResourceConfig("/ops/yui/event/event.js", "/ops/yui/event/event-min.js"), new ResourceConfig("/ops/yui/dom/dom.js", "/ops/yui/dom/dom-min.js"), new ResourceConfig("/ops/yui/connection/connection.js", "/ops/yui/connection/connection-min.js"), new ResourceConfig("/ops/yui/element/element.js", "/ops/yui/element/element-min.js"), new ResourceConfig("/ops/yui/animation/animation.js", "/ops/yui/animation/animation-min.js"), new ResourceConfig("/ops/yui/progressbar/progressbar.js", "/ops/yui/progressbar/progressbar-min.js"), new ResourceConfig("/ops/yui/dragdrop/dragdrop.js", "/ops/yui/dragdrop/dragdrop-min.js"), new ResourceConfig("/ops/yui/container/container.js", "/ops/yui/container/container-min.js"), new ResourceConfig("/ops/yui/examples/container/assets/containerariaplugin.js", "/ops/yui/examples/container/assets/containerariaplugin-min.js"), new ResourceConfig("/ops/yui/calendar/calendar.js", "/ops/yui/calendar/calendar-min.js"), new ResourceConfig("/ops/yui/slider/slider.js", "/ops/yui/slider/slider-min.js") { public boolean isInUse(StaticStateGlobalOps staticStateGlobalOps) { return isRangeInUse(staticStateGlobalOps); } }, new ResourceConfig("/ops/yui/treeview/treeview.js", "/ops/yui/treeview/treeview-min.js") { public boolean isInUse(StaticStateGlobalOps staticStateGlobalOps) { return isTreeInUse(staticStateGlobalOps); } }, new ResourceConfig("/ops/yui/examples/treeview/assets/js/TaskNode.js", "/ops/yui/examples/treeview/assets/js/TaskNode-min.js") { public boolean isInUse(StaticStateGlobalOps staticStateGlobalOps) { return isTreeInUse(staticStateGlobalOps); } }, new ResourceConfig("/ops/yui/menu/menu.js", "/ops/yui/menu/menu-min.js") { public boolean isInUse(StaticStateGlobalOps staticStateGlobalOps) { return isMenuInUse(staticStateGlobalOps) || isYUIRTEInUse(staticStateGlobalOps); } }, // HTML area new ResourceConfig("/ops/yui/button/button.js", "/ops/yui/button/button-min.js") { public boolean isInUse(StaticStateGlobalOps staticStateGlobalOps) { return isYUIRTEInUse(staticStateGlobalOps); } }, new ResourceConfig("/ops/yui/editor/editor.js", "/ops/yui/editor/editor-min.js") { public boolean isInUse(StaticStateGlobalOps staticStateGlobalOps) { return isYUIRTEInUse(staticStateGlobalOps); } }, // Underscore library new ResourceConfig("/ops/javascript/underscore/underscore.js", "/ops/javascript/underscore/underscore-min.js"), // XForms client new ResourceConfig("/ops/javascript/xforms.js", "/ops/javascript/xforms-min.js"), new ResourceConfig("/ops/javascript/orbeon/util/ExecutionQueue.js", "/ops/javascript/orbeon/util/ExecutionQueue-min.js"), new ResourceConfig("/ops/javascript/orbeon/xforms/server/Server.js", "/ops/javascript/orbeon/xforms/server/Server-min.js"), new ResourceConfig("/ops/javascript/orbeon/xforms/server/AjaxServer.js", "/ops/javascript/orbeon/xforms/server/AjaxServer-min.js"), new ResourceConfig("/ops/javascript/orbeon/xforms/server/UploadServer.js", "/ops/javascript/orbeon/xforms/server/UploadServer-min.js"), new ResourceConfig("/ops/javascript/orbeon/xforms/LoadingIndicator.js", "/ops/javascript/orbeon/xforms/LoadingIndicator-min.js"), new ResourceConfig("/ops/javascript/orbeon/xforms/Form.js", "/ops/javascript/orbeon/xforms/Form-min.js"), new ResourceConfig("/ops/javascript/orbeon/xforms/Page.js", "/ops/javascript/orbeon/xforms/Page-min.js"), new ResourceConfig("/ops/javascript/orbeon/xforms/control/Control.js", "/ops/javascript/orbeon/xforms/control/Control-min.js"), new ResourceConfig("/ops/javascript/orbeon/xforms/control/CalendarResources.js", "/ops/javascript/orbeon/xforms/control/CalendarResources-min.js"), new ResourceConfig("/ops/javascript/orbeon/xforms/control/Calendar.js", "/ops/javascript/orbeon/xforms/control/Calendar-min.js"), new ResourceConfig("/ops/javascript/orbeon/xforms/control/Upload.js", "/ops/javascript/orbeon/xforms/control/Upload-min.js"), new ResourceConfig("/ops/javascript/orbeon/xforms/control/RTEConfig.js", "/ops/javascript/orbeon/xforms/control/RTEConfig-min.js"), new ResourceConfig("/ops/javascript/orbeon/xforms/control/RTE.js", "/ops/javascript/orbeon/xforms/control/RTE-min.js"), new ResourceConfig("/ops/javascript/orbeon/xforms/control/Tree.js", "/ops/javascript/orbeon/xforms/control/Tree-min.js"), new ResourceConfig("/ops/javascript/orbeon/xforms/action/Message.js", "/ops/javascript/orbeon/xforms/action/Message-min.js") }; public static class ResourceConfig { private String fullResource; private String minResource; public ResourceConfig(String fullResource, String minResource) { this.fullResource = fullResource; this.minResource = minResource; } public String getResourcePath(boolean tryMinimal) { // Load minimal resource if requested and there exists a minimal resource return (tryMinimal && minResource != null) ? minResource : fullResource; } public boolean isInUse(StaticStateGlobalOps staticStateGlobalOps) { // Default to true but can be overridden return true; } public boolean isInUse(StaticStateGlobalOps staticStateGlobalOps, String controlName) { return staticStateGlobalOps != null && staticStateGlobalOps.hasControlByName(controlName); } public boolean isInUse(StaticStateGlobalOps staticStateGlobalOps, String controlName, QName appearanceOrMediatypeName) { return staticStateGlobalOps != null && staticStateGlobalOps.hasControlAppearance(controlName, appearanceOrMediatypeName); } protected boolean isRangeInUse(StaticStateGlobalOps staticStateGlobalOps) { return isInUse(staticStateGlobalOps, "range"); } protected boolean isTreeInUse(StaticStateGlobalOps staticStateGlobalOps) { return isInUse(staticStateGlobalOps, "select1", XFormsConstants.XXFORMS_TREE_APPEARANCE_QNAME) || isInUse(staticStateGlobalOps, "select", XFormsConstants.XXFORMS_TREE_APPEARANCE_QNAME); } protected boolean isMenuInUse(StaticStateGlobalOps staticStateGlobalOps) { return isInUse(staticStateGlobalOps, "select1", XFormsConstants.XXFORMS_MENU_APPEARANCE_QNAME) || isInUse(staticStateGlobalOps, "select", XFormsConstants.XXFORMS_MENU_APPEARANCE_QNAME); } private boolean isHtmlAreaInUse(StaticStateGlobalOps staticStateGlobalOps) { return isInUse(staticStateGlobalOps, "textarea", XFormsConstants.XXFORMS_RICH_TEXT_APPEARANCE_QNAME); } protected boolean isYUIRTEInUse(StaticStateGlobalOps staticStateGlobalOps) { return isHtmlAreaInUse(staticStateGlobalOps); } } public static List<ResourceConfig> getCSSResources(StaticStateGlobalOps staticStateGlobalOps) { final List<ResourceConfig> result = new ArrayList<ResourceConfig>(); for (final ResourceConfig resourceConfig: stylesheets) { if (resourceConfig.isInUse(staticStateGlobalOps)) { // Only include stylesheet if needed result.add(resourceConfig); } } return result; } public static List<ResourceConfig> getJavaScriptResources(StaticStateGlobalOps staticStateGlobalOps) { final List<ResourceConfig> result = new ArrayList<ResourceConfig>(); for (final ResourceConfig resourceConfig: scripts) { if (resourceConfig.isInUse(staticStateGlobalOps)) { // Only include script if needed result.add(resourceConfig); } } return result; } private static final ResourceConfig[] asyncPortletLoadScripts = { new ResourceConfig("/ops/javascript/underscore/underscore.js", "/ops/javascript/underscore/underscore-min.js"), new ResourceConfig("/ops/yui/yahoo/yahoo.js", "/ops/yui/yahoo/yahoo-min.js"), new ResourceConfig("/ops/yui/event/event.js", "/ops/yui/event/event-min.js"), new ResourceConfig("/ops/yui/dom/dom.js", "/ops/yui/dom/dom-min.js"), new ResourceConfig("/ops/yui/connection/connection.js", "/ops/yui/connection/connection-min.js"), new ResourceConfig("/ops/yui/get/get.js", "/ops/yui/get/get-min.js"), new ResourceConfig("/ops/yui/stylesheet/stylesheet.js", "/ops/yui/stylesheet/stylesheet-min.js"), new ResourceConfig("/ops/javascript/orbeon/util/DeferredPortletLoader.js", "/ops/javascript/orbeon/util/DeferredPortletLoader-min.js") }; public static ResourceConfig[] getAsyncPortletLoadScripts() { return asyncPortletLoadScripts; } }
package jsettlers.buildingcreator.editor.map; import jsettlers.common.buildings.EBuildingType; import jsettlers.common.buildings.IBuilding; import jsettlers.common.position.ISPosition2D; public class PseudoBuilding implements IBuilding { private final EBuildingType type; private final ISPosition2D pos; PseudoBuilding(EBuildingType type, ISPosition2D pos) { this.type = type; this.pos = pos; } @Override public int getActionImgIdx() { return 0; } @Override public EBuildingType getBuildingType() { return type; } @Override public float getStateProgress() { return 1; } @Override public ISPosition2D getPos() { return pos; } @Override public boolean isOccupied() { return true; } @Override public byte getPlayer() { return 0; } @Override public boolean isSelected() { return false; } @Override public void setSelected(boolean b) { } @Override public void stopOrStartWorking(boolean stop) { } }
package at.ac.tuwien.inso.service; import org.springframework.security.access.prepost.PreAuthorize; import at.ac.tuwien.inso.entity.*; import java.util.*; public interface SemesterService { @PreAuthorize("hasRole('ADMIN')") Semester create(Semester semester); @PreAuthorize("isAuthenticated()") Semester getCurrentSemester(); @PreAuthorize("isAuthenticated()") List<Semester> findAll(); }
package bdv.viewer.render; import java.awt.image.BufferedImage; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.concurrent.ExecutorService; import bdv.cache.CacheControl; import bdv.img.cache.VolatileCachedCellImg; import bdv.viewer.Interpolation; import bdv.viewer.Source; import bdv.viewer.render.MipmapOrdering.Level; import bdv.viewer.render.MipmapOrdering.MipmapHints; import bdv.viewer.state.SourceState; import bdv.viewer.state.ViewerState; import net.imglib2.Dimensions; import net.imglib2.RandomAccess; import net.imglib2.RandomAccessible; import net.imglib2.RandomAccessibleInterval; import net.imglib2.RealRandomAccessible; import net.imglib2.Volatile; import net.imglib2.cache.iotiming.CacheIoTiming; import net.imglib2.cache.volatiles.CacheHints; import net.imglib2.cache.volatiles.LoadingStrategy; import net.imglib2.converter.Converter; import net.imglib2.display.screenimage.awt.ARGBScreenImage; import net.imglib2.realtransform.AffineTransform3D; import net.imglib2.realtransform.RealViews; import net.imglib2.type.numeric.ARGBType; import net.imglib2.ui.PainterThread; import net.imglib2.ui.RenderTarget; import net.imglib2.ui.Renderer; import net.imglib2.ui.SimpleInterruptibleProjector; import net.imglib2.ui.TransformListener; import net.imglib2.ui.util.GuiUtil; /** * A {@link Renderer} that uses a coarse-to-fine rendering scheme. First, a * small {@link BufferedImage} at a fraction of the canvas resolution is * rendered. Then, increasingly larger images are rendered, until the full * canvas resolution is reached. * <p> * When drawing the low-resolution {@link BufferedImage} to the screen, they * will be scaled up by Java2D to the full canvas size, which is relatively * fast. Rendering the small, low-resolution images is usually very fast, such * that the display is very interactive while the user changes the viewing * transformation for example. When the transformation remains fixed for a * longer period, higher-resolution details are filled in successively. * <p> * The renderer allocates a {@link BufferedImage} for each of a predefined set * of <em>screen scales</em> (a screen scale of 1 means that 1 pixel in the * screen image is displayed as 1 pixel on the canvas, a screen scale of 0.5 * means 1 pixel in the screen image is displayed as 2 pixel on the canvas, * etc.) * <p> * At any time, one of these screen scales is selected as the * <em>highest screen scale</em>. Rendering starts with this highest screen * scale and then proceeds to lower screen scales (higher resolution images). * Unless the highest screen scale is currently rendering, * {@link #requestRepaint() repaint request} will cancel rendering, such that * display remains interactive. * <p> * The renderer tries to maintain a per-frame rendering time close to a desired * number of <code>targetRenderNanos</code> nanoseconds. If the rendering time * (in nanoseconds) for the (currently) highest scaled screen image is above * this threshold, a coarser screen scale is chosen as the highest screen scale * to use. Similarly, if the rendering time for the (currently) second-highest * scaled screen image is below this threshold, this finer screen scale chosen * as the highest screen scale to use. * <p> * The renderer uses multiple threads (if desired) and double-buffering (if * desired). * <p> * Double buffering means that three {@link BufferedImage BufferedImages} are * created for every screen scale. After rendering the first one of them and * setting it to the {@link RenderTarget}, next time, rendering goes to the * second one, then to the third. The {@link RenderTarget} will always have a * complete image, which is not rendered to while it is potentially drawn to the * screen. When setting an image to the {@link RenderTarget}, the * {@link RenderTarget} will release one of the previously set images to be * rendered again. Thus, rendering will not interfere with painting the * {@link BufferedImage} to the canvas. * <p> * The renderer supports rendering of {@link Volatile} sources. In each * rendering pass, all currently valid data for the best fitting mipmap level * and all coarser levels is rendered to a {@link #renderImages temporary image} * for each visible source. Then the temporary images are combined to the final * image for display. The number of passes required until all data is valid * might differ between visible sources. * <p> * Rendering timing is tied to a {@link CacheControl} control for IO budgeting, etc. * * @author Tobias Pietzsch &lt;tobias.pietzsch@gmail.com&gt; */ public class MultiResolutionRenderer { /** * Receiver for the {@link BufferedImage BufferedImages} that we render. */ protected final TransformAwareRenderTarget display; /** * Thread that triggers repainting of the display. * Requests for repainting are send there. */ protected final PainterThread painterThread; /** * Currently active projector, used to re-paint the display. It maps the * source data to {@link #screenImages}. */ protected VolatileProjector projector; /** * The index of the screen scale of the {@link #projector current projector}. */ protected int currentScreenScaleIndex; /** * Whether double buffering is used. */ protected final boolean doubleBuffered; /** * Double-buffer index of next {@link #screenImages image} to render. */ protected final ArrayDeque< Integer > renderIdQueue; /** * Maps from {@link BufferedImage} to double-buffer index. * Needed for double-buffering. */ protected final HashMap< BufferedImage, Integer > bufferedImageToRenderId; /** * Used to render an individual source. One image per screen resolution and * visible source. First index is screen scale, second index is index in * list of visible sources. */ protected ARGBScreenImage[][] renderImages; /** * Storage for mask images of {@link VolatileHierarchyProjector}. * One array per visible source. (First) index is index in list of visible sources. */ protected byte[][] renderMaskArrays; /** * Used to render the image for display. Three images per screen resolution * if double buffering is enabled. First index is screen scale, second index * is double-buffer. */ protected ARGBScreenImage[][] screenImages; /** * {@link BufferedImage}s wrapping the data in the {@link #screenImages}. * First index is screen scale, second index is double-buffer. */ protected BufferedImage[][] bufferedImages; /** * Scale factors from the {@link #display viewer canvas} to the * {@link #screenImages}. * * A scale factor of 1 means 1 pixel in the screen image is displayed as 1 * pixel on the canvas, a scale factor of 0.5 means 1 pixel in the screen * image is displayed as 2 pixel on the canvas, etc. */ protected final double[] screenScales; /** * The scale transformation from viewer to {@link #screenImages screen * image}. Each transformations corresponds to a {@link #screenScales screen * scale}. */ protected AffineTransform3D[] screenScaleTransforms; /** * If the rendering time (in nanoseconds) for the (currently) highest scaled * screen image is above this threshold, increase the * {@link #maxScreenScaleIndex index} of the highest screen scale to use. * Similarly, if the rendering time for the (currently) second-highest * scaled screen image is below this threshold, decrease the * {@link #maxScreenScaleIndex index} of the highest screen scale to use. */ protected final long targetRenderNanos; /** * The index of the (coarsest) screen scale with which to start rendering. * Once this level is painted, rendering proceeds to lower screen scales * until index 0 (full resolution) has been reached. While rendering, the * maxScreenScaleIndex is adapted such that it is the highest index for * which rendering in {@link #targetRenderNanos} nanoseconds is still * possible. */ protected int maxScreenScaleIndex; /** * The index of the screen scale which should be rendered next. */ protected int requestedScreenScaleIndex; /** * Whether the current rendering operation may be cancelled (to start a * new one). Rendering may be cancelled unless we are rendering at * coarsest screen scale and coarsest mipmap level. */ protected volatile boolean renderingMayBeCancelled; /** * How many threads to use for rendering. */ protected final int numRenderingThreads; /** * {@link ExecutorService} used for rendering. */ protected final ExecutorService renderingExecutorService; /** * TODO */ protected final AccumulateProjectorFactory< ARGBType > accumulateProjectorFactory; /** * Controls IO budgeting and fetcher queue. */ protected final CacheControl cacheControl; /** * Whether volatile versions of sources should be used if available. */ protected final boolean useVolatileIfAvailable; /** * Whether a repaint was {@link #requestRepaint() requested}. This will * cause {@link CacheControl#prepareNextFrame()}. */ protected boolean newFrameRequest; /** * The timepoint for which last a projector was * {@link #createProjector(ViewerState, ARGBScreenImage) created}. */ protected int previousTimepoint; // TODO: should be settable protected long[] iobudget = new long[] { 100l * 1000000l, 10l * 1000000l }; // TODO: should be settable protected boolean prefetchCells = true; /** * @param display * The canvas that will display the images we render. * @param painterThread * Thread that triggers repainting of the display. Requests for * repainting are send there. * @param screenScales * Scale factors from the viewer canvas to screen images of * different resolutions. A scale factor of 1 means 1 pixel in * the screen image is displayed as 1 pixel on the canvas, a * scale factor of 0.5 means 1 pixel in the screen image is * displayed as 2 pixel on the canvas, etc. * @param targetRenderNanos * Target rendering time in nanoseconds. The rendering time for * the coarsest rendered scale should be below this threshold. * @param doubleBuffered * Whether to use double buffered rendering. * @param numRenderingThreads * How many threads to use for rendering. * @param renderingExecutorService * if non-null, this is used for rendering. Note, that it is * still important to supply the numRenderingThreads parameter, * because that is used to determine into how many sub-tasks * rendering is split. * @param useVolatileIfAvailable * whether volatile versions of sources should be used if * available. * @param accumulateProjectorFactory * can be used to customize how sources are combined. * @param cacheControl * the cache controls IO budgeting and fetcher queue. */ public MultiResolutionRenderer( final RenderTarget display, final PainterThread painterThread, final double[] screenScales, final long targetRenderNanos, final boolean doubleBuffered, final int numRenderingThreads, final ExecutorService renderingExecutorService, final boolean useVolatileIfAvailable, final AccumulateProjectorFactory< ARGBType > accumulateProjectorFactory, final CacheControl cacheControl ) { this.display = wrapTransformAwareRenderTarget( display ); this.painterThread = painterThread; projector = null; currentScreenScaleIndex = -1; this.screenScales = screenScales.clone(); this.doubleBuffered = doubleBuffered; renderIdQueue = new ArrayDeque<>(); bufferedImageToRenderId = new HashMap<>(); renderImages = new ARGBScreenImage[ screenScales.length ][ 0 ]; renderMaskArrays = new byte[ 0 ][]; screenImages = new ARGBScreenImage[ screenScales.length ][ 3 ]; bufferedImages = new BufferedImage[ screenScales.length ][ 3 ]; screenScaleTransforms = new AffineTransform3D[ screenScales.length ]; this.targetRenderNanos = targetRenderNanos; maxScreenScaleIndex = screenScales.length - 1; requestedScreenScaleIndex = maxScreenScaleIndex; renderingMayBeCancelled = true; this.numRenderingThreads = numRenderingThreads; this.renderingExecutorService = renderingExecutorService; this.useVolatileIfAvailable = useVolatileIfAvailable; this.accumulateProjectorFactory = accumulateProjectorFactory; this.cacheControl = cacheControl; newFrameRequest = false; previousTimepoint = -1; } /** * Check whether the size of the display component was changed and * recreate {@link #screenImages} and {@link #screenScaleTransforms} accordingly. * * @return whether the size was changed. */ protected synchronized boolean checkResize() { final int componentW = display.getWidth(); final int componentH = display.getHeight(); if ( screenImages[ 0 ][ 0 ] == null || screenImages[ 0 ][ 0 ].dimension( 0 ) != ( int ) ( componentW * screenScales[ 0 ] ) || screenImages[ 0 ][ 0 ].dimension( 1 ) != ( int ) ( componentH * screenScales[ 0 ] ) ) { renderIdQueue.clear(); renderIdQueue.addAll( Arrays.asList( 0, 1, 2 ) ); bufferedImageToRenderId.clear(); for ( int i = 0; i < screenScales.length; ++i ) { final double screenToViewerScale = screenScales[ i ]; final int w = ( int ) ( screenToViewerScale * componentW ); final int h = ( int ) ( screenToViewerScale * componentH ); if ( doubleBuffered ) { for ( int b = 0; b < 3; ++b ) { // reuse storage arrays of level 0 (highest resolution) screenImages[ i ][ b ] = ( i == 0 ) ? new ARGBScreenImage( w, h ) : new ARGBScreenImage( w, h, screenImages[ 0 ][ b ].getData() ); final BufferedImage bi = GuiUtil.getBufferedImage( screenImages[ i ][ b ] ); bufferedImages[ i ][ b ] = bi; bufferedImageToRenderId.put( bi, b ); } } else { screenImages[ i ][ 0 ] = new ARGBScreenImage( w, h ); bufferedImages[ i ][ 0 ] = GuiUtil.getBufferedImage( screenImages[ i ][ 0 ] ); } final AffineTransform3D scale = new AffineTransform3D(); final double xScale = ( double ) w / componentW; final double yScale = ( double ) h / componentH; scale.set( xScale, 0, 0 ); scale.set( yScale, 1, 1 ); scale.set( 0.5 * xScale - 0.5, 0, 3 ); scale.set( 0.5 * yScale - 0.5, 1, 3 ); screenScaleTransforms[ i ] = scale; } return true; } return false; } protected boolean checkRenewRenderImages( final int numVisibleSources ) { final int n = numVisibleSources > 1 ? numVisibleSources : 0; if ( n != renderImages[ 0 ].length || ( n != 0 && ( renderImages[ 0 ][ 0 ].dimension( 0 ) != screenImages[ 0 ][ 0 ].dimension( 0 ) || renderImages[ 0 ][ 0 ].dimension( 1 ) != screenImages[ 0 ][ 0 ].dimension( 1 ) ) ) ) { renderImages = new ARGBScreenImage[ screenScales.length ][ n ]; for ( int i = 0; i < screenScales.length; ++i ) { final int w = ( int ) screenImages[ i ][ 0 ].dimension( 0 ); final int h = ( int ) screenImages[ i ][ 0 ].dimension( 1 ); for ( int j = 0; j < n; ++j ) { renderImages[ i ][ j ] = ( i == 0 ) ? new ARGBScreenImage( w, h ) : new ARGBScreenImage( w, h, renderImages[ 0 ][ j ].getData() ); } } return true; } return false; } protected boolean checkRenewMaskArrays( final int numVisibleSources ) { if ( numVisibleSources != renderMaskArrays.length || ( numVisibleSources != 0 && ( renderMaskArrays[ 0 ].length < screenImages[ 0 ][ 0 ].size() ) ) ) { final int size = ( int ) screenImages[ 0 ][ 0 ].size(); renderMaskArrays = new byte[ numVisibleSources ][]; for ( int j = 0; j < numVisibleSources; ++j ) renderMaskArrays[ j ] = new byte[ size ]; return true; } return false; } protected final AffineTransform3D currentProjectorTransform = new AffineTransform3D(); /** * Render image at the {@link #requestedScreenScaleIndex requested screen * scale}. */ public boolean paint( final ViewerState state ) { if ( display.getWidth() <= 0 || display.getHeight() <= 0 ) return false; final boolean resized = checkResize(); // the BufferedImage that is rendered to (to paint to the canvas) final BufferedImage bufferedImage; final ARGBScreenImage screenImage; final boolean clearQueue; final boolean createProjector; synchronized ( this ) { // Rendering may be cancelled unless we are rendering at coarsest // screen scale and coarsest mipmap level. renderingMayBeCancelled = ( requestedScreenScaleIndex < maxScreenScaleIndex ); clearQueue = newFrameRequest; if ( clearQueue ) cacheControl.prepareNextFrame(); createProjector = newFrameRequest || resized || ( requestedScreenScaleIndex != currentScreenScaleIndex ); newFrameRequest = false; if ( createProjector ) { final int renderId = renderIdQueue.peek(); currentScreenScaleIndex = requestedScreenScaleIndex; bufferedImage = bufferedImages[ currentScreenScaleIndex ][ renderId ]; screenImage = screenImages[ currentScreenScaleIndex ][ renderId ]; } else { bufferedImage = null; screenImage = null; } requestedScreenScaleIndex = 0; } // the projector that paints to the screenImage. final VolatileProjector p; if ( createProjector ) { synchronized ( state.getState() ) { final int numVisibleSources = state.getVisibleSourceIndices().size(); checkRenewRenderImages( numVisibleSources ); checkRenewMaskArrays( numVisibleSources ); p = createProjector( state, screenImage ); } synchronized ( this ) { projector = p; } } else { synchronized ( this ) { p = projector; } } // try rendering final boolean success = p.map( createProjector ); final long rendertime = p.getLastFrameRenderNanoTime(); synchronized ( this ) { // if rendering was not cancelled... if ( success ) { if ( createProjector ) { final BufferedImage bi = display.setBufferedImageAndTransform( bufferedImage, currentProjectorTransform ); if ( doubleBuffered ) { renderIdQueue.pop(); final Integer id = bufferedImageToRenderId.get( bi ); if ( id != null ) renderIdQueue.add( id ); } if ( currentScreenScaleIndex == maxScreenScaleIndex ) { if ( rendertime > targetRenderNanos && maxScreenScaleIndex < screenScales.length - 1 ) maxScreenScaleIndex++; else if ( rendertime < targetRenderNanos / 3 && maxScreenScaleIndex > 0 ) maxScreenScaleIndex } else if ( currentScreenScaleIndex == maxScreenScaleIndex - 1 ) { if ( rendertime < targetRenderNanos && maxScreenScaleIndex > 0 ) maxScreenScaleIndex } // System.out.println( String.format( "rendering:%4d ms", rendertime / 1000000 ) ); // System.out.println( "scale = " + currentScreenScaleIndex ); // System.out.println( "maxScreenScaleIndex = " + maxScreenScaleIndex + " (" + screenImages[ maxScreenScaleIndex ][ 0 ].dimension( 0 ) + " x " + screenImages[ maxScreenScaleIndex ][ 0 ].dimension( 1 ) + ")" ); } if ( currentScreenScaleIndex > 0 ) requestRepaint( currentScreenScaleIndex - 1 ); else if ( !p.isValid() ) { try { Thread.sleep( 1 ); } catch ( final InterruptedException e ) { // restore interrupted state Thread.currentThread().interrupt(); } requestRepaint( currentScreenScaleIndex ); } } } return success; } /** * Request a repaint of the display from the painter thread, with maximum * screen scale index and mipmap level. */ public synchronized void requestRepaint() { newFrameRequest = true; requestRepaint( maxScreenScaleIndex ); } /** * Request a repaint of the display from the painter thread. The painter * thread will trigger a {@link #paint(ViewerState)} as soon as possible (that is, * immediately or after the currently running {@link #paint(ViewerState)} has * completed). */ public synchronized void requestRepaint( final int screenScaleIndex ) { if ( renderingMayBeCancelled && projector != null ) projector.cancel(); if ( screenScaleIndex > requestedScreenScaleIndex ) requestedScreenScaleIndex = screenScaleIndex; painterThread.requestRepaint(); } public void kill() { if ( display instanceof TransformAwareBufferedImageOverlayRenderer ) ( ( TransformAwareBufferedImageOverlayRenderer ) display ).kill(); projector = null; renderIdQueue.clear(); bufferedImageToRenderId.clear(); for ( int i = 0; i < renderImages.length; ++i ) renderImages[ i ] = null; for ( int i = 0; i < renderMaskArrays.length; ++i ) renderMaskArrays[ i ] = null; for ( int i = 0; i < screenImages.length; ++i ) screenImages[ i ] = null; for ( int i = 0; i < bufferedImages.length; ++i ) bufferedImages[ i ] = null; } private VolatileProjector createProjector( final ViewerState viewerState, final ARGBScreenImage screenImage ) { /* * This shouldn't be necessary, with * CacheHints.LoadingStrategy==VOLATILE */ // CacheIoTiming.getIoTimeBudget().clear(); // clear time budget such that prefetching doesn't wait for loading blocks. final List< SourceState< ? > > sourceStates = viewerState.getSources(); final List< Integer > visibleSourceIndices = viewerState.getVisibleSourceIndices(); VolatileProjector projector; if ( visibleSourceIndices.isEmpty() ) projector = new EmptyProjector<>( screenImage ); else if ( visibleSourceIndices.size() == 1 ) { final int i = visibleSourceIndices.get( 0 ); projector = createSingleSourceProjector( viewerState, sourceStates.get( i ), i, currentScreenScaleIndex, screenImage, renderMaskArrays[ 0 ] ); } else { final ArrayList< VolatileProjector > sourceProjectors = new ArrayList<>(); final ArrayList< ARGBScreenImage > sourceImages = new ArrayList<>(); final ArrayList< Source< ? > > sources = new ArrayList<>(); int j = 0; for ( final int i : visibleSourceIndices ) { final ARGBScreenImage renderImage = renderImages[ currentScreenScaleIndex ][ j ]; final byte[] maskArray = renderMaskArrays[ j ]; ++j; final VolatileProjector p = createSingleSourceProjector( viewerState, sourceStates.get( i ), i, currentScreenScaleIndex, renderImage, maskArray ); sourceProjectors.add( p ); sources.add( sourceStates.get( i ).getSpimSource() ); sourceImages.add( renderImage ); } projector = accumulateProjectorFactory.createAccumulateProjector( sourceProjectors, sources, sourceImages, screenImage, numRenderingThreads, renderingExecutorService ); } previousTimepoint = viewerState.getCurrentTimepoint(); viewerState.getViewerTransform( currentProjectorTransform ); CacheIoTiming.getIoTimeBudget().reset( iobudget ); return projector; } private static class SimpleVolatileProjector< A, B > extends SimpleInterruptibleProjector< A, B > implements VolatileProjector { private boolean valid = false; public SimpleVolatileProjector( final RandomAccessible< A > source, final Converter< ? super A, B > converter, final RandomAccessibleInterval< B > target, final int numThreads, final ExecutorService executorService ) { super( source, converter, target, numThreads, executorService ); } @Override public boolean map( final boolean clearUntouchedTargetPixels ) { final boolean success = super.map(); valid |= success; return success; } @Override public boolean isValid() { return valid; } } private < T > VolatileProjector createSingleSourceProjector( final ViewerState viewerState, final SourceState< T > source, final int sourceIndex, final int screenScaleIndex, final ARGBScreenImage screenImage, final byte[] maskArray ) { if ( useVolatileIfAvailable ) { if ( source.asVolatile() != null ) return createSingleSourceVolatileProjector( viewerState, source.asVolatile(), sourceIndex, screenScaleIndex, screenImage, maskArray ); else if ( source.getSpimSource().getType() instanceof Volatile ) { @SuppressWarnings( "unchecked" ) final SourceState< ? extends Volatile< ? > > vsource = ( SourceState< ? extends Volatile< ? > > ) source; return createSingleSourceVolatileProjector( viewerState, vsource, sourceIndex, screenScaleIndex, screenImage, maskArray ); } } final AffineTransform3D screenScaleTransform = screenScaleTransforms[ currentScreenScaleIndex ]; final int bestLevel = viewerState.getBestMipMapLevel( screenScaleTransform, sourceIndex ); return new SimpleVolatileProjector<>( getTransformedSource( viewerState, source.getSpimSource(), screenScaleTransform, bestLevel, null ), source.getConverter(), screenImage, numRenderingThreads, renderingExecutorService ); } private < T extends Volatile< ? > > VolatileProjector createSingleSourceVolatileProjector( final ViewerState viewerState, final SourceState< T > source, final int sourceIndex, final int screenScaleIndex, final ARGBScreenImage screenImage, final byte[] maskArray ) { final AffineTransform3D screenScaleTransform = screenScaleTransforms[ currentScreenScaleIndex ]; final ArrayList< RandomAccessible< T > > renderList = new ArrayList<>(); final Source< T > spimSource = source.getSpimSource(); final int t = viewerState.getCurrentTimepoint(); final MipmapOrdering ordering = MipmapOrdering.class.isInstance( spimSource ) ? ( MipmapOrdering ) spimSource : new DefaultMipmapOrdering( spimSource ); final AffineTransform3D screenTransform = new AffineTransform3D(); viewerState.getViewerTransform( screenTransform ); screenTransform.preConcatenate( screenScaleTransform ); final MipmapHints hints = ordering.getMipmapHints( screenTransform, t, previousTimepoint ); final List< Level > levels = hints.getLevels(); if ( prefetchCells ) { Collections.sort( levels, MipmapOrdering.prefetchOrderComparator ); for ( final Level l : levels ) { final CacheHints cacheHints = l.getPrefetchCacheHints(); if ( cacheHints == null || cacheHints.getLoadingStrategy() != LoadingStrategy.DONTLOAD ) prefetch( viewerState, spimSource, screenScaleTransform, l.getMipmapLevel(), cacheHints, screenImage ); } } Collections.sort( levels, MipmapOrdering.renderOrderComparator ); for ( final Level l : levels ) renderList.add( getTransformedSource( viewerState, spimSource, screenScaleTransform, l.getMipmapLevel(), l.getRenderCacheHints() ) ); if ( hints.renewHintsAfterPaintingOnce() ) newFrameRequest = true; return new VolatileHierarchyProjector<>( renderList, source.getConverter(), screenImage, maskArray, numRenderingThreads, renderingExecutorService ); } private static < T > RandomAccessible< T > getTransformedSource( final ViewerState viewerState, final Source< T > source, final AffineTransform3D screenScaleTransform, final int mipmapIndex, final CacheHints cacheHints ) { final int timepoint = viewerState.getCurrentTimepoint(); final RandomAccessibleInterval< T > img = source.getSource( timepoint, mipmapIndex ); if ( VolatileCachedCellImg.class.isInstance( img ) ) ( ( VolatileCachedCellImg< ?, ? > ) img ).setCacheHints( cacheHints ); final Interpolation interpolation = viewerState.getInterpolation(); final RealRandomAccessible< T > ipimg = source.getInterpolatedSource( timepoint, mipmapIndex, interpolation ); final AffineTransform3D sourceToScreen = new AffineTransform3D(); viewerState.getViewerTransform( sourceToScreen ); final AffineTransform3D sourceTransform = new AffineTransform3D(); source.getSourceTransform( timepoint, mipmapIndex, sourceTransform ); sourceToScreen.concatenate( sourceTransform ); sourceToScreen.preConcatenate( screenScaleTransform ); return RealViews.affine( ipimg, sourceToScreen ); } private static < T > void prefetch( final ViewerState viewerState, final Source< T > source, final AffineTransform3D screenScaleTransform, final int mipmapIndex, final CacheHints prefetchCacheHints, final Dimensions screenInterval ) { final int timepoint = viewerState.getCurrentTimepoint(); final RandomAccessibleInterval< T > img = source.getSource( timepoint, mipmapIndex ); if ( VolatileCachedCellImg.class.isInstance( img ) ) { final VolatileCachedCellImg< ?, ? > cellImg = ( VolatileCachedCellImg< ?, ? > ) img; CacheHints hints = prefetchCacheHints; if ( hints == null ) { final CacheHints d = cellImg.getDefaultCacheHints(); hints = new CacheHints( LoadingStrategy.VOLATILE, d.getQueuePriority(), false ); } cellImg.setCacheHints( hints ); final int[] cellDimensions = new int[ 3 ]; cellImg.getCellGrid().cellDimensions( cellDimensions ); final long[] dimensions = new long[ 3 ]; cellImg.dimensions( dimensions ); final RandomAccess< ? > cellsRandomAccess = cellImg.getCells().randomAccess(); final Interpolation interpolation = viewerState.getInterpolation(); final AffineTransform3D sourceToScreen = new AffineTransform3D(); viewerState.getViewerTransform( sourceToScreen ); final AffineTransform3D sourceTransform = new AffineTransform3D(); source.getSourceTransform( timepoint, mipmapIndex, sourceTransform ); sourceToScreen.concatenate( sourceTransform ); sourceToScreen.preConcatenate( screenScaleTransform ); Prefetcher.fetchCells( sourceToScreen, cellDimensions, dimensions, screenInterval, interpolation, cellsRandomAccess ); } } private static TransformAwareRenderTarget wrapTransformAwareRenderTarget( final RenderTarget t ) { if ( t instanceof TransformAwareRenderTarget ) return ( TransformAwareRenderTarget ) t; else return new TransformAwareRenderTarget() { @Override public BufferedImage setBufferedImage( final BufferedImage img ) { return t.setBufferedImage( img ); } @Override public int getWidth() { return t.getWidth(); } @Override public int getHeight() { return t.getHeight(); } @Override public BufferedImage setBufferedImageAndTransform( final BufferedImage img, final AffineTransform3D transform ) { return t.setBufferedImage( img ); } @Override public void removeTransformListener( final TransformListener< AffineTransform3D > listener ) {} @Override public void addTransformListener( final TransformListener< AffineTransform3D > listener, final int index ) {} @Override public void addTransformListener( final TransformListener< AffineTransform3D > listener ) {} }; } }
package beneficialblocks.items; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.projectile.EntityFireball; import net.minecraft.entity.projectile.EntitySmallFireball; import net.minecraft.entity.projectile.EntitySnowball; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.IFluidContainerItem; import beneficialblocks.BeneficialBlocks; import beneficialblocks.setup.CreativeTabBB; public class ItemIgnisProiectum extends Item { public ItemIgnisProiectum() { setUnlocalizedName("bbIgnisProiectum"); setTextureName("beneficialblocks:IgnisProiectum"); setCreativeTab(CreativeTabBB.BB_TAB); //setMaxDamage(); setMaxStackSize(1); } /** * Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer */ @Override public ItemStack onItemRightClick(ItemStack iStack, World world, EntityPlayer player) { FluidStack fluid = null; int index=0; //searching inventory for a fluid container for(int i=0;i<player.inventory.getSizeInventory();i++) { ItemStack invoStack = player.inventory.getStackInSlot(i); if(invoStack == null) { continue; } if(invoStack.getItem() instanceof IFluidContainerItem) { fluid = ((IFluidContainerItem)invoStack.getItem()).getFluid(invoStack); if(fluid == null) { continue; } //breaks if Fluid container doesn't contain water if(fluid != null && fluid.getFluid() != FluidRegistry.LAVA) { continue; } //if tanks are stacked and need to be separated ItemStack newStack = invoStack.copy(); //Makes a copy with all the NBT data intact if(newStack.stackSize > 1) { if(player.inventory.getFirstEmptyStack() < 0) //check if inventory space is available for a split { continue; } newStack.stackSize = 1; } //simulated drain to see if enough fluid fluid = ((IFluidContainerItem)newStack.getItem()).drain(newStack, 250, false); if(fluid.amount >= 250) { index = i; break; } } } //BeneficialBlocks.bbLog.info("The tank is located at index: " + index); //actually pulling liquid from container if(index >= 0 && fluid != null) { int drain = 250; if(drain > 0) { ItemStack invoStack = player.inventory.getStackInSlot(index); MovingObjectPosition mop = this.getMovingObjectPositionFromPlayer(world, player, true); BeneficialBlocks.bbLog.info("Rotation Yaw: " + player.rotationYaw); BeneficialBlocks.bbLog.info("Rotation Pitch: " + player.rotationPitch); if(mop == null) { BeneficialBlocks.bbLog.info("mop is null"); return iStack; } if(invoStack.getItem() instanceof IFluidContainerItem) { if(invoStack.stackSize > 1) { ItemStack drainStack = invoStack.copy(); invoStack.stackSize -= 1; drainStack.stackSize = 1; ((IFluidContainerItem)invoStack.getItem()).drain(drainStack, drain, true); player.inventory.addItemStackToInventory(drainStack); //We checked for space earlier } else { ((IFluidContainerItem)invoStack.getItem()).drain(invoStack, drain, true); } double motionX = (double)(-MathHelper.sin(player.rotationYaw / 180.0F * (float)Math.PI) * MathHelper.cos(player.rotationPitch / 180.0F * (float)Math.PI) * 0.4F); double motionZ = (double)(MathHelper.cos(player.rotationYaw / 180.0F * (float)Math.PI) * MathHelper.cos(player.rotationPitch / 180.0F * (float)Math.PI) * 0.4F); double motionY = (double)(-MathHelper.sin((player.rotationPitch + 0.0F) / 180.0F * (float)Math.PI) * 0.4F); ForgeDirection dirOff = ForgeDirection.getOrientation(mop.sideHit); BeneficialBlocks.bbLog.info("Motion X: " + motionX + ", Motion Y: " + motionY + ", motionZ: " + motionZ); if(!world.isRemote) { world.spawnEntityInWorld(new EntitySmallFireball(world, player.posX+dirOff.offsetX, player.posY+1+dirOff.offsetY, player.posZ+dirOff.offsetY, motionX, motionY, motionZ)); } //world.spawnEntityInWorld(new EntityItem(world, player.posX, player.posY, player.posZ, new ItemStack(Items.fire_charge))); } } } return iStack; } }
package cd.go.plugin.config.yaml; import cd.go.plugin.config.yaml.transforms.RootTransform; import com.esotericsoftware.yamlbeans.YamlConfig; import com.esotericsoftware.yamlbeans.YamlReader; import java.io.*; public class YamlConfigParser { private RootTransform rootTransform; public YamlConfigParser() { this(new RootTransform()); } public YamlConfigParser(RootTransform rootTransform) { this.rootTransform = rootTransform; } public JsonConfigCollection parseFiles(File baseDir, String[] files) { JsonConfigCollection collection = new JsonConfigCollection(); for (String file : files) { try { parseStream(collection, new FileInputStream(new File(baseDir, file)), file); } catch (FileNotFoundException ex) { collection.addError("File matching GoCD YAML pattern disappeared", file); } } return collection; } public void parseStream(JsonConfigCollection result, InputStream input, String location) { try (InputStreamReader contentReader = new InputStreamReader(input)) { if (input.available() < 1) { result.addError("File is empty", location); return; } YamlConfig config = new YamlConfig(); config.setAllowDuplicates(false); YamlReader reader = new YamlReader(contentReader, config); Object rootObject = reader.read(); JsonConfigCollection filePart = rootTransform.transform(rootObject, location); result.append(filePart); } catch (YamlReader.YamlReaderException e) { result.addError(e.getMessage(), location); } catch (IOException e) { result.addError(e.getMessage() + " : " + e.getCause().getMessage() + " : ", location); } } }
package cms.qermit.prototype; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class PrototypeApplication { public static void main(String[] args) throws Exception { SpringApplication.run(PrototypeApplication.class, args); } }
package co.phoenixlab.discord.commands; import co.phoenixlab.common.lang.number.ParseInt; import co.phoenixlab.common.lang.number.ParseLong; import co.phoenixlab.common.localization.Localizer; import co.phoenixlab.discord.CommandDispatcher; import co.phoenixlab.discord.MessageContext; import co.phoenixlab.discord.VahrhedralBot; import co.phoenixlab.discord.api.DiscordApiClient; import co.phoenixlab.discord.api.entities.Message; public class DnCommands { public static final double DEFENSE_MAX_PERCENT = 0.85D; public static final double CRITDMG_MAX_PERCENT = 1D; public static final double CRIT_MAX_PERCENT = 0.89D; public static final double FD_MAX_PERCENT = 1D; public static final double[] fdCaps = { 75.0, 87.0, 99.0, 111.0, 123.0, 135.0, 147.0, 159.0, 171.0, 183.0, 195.0, 207.0, 219.0, 231.0, 285.0, 300.0, 315.0, 330.0, 345.0, 360.0, 375.0, 390.0, 405.0, 420.0, 442.0, 465.0, 487.0, 510.0, 532.0, 555.0, 577.0, 600.0, 630.0, 660.0, 690.0, 720.0, 750.0, 780.0, 810.0, 850.0, 894.0, 938.0, 982.0, 1026.0, 1070.0, 1114.0, 1158.0, 1202.0, 1246.0, 1290.0, 1346.0, 1402.0, 1458.0, 1514.0, 1570.0, 1626.0, 1682.0, 1738.0, 1794.0, 1850.0, 1962.0, 2074.0, 2187.0, 2299.0, 2412.0, 2524.0, 2636.0, 2749.0, 2861.0, 2974.0, 3128.0, 3283.0, 3437.0, 3592.0, 3747.0, 3901.0, 4056.0, 4210.0, 4365.0, 4520.0, 4704.0, 4889.0, 5074.0, 5258.0, 5443.0, 5628.0, 5812.0, 5997.0, 6182.0, 6367.0, 7022.0, 7678.0, 8333.0, 8989.0, 9644.0, 10300.0, 10955.0, 11611.0, 12266.0, 12922.0 }; public static final double[] defenseCaps = { 750.0, 870.0, 990.0, 1110.0, 1230.0, 1350.0, 1470.0, 1590.0, 1710.0, 1830.0, 1950.0, 2070.0, 2190.0, 2310.0, 2850.0, 3000.0, 3150.0, 3300.0, 3450.0, 3600.0, 3750.0, 3900.0, 4050.0, 4200.0, 4425.0, 4650.0, 4875.0, 5100.0, 5325.0, 5550.0, 5775.0, 6000.0, 6300.0, 6600.0, 6900.0, 7200.0, 7500.0, 7800.0, 8100.0, 8400.0, 9000.0, 9600.0, 10200.0, 10800.0, 11475.0, 12150.0, 12825.0, 13500.0, 14250.0, 15000.0, 15750.0, 16912.0, 18277.0, 19695.0, 21157.0, 22672.0, 24427.0, 26355.0, 28125.0, 29250.0, 30868.0, 33056.0, 35685.0, 38771.0, 42331.0, 46383.0, 50943.0, 56137.0, 61977.0, 68186.0, 72523.0, 76637.0, 80534.0, 84201.0, 88328.0, 92188.0, 95006.0, 99837.0, 104590.0, 106722.0, 112014.0, 117306.0, 122598.0, 127890.0, 134064.0, 140238.0, 146412.0, 152586.0, 158760.0, 165816.0, 187278.0, 209916.0, 233730.0, 258720.0, 286135.0, 314874.0, 344935.0, 376320.0, 409027.0, 443058.0 }; public static final double[] critCaps = { 1000.0, 1160.0, 1320.0, 1480.0, 1640.0, 1800.0, 1960.0, 2120.0, 2280.0, 2440.0, 2600.0, 2760.0, 2920.0, 3080.0, 3800.0, 4000.0, 4200.0, 4400.0, 4600.0, 4800.0, 5000.0, 5200.0, 5400.0, 5600.0, 5900.0, 6200.0, 6500.0, 6800.0, 7100.0, 7400.0, 7700.0, 8000.0, 8400.0, 8800.0, 9200.0, 9600.0, 10000.0, 10400.0, 10800.0, 11200.0, 12000.0, 12800.0, 13600.0, 14400.0, 15300.0, 16200.0, 17100.0, 18000.0, 19000.0, 20000.0, 21500.0, 23000.0, 24600.0, 26200.0, 27900.0, 29600.0, 31400.0, 33200.0, 35200.0, 37200.0, 40200.0, 43200.0, 46200.0, 49200.0, 52400.0, 55600.0, 58800.0, 62000.0, 65400.0, 68800.0, 74745.0, 80619.0, 86438.0, 92373.0, 98284.0, 104245.0, 110176.0, 116008.0, 121899.0, 127685.0, 138684.0, 149565.0, 160545.0, 171433.0, 182263.0, 192994.0, 203931.0, 214891.0, 225855.0, 236880.0, 277830.0, 321300.0, 367290.0, 415800.0, 468877.0, 524790.0, 583537.0, 645120.0, 709537.0, 776790.0 }; public static final double[] critDmgCaps = { 2650.0, 3074.0, 3498.0, 3922.0, 4346.0, 4770.0, 5194.0, 5618.0, 6042.0, 6466.0, 6890.0, 7314.0, 7738.0, 8162.0, 10070.0, 10600.0, 11130.0, 11660.0, 12190.0, 12720.0, 13250.0, 13780.0, 14310.0, 14840.0, 15635.0, 16430.0, 17225.0, 18020.0, 18815.0, 19610.0, 20405.0, 21200.0, 22260.0, 23320.0, 24380.0, 25440.0, 26500.0, 27560.0, 28620.0, 29680.0, 31641.0, 33575.0, 35510.0, 37206.0, 39326.0, 41419.0, 43513.0, 45553.0, 47832.0, 50350.0, 55650.0, 59757.0, 64580.0, 69589.0, 74756.0, 80109.0, 86310.0, 93121.0, 99375.0, 103350.0, 107987.0, 113950.0, 121237.0, 129850.0, 139787.0, 151050.0, 163637.0, 177894.0, 193794.0, 211337.0, 228555.0, 245520.0, 262220.0, 278587.0, 296902.0, 320100.0, 343263.0, 374976.0, 407979.0, 431970.0, 453390.0, 474810.0, 496230.0, 517650.0, 542640.0, 567630.0, 592620.0, 617610.0, 642600.0, 671160.0, 769692.0, 801108.0, 832524.0, 863940.0, 899283.0, 934626.0, 969969.0, 1005312.0, 1040655.0, 1075998.0 }; private final CommandDispatcher dispatcher; private final VahrhedralBot bot; private Localizer loc; public DnCommands(VahrhedralBot bot) { this.bot = bot; dispatcher = new CommandDispatcher(bot, ""); loc = bot.getLocalizer(); } public void registerDnCommands() { dispatcher.registerCommand("commands.dn.defense", this::defenseCalculator); dispatcher.registerCommand("commands.dn.finaldamage", this::finalDamageCalculator); dispatcher.registerCommand("commands.dn.crit", this::critChanceCalculator); dispatcher.registerCommand("commands.dn.critdmg", this::critDamageCalculator); } public CommandDispatcher getDispatcher() { return dispatcher; } private void critChanceCalculator(MessageContext context, String args) { DiscordApiClient apiClient = context.getApiClient(); // Strip commas args = args.replace(",", ""); String[] split = args.split(" "); if (split.length >= 1) { String value = split[0]; if (value.endsWith("%")) { double critPercent = Math.min(Double.parseDouble(value.substring(0, value.length() - 1)) / 100D, CRIT_MAX_PERCENT); if (critPercent < 0) { throw new IllegalArgumentException("must be at least 0%"); } int level = 80; if (split.length >= 2) { level = ParseInt.parseOrDefault(split[1], level); } if (level < 1 || level > 100) { apiClient.sendMessage(loc.localize("commands.dn.crit.response.level_out_of_range", 1, 100), context.getChannel()); return; } double crit = critCaps[level - 1] * critPercent; apiClient.sendMessage(loc.localize("commands.dn.crit.response.format.required", level, (int) crit, critPercent * 100D), context.getChannel()); } else { int crit = (int) parseStat(split[0]); int level = 80; if (split.length >= 2) { level = ParseInt.parseOrDefault(split[1], level); } if (level < 1 || level > 100) { apiClient.sendMessage(loc.localize("commands.dn.crit.response.level_out_of_range", 1, 100), context.getChannel()); return; } double critPercent; double critCap = critCaps[level - 1]; critPercent = crit / critCap; critPercent = Math.max(0, Math.min(CRIT_MAX_PERCENT, critPercent)) * 100D; apiClient.sendMessage(loc.localize("commands.dn.crit.response.format", level, critPercent, (int) (critCap * CRIT_MAX_PERCENT), (int) (CRIT_MAX_PERCENT * 100D)), context.getChannel()); } return; } apiClient.sendMessage(loc.localize("commands.dn.crit.response.invalid", bot.getMainCommandDispatcher().getCommandPrefix()), context.getChannel()); } private void critDamageCalculator(MessageContext context, String args) { DiscordApiClient apiClient = context.getApiClient(); // Strip commas args = args.replace(",", ""); String[] split = args.split(" "); if (split.length >= 1) { String value = split[0]; if (value.endsWith("%")) { double critDmgPercent = Math.min(Double.parseDouble(value.substring(0, value.length() - 1)) / 100D - 2D, CRITDMG_MAX_PERCENT); if (critDmgPercent < 0) { throw new IllegalArgumentException("must be at least 0%"); } int level = 80; if (split.length >= 2) { level = ParseInt.parseOrDefault(split[1], level); } if (level < 1 || level > 100) { apiClient.sendMessage(loc.localize("commands.dn.critdmg.response.level_out_of_range", 1, 100), context.getChannel()); return; } double critDmg = critDmgCaps[level - 1] * critDmgPercent; apiClient.sendMessage(loc.localize("commands.dn.critdmg.response.format.required", level, (int) critDmg, (critDmgPercent + 2D) * 100D), context.getChannel()); } else { int critdmg = (int) parseStat(value); int level = 80; if (split.length >= 2) { level = ParseInt.parseOrDefault(split[1], level); } if (level < 1 || level > 100) { apiClient.sendMessage(loc.localize("commands.dn.critdmg.response.level_out_of_range", 1, 100), context.getChannel()); return; } double critDmgPercent; double critDmgCap = critDmgCaps[level - 1]; critDmgPercent = critdmg / critDmgCap; critDmgPercent = Math.max(0, Math.min(CRITDMG_MAX_PERCENT, critDmgPercent)) * 100D + 200D; apiClient.sendMessage(loc.localize("commands.dn.critdmg.response.format", level, critDmgPercent, (int) (critDmgCap * CRITDMG_MAX_PERCENT), (int) (CRITDMG_MAX_PERCENT * 100D) + 200), context.getChannel()); } return; } apiClient.sendMessage(loc.localize("commands.dn.critdmg.response.invalid", bot.getMainCommandDispatcher().getCommandPrefix()), context.getChannel()); } private void finalDamageCalculator(MessageContext context, String args) { DiscordApiClient apiClient = context.getApiClient(); // Strip commas args = args.replace(",", ""); String[] split = args.split(" "); try { if (split.length >= 1) { String quantity = split[0]; if (quantity.endsWith("%")) { double fdPercent = Math.min(Double.parseDouble(quantity.substring(0, quantity.length() - 1)) / 100D, 1D); if (fdPercent < 0) { throw new IllegalArgumentException("must be at least 0%"); } int level = 80; if (split.length >= 2) { level = ParseInt.parseOrDefault(split[1], level); } if (level < 1 || level > 100) { apiClient.sendMessage(loc.localize("commands.dn.finaldamage.response.level_out_of_range", 1, 100), context.getChannel()); return; } double fd; if (fdPercent < 0.146D) { fd = 2.857142857D * fdPercent * fdCaps[level - 1]; } else { // Since we know fdPercent must be between 0 and 100, we can't overflow //noinspection NumericOverflow fd = fdCaps[level - 1] * Math.pow(fdPercent, 1D / 2.2D); } apiClient.sendMessage(loc.localize("commands.dn.finaldamage.response.format.required", level, (int) fd, fdPercent * 100D), context.getChannel()); } else { int fd = (int) parseStat(quantity); int level = 80; if (split.length >= 2) { level = ParseInt.parseOrDefault(split[1], level); } if (level < 1 || level > 100) { apiClient.sendMessage(loc.localize("commands.dn.finaldamage.response.level_out_of_range", 1, 100), context.getChannel()); return; } double fdPercent; double fdCap = fdCaps[level - 1]; double ratio = fd / fdCap; if (ratio < 0.417D) { fdPercent = (0.35D * fd) / fdCap; } else { fdPercent = Math.pow(fd / fdCap, 2.2D); } fdPercent = Math.max(0, Math.min(FD_MAX_PERCENT, fdPercent)) * 100D; apiClient.sendMessage(loc.localize("commands.dn.finaldamage.response.format", level, fdPercent, (int) (fdCap * FD_MAX_PERCENT), (int) (FD_MAX_PERCENT * 100D)), context.getChannel()); } } return; } catch (Exception ignored) { } apiClient.sendMessage(loc.localize("commands.dn.finaldamage.response.invalid", bot.getMainCommandDispatcher().getCommandPrefix()), context.getChannel()); } private void defenseCalculator(MessageContext context, String args) { DiscordApiClient apiClient = context.getApiClient(); Message message = context.getMessage(); // Strip commas args = args.replace(",", ""); String[] split = args.split(" "); if (split.length >= 3) { try { double rawHp = parseStat(split[0]); double rawDef = parseStat(split[1]); double rawMDef = parseStat(split[2]); if (rawHp < 0 || rawDef < 0 || rawMDef < 0) { throw new NumberFormatException(); } int level = 80; if (split.length >= 4) { level = ParseInt.parseOrDefault(split[3], level); } if (level < 1 || level > 100) { apiClient.sendMessage(loc.localize("commands.dn.defense.response.level_out_of_range", 1, 100), context.getChannel()); return; } double defCap = defenseCaps[level - 1]; double def = calculateDef(rawDef, defCap); double mDef = calculateDef(rawMDef, defCap); double eDHp = rawHp / (1D - (def / 100D)); double eMHp = rawHp / (1D - (mDef / 100D)); apiClient.sendMessage(loc.localize("commands.dn.defense.response.format", def, mDef, (long) eDHp, (long) eMHp, level, (int) defCap, (int) (DEFENSE_MAX_PERCENT * 100D)), context.getChannel()); return; } catch (NumberFormatException ignored) { } } apiClient.sendMessage(loc.localize("commands.dn.defense.response.invalid", bot.getMainCommandDispatcher().getCommandPrefix()), context.getChannel()); } private double calculateDef(double def, double defCap) { double defPercent; defPercent = def / defCap; defPercent = Math.max(0, Math.min(DEFENSE_MAX_PERCENT, defPercent)) * 100D; return defPercent; } private double lerp(double a, double b, double alpha) { return a + (b - a) * alpha; } private double parseStat(String s) throws NumberFormatException { // Check if it ends in thousand or million String thousandSuffix = loc.localize("commands.dn.defense.suffix.thousand"); int start = s.indexOf(thousandSuffix); double working; double ret = 0; if (start == 0) { // Invalid, cannot be just "k" throw new NumberFormatException(); } if (start != -1) { String num = s.substring(0, start); try { working = Double.parseDouble(num); } catch (NumberFormatException nfe) { throw new NumberFormatException(); } ret = working * 1000.0; } else { String millionSuffix = loc.localize("commands.dn.defense.suffix.million"); start = s.indexOf(millionSuffix); if (start == 0) { // Invalid, cannot be just "m" throw new NumberFormatException(); } if (start != -1) { String num = s.substring(0, start); try { working = Double.parseDouble(num); } catch (NumberFormatException nfe) { throw new NumberFormatException(); } ret = working * 1000000.0; } else { String billionSuffix = loc.localize("commands.dn.defense.suffix.billion"); start = s.indexOf(billionSuffix); if (start == 0) { // Invalid, cannot be just "b" throw new NumberFormatException(); } if (start != -1) { String num = s.substring(0, start); try { working = Double.parseDouble(num); } catch (NumberFormatException nfe) { throw new NumberFormatException(); } ret = working * 1000000000.0; } else { ret = ParseLong.parseDec(s); } } } return ret; } }
package codemining.util.parallel; import static com.google.common.base.Preconditions.checkArgument; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import org.apache.commons.lang.exception.ExceptionUtils; import codemining.util.SettingsLoader; /** * A wrapper around Java's thread pool using Future. Uses Callable so tasks can * return values. * * @author Jaroslav Fowkes <jaroslav.fowkes@ed.ac.uk> * */ public class FutureThreadPool { private static final Logger LOGGER = Logger .getLogger(FutureThreadPool.class.getName()); private final ExecutorService threadPool; private List<Future<?>> futures; public static final int NUM_THREADS = (int) SettingsLoader .getNumericSetting("nThreads", Runtime.getRuntime() .availableProcessors()); public FutureThreadPool() { threadPool = Executors.newFixedThreadPool(NUM_THREADS); } /** * @param nThreads * number of parallel threads to use. */ public FutureThreadPool(final int nThreads) { threadPool = Executors.newFixedThreadPool(nThreads); } /** * Interrupt the execution of any future tasks, returning tasks that have * been interrupted. */ public List<Runnable> interrupt() { return threadPool.shutdownNow(); } public void pushAll(final Collection<Callable<?>> tasks) { futures = new ArrayList<Future<?>>(); for (final Callable<?> task : tasks) { futures.add(threadPool.submit(task)); } } /** * Push a task to be executed. * * @param task */ public void pushTask(final Callable<?> task) { checkArgument(!threadPool.isShutdown(), "Cannot submit task to thread pool that has already been shutdown."); if (futures == null) { futures = new ArrayList<Future<?>>(); } futures.add(threadPool.submit(task)); } public <T> void putCompletedTasks(final Collection<T> outputs) { threadPool.shutdown(); try { threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); } catch (final InterruptedException e) { LOGGER.warning("Thread Pool Interrupted " + ExceptionUtils.getFullStackTrace(e)); } for (final Future<?> future : futures) { try { outputs.add((T) future.get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } } }
package com.adobe.epubcheck.util; import java.io.PrintWriter; import com.adobe.epubcheck.api.Report; public class WriterReportImpl implements Report { private PrintWriter out; private int errorCount, warningCount, exceptionCount, hintCount; private boolean quiet; public WriterReportImpl(PrintWriter out) { this(out, false); } public WriterReportImpl(PrintWriter out, boolean quiet) { this(out, null, quiet); } public WriterReportImpl(PrintWriter out, String info) { this(out, info, false); } public WriterReportImpl(PrintWriter out, String info, boolean quiet) { this.out = out; if (info != null) warning("", 0, 0, info); errorCount = 0; warningCount = 0; exceptionCount = 0; hintCount = 0; this.quiet = quiet; } private String fixMessage(String message) { if (message == null) return ""; return message.replaceAll("[\\s]+", " "); } public void error(String resource, int line, int column, String message) { errorCount++; message = fixMessage(message); out.println("ERROR: " + (resource == null ? "[top level]" : resource) + (line <= 0 ? "" : "(" + line + (column <= 0 ? "" : "," + column) + ")") + ": " + message); } public void warning(String resource, int line, int column, String message) { warningCount++; message = fixMessage(message); out.println("WARNING: " + (resource == null ? "[top level]" : resource) + (line <= 0 ? "" : "(" + line + (column <= 0 ? "" : "," + column) + ")") + ": " + message); } public int getErrorCount() { return errorCount; } public int getWarningCount() { return warningCount; } public void exception(String resource, Exception e) { exceptionCount++; out.println("EXCEPTION: " + (resource == null ? "" : "/" + resource) + ": " + e.getMessage()); } public int getExceptionCount() { return exceptionCount; } public int getHintCount() { return hintCount; } @Override public void info(String resource, FeatureEnum feature, String value) { if (feature == FeatureEnum.FORMAT_VERSION && !quiet) { out.println("INFO: " + String.format(Messages.VALIDATING_VERSION_MESSAGE, value)); } } @Override public void hint(String resource, int line, int column, String message) { hintCount++; if (!quiet) { out.println("HINT: " + (resource == null ? "[top level]" : resource) + (line <= 0 ? "" : "(" + line + (column <= 0 ? "" : "," + column) + ")") + ": " + message); } } }
package com.akiban.server.service.ui; import com.akiban.server.service.ServiceManager; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.text.*; import java.net.URL; import java.io.OutputStream; import java.io.PrintStream; public class SwingConsole extends JFrame implements WindowListener { public static final String TITLE = "Akiban Server"; public static final String ICON_PATH = "Akiban_Server_128x128.png"; private final ServiceManager serviceManager; private JTextArea textArea; private PrintStream printStream; public SwingConsole(ServiceManager serviceManager) { super(TITLE); this.serviceManager = serviceManager; setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); addWindowListener(this); { boolean macOSX = "Mac OS X".equals(System.getProperty("os.name")); int shift = (macOSX) ? InputEvent.META_MASK : InputEvent.CTRL_MASK; JMenuBar menuBar = new JMenuBar(); if (!macOSX || !Boolean.getBoolean("apple.laf.useScreenMenuBar")) { JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic(KeyEvent.VK_F); JMenuItem quitMenuItem = new JMenuItem("Quit", KeyEvent.VK_Q); quitMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { quit(true); } }); quitMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, shift)); fileMenu.add(quitMenuItem); menuBar.add(fileMenu); } JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic(KeyEvent.VK_E); Action action = new DefaultEditorKit.CutAction(); action.putValue(Action.NAME, "Cut"); action.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_X, shift)); editMenu.add(action); action = new DefaultEditorKit.CopyAction(); action.putValue(Action.NAME, "Copy"); action.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_C, shift)); editMenu.add(action); action = new DefaultEditorKit.PasteAction(); action.putValue(Action.NAME, "Paste"); action.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_V, shift)); editMenu.add(action); action = new TextAction(DefaultEditorKit.selectAllAction) { public void actionPerformed(ActionEvent e) { getFocusedComponent().selectAll(); } }; action.putValue(Action.NAME, "Select All"); action.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A, shift)); editMenu.add(action); menuBar.add(editMenu); setJMenuBar(menuBar); } textArea = new JTextArea(50, 100); textArea.setLineWrap(true); DefaultCaret caret = (DefaultCaret)textArea.getCaret(); caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); textArea.setEditable(false); JScrollPane scrollPane = new JScrollPane(textArea); add(scrollPane); pack(); setLocation(200, 200); URL iconURL = SwingConsole.class.getClassLoader().getResource(SwingConsole.class.getPackage().getName().replace('.', '/') + "/" + ICON_PATH); if (iconURL != null) { ImageIcon icon = new ImageIcon(iconURL); setIconImage(icon.getImage()); } } @Override public void windowClosing(WindowEvent arg0) { quit(false); } @Override public void windowClosed(WindowEvent arg0) { } @Override public void windowActivated(WindowEvent arg0) { } @Override public void windowDeactivated(WindowEvent arg0) { } @Override public void windowDeiconified(WindowEvent arg0) { } @Override public void windowIconified(WindowEvent arg0) { } @Override public void windowOpened(WindowEvent arg0) { } public PrintStream getPrintStream() { return printStream; } static class TextAreaPrintStream extends PrintStream { public TextAreaPrintStream() { this(new TextAreaOutputStream()); } public TextAreaPrintStream(TextAreaOutputStream out) { super(out, true); } public TextAreaOutputStream getOut() { return (TextAreaOutputStream)out; } } public PrintStream openPrintStream(boolean reuseSystem) { if (reuseSystem && (System.out instanceof TextAreaPrintStream) && ((TextAreaPrintStream)System.out).getOut().setTextAreaIfUnbound(textArea)) { printStream = System.out; } else { printStream = new PrintStream(new TextAreaOutputStream(textArea)); } return printStream; } public void closePrintStream() { if (printStream == System.out) { ((TextAreaPrintStream)System.out).getOut().clearTextAreaIfBound(textArea); } printStream = null; } protected void quit(boolean force) { switch (serviceManager.getState()) { default: try { serviceManager.stopServices(); } catch (Exception ex) { } break; case IDLE: case ERROR_STARTING: if (force) { dispose(); } break; } } }
package com.akiban.sql.optimizer.rule; import com.akiban.sql.optimizer.plan.*; import com.akiban.sql.optimizer.plan.Sort.OrderByExpression; import com.akiban.sql.optimizer.plan.JoinNode.JoinType; import com.akiban.server.error.UnsupportedSQLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; /** A goal for indexing: conditions on joined tables and ordering / grouping. */ public class IndexPicker extends BaseRule { private static final Logger logger = LoggerFactory.getLogger(IndexPicker.class); @Override protected Logger getLogger() { return logger; } @Override public void apply(PlanContext planContext) { BaseQuery query = (BaseQuery)planContext.getPlan(); List<Picker> pickers = new JoinsFinder().find(query); for (Picker picker : pickers) picker.pickIndexes(); } static class Picker { Joinable joinable; BaseQuery query; Set<ColumnSource> boundTables; public Picker(Joinable joinable) { this.joinable = joinable; } public void pickIndexes() { // Start with tables outside this subquery. Then add as we // set up each nested loop join. boundTables = new HashSet<ColumnSource>(query.getOuterTables()); pickIndexes(joinable); } protected void pickIndexes(Joinable joinable) { if (joinable instanceof TableJoins) { pickIndex((TableJoins)joinable); return; } if (joinable instanceof JoinNode) { pickIndexes((JoinNode)joinable); return; } assert !(joinable instanceof TableSource); if (joinable instanceof ColumnSource) { // Subqueries, VALUES, etc. now available. boundTables.add((ColumnSource)joinable); } } protected void pickIndex(TableJoins tableJoins) { if (tableJoins.getScan() != null) // This can happen if a subquery source gets replaced // by ordinary joins that then get dealt with. return; // Goal is to get all the tables joined right here. Others // in the group may come via XxxLookup in a nested // loop. Can only consider table indexes on the inner // joined tables and group indexes corresponding to outer // joins. IndexGoal goal = determineIndexGoal(tableJoins); IndexScan index = pickBestIndex(tableJoins, goal); pickedIndex(tableJoins, goal, index); } protected IndexGoal determineIndexGoal(TableJoins tableJoins) { return determineIndexGoal(tableJoins, tableJoins.getTables()); } protected void pickedIndex(TableJoins tableJoins, IndexGoal goal, IndexScan index) { if (index != null) { goal.installUpstream(index); } PlanNode scan = index; if (scan == null) scan = new GroupScan(tableJoins.getGroup()); tableJoins.setScan(scan); boundTables.addAll(tableJoins.getTables()); } protected IndexGoal determineIndexGoal(PlanNode input, Collection<TableSource> tables) { List<ConditionList> conditionSources = new ArrayList<ConditionList>(); Sort ordering = null; AggregateSource grouping = null; Project projectDistinct = null; while (true) { input = input.getOutput(); if (!(input instanceof Joinable)) break; if (input instanceof JoinNode) { ConditionList conds = ((JoinNode)input).getJoinConditions(); if ((conds != null) && !conds.isEmpty()) conditionSources.add(conds); } } if (input instanceof Select) { ConditionList conds = ((Select)input).getConditions(); if (!conds.isEmpty()) { conditionSources.add(conds); } } input = input.getOutput(); if (input instanceof Sort) { ordering = (Sort)input; } else if (input instanceof AggregateSource) { grouping = (AggregateSource)input; if (!grouping.hasGroupBy()) grouping = null; input = input.getOutput(); if (input instanceof Select) input = input.getOutput(); if (input instanceof Sort) { // Needs to be possible to satisfy both. ordering = (Sort)input; if (grouping != null) { List<ExpressionNode> groupBy = grouping.getGroupBy(); for (OrderByExpression orderBy : ordering.getOrderBy()) { ExpressionNode orderByExpr = orderBy.getExpression(); if (!((orderByExpr.isColumn() && (((ColumnExpression)orderByExpr).getTable() == grouping)) || groupBy.contains(orderByExpr))) { ordering = null; break; } } } } } else if (input instanceof Project) { Project project = (Project)input; input = project.getOutput(); if (input instanceof Distinct) projectDistinct = project; else if (input instanceof Sort) ordering = (Sort)input; } if (conditionSources.isEmpty() && (ordering == null) && (grouping == null) && (projectDistinct == null)) return null; return new IndexGoal(query, boundTables, conditionSources, grouping, ordering, projectDistinct, tables); } protected IndexScan pickBestIndex(TableJoins tableJoins, IndexGoal goal) { if (goal == null) return null; Collection<TableSource> tables = new ArrayList<TableSource>(); Set<TableSource> required = new HashSet<TableSource>(); getRequiredTables(tableJoins.getJoins(), tables, required, true); return goal.pickBestIndex(tables, required); } protected void getRequiredTables(Joinable joinable, Collection<TableSource> tables, Set<TableSource> required, boolean allInner) { if (joinable instanceof JoinNode) { JoinNode join = (JoinNode)joinable; getRequiredTables(join.getLeft(), tables, required, allInner && (join.getJoinType() != JoinType.RIGHT)); getRequiredTables(join.getRight(), tables, required, allInner && (join.getJoinType() != JoinType.LEFT)); } else if (joinable instanceof TableSource) { TableSource table = (TableSource)joinable; tables.add(table); if (allInner) required.add(table); } } protected void pickIndexes(JoinNode join) { join.setImplementation(JoinNode.Implementation.NESTED_LOOPS); Joinable left = join.getLeft(); Joinable right = join.getRight(); boolean tryReverse = false, twoTablesInner = false; if (join.getReverseHook() == null) { switch (join.getJoinType()) { case INNER: twoTablesInner = ((left instanceof TableJoins) && (right instanceof TableJoins)); tryReverse = twoTablesInner; break; case RIGHT: join.reverse(); } } else { tryReverse = join.getReverseHook().canReverse(join); if (!tryReverse) { join.getReverseHook().didNotReverse(join); left = join.getLeft(); right = join.getRight(); } } if (tryReverse) { if (twoTablesInner) { if (pickIndexesTablesInner(join)) return; } if (right instanceof ColumnSource) { if (pickIndexesTableValues(join)) return; left = join.getLeft(); right = join.getRight(); } } // Default is just to do each in the given order. pickIndexes(left); pickIndexes(right); } // Pick indexes for two tables. See which one gets a better // initial index. // TODO: Better to find all the INNER joins beneath this and // do them all at once, not a pair at a time. protected boolean pickIndexesTablesInner(JoinNode join) { TableJoins left = (TableJoins)join.getLeft(); TableJoins right = (TableJoins)join.getRight(); IndexGoal lgoal = determineIndexGoal(left); IndexScan lindex = pickBestIndex(left, lgoal); IndexGoal rgoal = determineIndexGoal(right); IndexScan rindex = pickBestIndex(right, rgoal); boolean rightFirst = false; if (lindex == null) rightFirst = (rindex != null); else if (rindex != null) rightFirst = (lgoal.compare(lindex, rindex) < 0); if (rightFirst) { TableJoins temp = left; left = right; right = temp; join.reverse(); lgoal = rgoal; lindex = rindex; } else if (join.getReverseHook() != null) { join.getReverseHook().didNotReverse(join); } // Commit to the left choice and redo the right with it bound. pickedIndex(left, lgoal, lindex); pickIndexes(right); return true; } // Pick indexes for table and VALUES (or generally a non-table ColumnSource). // Put the VALUES outside if the join condition ends up indexed. protected boolean pickIndexesTableValues(JoinNode join) { TableJoins left = leftOfValues(join); ColumnSource right = (ColumnSource)join.getRight(); boundTables.add(right); IndexGoal lgoal = determineIndexGoal(left); IndexScan lindex = pickBestIndex(left, lgoal); boundTables.remove(right); if ((lindex == null) || !lindex.hasConditions()) return false; boolean found = false; for (ConditionExpression joinCondition : join.getJoinConditions()) { if (lindex.getConditions().contains(joinCondition)) { found = true; } } if (!found) { if (join.getReverseHook() != null) { join.getReverseHook().didNotReverse(join); } return false; } // Put the VALUES outside and commit to that in the simple case. join.reverse(); if (left != join.getRight()) return false; pickedIndex(left, lgoal, lindex); return true; } // Get the table joins that seems to be most interestingly // joined with a VALUES. // TODO: Not very general. protected TableJoins leftOfValues(JoinNode join) { Joinable left = join.getLeft(); if (left instanceof TableJoins) return (TableJoins)left; Collection<TableSource> tables = new ArrayList<TableSource>(); for (ConditionExpression joinCondition : join.getJoinConditions()) { if (joinCondition instanceof ComparisonCondition) { ExpressionNode lop = ((ComparisonCondition)joinCondition).getLeft(); if (lop.isColumn()) { ColumnSource table = ((ColumnExpression)lop).getTable(); if (table instanceof TableSource) tables.add((TableSource)table); } } } if (tables.isEmpty()) return null; return findTableSource(left, tables); } protected TableJoins findTableSource(Joinable joinable, Collection<TableSource> tables) { if (joinable instanceof TableJoins) { TableJoins tjoins = (TableJoins)joinable; for (TableSource table : tables) { if (tjoins.getTables().contains(table)) return tjoins; } } else if (joinable instanceof JoinNode) { JoinNode join = (JoinNode)joinable; TableJoins result = findTableSource(join.getLeft(), tables); if (result != null) return result; return findTableSource(join.getRight(), tables); } return null; } } // Purpose is twofold: // Find top-level joins and note what query they come from; // Annotate subqueries with their outer table references. static class JoinsFinder implements PlanVisitor, ExpressionVisitor { List<Picker> result = new ArrayList<Picker>(); Deque<SubqueryState> subqueries = new ArrayDeque<SubqueryState>(); public List<Picker> find(BaseQuery query) { query.accept(this); for (Picker entry : result) if (entry.query == null) entry.query = query; return result; } @Override public boolean visitEnter(PlanNode n) { if (n instanceof Subquery) { subqueries.push(new SubqueryState((Subquery)n)); return true; } return visit(n); } @Override public boolean visitLeave(PlanNode n) { if (n instanceof Subquery) { SubqueryState s = subqueries.pop(); s.subquery.setOuterTables(s.getTablesReferencedButNotDefined()); } return true; } @Override public boolean visit(PlanNode n) { if (!subqueries.isEmpty() && (n instanceof ColumnSource)) { boolean added = subqueries.peek().tablesDefined.add((ColumnSource)n); assert added : "Table defined more than once"; } if (n instanceof Joinable) { Joinable j = (Joinable)n; while (j.getOutput() instanceof Joinable) j = (Joinable)j.getOutput(); for (Picker entry : result) { if (entry.joinable == j) // Already have another set of joins to same root join. return true; } Picker entry = new Picker(j); if (!subqueries.isEmpty()) { entry.query = subqueries.peek().subquery; } result.add(entry); } return true; } @Override public boolean visitEnter(ExpressionNode n) { return visit(n); } @Override public boolean visitLeave(ExpressionNode n) { return true; } @Override public boolean visit(ExpressionNode n) { if (!subqueries.isEmpty() && (n instanceof ColumnExpression)) { subqueries.peek().tablesReferenced.add(((ColumnExpression)n).getTable()); } return true; } } static class SubqueryState { Subquery subquery; Set<ColumnSource> tablesReferenced = new HashSet<ColumnSource>(); Set<ColumnSource> tablesDefined = new HashSet<ColumnSource>(); public SubqueryState(Subquery subquery) { this.subquery = subquery; } public Set<ColumnSource> getTablesReferencedButNotDefined() { tablesReferenced.removeAll(tablesDefined); return tablesReferenced; } } }
package com.amazon.jenkins.ec2fleet; import com.amazon.jenkins.ec2fleet.cloud.FleetNode; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import com.amazonaws.services.ec2.model.DescribeInstancesResult; import com.amazonaws.services.ec2.model.DescribeRegionsResult; import com.amazonaws.services.ec2.model.DescribeSpotFleetInstancesRequest; import com.amazonaws.services.ec2.model.DescribeSpotFleetRequestsRequest; import com.amazonaws.services.ec2.model.DescribeSpotFleetRequestsResult; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.ModifySpotFleetRequestRequest; import com.amazonaws.services.ec2.model.Region; import com.amazonaws.services.ec2.model.SpotFleetRequestConfig; import com.amazonaws.services.ec2.model.TerminateInstancesRequest; import com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsHelper; import com.cloudbees.jenkins.plugins.awscredentials.AmazonWebServicesCredentials; import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardListBoxModel; import com.google.common.util.concurrent.SettableFuture; import hudson.Extension; import hudson.model.Descriptor; import hudson.model.Label; import hudson.model.Node; import hudson.model.TaskListener; import hudson.security.ACL; import hudson.slaves.Cloud; import hudson.slaves.ComputerConnector; import hudson.slaves.NodeProperty; import hudson.slaves.NodeProvisioner; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import org.springframework.util.ObjectUtils; import javax.annotation.Nonnull; import javax.servlet.ServletException; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; @SuppressWarnings("unused") public class EC2FleetCloud extends Cloud { public static final String FLEET_CLOUD_ID="FleetCloud"; private static final SimpleFormatter sf = new SimpleFormatter(); private final String credentialsId; private final String region; private final String fleet; private final ComputerConnector computerConnector; private final boolean privateIpUsed; private final Integer idleMinutes; private final Integer maxSize; private @Nonnull FleetStateStats status; private final Set<NodeProvisioner.PlannedNode> plannedNodes = new HashSet<NodeProvisioner.PlannedNode>(); private final Set<String> instancesSeen = new HashSet<String>(); private final Set<String> instancesDying = new HashSet<String>(); @DataBoundConstructor public EC2FleetCloud(final String credentialsId, final String region, final String fleet, final ComputerConnector computerConnector, final boolean privateIpUsed, final Integer idleMinutes, final Integer maxSize) { super(FLEET_CLOUD_ID); this.credentialsId = credentialsId; this.region = region; this.fleet = fleet; this.computerConnector = computerConnector; this.idleMinutes = idleMinutes; this.privateIpUsed = privateIpUsed; this.maxSize = maxSize; this.status = new FleetStateStats(fleet, 0, "Initializing", Collections.<String>emptySet()); } public String getCredentialsId() { return credentialsId; } public String getRegion() { return region; } public String getFleet() { return fleet; } public ComputerConnector getComputerConnector() { return computerConnector; } public boolean isPrivateIpUsed() { return privateIpUsed; } public Integer getIdleMinutes() { return idleMinutes; } public Integer getMaxSize() { return maxSize; } public String getJvmSettings() { return ""; } public @Nonnull FleetStateStats getStatus() { return status; } public static void log(final Logger logger, final Level level, final TaskListener listener, final String message) { log(logger, level, listener, message, null); } public static void log(final Logger logger, final Level level, final TaskListener listener, String message, final Throwable exception) { logger.log(level, message, exception); if (listener != null) { if (exception != null) message += " Exception: " + exception; final LogRecord lr = new LogRecord(level, message); final PrintStream printStream = listener.getLogger(); printStream.print(sf.format(lr)); } } @Override public synchronized Collection<NodeProvisioner.PlannedNode> provision( final Label label, final int excessWorkload) { final FleetStateStats stats=updateStatus(); final int maxAllowed = this.getMaxSize(); if (stats.getNumDesired() >= maxAllowed || !"active".equals(stats.getState())) return Collections.emptyList(); final ModifySpotFleetRequestRequest request=new ModifySpotFleetRequestRequest(); request.setSpotFleetRequestId(fleet); request.setTargetCapacity(stats.getNumDesired() + excessWorkload); final AmazonEC2 ec2=connect(credentialsId, region); ec2.modifySpotFleetRequest(request); final List<NodeProvisioner.PlannedNode> resultList = new ArrayList<NodeProvisioner.PlannedNode>(); for(int f=0;f<excessWorkload; ++f) { final SettableFuture<Node> futureNode=SettableFuture.create(); final NodeProvisioner.PlannedNode plannedNode= new NodeProvisioner.PlannedNode("FleetNode-"+f, futureNode, 1); resultList.add(plannedNode); this.plannedNodes.add(plannedNode); } return resultList; } public synchronized FleetStateStats updateStatus() { final AmazonEC2 ec2=connect(credentialsId, region); final FleetStateStats curStatus=FleetStateStats.readClusterState(ec2, getFleet()); status = curStatus; // Check the nodes to see if we have some new ones final Set<String> newInstances = new HashSet<String>(curStatus.getInstances()); final Set<String> jenkinsInstances = new HashSet<String>(); for(final Node node : Jenkins.getActiveInstance().getNodes()) { newInstances.remove(node.getDisplayName()); jenkinsInstances.add(node.getDisplayName()); } newInstances.removeAll(instancesSeen); newInstances.removeAll(instancesDying); // Instance unknown to Jenkins but known to Fleet. Terminate it. for(final String instId : instancesSeen) { if (!instancesDying.contains(instId) && !jenkinsInstances.contains(instId)) { // Use a nuclear option to terminate an unknown instance ec2.terminateInstances(new TerminateInstancesRequest(Collections.singletonList(instId))); } } // If we have new instances - create nodes for them! for(final String instanceId : newInstances) { try { addNewSlave(ec2, instanceId); } catch(final Exception ex) { throw new IllegalStateException(ex); } } return curStatus; } private void addNewSlave(final AmazonEC2 ec2, final String instanceId) throws Exception { // Generate a random FS root final String fsRoot = "/tmp/jenkins-"+UUID.randomUUID().toString().substring(0, 8); final DescribeInstancesResult result=ec2.describeInstances( new DescribeInstancesRequest().withInstanceIds(instanceId)); if (result.getReservations().isEmpty()) //Can't find this instance, skip it return; final Instance instance=result.getReservations().get(0).getInstances().get(0); final String address = isPrivateIpUsed() ? instance.getPrivateIpAddress() : instance.getPublicIpAddress(); // Check if we have the address to use. Nodes don't get it immediately. if (address == null) return; // Wait some more... final FleetNode slave = new FleetNode(instanceId, "Fleet slave for" + instanceId, fsRoot, "1", Node.Mode.NORMAL, "ec2-fleet", new ArrayList<NodeProperty<?>>(), FLEET_CLOUD_ID, computerConnector.launch(address, TaskListener.NULL)); // Initialize our retention strategy if (getIdleMinutes() != null) slave.setRetentionStrategy(new IdleRetentionStrategy(getIdleMinutes(), this)); final Jenkins jenkins=Jenkins.getActiveInstance(); //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (jenkins) { // Try to avoid duplicate nodes final Node n = jenkins.getNode(instanceId); if (n != null) jenkins.removeNode(n); jenkins.addNode(slave); } //A new node, wheee! instancesSeen.add(instanceId); if (!plannedNodes.isEmpty()) { //If we're waiting for a new node - mark it as ready final NodeProvisioner.PlannedNode curNode=plannedNodes.iterator().next(); plannedNodes.remove(curNode); ((SettableFuture<Node>)curNode.future).set(slave); } } public synchronized void terminateInstance(final String instanceId) { if (!instancesSeen.contains(instanceId) && !instancesDying.contains(instanceId)) throw new IllegalStateException("Unknown instance terminated: " + instanceId); if (instancesDying.contains(instanceId)) { final Jenkins jenkins=Jenkins.getActiveInstance(); //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (jenkins) { // If this node has been dying for long enough, get rid of it final Node n = jenkins.getNode(instanceId); if (n != null) { try { jenkins.removeNode(n); } catch(final Exception ex) { throw new IllegalStateException(ex); } } } return; } final FleetStateStats stats=updateStatus(); //We can't remove the last instance if (stats.getNumDesired() == 1 || !"active".equals(stats.getState())) return; final AmazonEC2 ec2 = connect(credentialsId, region); final ModifySpotFleetRequestRequest request=new ModifySpotFleetRequestRequest(); request.setSpotFleetRequestId(fleet); request.setTargetCapacity(stats.getNumDesired() - 1); request.setExcessCapacityTerminationPolicy("NoTermination"); ec2.modifySpotFleetRequest(request); ec2.terminateInstances(new TerminateInstancesRequest(Collections.singletonList(instanceId))); //And remove the instance instancesSeen.remove(instanceId); instancesDying.add(instanceId); } @Override public boolean canProvision(final Label label) { return fleet != null; } private static AmazonEC2 connect(final String credentialsId, final String region) { final AmazonWebServicesCredentials credentials = AWSCredentialsHelper.getCredentials(credentialsId, Jenkins.getActiveInstance()); final AmazonEC2Client client = credentials != null ? new AmazonEC2Client(credentials) : new AmazonEC2Client(); if (region != null) client.setEndpoint("https://ec2." + region + ".amazonaws.com/"); return client; } @Extension @SuppressWarnings("unused") public static class DescriptorImpl extends Descriptor<Cloud> { public boolean useInstanceProfileForCredentials; public String accessId; public String secretKey; public String region; public String fleet; public String userName="root"; public boolean privateIpUsed; public String privateKey; public DescriptorImpl() { super(); load(); } @Override public String getDisplayName() { return "Amazon SpotFleet"; } public List getComputerConnectorDescriptors() { return Jenkins.getActiveInstance().getDescriptorList(ComputerConnector.class); } public ListBoxModel doFillCredentialsIdItems() { return AWSCredentialsHelper.doFillCredentialsIdItems(Jenkins.getActiveInstance()); } public ListBoxModel doFillRegionItems(@QueryParameter final String credentialsId, @QueryParameter final String region) throws IOException, ServletException { final List<Region> regionList; try { final AmazonEC2 client = connect(credentialsId, null); final DescribeRegionsResult regions=client.describeRegions(); regionList=regions.getRegions(); } catch(final Exception ex) { //Ignore bad exceptions return new ListBoxModel(); } final ListBoxModel model = new ListBoxModel(); for(final Region reg : regionList) { model.add(new ListBoxModel.Option(reg.getRegionName(), reg.getRegionName())); } return model; } public ListBoxModel doFillFleetItems(@QueryParameter final String region, @QueryParameter final String credentialsId, @QueryParameter final String fleet) throws IOException, ServletException { final ListBoxModel model = new ListBoxModel(); try { final AmazonEC2 client=connect(credentialsId, region); String token = null; do { final DescribeSpotFleetRequestsRequest req=new DescribeSpotFleetRequestsRequest(); req.withNextToken(token); final DescribeSpotFleetRequestsResult result=client.describeSpotFleetRequests(req); for(final SpotFleetRequestConfig config : result.getSpotFleetRequestConfigs()) { final String curFleetId=config.getSpotFleetRequestId(); final String displayStr=curFleetId+ " ("+config.getSpotFleetRequestState()+")"; model.add(new ListBoxModel.Option(displayStr, curFleetId, ObjectUtils.nullSafeEquals(fleet, curFleetId))); } token = result.getNextToken(); } while(token != null); } catch(final Exception ex) { //Ignore bad exceptions return model; } return model; } public FormValidation doTestConnection( @QueryParameter final String credentialsId, @QueryParameter final String region, @QueryParameter final String fleet) { try { final AmazonEC2 client=connect(credentialsId, region); client.describeSpotFleetInstances( new DescribeSpotFleetInstancesRequest().withSpotFleetRequestId(fleet)); } catch(final Exception ex) { return FormValidation.error(ex.getMessage()); } return FormValidation.ok("Success"); } @Override public boolean configure(final StaplerRequest req, final JSONObject formData) throws FormException { req.bindJSON(this, formData); save(); return super.configure(req,formData); } public boolean isUseInstanceProfileForCredentials() { return useInstanceProfileForCredentials; } public String getAccessId() { return accessId; } public String getSecretKey() { return secretKey; } public String getRegion() { return region; } public String getFleet() { return fleet; } } }
package com.dongdongxia.myfastjson.util; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.security.AccessControlException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.dongdongxia.myfastjson.PropertyNamingStrategy; import com.dongdongxia.myfastjson.annotation.JSONField; import com.dongdongxia.myfastjson.annotation.JSONType; import com.dongdongxia.myfastjson.parser.Feature; import com.dongdongxia.myfastjson.parser.ParserConfig; import com.dongdongxia.myfastjson.serializer.SerializerFeature; /** * * <P>Description: </P> * @ClassName: TypeUtils * @author java_liudong@163.com 2017523 5:53:56 */ public class TypeUtils { public static boolean compatibleWithJavaBean = false; private static boolean setAccessibleEnable = true; private static boolean transientClassInited = false; private static Class<? extends Annotation> transientClass; /** field name */ public static boolean compatibleWithFieldName = false; static { try { TypeUtils.compatibleWithJavaBean = "true".equals(IOUtils.getStringProperty(IOUtils.MYFASTJSON_COMPATIBLEWITHJAVABEAN)); TypeUtils.compatibleWithFieldName = "true".equals(IOUtils.getStringProperty(IOUtils.MYFASTJSON_COMPATIBLEWITHFIELDBEAN)); } catch (Throwable e) { // skip } } /** * * <p>Title: setAccessible</p> * <p>Description: , </p> * @param obj * @author java_liudong@163.com 2017523 5:56:57 */ static void setAccessible(AccessibleObject obj) { if (!setAccessibleEnable) { return ; } // public if (obj.isAccessible()) { return ; } try { obj.setAccessible(true); } catch (AccessControlException error) { setAccessibleEnable = false; } } /** * * <p>Title: isTransient</p> * <p>Description: TODO</p> * @param method * @return * @author java_liudong@163.com 2017523 6:17:27 */ @SuppressWarnings("unchecked") public static boolean isTransient(Method method) { if (method == null) { return false; } if (!transientClassInited) { try { transientClass = (Class<? extends Annotation>) Class.forName("java.beans.Transient"); } catch (Exception e) { // skip } finally { transientClassInited = true; } } if (transientClass != null) { Annotation annotation = method.getAnnotation(transientClass); return annotation != null; } return false; } /** * * <p>Title: getClass</p> * <p>Description: </p> * @param type * @return * @author java_liudong@163.com 2017523 6:48:54 */ public static Class<?> getClass(Type type) { if (type.getClass() == Class.class) { return (Class<?>) type; } if (type instanceof ParameterizedType) { return getClass(((ParameterizedType) type).getRawType()); } if (type instanceof TypeVariable) { Type boundType = ((TypeVariable<?>) type).getBounds()[0]; return (Class<?>) boundType; } return Object.class; } /** * * <p>Title: isGenericParamType</p> * <p>Description: , Object </p> * @param type * @return * @author java_liudong@163.com 2017524 10:40:02 */ public static boolean isGenericParamType(Type type) { if (type instanceof ParameterizedType) { return true; } if (type instanceof Class) { Type superType = ((Class<?>) type).getGenericSuperclass(); if (superType == Object.class) { return false; } return isGenericParamType(superType); } return false; } /** * * <p>Title: getGenericParamType</p> * <p>Description: </p> * @param type * @return * @author java_liudong@163.com 2017524 10:46:50 */ public static Type getGenericParamType(Type type) { if (type instanceof ParameterizedType) { return type; } if (type instanceof Class) { return getGenericParamType(((Class<?>) type).getGenericSuperclass()); } return type; } /** * * <p>Title: getSuperMethodAnnotation</p> * <p>Description: </p> * @param clazz * @param method * @return * @author java_liudong@163.com 201765 5:06:31 */ public static JSONField getSuperMethodAnnotation(final Class<?> clazz, final Method method) { Class<?>[] interfaces = clazz.getInterfaces(); if (interfaces.length > 0) { Class<?>[] types = method.getParameterTypes(); for (Class<?> interfaceClass : interfaces) { for (Method interfaceMethod : interfaceClass.getMethods()) { Class<?>[] interfaceTypes = interfaceMethod.getParameterTypes(); if (interfaceTypes.length != types.length) { continue ; } if (!interfaceMethod.getName().equals(method.getName())) { continue ; } boolean match = true; for (int i = 0; i < types.length; ++i) { if (!interfaceTypes[i].equals(types[i])) { match = false; break ; } } if (!match) { continue ; } JSONField annotation = interfaceMethod.getAnnotation(JSONField.class); if (annotation != null) { return annotation; } } } } Class<?> superClass = clazz.getSuperclass(); if (superClass == null) { return null; } if (Modifier.isAbstract(superClass.getModifiers())) { Class<?>[] types = method.getParameterTypes(); for (Method interfaceMethod : superClass.getMethods()) { Class<?>[] interfaceTypes = interfaceMethod.getParameterTypes(); if (interfaceTypes.length != types.length) { continue ; } if (!interfaceMethod.getName().equals(method.getName())) { continue ; } boolean match = true; for (int i = 0; i < types.length; ++i) { if (!interfaceTypes[i].equals(types[i])) { match = false; break; } } if (!match) { continue ; } JSONField annotation = interfaceMethod.getAnnotation(JSONField.class); if (annotation != null) { return annotation; } } } return null; } /** * * <p>Title: isJSONTypeIgnore</p> * <p>Description: , </p> * @param clazz * @param propertyName * @return * @author java_liudong@163.com 201765 6:20:12 */ private static boolean isJSONTypeIgnore(Class<?> clazz, String propertyName) { JSONType jsonType = clazz.getAnnotation(JSONType.class); if (jsonType != null) { /** * 1, includes , JSONType includes ignores , includes * 2, JavaJS, equals() equalsIgnoreClase(), * , */ String[] fields = jsonType.includes(); if (fields.length > 0) { for (int i = 0; i < fields.length; i++) { if (propertyName.equals(fields[i])) { return false; } } return true; } else { fields = jsonType.ignores(); for (int i = 0; i < fields.length; i++) { if (propertyName.equals(fields[i])) { return true; } } } } if (clazz.getSuperclass() != Object.class && clazz.getSuperclass() != null) { if (isJSONTypeIgnore(clazz.getSuperclass(), propertyName)) { return true; } } return false; } /** * * <p>Title: getPropertyNameByCompatibleFieldName</p> * <p>Description: </p> * @param fieldCacheMap * @param methodName * @param propertyName * @param fromIdx * @return * @author java_liudong@163.com 201766 9:31:55 */ private static String getPropertyNameByCompatibleFieldName(Map<String, Field> fieldCacheMap, String methodName, String propertyName, int fromIdx) { if (compatibleWithFieldName) { if (!fieldCacheMap.containsKey(propertyName)) { String tempPropertyName = methodName.substring(fromIdx); return fieldCacheMap.containsKey(tempPropertyName) ? tempPropertyName : propertyName; } } return propertyName; } /** * * <p>Title: decapotalize</p> * <p>Description: </p> * @param name * @return * @author java_liudong@163.com 201766 9:46:06 */ public static String decapotalize(String name) { if (name == null || name.length() == 0) { return name; } if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) && Character.isUpperCase(name.charAt(0)) ) { return name; } char chars[] = name.toCharArray(); chars[0] = Character.toLowerCase(chars[0]); return new String(chars); } /** * * <p>Title: computeFields</p> * <p>Description: </p> * @param clazz * @param aliasMap MAP * @param propertyNamingStrategy * @param fieldInfoMap * @param fields * @author java_liudong@163.com 201766 10:05:04 */ private static void computeFields(Class<?> clazz, Map<String, String> aliasMap, PropertyNamingStrategy propertyNamingStrategy, Map<String, FieldInfo> fieldInfoMap, Field[] fields) { for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) { continue ; } JSONField fieldAnnotation = field.getAnnotation(JSONField.class); int ordinal = 0, serializeFeatures = 0, parserFeatures = 0; String propertyName = field.getName(); String label = null; if (fieldAnnotation != null) { if (!fieldAnnotation.serialize()) { continue ; } ordinal = fieldAnnotation.ordinal(); serializeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures()); parserFeatures = Feature.of(fieldAnnotation.parseFeatures()); if (fieldAnnotation.name().length() != 0) { propertyName = fieldAnnotation.name(); } if (fieldAnnotation.label().length() != 0) { label = fieldAnnotation.label(); } } if (aliasMap != null) { propertyName = aliasMap.get(propertyName); if (propertyName == null) { continue ; } } if (propertyNamingStrategy != null) { propertyName = propertyNamingStrategy.translate(propertyName); } if (!fieldInfoMap.containsKey(propertyName)) { FieldInfo fieldInfo = new FieldInfo(propertyName, null, field, clazz, null, ordinal, serializeFeatures, parserFeatures, null, fieldAnnotation, label); fieldInfoMap.put(propertyName, fieldInfo); } } } /** * * <p>Title: getFieldInfos</p> * <p>Description: ,List, </p> * @param clazz * @param sorted * @param fieldInfoMap * @return * @author java_liudong@163.com 201766 10:54:09 */ private static List<FieldInfo> getFieldInfos(Class<?> clazz, boolean sorted, Map<String, FieldInfo> fieldInfoMap) { List<FieldInfo> fieldInfoList = new ArrayList<FieldInfo>(); boolean containsAll = false; String[] orders = null; JSONType annotation = clazz.getAnnotation(JSONType.class); if (annotation != null) { orders = annotation.orders(); if (orders != null && orders.length == fieldInfoMap.size()) { containsAll = true; for (String item : orders) { if (!fieldInfoMap.containsKey(item)) { containsAll = false; break ; } } } else { containsAll = false; } } if (containsAll) { for (FieldInfo fieldInfo : fieldInfoMap.values()) { fieldInfoList.add(fieldInfo); } if (sorted) { Collections.sort(fieldInfoList); } } return fieldInfoList; } /** * * <p>Title: computeGetters</p> * <p>Description: ,get</p> * @param clazz * @param jsonType * @param aliasMap * @param fieldCacheMap * @param sorted * @param propertyNamingStrategy * @return * @author java_liudong@163.com 201766 11:12:13 */ public static List<FieldInfo> computeGetters(Class<?> clazz, JSONType jsonType, Map<String, String> aliasMap, Map<String, Field> fieldCacheMap, boolean sorted, PropertyNamingStrategy propertyNamingStrategy) { Map<String, FieldInfo> fieldInfoMap = new LinkedHashMap<String, FieldInfo>(); for (Method method : clazz.getMethods()) { String methodName = method.getName(); int ordinal = 0, serializeFeatures = 0, parserFeatures = 0; String label = null; if (Modifier.isStatic(method.getModifiers())) { continue ; } if (method.getReturnType().equals(Void.TYPE)) { continue ; } if (method.getParameterTypes().length != 0) { continue ; } if (method.getReturnType() == ClassLoader.class) { continue ; } if (method.getName().equals("getMetaClass") && method.getReturnType().getName().equals("groovy.lang.MetaClass")) { continue ; } JSONField annotation = method.getAnnotation(JSONField.class); if (annotation == null) { annotation = getSuperMethodAnnotation(clazz, method); } if (annotation != null) { if (!annotation.serialize()) { continue ; } ordinal = annotation.ordinal(); serializeFeatures = SerializerFeature.of(annotation.serialzeFeatures()); parserFeatures = Feature.of(annotation.parseFeatures()); if (annotation.name().length() != 0) { String propertyName = annotation.name(); if (aliasMap != null) { propertyName = aliasMap.get(propertyName); if (propertyName == null) { continue ; } } FieldInfo fieldInfo = new FieldInfo(propertyName, method, null, clazz, null, ordinal, serializeFeatures, parserFeatures, annotation, null, label); fieldInfoMap.put(propertyName, fieldInfo); continue ; } if (annotation.label().length() != 0) { label = annotation.label(); } } if (methodName.startsWith("get")) { if (methodName.length() < 4) { continue ; } if (methodName.equals("getClass")) { continue ; } if (methodName.equals("getDeclaringClass") && clazz.isEnum()) { continue ; } char c3 = methodName.charAt(3); // getName , N String propertyName; if (Character.isUpperCase(c3) || c3 > 512 ) { if (compatibleWithJavaBean) { propertyName = decapitalize(methodName.substring(3)); } else { propertyName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4); } propertyName = getPropertyNameByCompatibleFieldName(fieldCacheMap, methodName, propertyName, 3); } else if (c3 == '_') { propertyName = methodName.substring(4); } else if (c3 == 'f') { propertyName = methodName.substring(3); } else if (methodName.length() >= 5 && Character.isUpperCase(methodName.charAt(4))) { propertyName = decapitalize(methodName.substring(3)); } else { continue ; } boolean ignore = isJSONTypeIgnore(clazz, propertyName); if (ignore) { continue ; } // beanfield, Field field = ParserConfig.getFieldFromCache(propertyName, fieldCacheMap); if (field == null && propertyName.length() > 1) { char ch = propertyName.charAt(1); if (ch >= 'A' && ch <= 'Z') { String javaBeanCompatiblePropertyName = decapitalize(methodName.substring(3)); field = ParserConfig.getFieldFromCache(javaBeanCompatiblePropertyName, fieldCacheMap); } } JSONField fieldAnnotation = null; if (field != null) { fieldAnnotation = field.getAnnotation(JSONField.class); if (fieldAnnotation != null) { if (!fieldAnnotation.serialize()) { continue ; } ordinal = fieldAnnotation.ordinal(); serializeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures()); parserFeatures = Feature.of(fieldAnnotation.parseFeatures()); if (fieldAnnotation.name().length() != 0) { propertyName = fieldAnnotation.name(); if (aliasMap != null) { propertyName = aliasMap.get(propertyName); if (propertyName == null) { continue ; } } } if (fieldAnnotation.label().length() != 0) { label = fieldAnnotation.label(); } } } if (aliasMap != null) { propertyName = aliasMap.get(propertyName); if (propertyName == null) { continue ; } } if (propertyNamingStrategy != null) { propertyName = propertyNamingStrategy.translate(propertyName); } FieldInfo fieldInfo = new FieldInfo(propertyName, method, field, clazz, null, ordinal, serializeFeatures, parserFeatures, annotation, fieldAnnotation, label); fieldInfoMap.put(propertyName, fieldInfo); } // boolean if (methodName.startsWith("is")) { if (methodName.length() < 3) { continue ; } if (method.getReturnType() != Boolean.TYPE && method.getReturnType() != Boolean.class) { continue ; } char c2 = methodName.charAt(2); String propertyName; if (Character.isUpperCase(c2)) { if (compatibleWithJavaBean) { propertyName = decapitalize(methodName.substring(2)); } else { propertyName = Character.toLowerCase(methodName.charAt(2)) + methodName.substring(3); } propertyName = getPropertyNameByCompatibleFieldName(fieldCacheMap, methodName, propertyName, 2); } else if (c2 == '_') { propertyName = methodName.substring(3); } else if (c2 == 'f') { propertyName = methodName.substring(2); } else { continue ; } Field field = ParserConfig.getFieldFromCache(propertyName, fieldCacheMap); if (field == null) { field = ParserConfig.getFieldFromCache(methodName, fieldCacheMap); } JSONField fieldAnnotation = null; if (field != null) { fieldAnnotation = field.getAnnotation(JSONField.class); if (fieldAnnotation != null) { if (!fieldAnnotation.serialize()) { continue ; } ordinal = fieldAnnotation.ordinal(); serializeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures()); parserFeatures = Feature.of(fieldAnnotation.parseFeatures()); if (fieldAnnotation.name().length() != 0) { propertyName = fieldAnnotation.name(); if (aliasMap != null) { propertyName = aliasMap.get(propertyName); if (propertyName == null) { continue ; } } if (propertyNamingStrategy != null) { propertyName = propertyNamingStrategy.translate(propertyName); } // get if (fieldInfoMap.containsKey(propertyName)) { continue ; } FieldInfo fieldInfo = new FieldInfo(propertyName, method, field, clazz, null, ordinal, serializeFeatures, parserFeatures, annotation, fieldAnnotation, label); fieldInfoMap.put(propertyName, fieldInfo); } } Field[] fields = clazz.getFields(); computeFields(clazz, aliasMap, propertyNamingStrategy, fieldInfoMap, fields); return getFieldInfos(clazz, sorted, fieldInfoMap); } } } return null; } /** * * <p>Title: decapitalize</p> * <p>Description: </p> * @param name * @return * @author java_liudong@163.com 201766 6:40:34 */ public static String decapitalize(String name) { if (name == null || name.length() == 0) { return name; } if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) && Character.isUpperCase(0)) { return name; } char[] chars = name.toCharArray(); chars[0] = Character.toLowerCase(chars[0]); return new String(chars); } }
package com.elmakers.mine.bukkit.utility; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collection; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.BlockFace; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; /** * Contains some raw methods for doing some simple NMS utilities. * * This is not meant to be a replacement for full-on NMS or Protocol libs, * but it is enough for Magic to use internally without requiring any * external dependencies. * * Use any of this at your own risk! */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class NMSUtils { protected static boolean failed = false; protected static String versionPrefix = ""; protected static Class<?> class_ItemStack; protected static Class<?> class_NBTBase; protected static Class<?> class_NBTTagCompound; protected static Class<?> class_NBTTagList; protected static Class<?> class_NBTTagByte; protected static Class<?> class_NBTTagString; protected static Class<?> class_CraftTask; protected static Class<?> class_CraftInventoryCustom; protected static Class<?> class_CraftItemStack; protected static Class<?> class_CraftLivingEntity; protected static Class<?> class_Entity; protected static Class<?> class_EntityCreature; protected static Class<?> class_EntityLiving; protected static Class<?> class_DataWatcher; protected static Class<?> class_DamageSource; protected static Class<?> class_World; protected static Class<?> class_Packet; protected static Class<Enum> class_EnumSkyBlock; protected static Class<?> class_PacketPlayOutMapChunkBulk; protected static Class<?> class_EntityPainting; protected static Class<?> class_EntityItemFrame; protected static Class<?> class_EntityMinecartRideable; protected static Class<?> class_AxisAlignedBB; protected static Class<?> class_PathPoint; protected static Class<?> class_PathEntity; protected static Method class_NBTTagList_addMethod; protected static Method class_NBTTagCompound_setMethod; protected static Method class_DataWatcher_watchMethod; protected static Method class_World_getEntitiesMethod; protected static Method class_Entity_getBukkitEntityMethod; protected static Method class_EntityLiving_damageEntityMethod; protected static Method class_DamageSource_getMagicSourceMethod; protected static Method class_AxisAlignedBB_createBBMethod; protected static Method class_World_explodeMethod; protected static Method class_NBTTagCompound_setBooleanMethod; protected static Method class_NBTTagCompound_setStringMethod; protected static Method class_NBTTagCompound_removeMethod; protected static Method class_NBTTagCompound_getStringMethod; protected static Method class_NBTTagCompound_getMethod; protected static Method class_NBTTagCompound_getCompoundMethod; protected static Method class_CraftItemStack_copyMethod; protected static Method class_CraftItemStack_mirrorMethod; protected static Method class_NBTTagCompound_hasKeyMethod; protected static Constructor class_NBTTagList_consructor; protected static Constructor class_NBTTagList_legacy_consructor; protected static Constructor class_CraftInventoryCustom_constructor; protected static Constructor class_NBTTagByte_constructor; protected static Constructor class_NBTTagByte_legacy_constructor; protected static Field class_Entity_invulnerableField; protected static Field class_ItemStack_tagField; protected static Field class_DamageSource_MagicField; static { // Find classes Bukkit hides from us. :-D // Much thanks to @DPOHVAR for sharing the PowerNBT code that powers the reflection approach. String className = Bukkit.getServer().getClass().getName(); String[] packages = className.split("\\."); if (packages.length == 5) { versionPrefix = packages[3] + "."; } try { class_Entity = fixBukkitClass("net.minecraft.server.Entity"); class_EntityLiving = fixBukkitClass("net.minecraft.server.EntityLiving"); class_ItemStack = fixBukkitClass("net.minecraft.server.ItemStack"); class_DataWatcher = fixBukkitClass("net.minecraft.server.DataWatcher"); class_NBTBase = fixBukkitClass("net.minecraft.server.NBTBase"); class_NBTTagCompound = fixBukkitClass("net.minecraft.server.NBTTagCompound"); class_NBTTagList = fixBukkitClass("net.minecraft.server.NBTTagList"); class_NBTTagString = fixBukkitClass("net.minecraft.server.NBTTagString"); class_NBTTagByte = fixBukkitClass("net.minecraft.server.NBTTagByte"); class_CraftInventoryCustom = fixBukkitClass("org.bukkit.craftbukkit.inventory.CraftInventoryCustom"); class_CraftItemStack = fixBukkitClass("org.bukkit.craftbukkit.inventory.CraftItemStack"); class_CraftTask = fixBukkitClass("org.bukkit.craftbukkit.scheduler.CraftTask"); class_CraftLivingEntity = fixBukkitClass("org.bukkit.craftbukkit.entity.CraftLivingEntity"); class_Packet = fixBukkitClass("net.minecraft.server.Packet"); class_World = fixBukkitClass("net.minecraft.server.World"); class_EnumSkyBlock = (Class<Enum>)fixBukkitClass("net.minecraft.server.EnumSkyBlock"); class_EntityPainting = fixBukkitClass("net.minecraft.server.EntityPainting"); class_EntityCreature = fixBukkitClass("net.minecraft.server.EntityCreature"); class_EntityItemFrame = fixBukkitClass("net.minecraft.server.EntityItemFrame"); class_EntityMinecartRideable = fixBukkitClass("net.minecraft.server.EntityMinecartRideable"); class_AxisAlignedBB = fixBukkitClass("net.minecraft.server.AxisAlignedBB"); class_DamageSource = fixBukkitClass("net.minecraft.server.DamageSource"); class_PathEntity = fixBukkitClass("net.minecraft.server.PathEntity"); class_PathPoint = fixBukkitClass("net.minecraft.server.PathPoint"); class_NBTTagList_addMethod = class_NBTTagList.getMethod("add", class_NBTBase); class_NBTTagCompound_setMethod = class_NBTTagCompound.getMethod("set", String.class, class_NBTBase); class_DataWatcher_watchMethod = class_DataWatcher.getMethod("watch", Integer.TYPE, Object.class); class_World_getEntitiesMethod = class_World.getMethod("getEntities", class_Entity, class_AxisAlignedBB); class_Entity_getBukkitEntityMethod = class_Entity.getMethod("getBukkitEntity"); class_AxisAlignedBB_createBBMethod = class_AxisAlignedBB.getMethod("a", Double.TYPE, Double.TYPE, Double.TYPE, Double.TYPE, Double.TYPE, Double.TYPE); class_World_explodeMethod = class_World.getMethod("createExplosion", class_Entity, Double.TYPE, Double.TYPE, Double.TYPE, Float.TYPE, Boolean.TYPE, Boolean.TYPE); class_NBTTagCompound_setBooleanMethod = class_NBTTagCompound.getMethod("setBoolean", String.class, Boolean.TYPE); class_NBTTagCompound_setStringMethod = class_NBTTagCompound.getMethod("setString", String.class, String.class); class_NBTTagCompound_removeMethod = class_NBTTagCompound.getMethod("remove", String.class); class_NBTTagCompound_getStringMethod = class_NBTTagCompound.getMethod("getString", String.class); class_CraftItemStack_copyMethod = class_CraftItemStack.getMethod("asNMSCopy", org.bukkit.inventory.ItemStack.class); class_CraftItemStack_mirrorMethod = class_CraftItemStack.getMethod("asCraftMirror", class_ItemStack); class_NBTTagCompound_hasKeyMethod = class_NBTTagCompound.getMethod("hasKey", String.class); class_NBTTagCompound_getMethod = class_NBTTagCompound.getMethod("get", String.class); class_NBTTagCompound_getCompoundMethod = class_NBTTagCompound.getMethod("getCompound", String.class); class_EntityLiving_damageEntityMethod = class_EntityLiving.getMethod("damageEntity", class_DamageSource, Float.TYPE); class_DamageSource_getMagicSourceMethod = class_DamageSource.getMethod("b", class_Entity, class_Entity); class_CraftInventoryCustom_constructor = class_CraftInventoryCustom.getConstructor(InventoryHolder.class, Integer.TYPE, String.class); class_Entity_invulnerableField = class_Entity.getDeclaredField("invulnerable"); class_Entity_invulnerableField.setAccessible(true); class_ItemStack_tagField = class_ItemStack.getField("tag"); class_DamageSource_MagicField = class_DamageSource.getField("MAGIC"); try { class_NBTTagList_legacy_consructor = class_NBTTagString.getConstructor(String.class, String.class); class_NBTTagByte_legacy_constructor = class_NBTTagByte.getConstructor(String.class, Byte.TYPE); } catch (Throwable legacy) { class_NBTTagList_consructor = class_NBTTagString.getConstructor(String.class); class_NBTTagByte_constructor = class_NBTTagByte.getConstructor(Byte.TYPE); } class_PacketPlayOutMapChunkBulk = getVersionedBukkitClass("net.minecraft.server.PacketPlayOutMapChunkBulk", "net.minecraft.server.Packet56MapChunkBulk"); } catch (Throwable ex) { failed = true; ex.printStackTrace(); } } public static boolean getFailed() { return failed; } public static Class<?> getVersionedBukkitClass(String newVersion, String oldVersion) { Class<?> c = fixBukkitClass(newVersion, true); if (c == null) { c = fixBukkitClass(oldVersion, true); if (c == null) { Bukkit.getLogger().warning("Could not bind to " + newVersion + " or " + oldVersion); } } return c; } public static Class<?> fixBukkitClass(String className) { return fixBukkitClass(className, false); } public static Class<?> fixBukkitClass(String className, boolean quiet) { if (!versionPrefix.isEmpty()) { className = className.replace("org.bukkit.craftbukkit.", "org.bukkit.craftbukkit." + versionPrefix); className = className.replace("net.minecraft.server.", "net.minecraft.server." + versionPrefix); } Class<?> result = null; try { result = NMSUtils.class.getClassLoader().loadClass(className); } catch (ClassNotFoundException e) { result = null; } if (!quiet && result == null) { Bukkit.getLogger().warning("Failed to bind to class " + className); } return result; } public static Object getHandle(org.bukkit.inventory.ItemStack stack) { Object handle = null; try { Field handleField = stack.getClass().getDeclaredField("handle"); handleField.setAccessible(true); handle = handleField.get(stack); } catch (Throwable ex) { handle = null; } return handle; } public static Object getHandle(org.bukkit.World world) { if (world == null) return null; Object handle = null; try { Method handleMethod = world.getClass().getMethod("getHandle"); handle = handleMethod.invoke(world); } catch (Throwable ex) { ex.printStackTrace(); } return handle; } public static Object getHandle(org.bukkit.entity.Entity entity) { if (entity == null) return null; Object handle = null; try { Method handleMethod = entity.getClass().getMethod("getHandle"); handle = handleMethod.invoke(entity); } catch (Throwable ex) { ex.printStackTrace(); } return handle; } public static Object getHandle(org.bukkit.entity.LivingEntity entity) { if (entity == null) return null; Object handle = null; try { Method handleMethod = entity.getClass().getMethod("getHandle"); handle = handleMethod.invoke(entity); } catch (Throwable ex) { ex.printStackTrace(); } return handle; } public static boolean isDone(org.bukkit.Chunk chunk) { Object chunkHandle = getHandle(chunk); boolean done = false; try { Field doneField = chunkHandle.getClass().getDeclaredField("done"); doneField.setAccessible(true); done = (Boolean)doneField.get(chunkHandle); } catch (Throwable ex) { ex.printStackTrace(); } return done; } public static Object getHandle(org.bukkit.Chunk chunk) { Object handle = null; try { Method handleMethod = chunk.getClass().getMethod("getHandle"); handle = handleMethod.invoke(chunk); } catch (Throwable ex) { ex.printStackTrace(); } return handle; } public static Object getHandle(org.bukkit.entity.Player player) { Object handle = null; try { Method handleMethod = player.getClass().getMethod("getHandle"); handle = handleMethod.invoke(player); } catch (Throwable ex) { ex.printStackTrace(); } return handle; } protected static Object getHandle(Object object) { Object handle = null; try { Method handleMethod = object.getClass().getMethod("getHandle"); handle = handleMethod.invoke(object); } catch (Throwable ex) { ex.printStackTrace(); } return handle; } protected static void sendPacket(Location source, Collection<Player> players, Object packet) throws Exception { players = ((players != null && players.size() > 0) ? players : source.getWorld().getPlayers()); int viewDistanceSquared = Bukkit.getServer().getViewDistance() * Bukkit.getServer().getViewDistance(); for(Player p1 : players) { if(p1.getLocation().distanceSquared(source) <= viewDistanceSquared) { sendPacket(p1, packet); } } } protected static void sendPacket(Player player, Object packet) throws Exception { Object playerHandle = getHandle(player); Field connectionField = playerHandle.getClass().getField("playerConnection"); Object connection = connectionField.get(playerHandle); Method sendPacketMethod = connection.getClass().getMethod("sendPacket", class_Packet); sendPacketMethod.invoke(connection, packet); } public static int getFacing(BlockFace direction) { int dir; switch (direction) { case SOUTH: default: dir = 0; break; case WEST: dir = 1; break; case NORTH: dir = 2; break; case EAST: dir = 3; break; } return dir; } public static org.bukkit.entity.Entity getBukkitEntity(Object entity) { if (entity == null) return null; try { Method getMethod = entity.getClass().getMethod("getBukkitEntity"); Object bukkitEntity = getMethod.invoke(entity); if (!(bukkitEntity instanceof org.bukkit.entity.Entity)) return null; return (org.bukkit.entity.Entity)bukkitEntity; } catch (Throwable ex) { ex.printStackTrace(); } return null; } public static Object getTag(Object mcItemStack) { Object tag = null; try { tag = class_ItemStack_tagField.get(mcItemStack); } catch (Throwable ex) { ex.printStackTrace(); } return tag; } protected static Object getNMSCopy(ItemStack stack) { Object nms = null; try { nms = class_CraftItemStack_copyMethod.invoke(null, stack); } catch (Throwable ex) { ex.printStackTrace(); } return nms; } public static ItemStack getCopy(ItemStack stack) { if (stack == null) return null; try { Object craft = getNMSCopy(stack); stack = (ItemStack)class_CraftItemStack_mirrorMethod.invoke(null, craft); } catch (Throwable ex) { stack = null; } return stack; } public static ItemStack makeReal(ItemStack stack) { if (stack == null) return null; Object nmsStack = getHandle(stack); if (nmsStack == null) { stack = getCopy(stack); nmsStack = getHandle(stack); } if (nmsStack == null) { return null; } try { Object tag = class_ItemStack_tagField.get(nmsStack); if (tag == null) { class_ItemStack_tagField.set(nmsStack, class_NBTTagCompound.newInstance()); } } catch (Throwable ex) { ex.printStackTrace(); return null; } return stack; } public static String getMeta(ItemStack stack, String tag, String defaultValue) { String result = getMeta(stack, tag); return result == null ? defaultValue : result; } public static boolean hasMeta(ItemStack stack, String tag) { return getNode(stack, tag) != null; } public static Object getNode(ItemStack stack, String tag) { if (stack == null) return null; Object meta = null; try { Object craft = getHandle(stack); if (craft == null) return null; Object tagObject = getTag(craft); if (tagObject == null) return null; meta = class_NBTTagCompound_getMethod.invoke(tagObject, tag); } catch (Throwable ex) { ex.printStackTrace(); } return meta; } public static boolean containsNode(Object nbtBase, String tag) { if (nbtBase == null) return false; Boolean result = false; try { result = (Boolean)class_NBTTagCompound_hasKeyMethod.invoke(nbtBase, tag); } catch (Throwable ex) { ex.printStackTrace(); } return result; } public static Object getNode(Object nbtBase, String tag) { if (nbtBase == null) return null; Object meta = null; try { meta = class_NBTTagCompound_getMethod.invoke(nbtBase, tag); } catch (Throwable ex) { ex.printStackTrace(); } return meta; } public static Object createNode(Object nbtBase, String tag) { if (nbtBase == null) return null; Object meta = null; try { meta = class_NBTTagCompound_getCompoundMethod.invoke(nbtBase, tag); class_NBTTagCompound_setMethod.invoke(nbtBase, tag, meta); } catch (Throwable ex) { ex.printStackTrace(); } return meta; } public static Object createNode(ItemStack stack, String tag) { if (stack == null) return null; Object outputObject = getNode(stack, tag); if (outputObject == null) { try { Object craft = getHandle(stack); if (craft == null) return null; Object tagObject = getTag(craft); if (tagObject == null) return null; outputObject = class_NBTTagCompound.newInstance(); class_NBTTagCompound_setMethod.invoke(tagObject, tag, outputObject); } catch (Throwable ex) { ex.printStackTrace(); } } return outputObject; } public static String getMeta(Object node, String tag, String defaultValue) { String meta = getMeta(node, tag); return meta == null || meta.length() == 0 ? defaultValue : meta; } public static String getMeta(Object node, String tag) { if (node == null || !class_NBTTagCompound.isInstance(node)) return null; String meta = null; try { meta = (String)class_NBTTagCompound_getStringMethod.invoke(node, tag); } catch (Throwable ex) { ex.printStackTrace(); } return meta; } public static void setMeta(Object node, String tag, String value) { if (node == null|| !class_NBTTagCompound.isInstance(node)) return; try { if (value == null || value.length() == 0) { class_NBTTagCompound_removeMethod.invoke(node, tag); } else { class_NBTTagCompound_setStringMethod.invoke(node, tag, value); } } catch (Throwable ex) { ex.printStackTrace(); } } public static void removeMeta(Object node, String tag) { if (node == null|| !class_NBTTagCompound.isInstance(node)) return; try { class_NBTTagCompound_removeMethod.invoke(node, tag); } catch (Throwable ex) { ex.printStackTrace(); } } public static String getMeta(ItemStack stack, String tag) { if (stack == null) return null; String meta = null; try { Object craft = getHandle(stack); if (craft == null) return null; Object tagObject = getTag(craft); if (tagObject == null) return null; meta = (String)class_NBTTagCompound_getStringMethod.invoke(tagObject, tag); } catch (Throwable ex) { ex.printStackTrace(); } return meta; } public static void setMeta(ItemStack stack, String tag, String value) { if (stack == null) return; try { Object craft = getHandle(stack); if (craft == null) return; Object tagObject = getTag(craft); if (tagObject == null) return; class_NBTTagCompound_setStringMethod.invoke(tagObject, tag, value); } catch (Throwable ex) { ex.printStackTrace(); } } public static void addGlow(ItemStack stack) { if (stack == null) return; try { Object craft = getHandle(stack); if (craft == null) return; Object tagObject = getTag(craft); if (tagObject == null) return; final Object enchList = class_NBTTagList.newInstance(); class_NBTTagCompound_setMethod.invoke(tagObject, "ench", enchList); // Testing Glow API based on ItemMetadata storage Object bukkitData = createNode(stack, "bukkit"); class_NBTTagCompound_setBooleanMethod.invoke(bukkitData, "glow", true); } catch (Throwable ex) { } } public static void makeUnbreakable(ItemStack stack) { if (stack == null) return; try { Object craft = getHandle(stack); if (craft == null) return; Object tagObject = getTag(craft); if (tagObject == null) return; Object unbreakableFlag = null; if (class_NBTTagByte_constructor != null) { unbreakableFlag = class_NBTTagByte_constructor.newInstance((byte) 1); } else { unbreakableFlag = class_NBTTagByte_legacy_constructor.newInstance("", (byte) 1); } class_NBTTagCompound_setMethod.invoke(tagObject, "Unbreakable", unbreakableFlag); } catch (Throwable ex) { } } public static void hideFlags(ItemStack stack) { if (stack == null) return; try { Object craft = getHandle(stack); if (craft == null) return; Object tagObject = getTag(craft); if (tagObject == null) return; Object hideFlag = null; if (class_NBTTagByte_constructor != null) { hideFlag = class_NBTTagByte_constructor.newInstance((byte) 63); } else { hideFlag = class_NBTTagByte_legacy_constructor.newInstance("", (byte) 63); } class_NBTTagCompound_setMethod.invoke(tagObject, "HideFlags", hideFlag); } catch (Throwable ex) { } } public static boolean createExplosion(Entity entity, World world, double x, double y, double z, float power, boolean setFire, boolean breakBlocks) { boolean result = false; if (world == null) return false; try { Object worldHandle = getHandle(world); if (worldHandle == null) return false; Object entityHandle = entity == null ? null : getHandle(entity); Object explosion = class_World_explodeMethod.invoke(worldHandle, entityHandle, x, y, z, power, setFire, breakBlocks); Field cancelledField = explosion.getClass().getDeclaredField("wasCanceled"); result = (Boolean)cancelledField.get(explosion); } catch (Throwable ex) { ex.printStackTrace(); result = false; } return result; } public static void makeTemporary(ItemStack itemStack, String message) { setMeta(itemStack, "temporary", message); } public static boolean isTemporary(ItemStack itemStack) { return hasMeta(itemStack, "temporary"); } public static String getTemporaryMessage(ItemStack itemStack) { return getMeta(itemStack, "temporary"); } }
package com.github.dockerjava.client; import static org.apache.commons.io.IOUtils.closeQuietly; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.net.URI; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.apache.http.client.HttpClient; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; import com.github.dockerjava.client.command.AbstrDockerCmd; import com.github.dockerjava.client.command.AttachContainerCmd; import com.github.dockerjava.client.command.AuthCmd; import com.github.dockerjava.client.command.BuildImgCmd; import com.github.dockerjava.client.command.CommitCmd; import com.github.dockerjava.client.command.ContainerDiffCmd; import com.github.dockerjava.client.command.CopyFileFromContainerCmd; import com.github.dockerjava.client.command.CreateContainerCmd; import com.github.dockerjava.client.command.ImportImageCmd; import com.github.dockerjava.client.command.InfoCmd; import com.github.dockerjava.client.command.InspectContainerCmd; import com.github.dockerjava.client.command.InspectImageCmd; import com.github.dockerjava.client.command.KillContainerCmd; import com.github.dockerjava.client.command.ListContainersCmd; import com.github.dockerjava.client.command.ListImagesCmd; import com.github.dockerjava.client.command.LogContainerCmd; import com.github.dockerjava.client.command.PullImageCmd; import com.github.dockerjava.client.command.PushImageCmd; import com.github.dockerjava.client.command.RemoveContainerCmd; import com.github.dockerjava.client.command.RemoveImageCmd; import com.github.dockerjava.client.command.RestartContainerCmd; import com.github.dockerjava.client.command.SearchImagesCmd; import com.github.dockerjava.client.command.StartContainerCmd; import com.github.dockerjava.client.command.StopContainerCmd; import com.github.dockerjava.client.command.TagImageCmd; import com.github.dockerjava.client.command.TopContainerCmd; import com.github.dockerjava.client.command.VersionCmd; import com.github.dockerjava.client.command.WaitContainerCmd; import com.github.dockerjava.client.model.AuthConfig; import com.github.dockerjava.client.model.CreateContainerConfig; import com.github.dockerjava.client.utils.JsonClientFilter; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.client.apache4.ApacheHttpClient4; import com.sun.jersey.client.apache4.ApacheHttpClient4Handler; /** * @author Konstantin Pelykh (kpelykh@gmail.com) */ public class DockerClient { private Client client; private WebResource baseResource; private AuthConfig authConfig; public DockerClient() throws DockerException { this(Config.createConfig()); } public DockerClient(String serverUrl) throws DockerException { this(configWithServerUrl(serverUrl)); } private static Config configWithServerUrl(String serverUrl) throws DockerException { final Config c = Config.createConfig(); c.url = URI.create(serverUrl); return c; } private DockerClient(Config config) { // restEndpointUrl = config.url + "/v" + config.version; ClientConfig clientConfig = new DefaultClientConfig(); // clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, // Boolean.TRUE); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", config.url.getPort(), PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory .getSocketFactory())); PoolingClientConnectionManager cm = new PoolingClientConnectionManager( schemeRegistry); // Increase max total connection cm.setMaxTotal(1000); // Increase default max connection per route cm.setDefaultMaxPerRoute(1000); HttpClient httpClient = new DefaultHttpClient(cm); client = new ApacheHttpClient4(new ApacheHttpClient4Handler(httpClient, null, false), clientConfig); client.setReadTimeout(10000); // Experimental support for unix sockets: // client = new UnixSocketClient(clientConfig); client.addFilter(new JsonClientFilter()); client.addFilter(new SelectiveLoggingFilter()); baseResource = client.resource(config.url + "/v" + config.version); } public void setCredentials(String username, String password, String email) { if (username == null) { throw new IllegalArgumentException("username is null"); } if (password == null) { throw new IllegalArgumentException("password is null"); } if (email == null) { throw new IllegalArgumentException("email is null"); } authConfig = new AuthConfig(); authConfig.setUsername(username); authConfig.setPassword(password); authConfig.setEmail(email); } public <RES_T> RES_T execute(AbstrDockerCmd<?, RES_T> command) throws DockerException { return command.withBaseResource(baseResource).exec(); } public AuthConfig authConfig() throws DockerException { return authConfig != null ? authConfig : authConfigFromProperties(); } private static AuthConfig authConfigFromProperties() throws DockerException { final AuthConfig a = new AuthConfig(); a.setUsername(Config.createConfig().username); a.setPassword(Config.createConfig().password); a.setEmail(Config.createConfig().email); if (a.getUsername() == null) { throw new IllegalStateException("username is null"); } if (a.getPassword() == null) { throw new IllegalStateException("password is null"); } if (a.getEmail() == null) { throw new IllegalStateException("email is null"); } return a; } /** * * MISC API * */ /** * Authenticate with the server, useful for checking authentication. */ public AuthCmd authCmd() { return new AuthCmd(authConfig()).withBaseResource(baseResource); } public InfoCmd infoCmd() throws DockerException { return new InfoCmd().withBaseResource(baseResource); } public VersionCmd versionCmd() throws DockerException { return new VersionCmd().withBaseResource(baseResource); } /** * * IMAGE API * */ public PullImageCmd pullImageCmd(String repository) { return new PullImageCmd(repository).withBaseResource(baseResource); } public PushImageCmd pushImageCmd(String name) { return new PushImageCmd(name).withAuthConfig(authConfig()) .withBaseResource(baseResource); } // public ClientResponse pushImage(String name) { // return execute(pushImageCmd(name)); public ImportImageCmd importImageCmd(String repository, InputStream imageStream) { return new ImportImageCmd(repository, imageStream) .withBaseResource(baseResource); } // public ImageCreateResponse importImage(String repository, // InputStream imageStream) { // return execute(importImageCmd(repository, imageStream)); public SearchImagesCmd searchImagesCmd(String term) { return new SearchImagesCmd(term).withBaseResource(baseResource); } // public List<SearchItem> searchImages(String term) { // return execute(searchImagesCmd(term)); public RemoveImageCmd removeImageCmd(String imageId) { return new RemoveImageCmd(imageId).withBaseResource(baseResource); } // /** // * Remove an image, deleting any tags it might have. // */ // public void removeImage(String imageId) { // execute(removeImageCmd(imageId)); // public void removeImages(List<String> images) { // Preconditions.checkNotNull(images, "List of images can't be null"); // for (String imageId : images) { // removeImage(imageId); public ListImagesCmd listImagesCmd() { return new ListImagesCmd().withBaseResource(baseResource); } // public List<Image> listImages() { // return execute(listImagesCmd()); public InspectImageCmd inspectImageCmd(String imageId) { return new InspectImageCmd(imageId).withBaseResource(baseResource); } // public ImageInspectResponse inspectImage(String imageId) { // return execute(inspectImageCmd(imageId)); /** * * CONTAINER API * */ public ListContainersCmd listContainersCmd() { return new ListContainersCmd().withBaseResource(baseResource); } // public List<Container> listContainers() { // return execute(listContainersCmd()); public CreateContainerCmd createContainerCmd(String image) { return new CreateContainerCmd(new CreateContainerConfig()).withImage( image).withBaseResource(baseResource); } public StartContainerCmd startContainerCmd(String containerId) { return new StartContainerCmd(containerId) .withBaseResource(baseResource); } public InspectContainerCmd inspectContainerCmd(String containerId) { return new InspectContainerCmd(containerId) .withBaseResource(baseResource); } public RemoveContainerCmd removeContainerCmd(String containerId) { return new RemoveContainerCmd(containerId) .withBaseResource(baseResource); } public WaitContainerCmd waitContainerCmd(String containerId) { return new WaitContainerCmd(containerId).withBaseResource(baseResource); } public AttachContainerCmd attachContainerCmd(String containerId) { return new AttachContainerCmd(containerId).withBaseResource(baseResource); } public LogContainerCmd logContainerCmd(String containerId) { return new LogContainerCmd(containerId).withBaseResource(baseResource); } public CopyFileFromContainerCmd copyFileFromContainerCmd( String containerId, String resource) { return new CopyFileFromContainerCmd(containerId, resource) .withBaseResource(baseResource); } public ContainerDiffCmd containerDiffCmd(String containerId) { return new ContainerDiffCmd(containerId).withBaseResource(baseResource); } public StopContainerCmd stopContainerCmd(String containerId) { return new StopContainerCmd(containerId).withBaseResource(baseResource); } public KillContainerCmd killContainerCmd(String containerId) { return new KillContainerCmd(containerId).withBaseResource(baseResource); } public RestartContainerCmd restartContainerCmd(String containerId) { return new RestartContainerCmd(containerId) .withBaseResource(baseResource); } public CommitCmd commitCmd(String containerId) { return new CommitCmd(containerId).withBaseResource(baseResource); } public BuildImgCmd buildImageCmd(File dockerFolder) { return new BuildImgCmd(dockerFolder).withBaseResource(baseResource); } public BuildImgCmd buildImageCmd(InputStream tarInputStream) { return new BuildImgCmd(tarInputStream).withBaseResource(baseResource); } public TopContainerCmd topContainerCmd(String containerId) { return new TopContainerCmd(containerId).withBaseResource(baseResource); } public TagImageCmd tagImageCmd(String imageId, String repository, String tag) { return new TagImageCmd(imageId, repository, tag).withBaseResource(baseResource); } /** * @return The output slurped into a string. */ public static String asString(ClientResponse response) throws IOException { StringWriter out = new StringWriter(); try { LineIterator itr = IOUtils.lineIterator( response.getEntityInputStream(), "UTF-8"); while (itr.hasNext()) { String line = itr.next(); out.write(line + (itr.hasNext() ? "\n" : "")); } } finally { closeQuietly(response.getEntityInputStream()); } return out.toString(); } }
package com.github.pagehelper.util; import com.github.pagehelper.Page; import com.github.pagehelper.PageException; import org.apache.ibatis.reflection.MetaObject; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; /** * * * @author liuzh */ public abstract class PageObjectUtil { //request protected static Boolean hasRequest; protected static Class<?> requestClass; protected static Method getParameterMap; protected static Map<String, String> PARAMS = new HashMap<String, String>(5,1); static { try { requestClass = Class.forName("javax.servlet.ServletRequest"); getParameterMap = requestClass.getMethod("getParameterMap", new Class[]{}); hasRequest = true; } catch (Throwable e) { hasRequest = false; } PARAMS.put("pageNum", "pageNum"); PARAMS.put("pageSize", "pageSize"); PARAMS.put("count", "countSql"); PARAMS.put("orderBy", "orderBy"); PARAMS.put("reasonable", "reasonable"); PARAMS.put("pageSizeZero", "pageSizeZero"); } /** * * * @param params * @return */ public static <T> Page<T> getPageFromObject(Object params, boolean required) { int pageNum; int pageSize; MetaObject paramsObject = null; if (params == null) { throw new PageException("!"); } if (hasRequest && requestClass.isAssignableFrom(params.getClass())) { try { paramsObject = MetaObjectUtil.forObject(getParameterMap.invoke(params, new Object[]{})); } catch (Exception e) { } } else { paramsObject = MetaObjectUtil.forObject(params); } if (paramsObject == null) { throw new PageException("!"); } Object orderBy = getParamValue(paramsObject, "orderBy", false); boolean hasOrderBy = false; if (orderBy != null && orderBy.toString().length() > 0) { hasOrderBy = true; } try { Object _pageNum = getParamValue(paramsObject, "pageNum", required); Object _pageSize = getParamValue(paramsObject, "pageSize", required); if (_pageNum == null || _pageSize == null) { if(hasOrderBy){ Page page = new Page(); page.setOrderBy(orderBy.toString()); page.setOrderByOnly(true); return page; } return null; } pageNum = Integer.parseInt(String.valueOf(_pageNum)); pageSize = Integer.parseInt(String.valueOf(_pageSize)); } catch (NumberFormatException e) { throw new PageException("!"); } Page page = new Page(pageNum, pageSize); //count Object _count = getParamValue(paramsObject, "count", false); if (_count != null) { page.setCount(Boolean.valueOf(String.valueOf(_count))); } if (hasOrderBy) { page.setOrderBy(orderBy.toString()); } Object reasonable = getParamValue(paramsObject, "reasonable", false); if (reasonable != null) { page.setReasonable(Boolean.valueOf(String.valueOf(reasonable))); } Object pageSizeZero = getParamValue(paramsObject, "pageSizeZero", false); if (pageSizeZero != null) { page.setPageSizeZero(Boolean.valueOf(String.valueOf(pageSizeZero))); } return page; } /** * * * @param paramsObject * @param paramName * @param required * @return */ protected static Object getParamValue(MetaObject paramsObject, String paramName, boolean required) { Object value = null; if (paramsObject.hasGetter(PARAMS.get(paramName))) { value = paramsObject.getValue(PARAMS.get(paramName)); } if (value != null && value.getClass().isArray()) { Object[] values = (Object[]) value; if (values.length == 0) { value = null; } else { value = values[0]; } } if (required && value == null) { throw new PageException(":" + PARAMS.get(paramName)); } return value; } public static void setParams(String params) { if (StringUtil.isNotEmpty(params)) { String[] ps = params.split("[;|,|&]"); for (String s : ps) { String[] ss = s.split("[=|:]"); if (ss.length == 2) { PARAMS.put(ss[0], ss[1]); } } } } }
package com.github.rodionovsasha; import java.util.Set; import java.util.TreeSet; class ArmstrongNumbers { private static final int AMOUNT_OF_SIMPLE_DIGITS = 10; // from 0 to 9 private static final long MAX_NUMBER = Long.MAX_VALUE; private static final long[][] ARRAY_OF_POWERS = new long[AMOUNT_OF_SIMPLE_DIGITS][getDigitsAmount(MAX_NUMBER) + 1]; private static int counter = 1; static { for (int i = 0; i < AMOUNT_OF_SIMPLE_DIGITS; i++) { for (int j = 0; j < getDigitsAmount(MAX_NUMBER) + 1; j++) { ARRAY_OF_POWERS[i][j] = pow(i, j); } } assert ARRAY_OF_POWERS[0][0] == 1; assert ARRAY_OF_POWERS[2][2] == 4; assert ARRAY_OF_POWERS[9][4] == 6561; } public static void main(String[] args) { long startTime = System.currentTimeMillis(); Set<Long> result = getNumbers(); for (long armstrongNumber : result) { System.out.println(counter++ + ". " + armstrongNumber); } System.out.println(String.format("Execution time: %dms", (System.currentTimeMillis() - startTime))); System.out.println("Used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (1024 * 1024) + "mb"); } private static Set<Long> getNumbers() { Set<Long> armstrongNumbers = new TreeSet<>(); //Main loop for (long i = 1; i < MAX_NUMBER; i = getNextNumber(i)) { if (i < 0) { break; // the maximum value is reached } long sumOfPowers = getSumOfPowers(i); if (sumOfPowers <= MAX_NUMBER && isArmstrongNumber(sumOfPowers)) { armstrongNumbers.add(sumOfPowers); } } return armstrongNumbers; } private static long getNextNumber(final long number) { long copyOfNumber = number; if (isGrowingNumber(copyOfNumber)) { // here we have numbers where each digit not less than previous one and not more than next one: 12, 1557, 333 and so on. return ++copyOfNumber; } // here we have numbers which end in zero: 10, 20, ..., 100, 110, 5000, 1000000 and so on. long lastNumber = 1; //can be: 1,2,3..., 10,20,30,...,100,200,300,... while (copyOfNumber % 10 == 0) {// 5000 -> 500 -> 50: try to get the last non-zero digit copyOfNumber = copyOfNumber / 10; lastNumber = lastNumber * 10; } long lastNonZeroDigit = copyOfNumber % 10; return number + (lastNonZeroDigit * lastNumber / 10); //e.g. number=100, lastNumber=10, lastNonZeroDigit=1 } /** * Analog of Math.pow which works with long type */ private static long pow(final int base, final int exponent) { long pow = 1; for (int i = 1; i <= exponent; i++) { pow *= base; } return pow; } /* * 135 returns true: 1 < 3 < 5 * 153 returns false: 1 < 5 > 3 * */ private static boolean isGrowingNumber(final long number) { return (number + 1) % 10 != 1; } private static long getSumOfPowers(final long number) { long currentNumber = number; int power = getDigitsAmount(currentNumber); long currentSum = 0; while (currentNumber > 0) { currentSum = currentSum + ARRAY_OF_POWERS[(int) (currentNumber % 10)][power]; // get powers from array by indexes and then the sum. currentNumber /= 10; } return currentSum; } private static boolean isArmstrongNumber(final long number) { return number == getSumOfPowers(number); } private static int getDigitsAmount(long number) { return (int) Math.log10(number) + 1; } }
package com.google.gcs.sdrs.JobManager; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import com.google.gcs.sdrs.JobScheduler.JobScheduler; import org.apache.commons.configuration2.Configuration; import org.apache.commons.configuration2.builder.fluent.Configurations; import org.apache.commons.configuration2.ex.ConfigurationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gcs.sdrs.worker.BaseWorker; import com.google.gcs.sdrs.worker.WorkerResult; /** * JobManager for creating and managing worker threads. */ public class JobManager { CompletionService<WorkerResult> completionService; AtomicInteger activeWorkerCount = new AtomicInteger(0); private ExecutorService executorService; private static JobManager jobManager; private static JobScheduler scheduler; private static JobManagerMonitor monitor; private static int DEFAULT_THREAD_POOL_SIZE = 10; private static int DEFAULT_SLEEP_MINUTES = 5; private static int DEFAULT_MONITOR_INITIAL_DELAY = 0; private static int DEFAULT_MONITOR_FREQUENCY = 30; private static TimeUnit DEFAULT_MONITOR_TIME_UNIT = TimeUnit.MINUTES; private static int THREAD_POOL_SIZE; private static int SLEEP_MINUTES; private static int MONITOR_INITIAL_DELAY; private static int MONITOR_FREQUENCY; private static TimeUnit MONITOR_TIME_UNIT = TimeUnit.SECONDS; private static final Logger logger = LoggerFactory.getLogger(JobManager.class); /** * Gets the current JobManager singleton and creates one if it doesn't exist. * @return The JobManager singleton. */ public static synchronized JobManager getJobManager() { if (jobManager == null) { logger.info("JobManager not created. Creating..."); jobManager = new JobManager(); monitor = new JobManagerMonitor(jobManager); scheduler = JobScheduler.getInstance(); scheduler.submitScheduledJob(monitor, MONITOR_INITIAL_DELAY, MONITOR_FREQUENCY, MONITOR_TIME_UNIT); } return jobManager; } /** * Immediately shuts down the job manager and doesn't wait for threads to resolve */ public void shutDownJobManagerNow(){ logger.info("Forcing shutdown now..."); executorService.shutdownNow(); scheduler.shutdownSchedulerNow(); // Ensure the job manager singleton is destroyed jobManager = null; logger.info("JobManager shut down."); } /** * Gracefully shuts down the Job Manager and associated threads */ public void shutDownJobManager() { logger.info("Shutting down JobManager."); // waits nicely for executing tasks to finish, and won't spawn new ones logger.info("Attempting graceful shutdown..."); executorService.shutdown(); try { if (!executorService.awaitTermination(SLEEP_MINUTES, TimeUnit.MINUTES)) { executorService.shutdownNow(); } } catch (InterruptedException e) { executorService.shutdownNow(); } scheduler.shutdownScheduler(); // Ensure the job manager singleton is destroyed jobManager = null; logger.info("JobManager shut down."); } /** * Submits a callable worker for execution * @param job A callable that returns a WorkerResult record. */ public void submitJob(BaseWorker job) { completionService.submit(job); activeWorkerCount.incrementAndGet(); logger.debug("Active Workers after submission: " + activeWorkerCount.get()); logger.info("Job submitted: " + job.getWorkerResult().toString()); } private JobManager () { try{ Configuration config = new Configurations().xml("applicationConfig.xml"); THREAD_POOL_SIZE = config.getInt("jobManager.threadPoolSize"); SLEEP_MINUTES = config.getInt("jobManager.shutdownSleepMinutes"); MONITOR_INITIAL_DELAY = config.getInt("jobManager.monitor.initialDelay"); MONITOR_FREQUENCY = config.getInt("jobManager.monitor.frequency"); MONITOR_TIME_UNIT = TimeUnit.valueOf(config.getString("jobManager.monitor.timeUnit")); } catch (ConfigurationException ex) { logger.error("Configuration file could not be read. Using defaults: " + ex.getMessage()); THREAD_POOL_SIZE = DEFAULT_THREAD_POOL_SIZE; SLEEP_MINUTES = DEFAULT_SLEEP_MINUTES; MONITOR_INITIAL_DELAY = DEFAULT_MONITOR_INITIAL_DELAY; MONITOR_FREQUENCY = DEFAULT_MONITOR_FREQUENCY; MONITOR_TIME_UNIT = DEFAULT_MONITOR_TIME_UNIT; } executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE); completionService = new ExecutorCompletionService<>(executorService); logger.info("JobManager created."); } }
package com.hasanozgan.flex.examples; import com.hasanozgan.flex.core.annotations.Authenticated; import com.hasanozgan.flex.core.HttpMethod; import com.hasanozgan.flex.core.annotations.Resource; import com.hasanozgan.flex.core.models.request.RequestContext; import com.hasanozgan.flex.core.models.request.RequestContextWith; import com.hasanozgan.flex.core.models.response.Result; import com.hasanozgan.flex.core.models.response.ResultWith; public class UserResource { @Authenticated @Resource(path = "/user/info", method = HttpMethod.GET) public static ResultWith<User> getUserInfo() { return Result.ok(new User(1, "hasan")); } @Authenticated @Resource(path = "/user/info", method = HttpMethod.POST) public static ResultWith<User> postUserInfo(RequestContextWith<User> ctx) { return Result.ok(ctx.getEntity()); } @Authenticated @Resource(path = "/user/coupons/{gameType}", method = HttpMethod.GET) public static ResultWith<String> postUserInfo(RequestContext ctx) { return Result.ok(ctx.getParameter("gameType")); } @Resource(path = "/user/details", method = HttpMethod.GET) public static Result getUserDetails(RequestContext ctx) { return Result.ok(); } }
package com.hubspot.jinjava.lib.filter; import java.io.Serializable; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.lang3.BooleanUtils; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.Lists; import com.hubspot.jinjava.doc.annotations.JinjavaDoc; import com.hubspot.jinjava.doc.annotations.JinjavaParam; import com.hubspot.jinjava.doc.annotations.JinjavaSnippet; import com.hubspot.jinjava.interpret.InvalidArgumentException; import com.hubspot.jinjava.interpret.InvalidInputException; import com.hubspot.jinjava.interpret.InvalidReason; import com.hubspot.jinjava.interpret.JinjavaInterpreter; import com.hubspot.jinjava.util.ObjectIterator; @JinjavaDoc( value = "Sort an iterable.", input = @JinjavaParam(value = "value", type = "iterable", desc = "The sequence or dict to sort through iteration", required = true), params = { @JinjavaParam(value = "reverse", type = "boolean", defaultValue = "False", desc = "Boolean to reverse the sort order"), @JinjavaParam(value = "case_sensitive", type = "boolean", defaultValue = "False", desc = "Determines whether or not the sorting is case sensitive"), @JinjavaParam(value = "attribute", desc = "Specifies an attribute to sort by") }, snippets = { @JinjavaSnippet( code = "{% for item in iterable|sort %}\n" + " ...\n" + "{% endfor %}"), @JinjavaSnippet( desc = "This filter requires all parameters to sort by an attribute in HubSpot. Below is a set of posts that are retrieved and alphabetized by 'name'.", code = "{% set my_posts = blog_recent_posts('default', limit=5) %}\n" + "{% for item in my_posts|sort(False, False,'name') %}\n" + " {{ item.name }}<br>\n" + "{% endfor %}") }) public class SortFilter implements Filter { private static final Splitter DOT_SPLITTER = Splitter.on('.').omitEmptyStrings(); private static final Joiner DOT_JOINER = Joiner.on('.'); @Override public String getName() { return "sort"; } @Override public Object filter(Object var, JinjavaInterpreter interpreter, String... args) { if (var == null) { return null; } boolean reverse = false; if (args.length > 0) { reverse = BooleanUtils.toBoolean(args[0]); } boolean caseSensitive = false; if (args.length > 1) { caseSensitive = BooleanUtils.toBoolean(args[1]); } List<String> attr = getAttributeArgument(interpreter, args); return Lists.newArrayList(ObjectIterator.getLoop(var)).stream() .sorted(Comparator.comparing((o) -> mapObject(interpreter, o, attr), new ObjectComparator(reverse, caseSensitive))) .collect(Collectors.toList()); } private List<String> getAttributeArgument(JinjavaInterpreter interpreter, String[] args) { if (args.length > 2) { String attrArg = args[2]; if (attrArg == null) { throw new InvalidArgumentException(interpreter, this, InvalidReason.NULL, 2); } return DOT_SPLITTER.splitToList(attrArg); } return Collections.emptyList(); } private Object mapObject(JinjavaInterpreter interpreter, Object o, List<String> propertyChain) { if (o == null) { throw new InvalidInputException(interpreter, this, InvalidReason.NULL_IN_LIST); } if (propertyChain.isEmpty()) { return o; } Object result = interpreter.resolveProperty(o, propertyChain); if (result == null) { throw new InvalidArgumentException(interpreter, this, InvalidReason.NULL_ATTRIBUTE_IN_LIST, 2, DOT_JOINER.join(propertyChain)); } return result; } private static class ObjectComparator implements Comparator<Object>, Serializable { private final boolean reverse; private final boolean caseSensitive; ObjectComparator(boolean reverse, boolean caseSensitive) { this.reverse = reverse; this.caseSensitive = caseSensitive; } @SuppressWarnings("unchecked") @Override public int compare(Object o1, Object o2) { int result = 0; if (o1 instanceof String && !caseSensitive) { result = ((String) o1).compareToIgnoreCase((String) o2); } else if (Comparable.class.isAssignableFrom(o1.getClass()) && Comparable.class.isAssignableFrom(o2.getClass())) { result = ((Comparable<Object>) o1).compareTo(o2); } if (reverse) { result = -1 * result; } return result; } } }
package com.ims.controllers.rest; import java.util.List; import org.hibernate.cfg.NotYetImplementedException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.ims.domain.PurchaseOrder; import com.ims.dto.PurchaseOrderDTO; import com.ims.logic.PurchaseOrderLogic; @RestController @RequestMapping(value="/purchase-order") public class PurchaseOrderAPI { @Autowired private PurchaseOrderLogic poLogic; @RequestMapping(method=RequestMethod.GET, value="/{id}") public PurchaseOrder getPurchaseOrder(@PathVariable("id") Integer id) { PurchaseOrder po = poLogic.getPurchaseOrder(id); return po; } //wait @RequestMapping(method=RequestMethod.GET, value="") public List<PurchaseOrder> getAllProducts() { List<PurchaseOrder> purchaseOrder = poLogic.getAllPurchaseOrders(); return purchaseOrder; } @RequestMapping(method=RequestMethod.GET, value="/retailer/{id}") public List<PurchaseOrder> getAllPurchaseOrdersById(@PathVariable("id") Integer id) { List<PurchaseOrder> purchaseOrder = poLogic.getAllPurchaseOrdersByRetailer(id); return purchaseOrder; } // @RequestMapping(method=RequestMethod.POST, value="", params={"supplierId","retailerId","cost"}) // public boolean createPurchaseOrder(HttpServletRequest request) { // int supplierId = Integer.parseInt(request.getParameter("supplierId")); // int retailerId = Integer.parseInt(request.getParameter("retailerId")); // int cost = Integer.parseInt(request.getParameter("cost")); // PurchaseOrder po = PurchaseOrderLogic.createPurchaseOrder(supplierId, retailerId, cost); // if (po == null) { // return false; // else return true; @RequestMapping(method=RequestMethod.POST, value="", consumes="application/json") public boolean createPurchaseOrder(@RequestBody PurchaseOrderDTO json) { System.out.println(json); PurchaseOrder po = poLogic.createPurchaseOrder(json); if (po == null) { return false; } else return true; } }
package com.jonesdy.web.controller; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import javax.sql.DataSource; import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.jonesdy.web.model.WebGame; import com.jonesdy.database.DatabaseHelper; import com.jonesdy.database.model.DbGame; import com.jonesdy.database.model.DbPlayer; @Controller public class MainController { @RequestMapping(value = {"/", "index"}, method = RequestMethod.GET) public ModelAndView defaultPage() { ModelAndView model = new ModelAndView(); model.addObject("title", "Spring Security Login Form"); model.addObject("message", "This is the default page!"); model.setViewName("index"); return model; } @RequestMapping(value = "/admin**", method = RequestMethod.GET) public ModelAndView adminPage() { ModelAndView model = new ModelAndView(); model.addObject("title", "Spring Security Login Form"); model.addObject("message", "This page is for admins only!"); model.setViewName("admin"); return model; } @RequestMapping(value = "/login", method = RequestMethod.GET) public ModelAndView login(@RequestParam(value = "error", required = false) String error, @RequestParam(value = "logout", required = false) String logout) { ModelAndView model = new ModelAndView(); if(error != null) { model.addObject("error", "Invalid username or password!"); } if(logout != null) { model.addObject("msg", "You've been logged out succesfully."); } model.setViewName("login"); return model; } @RequestMapping(value = "/isUsernameAvailable", method = RequestMethod.GET, produces="application/json") public @ResponseBody boolean isUsernameAvailable(@RequestParam(value = "username", required = true) String username) { return DatabaseHelper.getDbUserByUsername(username) == null; } @RequestMapping(value = "/confirm", method = RequestMethod.GET) public ModelAndView confirm(@RequestParam(value = "code", required = true) String code) { ModelAndView model = new ModelAndView(); if(!DatabaseHelper.confirmUserByConfirmCode(code)) { model.addObject("error", "Confirmation code does not exist, or the user was already confirmed."); } else { model.addObject("message", "User successfully confirmed."); } model.setViewName("confirmation"); return model; } @RequestMapping(value = "/403", method = RequestMethod.GET) public ModelAndView accessDenied() { ModelAndView model = new ModelAndView(); // Check if a user is logged in Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if(!(auth instanceof AnonymousAuthenticationToken)) { UserDetails userDetails = (UserDetails)auth.getPrincipal(); model.addObject("username", userDetails.getUsername()); } model.setViewName("403"); return model; } @RequestMapping(value = "/games", method = RequestMethod.GET) public ModelAndView gamesPage() { ModelAndView model = new ModelAndView(); ArrayList<WebGame> userGames = new ArrayList<WebGame>(); ArrayList<WebGame> publicGames = new ArrayList<WebGame>(); ArrayList<Integer> userGids = new ArrayList<Integer>(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if(auth instanceof AnonymousAuthenticationToken) { userGames.add(new WebGame(0, "Please log in to see your games")); } else { String username = auth.getName(); ArrayList<DbPlayer> dbPlayers = DatabaseHelper.getDbPlayersByUsername(username); for(DbPlayer dbPlayer : dbPlayers) { userGids.add(dbPlayer.getGid()); DbGame dbGame = DatabaseHelper.getDbGameByGid(dbPlayer.getGid()); userGames.add(new WebGame(dbGame.getGid(), dbGame.getTitle())); } } ArrayList<DbGame> publicDbGames = DatabaseHelper.getPublicDbGames(); for(DbGame dbGame : publicDbGames) { if(!userGids.contains(dbGame.getGid())) { publicGames.add(new WebGame(dbGame.getGid(), dbGame.getTitle())); } } if(userGames.isEmpty()) { userGames.add(new WebGame(0, "You are currently not in any games")); } if(publicGames.isEmpty()) { publicGames.add(new WebGame(0, "There are no public games available")); } model.addObject("userGames", userGames); model.addObject("publicGames", publicGames); model.setViewName("games"); return model; } @RequestMapping(value = "/game", method = RequestMethod.GET) public ModelAndView gamePage(@RequestParam(value = "gid", required = true) String gid) { ModelAndView model = new ModelAndView(); try { DbGame game = DatabaseHelper.getDbGameByGid(Integer.parseInt(gid)); } catch(Exception e) { } model.setViewName("game"); return model; } }
package com.jt.selenium.factory; import org.apache.commons.lang3.SystemUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.phantomjs.PhantomJSDriverService; import org.openqa.selenium.remote.DesiredCapabilities; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.testng.ITestContext; import com.jt.selenium.SeleniumJT; import com.jt.selenium.configuration.SeleniumConfiguration; import com.jt.selenium.utils.FileHelper; import com.jt.selenium.utils.PropertiesHelper; public class SeleniumJTFactory { private static final String IE_DRIVER = "IEDriverServer"; private static final String WEBDRIVER_IE_DRIVER = "webdriver.ie.driver"; private static final String WEBDRIVER_FIREFOX_BIN = "webdriver.firefox.bin"; private static final String FIREFOX_EXE_LOCATION = "firefox.exe.location"; private static final String PHANTOM_JS_LOC = "phantomjs.binary.path"; private static final String CONFIG_PATH = "application-config.xml"; private static final String WEBDRIVER_SYSTEM_PROPERTY = "webdriver.chrome.driver"; private static final String CHROMEDRIVER_WIN_LOC = "chromedriver.exe"; private static final String PHANTOM_WIN_LOC = "phantomjs.exe"; private static final String CHROMEDRIVER_LINUX_LOC = "chromedriver"; protected static final Log logger = LogFactory.getLog(SeleniumJTFactory.class); private static SeleniumJT sjt; private static WebDriver getWebDriver(SeleniumConfiguration config) { WebDriver driver = null; if(config.getBrowserType().runningInIE()) { driver = getIEDriver(config); }else if(config.getBrowserType().runningInFireFox()) { driver = getFFDriver(config); }else if(config.getBrowserType().runningInChrome()) { driver = getChromeDriver(config); }else if(config.getBrowserType().runningInPhantom()) { driver = getPhantomDriver(config); } return driver; } private static WebDriver getChromeDriver(SeleniumConfiguration config) { String chromdriverLoc = CHROMEDRIVER_WIN_LOC; if(SystemUtils.IS_OS_LINUX) { chromdriverLoc = CHROMEDRIVER_LINUX_LOC; } System.setProperty(WEBDRIVER_SYSTEM_PROPERTY, getWebDriverLocation(config, "chrome", chromdriverLoc)); return new ChromeDriver(); } private static String getWebDriverLocation(SeleniumConfiguration config, String key, String loc) { String webDriverLocation; try { webDriverLocation = config.getWebDriverLocation(key); } catch (Exception e) { webDriverLocation = String.format("%s/target/jtcore/%s", SeleniumConfiguration.getOperationalDirectory(), loc); } logger.info("Getting web driver from "+webDriverLocation); return webDriverLocation; } private static WebDriver getPhantomDriver(SeleniumConfiguration config) { DesiredCapabilities dCaps = new DesiredCapabilities(); dCaps.setJavascriptEnabled(true); String[] args = { "--ignore-ssl-errors=yes" }; dCaps.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, args); System.setProperty(PHANTOM_JS_LOC, getWebDriverLocation(config, "phantom", PHANTOM_WIN_LOC)); return new PhantomJSDriver(dCaps); } private static WebDriver getFFDriver(SeleniumConfiguration config) { System.setProperty(WEBDRIVER_FIREFOX_BIN, config.get(FIREFOX_EXE_LOCATION)); return new FirefoxDriver(); } private static WebDriver getIEDriver(SeleniumConfiguration config) { String driverVersion = config.get("ieDriverVersion"); String ieDriver = driverVersion==null? IE_DRIVER+"32.exe" : IE_DRIVER+driverVersion+".exe"; System.setProperty(WEBDRIVER_IE_DRIVER, getWebDriverLocation(config, "ie", ieDriver)); return new InternetExplorerDriver(); } public static SeleniumJT getSeleniumJT(ITestContext testNgContext) { final ApplicationContext context = new ClassPathXmlApplicationContext(CONFIG_PATH); sjt = context.getBean(SeleniumJT.class); sjt.setConfiguration(SeleniumConfiguration.getInstance(testNgContext)); sjt.setWebDriver(getWebDriver(sjt.getConfiguration())); sjt.setTestData(PropertiesHelper.getDataProperties(testNgContext)); return sjt; } public static SeleniumJT getSeleniumJT(String browser) { final ApplicationContext context = new ClassPathXmlApplicationContext(CONFIG_PATH); sjt = context.getBean(SeleniumJT.class); sjt.setConfiguration(SeleniumConfiguration.getInstance(browser)); sjt.setWebDriver(getWebDriver(sjt.getConfiguration())); return sjt; } }
package com.kaazing.operations; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map.Entry; import java.util.TreeMap; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.ListObjectsV2Request; import com.amazonaws.services.s3.model.ListObjectsV2Result; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectRequest; import com.amazonaws.services.s3.model.S3ObjectSummary; /** * Create a browsable directory listing in an AWS S3 bucket from a given folder recursively. */ public class S3DirectoryListing { private String key; private String secret; private String bucket; private String rootFolder = ""; // This means the overall root directory: "/" private String indexFilename = "index.html"; private String cssFilename = "index.css"; private String folderIconFilename = "folder-icon.png"; private String folderUpIconFilename = "folder-up-icon.png"; private Level logLevel = Level.INFO; private boolean indexing = false; /** * Cache-Control: max-age directive for the index.html files. In seconds. */ private long htmlMaxAge = 2; /** * Cache-Control: max-age directive for the static resource files. e.g. CSS file, images, etc. In seconds. */ private long resourcesMaxAge = 9; private final Logger logger = Logger.getLogger(S3DirectoryListing.class); private AmazonS3 s3client; private TreeMap<String, S3Folder> folders = new TreeMap<String, S3Folder>(); public static void main(String[] args) { new S3DirectoryListing(args); } public S3DirectoryListing(String[] args) { if (!parseCommandLine(args)) { return; } LogManager.getRootLogger().setLevel(logLevel); readS3RootFolder(); if (indexing) { generateIndexFiles(); uploadResourceFiles(); } else { printDirectoryList(folders.get("/")); } logger.info("\nDone"); } private boolean parseCommandLine(String[] args) { CommandLineParser parser = new DefaultParser(); Options options = new Options(); options.addOption("k", "key", true, "AWS access key"); options.addOption("s", "secret", true, "AWS secret access key"); options.addOption("b", "bucket", true, "AWS S3 bucket name"); options.addOption("r", "root", true, "AWS S3 key that serves as the root directory. Default is /"); options.addOption("h", "max-age-html", true, "The Cache-Control: max-age value for the index.html files (in seconds). Default is " + htmlMaxAge+".\nIgnored if -i is not set"); options.addOption("e", "max-age-resources", true, "The Cache-Control: max-age value for static CSS, image, etc files (in seconds). Default is " + resourcesMaxAge + "\nIgnored if -i is not set."); options.addOption("l", "log-level", true, "Logging level: fatal, error, warn, info (default), debug, trace"); options.addOption("i", "index", true, "Upload index files to make the S3 folders browsable\nWARNING: This will override existing index.html files in every directory!"); options.addOption("?", "help", false, "Show usage help"); try { // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption("help") || line.hasOption("?")) { showUsage(options); return false; } if (line.hasOption("key")) { key = line.getOptionValue("key").trim(); } if (line.hasOption("secret")) { secret = line.getOptionValue("secret").trim(); } if (line.hasOption("bucket")) { bucket = line.getOptionValue("bucket").trim(); } if (line.hasOption("root")) { rootFolder = line.getOptionValue("root").trim(); if (rootFolder.equals("/")) { rootFolder = ""; // This is how to represent the / directory } else { // S3 expects the folder name to not have a starting slash. if (rootFolder.charAt(0) == '/') { rootFolder = rootFolder.substring(1); } // S3 expects the folder name to have a trailing slash. if (rootFolder.charAt(rootFolder.length() - 1) != '/') { rootFolder += "/"; } } } if (line.hasOption("max-age-html")) { try { htmlMaxAge = Long.valueOf(line.getOptionValue("max-age-html").trim()); } catch (NumberFormatException e) { logger.info(String.format("You specified an invalid value for max-age-html. Using default of %d", htmlMaxAge)); } } if (line.hasOption("max-age-resources")) { try { resourcesMaxAge = Long.valueOf(line.getOptionValue("max-age-resources").trim()); } catch (NumberFormatException e) { logger.info(String.format("You specified an invalid value for max-age-resources. Using default of %d", resourcesMaxAge)); } } if (line.hasOption("log-level")) { switch (line.getOptionValue("log-level").toUpperCase()) { case "FATAL": logLevel = Level.INFO; break; case "ERROR": logLevel = Level.ERROR; break; case "WARN": logLevel = Level.WARN; break; case "INFO": logLevel = Level.INFO; break; case "DEBUG": logLevel = Level.DEBUG; break; case "TRACE": logLevel = Level.TRACE; break; default: logLevel = Level.INFO; logger.info("Unknown log level specified. Setting to INFO"); } } if (line.hasOption("index")) { indexing = true; } } catch (ParseException exp) { logger.error(String.format("Unexpected exception: %s", exp.getMessage())); showUsage(options); return false; } // Make sure we've got all the parameters we need. if (key == null) { logger.error("You didn't supply a key!"); showUsage(options); return false; } if (secret == null) { logger.error("You didn't supply a secret!"); showUsage(options); return false; } if (bucket == null) { logger.error("You didn't supply a bucket!"); showUsage(options); return false; } if (rootFolder == null) { logger.error("You didn't supply a root!"); showUsage(options); return false; } return true; } private void showUsage(Options options) { HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); System.out.println(""); formatter.printHelp("s3-directory-listing", options); System.out.println(""); System.out.println("Example:"); System.out.println(""); System.out.println(" s3-directory-listing"); System.out.println(" --key XXXXXXXXXXXXXXXXXXXX"); System.out.println(" --secret XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); System.out.println(" --bucket cdn.example.com"); System.out.println(" --root public/releases"); } /** * Connect to S3, read the root folder and all of its sub-folders, and build up a data structure of all the folders and file * details. */ public void readS3RootFolder() { final BasicAWSCredentials awsCreds = new BasicAWSCredentials(key, secret); s3client = new AmazonS3Client(awsCreds); logger.info(String.format("Scanning %s/%s...%n", bucket, rootFolder)); try { final ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(bucket).withPrefix(rootFolder) .withMaxKeys(10); ListObjectsV2Result result; do { result = s3client.listObjectsV2(req); for (S3ObjectSummary objectSummary : result.getObjectSummaries()) { logger.trace(String.format("Found key: %s", objectSummary.getKey())); // Is this key a folder or file? if (objectSummary.getKey().substring(objectSummary.getKey().length() - 1).equals("/")) { S3Folder folder = addFolder(objectSummary.getKey()); logger.info(String.format("Reading folder: %s", folder.getPath())); } else { S3File file = new S3File(objectSummary.getKey(), objectSummary.getSize(), objectSummary.getLastModified()); logger.info(String.format("Reading file: %s", file.getPath())); // Extract the folder name holding this file. Handle special case if the parent is the root. int pos = objectSummary.getKey().lastIndexOf('/'); String folderName; if (pos == -1) { folderName = "/"; } else { folderName = objectSummary.getKey().substring(0, pos + 1); } S3Folder folder = addFolder(folderName); folder.addFile(file); } } // The S3 API returns paginated results. So keep looping through each page until we're done. req.setContinuationToken(result.getNextContinuationToken()); } while (result.isTruncated() == true); } catch (AmazonServiceException ase) { logger.info("Caught an AmazonServiceException, " + "which means your request made it " + "to Amazon S3, but was rejected with an error response " + "for some reason."); logger.info("Error Message: " + ase.getMessage()); logger.info("HTTP Status Code: " + ase.getStatusCode()); logger.info("AWS Error Code: " + ase.getErrorCode()); logger.info("Error Type: " + ase.getErrorType()); logger.info("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { logger.info("Caught an AmazonClientException, " + "which means the client encountered " + "an internal error while trying to communicate" + " with S3, " + "such as not being able to access the network."); logger.info("Error Message: " + ace.getMessage()); } } /** * Add a folder and recursively add the parents if they don't exist. */ private S3Folder addFolder(String folderName) { logger.trace(String.format("Attemping to add folder %s to folder list", folderName)); S3Folder folder = folders.get(folderName); if (folder == null) { logger.trace(String.format("%s does not exist in list, adding it", folderName)); folder = new S3Folder(folderName); folders.put(folderName, folder); } else { logger.trace(String.format("%s already in list", folderName)); } // Special case, if this is /, then there is no need to proceed, which would be an // infinite recursion. if (folder.getPath().equals("/")) { return folder; } // Figure out the parent folder. int secondLastSlash = folderName.lastIndexOf('/', folderName.length() - 2); String parentName; if (secondLastSlash == -1) { logger.trace(String.format("%s has no parent, so the parent must be the root", folderName)); parentName = "/"; // return folder; } else { parentName = folderName.substring(0, secondLastSlash + 1); } logger.trace(String.format("%s has parent folder, %s, adding it to list", folderName, parentName)); S3Folder parent = addFolder(parentName); parent.addFolder(folder); return folder; } /** * Loop over all of the folders collected from S3 and add an index.hmtl file to each one. */ private void generateIndexFiles() { logger.info(""); for (Entry<String, S3Folder> entry : folders.entrySet()) { S3Folder folder = entry.getValue(); logger.info(String.format("Generating index file for %s", folder.getPath())); uploadIndexFile(folder); } } /** * Generate and upload the index.html file for the given folder. */ private void uploadIndexFile(S3Folder folder) { try { String indexFile = createIndexFile(folder); byte[] bytes = indexFile.toString().getBytes(StandardCharsets.UTF_8); InputStream is = new ByteArrayInputStream(bytes); ObjectMetadata om = new ObjectMetadata(); om.setContentType("text/html"); om.setContentLength(bytes.length); om.setCacheControl("max-age=" + htmlMaxAge); String keyname = folder.getPath() + indexFilename; PutObjectRequest request = new PutObjectRequest(bucket, keyname, is, om); s3client.putObject(request); } catch (AmazonServiceException ase) { logger.info("Caught an AmazonServiceException, which " + "means your request made it " + "to Amazon S3, but was rejected with an error response" + " for some reason."); logger.info("Error Message: " + ase.getMessage()); logger.info("HTTP Status Code: " + ase.getStatusCode()); logger.info("AWS Error Code: " + ase.getErrorCode()); logger.info("Error Type: " + ase.getErrorType()); logger.info("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { logger.info("Caught an AmazonClientException, which " + "means the client encountered " + "an internal error while trying to " + "communicate with S3, " + "such as not being able to access the network."); logger.info("Error Message: " + ace.getMessage()); } } /** * Create a String representation of the index.html for the given folder. */ private String createIndexFile(S3Folder folder) { StringBuffer sb = new StringBuffer(500); sb.append("<!DOCTYPE html>"); sb.append("<html lang=\"en\">"); sb.append(""); sb.append("<head>"); sb.append(" <meta charset=\"utf-8\">"); sb.append(" <link rel=\"shortcut icon\" type=\"image/png\" href=\"//kaazing.com/static/images/favicon-kaazing.png\">"); sb.append(" <title>Directory Listing</title>"); sb.append(" <link rel=\"stylesheet\" href=\"//" + bucket + "/" + rootFolder + "index.css\">"); sb.append("</head>"); sb.append(""); sb.append("<body>"); sb.append(""); sb.append(String.format("<h1>%s</h1>", folder.getPath())); sb.append(String.format("")); sb.append(String.format("<table id=\"list\">")); sb.append(String.format(" <thead>")); sb.append(String.format(" <tr>")); sb.append(String.format(" <th class=\"icon\"></th>")); sb.append(String.format(" <th class=\"name\">Name</th>")); sb.append(String.format(" <th class=\"size\" colspan=\"2\">Size</th>")); sb.append(String.format(" <th class=\"last-modified\">Last modified</th>")); sb.append(String.format(" </tr>")); sb.append(String.format(" </thead>")); sb.append(String.format(" <tbody>")); // Let users navigate up to the parent folder, but not past the root. if (!folder.getPath().equals(rootFolder)) { sb.append(String.format(" <tr>")); sb.append(String.format(" <td class=\"icon\"><a href=\"..\"><img src=\"//" + bucket + "/" + rootFolder + folderUpIconFilename + "\"></a></td>")); sb.append(String.format(" <td class=\"name\"><a href=\"..\">Parent Directory</a></td>")); sb.append(String.format(" <td class=\"size\"></td>")); sb.append(String.format(" <td class=\"size-units\"></td>")); sb.append(String.format(" <td class=\"last-modified\"></td>")); sb.append(String.format(" </tr>")); } // Show folders first. for (Entry<String, S3Folder> folderEntry : folder.getFolders().entrySet()) { S3Folder childFolder = folderEntry.getValue(); String childFolderName = childFolder.getPath(); int secondLastSlash = childFolderName.lastIndexOf('/', childFolderName.length() - 2); String childFolderEnding = childFolderName.substring(secondLastSlash + 1, childFolderName.length() - 1); sb.append(String.format(" <tr>")); sb.append(String.format(" <td class=\"icon\"><a href=\"%s\"><img src=\"//" + bucket + "/" + rootFolder + folderIconFilename + "\"></a></td>", childFolderEnding)); sb.append(String.format(" <td class=\"name\"><a href=\"%s\">%s</a></td>", childFolderEnding, childFolderEnding)); sb.append(String.format(" <td class=\"size\"></td>")); sb.append(String.format(" <td class=\"size-units\"></td>")); sb.append(String.format(" <td class=\"last-modified\"></td>")); sb.append(String.format(" </tr>")); } // List files next. // Certain files will get stored in the root folder, such as the CSS file and icon images. They should not appear in the // directory listing and will be excluded. Also, the index.html file in each folder should not be displayed. final HashMap<String, String> rootExcludeList = new HashMap<String, String>(); rootExcludeList.put(indexFilename, indexFilename); rootExcludeList.put(cssFilename, cssFilename); rootExcludeList.put(folderIconFilename, folderIconFilename); rootExcludeList.put(folderUpIconFilename, folderUpIconFilename); for (Entry<String, S3File> fileEntry : folder.getFiles().entrySet()) { S3File file = fileEntry.getValue(); // Don't show excluded files if (rootExcludeList.containsKey(file.getFilename())) { logger.trace(String.format("Excluding %s", file.getFilename())); continue; } String size = S3File.humanReadableByteCount(file.getSize(), true); int spacePos = size.indexOf(' '); String sizeUnits = size.substring(spacePos + 1, size.length()); size = size.substring(0, spacePos); sb.append(String.format(" <tr>")); sb.append(String.format(" <td class=\"icon\"></td>")); sb.append(String.format(" <td class=\"name\"><a href=\"%s\">%s</a></td>", file.getFilename(), file.getFilename())); sb.append(String.format(" <td class=\"size\">%s</td>", size)); sb.append(String.format(" <td class=\"size-units\">%s</td>", sizeUnits)); sb.append(String.format(" <td class=\"last-modified\">%s</td>", file.getLastModified())); sb.append(String.format(" </tr>")); } sb.append(String.format(" </tbody>")); sb.append(String.format("</table>")); sb.append(""); sb.append("</body>"); sb.append(""); sb.append("</html>"); return sb.toString(); } /** * Upload the static files into the root folder. Static files are the CSS file, images, etc. */ private void uploadResourceFiles() { logger.info(""); ClassLoader classLoader = getClass().getClassLoader(); File cssfile = new File(classLoader.getResource(cssFilename).getFile()); uploadFile(cssfile, "text/css", resourcesMaxAge); File folderIconFile = new File(classLoader.getResource(folderIconFilename).getFile()); uploadFile(folderIconFile, "text/png", resourcesMaxAge); File folderUpIconFile = new File(classLoader.getResource(folderUpIconFilename).getFile()); uploadFile(folderUpIconFile, "text/png", resourcesMaxAge); } /** * Generic method to upload a file to S3. */ private void uploadFile(File file, String contentType, long maxAge) { try { String destPath = rootFolder + file.getName(); PutObjectRequest request = new PutObjectRequest(bucket, destPath, file); logger.info(String.format("Uploading %s", destPath)); ObjectMetadata om = new ObjectMetadata(); om.setContentLength(file.length()); om.setContentType(contentType); if (maxAge >= 0) { om.setCacheControl("max-age=" + maxAge); } request.setMetadata(om); s3client.putObject(request.withMetadata(om)); } catch (AmazonServiceException ase) { logger.info("Caught an AmazonServiceException, which " + "means your request made it " + "to Amazon S3, but was rejected with an error response" + " for some reason."); logger.info("Error Message: " + ase.getMessage()); logger.info("HTTP Status Code: " + ase.getStatusCode()); logger.info("AWS Error Code: " + ase.getErrorCode()); logger.info("Error Type: " + ase.getErrorType()); logger.info("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { logger.info("Caught an AmazonClientException, which " + "means the client encountered " + "an internal error while trying to " + "communicate with S3, " + "such as not being able to access the network."); logger.info("Error Message: " + ace.getMessage()); } } /** * Write out the directory structure, starting from the given root. */ private void printDirectoryList(S3Folder root) { logger.info(String.format("%s", root.getPath())); printDirectoryList(root, 1); } private void printDirectoryList(S3Folder folder, int level) { String padding = String.format("%1$" + (level * 2) + "s", " "); // List folders first. for (Entry<String, S3Folder> folderEntry : folder.getFolders().entrySet()) { S3Folder childFolder = folderEntry.getValue(); String childFolderPath = childFolder.getPath(); logger.info(String.format("%s%s", padding, childFolderPath)); printDirectoryList(childFolder, level + 1); } // List files second. for (Entry<String, S3File> fileEntry : folder.getFiles().entrySet()) { S3File file = fileEntry.getValue(); logger.info(String.format("%s%s, %s, %s", padding, file.getPath(), S3File.humanReadableByteCount(file.getSize(), true), file.getLastModified())); } } }
package com.laytonsmith.core.functions; import com.laytonsmith.PureUtilities.ClassLoading.ClassDiscovery; import com.laytonsmith.PureUtilities.ClassLoading.ClassMirror.ClassMirror; import com.laytonsmith.PureUtilities.ClassLoading.DynamicEnum; import com.laytonsmith.PureUtilities.Version; import com.laytonsmith.annotations.MDynamicEnum; import com.laytonsmith.annotations.MEnum; import com.laytonsmith.annotations.api; import com.laytonsmith.annotations.core; import com.laytonsmith.core.FullyQualifiedClassName; import com.laytonsmith.core.MSVersion; import com.laytonsmith.core.Optimizable; import com.laytonsmith.core.ParseTree; import com.laytonsmith.core.Procedure; import com.laytonsmith.core.Script; import com.laytonsmith.core.Static; import com.laytonsmith.core.compiler.CompilerEnvironment; import com.laytonsmith.core.compiler.FileOptions; import com.laytonsmith.core.compiler.Keyword; import com.laytonsmith.core.compiler.KeywordList; import com.laytonsmith.core.constructs.CArray; import com.laytonsmith.core.constructs.CClassType; import com.laytonsmith.core.constructs.CFunction; import com.laytonsmith.core.constructs.CInt; import com.laytonsmith.core.constructs.CNull; import com.laytonsmith.core.constructs.CString; import com.laytonsmith.core.constructs.IVariable; import com.laytonsmith.core.constructs.NativeTypeList; import com.laytonsmith.core.constructs.Target; import com.laytonsmith.core.environments.CommandHelperEnvironment; import com.laytonsmith.core.environments.Environment; import com.laytonsmith.core.environments.GlobalEnv; import com.laytonsmith.core.events.Event; import com.laytonsmith.core.events.EventList; import com.laytonsmith.core.exceptions.CRE.CRECastException; import com.laytonsmith.core.exceptions.CRE.CREFormatException; import com.laytonsmith.core.exceptions.CRE.CREIOException; import com.laytonsmith.core.exceptions.CRE.CREIllegalArgumentException; import com.laytonsmith.core.exceptions.CRE.CREInsufficientArgumentsException; import com.laytonsmith.core.exceptions.CRE.CREThrowable; import com.laytonsmith.core.exceptions.ConfigCompileException; import com.laytonsmith.core.exceptions.ConfigRuntimeException; import com.laytonsmith.core.natives.interfaces.MEnumTypeValue; import com.laytonsmith.core.natives.interfaces.Mixed; import com.laytonsmith.core.objects.ObjectDefinition; import com.laytonsmith.core.objects.ObjectDefinitionTable; import com.laytonsmith.persistence.DataSourceFactory; import com.laytonsmith.persistence.PersistenceNetwork; import java.io.IOException; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import java.util.regex.Matcher; import java.util.regex.Pattern; @core public class Reflection { public static String docs() { return "This class of functions allows scripts to hook deep into the interpreter itself," + " and get meta information about the operations of a script. This is useful for" + " debugging, testing, and ultra dynamic scripting. See the" + " [[Reflection|guide to reflection]] on the wiki for more" + " details. In order to make the most of these functions, you should familiarize" + " yourself with the general workings of the language. These functions explore" + " extremely advanced concepts, and should normally not be used; especially" + " if you are not familiar with the language."; } @api public static class reflect_pull extends AbstractFunction { private static Set<Mixed> protocols; @Override public String getName() { return "reflect_pull"; } @Override public Integer[] numArgs() { return new Integer[]{Integer.MAX_VALUE}; } @Override public String docs() { return "mixed {param, [args, ...]} Returns information about the runtime in a usable" + " format. Depending on the information returned, it may be usable directly," + " or it may be more of a referential format. ---- The following items can be retrieved:" + "{|\n" + "|-\n" + "! param\n" + "! args\n" + "! returns/description\n" + "|-\n" + "| label\n" + "| \n" + "| Return the label that the script is currently running under\n" + "|-\n" + "| command\n" + "|\n" + "| Returns the command that was used to fire off this script (if applicable)\n" + "|-\n" + "| varlist\n" + "| [name]\n" + "| Returns a list of currently in scope variables. If name" + " is provided, the currently set value is instead returned.\n" + "|-\n" + "| line_num\n" + "|\n" + "| The current line number\n" + "|-\n" + "| file\n" + "|\n" + "| The absolute path to the current file\n" + "|-\n" + "| dir\n" + "|\n" + "| The absolute path to the directory that the current file is in\n" + "|-\n" + "| col\n" + "|\n" + "| The current column number\n" + "|-\n" + "| datasources\n" + "|\n" + "| An array of data source protocols available\n" + "|-\n" + "| enum\n" + "| [enum name]\n" + "| An array of enum names, or if one is provided, a list of all" + " the values in that enum\n" + "|-\n" + "| keywords\n" + "| [keyword name]\n" + "| Lists the keywords, if no parameter is provided, otherwise" + " provides the documentation for the specified keyword\n" + "|}"; } @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CREFormatException.class, CREIOException.class}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment env, Mixed... args) throws ConfigRuntimeException { if(args.length < 1) { throw new CREInsufficientArgumentsException("Not enough parameters was sent to " + getName(), t); } String param = args[0].val(); if("label".equalsIgnoreCase(param)) { return new CString(env.getEnv(GlobalEnv.class).GetLabel(), t); } else if("command".equalsIgnoreCase(param)) { return new CString(env.getEnv(CommandHelperEnvironment.class).GetCommand(), t); } else if("varlist".equalsIgnoreCase(param)) { if(args.length == 1) { //No name provided CArray ca = new CArray(t); for(String name : env.getEnv(GlobalEnv.class).GetVarList().keySet()) { ca.push(new CString(name, t), t); } return ca; } else if(args.length == 2) { //The name was provided String name = args[1].val(); return env.getEnv(GlobalEnv.class).GetVarList().get(name, t, env).ival(); } } else if("line_num".equalsIgnoreCase(param)) { return new CInt(t.line(), t); } else if("file".equalsIgnoreCase(param)) { if(t.file() == null) { return new CString("Unknown (maybe the interpreter?)", t); } else { try { return new CString(t.file().getCanonicalPath().replace('\\', '/'), t); } catch (IOException ex) { throw new CREIOException(ex.getMessage(), t); } } } else if("dir".equalsIgnoreCase(param)) { if(t.file() == null) { return new CString("Unknown (maybe the interpreter?)", t); } else { try { String dir = t.file().getParentFile().getCanonicalPath().replace('\\', '/'); return new CString(dir, t); } catch (IOException ex) { throw new CREIOException(ex.getMessage(), t); } } } else if("col".equalsIgnoreCase(param)) { return new CInt(t.col(), t); } else if("datasources".equalsIgnoreCase(param)) { if(protocols == null) { protocols = new HashSet<>(); for(String s : DataSourceFactory.GetSupportedProtocols()) { protocols.add(new CString(s, Target.UNKNOWN)); } } return new CArray(t, protocols); } else if("enum".equalsIgnoreCase(param)) { CArray a = new CArray(t); Set<ClassMirror<? extends Enum>> enums = ClassDiscovery.getDefaultInstance().getClassesWithAnnotationThatExtend(MEnum.class, Enum.class); Set<ClassMirror<? extends DynamicEnum>> dEnums = ClassDiscovery.getDefaultInstance().getClassesWithAnnotationThatExtend(MDynamicEnum.class, DynamicEnum.class); if(args.length == 1) { try { //No name provided for(ClassMirror<? extends Enum> e : enums) { String name = (String) e.getAnnotation(MEnum.class).getValue("value"); a.push(CClassType.get(FullyQualifiedClassName.forNativeEnum(e.loadClass())), t); } for(ClassMirror<? extends DynamicEnum> d : dEnums) { String name = (String) d.getAnnotation(MDynamicEnum.class).getValue("value"); a.push(CClassType.get(FullyQualifiedClassName.forFullyQualifiedClass(name)), t); } } catch (ClassNotFoundException ex) { throw new Error(ex); } } else if(args.length == 2) { FullyQualifiedClassName enumName = FullyQualifiedClassName.forName(args[1].val(), t, env); try { for(MEnumTypeValue v : NativeTypeList.getNativeEnumType(enumName).values()) { a.push(v, t); } } catch (ClassNotFoundException ex) { // Actually, I don't think this can throw new CRECastException("Cannot find enum of type " + enumName, t, ex); } } return a; } else if("keywords".equalsIgnoreCase(param)) { if(args.length == 1) { CArray a = new CArray(t); List<Keyword> l = new ArrayList<>(KeywordList.getKeywordList()); l.forEach(new Consumer<Keyword>() { @Override public void accept(Keyword t) { a.push(new CString(t.getKeywordName(), Target.UNKNOWN), Target.UNKNOWN); } }); return new ArrayHandling.array_sort().exec(t, env, a); } else if(args.length == 2) { Keyword k = KeywordList.getKeywordByName(args[1].val()); if(k == null) { throw new CREIllegalArgumentException(args[1].val() + " is not a valid keyword", t); } return new CString(k.docs(), Target.UNKNOWN); } } throw new CREFormatException("The arguments passed to " + getName() + " are incorrect. Please check them and try again.", t); } @Override public MSVersion since() { return MSVersion.V3_3_1; } } @api public static class reflect_docs extends AbstractFunction implements Optimizable { public static enum DocField { TYPE, RETURN, ARGS, DESCRIPTION; public String getName() { return name().toLowerCase(); } public static DocField getValue(String value) { return DocField.valueOf(value.toUpperCase()); } } @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CREFormatException.class}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment env, Mixed... args) throws ConfigRuntimeException { String element = args[0].val(); DocField docField; try { docField = DocField.getValue(args[1].val()); } catch (IllegalArgumentException e) { throw new CREFormatException("Invalid docField provided: " + args[1].val(), t); } //For now, we have special handling, since functions are actually the only thing that will work, //but eventually this will be a generic interface. if(element.startsWith("@")) { IVariable var = env.getEnv(GlobalEnv.class).GetVarList().get(element, t, env); if(var == null) { throw new CREFormatException("Invalid variable provided: " + element + " does not exist in the current scope", t); } } else if(element.startsWith("_")) { if(!env.getEnv(GlobalEnv.class).GetProcs().containsKey(element)) { throw new CREFormatException("Invalid procedure name provided: " + element + " does not exist in the current scope", t); } } else { try { Function f = (Function) FunctionList.getFunction(new CFunction(element, t), env.getEnvClasses()); return new CString(formatFunctionDoc(f.docs(), docField), t); } catch (ConfigCompileException ex) { throw new CREFormatException("Unknown function: " + element, t); } } return CNull.NULL; } public String formatFunctionDoc(String docs, DocField field) { Pattern p = Pattern.compile("(?s)\\s*(.*?)\\s*\\{(.*?)\\}\\s*(.*)\\s*"); Matcher m = p.matcher(docs); if(!m.find()) { throw new Error("An error has occurred in " + getName() + ". While trying to get the documentation" + ", it was unable to parse this: " + docs); } if(field == DocField.RETURN || field == DocField.TYPE) { return m.group(1); } else if(field == DocField.ARGS) { return m.group(2); } else if(field == DocField.DESCRIPTION) { return m.group(3); } throw new Error("Unhandled case in formatFunctionDoc!"); } @Override public ParseTree optimizeDynamic(Target t, Environment env, Set<Class<? extends Environment.EnvironmentImpl>> envs, List<ParseTree> children, FileOptions fileOptions) throws ConfigCompileException, ConfigRuntimeException { if(children.isEmpty()) { //They are requesting this function's documentation. We can just return a string, //and then it will never actually get called, so we handle it entirely in here. return new ParseTree(new CString(docs(), t), null); } if(children.size() == 1) { return null; // not enough arguments, so an exception will be thrown later } if(children.get(0).isConst()) { //If it's a function, we can check to see if it actually exists, //and make it a compile error if it doesn't, even if parameter 2 is dynamic String value = children.get(0).getData().val(); if(!value.startsWith("_") && !value.startsWith("@")) { //It's a function FunctionList.getFunction(new CFunction(value, t), env.getEnvClasses()); } } if(children.get(1).isConst()) { try { DocField.getValue(children.get(1).getData().val()); } catch (IllegalArgumentException e) { throw new ConfigCompileException("Invalid docField provided: " + children.get(1).getData().val(), t); } } return null; } @Override public Set<OptimizationOption> optimizationOptions() { return EnumSet.of( OptimizationOption.CONSTANT_OFFLINE, OptimizationOption.OPTIMIZE_DYNAMIC ); } @Override public String getName() { return "reflect_docs"; } @Override public Integer[] numArgs() { return new Integer[]{0, 2}; } @Override public String docs() { return "string { | element, docField} Returns the documentation for an element. There are 4 things that an element might have," + " and one of these should be passed as the docField argument: type, return, args, description. A valid element is either" + " the name of an ivariable, or a function/proc. For instance, reflect_docs('reflect_docs', 'description') would return" + " what you are reading right now. User defined variables and procs may not have any documentation, in which case null" + " is returned. If the specified argument cannot be found, a FormatException is thrown. If no arguments are passed in," + " it returns the documentation for " + getName() + ", that is, what you're reading right now."; } @Override public MSVersion since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Return type", "reflect_docs('array_contains', 'return'); // Using 'type' would also work"), new ExampleScript("Args", "reflect_docs('array_contains', 'args');"), new ExampleScript("Description", "reflect_docs('array_contains', 'description');") }; } } @api public static class get_functions extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } private static final Map<String, List<String>> FUNCS = new HashMap<String, List<String>>(); private void initf(Environment env) { for(FunctionBase f : FunctionList.getFunctionList(api.Platforms.INTERPRETER_JAVA, env.getEnvClasses())) { String[] pack = f.getClass().getEnclosingClass().getName().split("\\."); String clazz = pack[pack.length - 1]; if(!FUNCS.containsKey(clazz)) { FUNCS.put(clazz, new ArrayList<String>()); } FUNCS.get(clazz).add(f.getName()); } } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { CArray ret = CArray.GetAssociativeArray(t); if(FUNCS.keySet().size() < 10) { initf(environment); } for(String cname : FUNCS.keySet()) { CArray fnames = new CArray(t); for(String fname : FUNCS.get(cname)) { fnames.push(new CString(fname, t), t); } ret.set(new CString(cname, t), fnames, t); } return ret; } @Override public String getName() { return "get_functions"; } @Override public Integer[] numArgs() { return new Integer[]{0}; } @Override public String docs() { return "array {} Returns an associative array of all loaded functions. The keys of this array are the" + " names of the classes containing the functions (which you know as the sections of the API page)," + " and the values are arrays of the names of the functions within those classes."; } @Override public Version since() { return MSVersion.V3_3_1; } } @api public static class get_events extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { CArray ret = new CArray(t); for(Event event : EventList.GetEvents()) { ret.push(new CString(event.getName(), t), t); } ret.sort(CArray.ArraySortType.STRING_IC); return ret; } @Override public String getName() { return "get_events"; } @Override public Integer[] numArgs() { return new Integer[]{0}; } @Override public String docs() { return "array {} Returns an array of all registered event names."; } @Override public Version since() { return MSVersion.V3_3_1; } } @api(environments = {CommandHelperEnvironment.class}) public static class get_aliases extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { CArray ret = new CArray(t); for(Script s : Static.getAliasCore().getScripts()) { ret.push(new CString(s.getSignature(), t), t); } ret.sort(CArray.ArraySortType.STRING_IC); return ret; } @Override public String getName() { return "get_aliases"; } @Override public Integer[] numArgs() { return new Integer[]{0}; } @Override public String docs() { return "array {} Returns an array of the defined alias signatures (The part left of the = sign)."; } @Override public Version since() { return MSVersion.V3_3_1; } } @api public static class reflect_value_source extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { PersistenceNetwork pn = environment.getEnv(GlobalEnv.class).GetPersistenceNetwork(); return new CString(pn.getKeySource(args[0].val().split("\\.")).toString(), t); } @Override public String getName() { return "reflect_value_source"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "string {persistenceKey} Returns the source file that this key will store a value to in the Persistence Network." + " For instance, in your persistence.ini file, if you have the entry \"storage.test.**=json:///path/to/file.json\"," + " then reflect_value_source('storage.test.testing') would return 'json:///path/to/file.json'. This is useful for" + " debugging, as it will definitively trace back the source/destination of a value."; } @Override public Version since() { return MSVersion.V3_3_1; } } @api public static class get_procedures extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { CArray ret = new CArray(t); for(Map.Entry<String, Procedure> p : environment.getEnv(GlobalEnv.class).GetProcs().entrySet()) { ret.push(new CString(p.getKey(), t), t); } ret.sort(CArray.ArraySortType.STRING_IC); return ret; } @Override public String getName() { return "get_procedures"; } @Override public Integer[] numArgs() { return new Integer[]{0}; } @Override public String docs() { return "array {} Returns an array of procedures callable in the current scope."; } @Override public Version since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Simple example", "msg(get_procedures());\n" + "proc _testProc() {}\n" + "msg(get_procedures());"), new ExampleScript("Example with procedures within procedures", "msg(get_procedures());\n" + "proc _testProc() {\n" + "\tproc _innerProc() {}\n" + "\tmsg(get_procedures());\n" + "}\n" + "_testProc();\n" + "msg(get_procedures());") }; } } @api public static class get_classes extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return null; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { CArray ret = new CArray(t); ObjectDefinitionTable odt = environment.getEnv(CompilerEnvironment.class).getObjectDefinitionTable(); for(ObjectDefinition od : odt.getObjectDefinitionSet()) { try { ret.push(CClassType.get(FullyQualifiedClassName.forFullyQualifiedClass(od.getClassName())), t); } catch (ClassNotFoundException ex) { throw ConfigRuntimeException.CreateUncatchableException(ex.getMessage(), t); } } // for(FullyQualifiedClassName c : NativeTypeList.getNativeTypeList()) { // CClassType cct; // try { // } catch (ClassNotFoundException ex) { // throw ConfigRuntimeException.CreateUncatchableException(ex.getMessage(), t); // if(cct == CNull.TYPE) { // continue; // ret.push(cct, t); return ret; } @Override public String getName() { return "get_classes"; } @Override public Integer[] numArgs() { return new Integer[]{0}; } @Override public String docs() { return "array {} Returns a list of all known classes. This may not be completely exhaustive, but will" + " at least contain all system defined classes. The returned value is an array of ClassType" + " objects."; } @Override public Version since() { return MSVersion.V3_3_3; } } }
package com.lothrazar.cyclic.gui; import com.lothrazar.cyclic.net.PacketTileData; import com.lothrazar.cyclic.registry.PacketRegistry; import com.mojang.blaze3d.matrix.MatrixStack; import java.util.ArrayList; import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.player.ClientPlayerEntity; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.widget.AbstractSlider; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TranslationTextComponent; public class GuiSliderInteger extends AbstractSlider implements IHasTooltip { public static final int ARROW_LEFT = 263; public static final int ARROW_RIGHT = 262; static final int ESC = 256; private final double min; private final double max; private final BlockPos pos; // Tile entity location private final int field; // field ID for saving value private List<ITextComponent> tooltip; public GuiSliderInteger(int x, int y, int width, int height, int field, BlockPos pos, int min, int max, double initialVal) { super(x, y, width, height, StringTextComponent.EMPTY, 0); this.field = field; this.pos = pos; this.min = min; this.max = max; setSliderValueActual((int) initialVal); } /** * exact copy of super() but replaced hardcoded 20 with this.height */ // @SuppressWarnings("deprecation") @Override protected void renderBg(MatrixStack matrixStack, Minecraft minecraft, int mouseX, int mouseY) { minecraft.getTextureManager().bindTexture(WIDGETS_LOCATION); // RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F); int i = (this.isHovered() ? 2 : 1) * 20; if(this.height != 20) { this.blit(matrixStack, this.x + (int) (this.sliderValue * (this.width - 8)), this.y, 0, 46 + i + 20 - this.height, 4, this.height); this.blit(matrixStack, this.x + (int) (this.sliderValue * (this.width - 8)) + 4, this.y, 196, 46 + i + 20 - this.height, 4, this.height); int height = this.height - 2; this.blit(matrixStack, this.x + (int) (this.sliderValue * (this.width - 8)), this.y, 0, 46 + i, 4, height); this.blit(matrixStack, this.x + (int) (this.sliderValue * (this.width - 8)) + 4, this.y, 196, 46 + i, 4, height); } else { this.blit(matrixStack, this.x + (int) (this.sliderValue * (this.width - 8)), this.y, 0, 46 + i, 4, this.height); this.blit(matrixStack, this.x + (int) (this.sliderValue * (this.width - 8)) + 4, this.y, 196, 46 + i, 4, this.height); } } /** * Call from Screen class to render tooltip during mouseover */ @Override public List<ITextComponent> getTooltip() { return tooltip; } /** * Add a tooltip to first line (second line hardcoded) */ @Override public void setTooltip(String tt) { // if (tooltip == null) { tooltip = new ArrayList<>(); this.tooltip.add(new TranslationTextComponent(tt)); this.tooltip.add(new TranslationTextComponent("cyclic.gui.sliderkeys").mergeStyle(TextFormatting.DARK_GRAY)); } /** * Mouse scrolling */ @Override public boolean mouseScrolled(double mouseX, double mouseY, double delta) { if (delta != 0) { setSliderValueActual(this.getSliderValueActual() + (int) delta); this.func_230979_b_(); return true; } return super.mouseScrolled(mouseX, mouseY, delta); } /** * Fires when control is selected, also I call this from screen class whenever mouse is hovered for extra UX */ @Override public boolean keyPressed(int keyCode, int scanCode, int modifiers) { if (keyCode == ESC) { //close ClientPlayerEntity pl = Minecraft.getInstance().player; if (pl != null) { pl.closeScreen(); } return true; } if (keyCode == ARROW_LEFT || keyCode == ARROW_RIGHT) { // move from arrow keys int delta = (keyCode == ARROW_LEFT) ? -1 : 1; if (Screen.hasShiftDown()) { delta = delta * 5; } else if (Screen.hasAltDown()) { delta = delta * 10; } setSliderValueActual(this.getSliderValueActual() + delta); this.func_230979_b_(); return true; } return super.keyPressed(keyCode, scanCode, modifiers); } /** * Refresh display message */ @Override protected void func_230979_b_() { int val = getSliderValueActual(); this.setMessage(new TranslationTextComponent("" + val)); } /** * SAVE to tile entity with packet */ @Override protected void func_230972_a_() { int val = getSliderValueActual(); PacketRegistry.INSTANCE.sendToServer(new PacketTileData(this.field, val, pos)); } @Override protected void onDrag(double mouseX, double mouseY, double dragX, double dragY) { // this.changeSliderValueActual(mouseX); super.onDrag(mouseX, mouseY, dragX, dragY); // ("ondrag" + mouseX); func_230972_a_(); func_230979_b_(); } /** * Set inner [0,1] value relative to maximum and trigger save/ & refresh */ private void setSliderValueActual(int val) { this.sliderValue = val / max; this.func_230979_b_(); this.func_230972_a_(); } public int getSliderValueActual() { return MathHelper.floor(MathHelper.clampedLerp(min, max, this.sliderValue)); } public int getField() { return this.field; } }
package com.mangopay.core.enumerations; /** * ISO 3166-1 alpha-2 country codes enumeration. */ public enum CountryIso { /** * Not specified. */ NotSpecified, /** * Andorra */ AD, /** * United Arab Emirates */ AE, /** * Afghanistan */ AF, /** * Antigua and Barbuda */ AG, /** * Anguilla */ AI, /** * Albania */ AL, /** * Armenia */ AM, /** * Netherlands Antilles */ AN, /** * Angola */ AO, /** * Antarctica */ AQ, /** * Argentina */ AR, /** * American Samoa */ AS, /** * Austria */ AT, /** * Australia */ AU, /** * Aruba */ AW, /** * Aland Islands */ AX, /** * Azerbaijan */ AZ, /** * Bosnia and Herzegovina */ BA, /** * Barbados */ BB, /** * Bangladesh */ BD, /** * Belgium */ BE, /** * Burkina Faso */ BF, /** * Bulgaria */ BG, /** * Bahrain */ BH, /** * Burundi */ BI, /** * Benin */ BJ, BL, /** * Bermuda */ BM, /** * Brunei Darussalam */ BN, /** * Bolivia, Plurinational State of */ BO, /** * Bonaire, Sint Eustatius and Saba */ BQ, /** * Brazil */ BR, /** * Bahamas */ BS, /** * Bhutan */ BT, /** * Bouvet Island */ BV, /** * Botswana */ BW, /** * Belarus */ BY, /** * Belize */ BZ, /** * Canada */ CA, /** * Cocos (Keeling) Islands */ CC, /** * Congo, the Democratic Republic of the */ CD, /** * Central African Republic */ CF, /** * Congo */ CG, /** * Switzerland */ CH, CI, /** * Cook Islands */ CK, /** * Chile */ CL, /** * Cameroon */ CM, /** * China */ CN, /** * Colombia */ CO, /** * Costa Rica */ CR, /** * Cuba */ CU, /** * Cabo Verde */ CV, CW, /** * Christmas Island */ CX, /** * Cyprus */ CY, /** * Czech Republic */ CZ, /** * Germany */ DE, /** * Djibouti */ DJ, /** * Denmark */ DK, /** * Dominica */ DM, /** * Dominican Republic */ DO, /** * Algeria */ DZ, /** * Ecuador */ EC, /** * Estonia */ EE, /** * Egypt */ EG, /** * Western Sahara */ EH, /** * Eritrea */ ER, /** * Spain */ ES, /** * Ethiopia */ ET, /** * Finland */ FI, /** * Fiji */ FJ, /** * Falkland Islands (Malvinas) */ FK, /** * Micronesia, Federated States of */ FM, /** * Faroe Islands */ FO, /** * France */ FR, /** * Gabon */ GA, /** * United Kingdom */ GB, /** * Grenada */ GD, /** * Georgia */ GE, /** * French Guiana */ GF, /** * Guernsey */ GG, /** * Ghana */ GH, /** * Gibraltar */ GI, /** * Greenland */ GL, /** * Gambia */ GM, /** * Guinea */ GN, /** * Guadeloupe */ GP, /** * Equatorial Guinea */ GQ, /** * Greece */ GR, /** * South Georgia and the South Sandwich Islands */ GS, /** * Guatemala */ GT, /** * Guam */ GU, /** * Guinea-Bissau */ GW, /** * Guyana */ GY, /** * Hong Kong */ HK, /** * Heard Island and McDonald Islands */ HM, /** * Honduras */ HN, /** * Croatia */ HR, /** * Haiti */ HT, /** * Hungary */ HU, /** * Indonesia */ ID, /** * Ireland */ IE, /** * Israel */ IL, /** * Isle of Man */ IM, /** * India */ IN, /** * British Indian Ocean Territory */ IO, /** * Iraq */ IQ, /** * Iran, Islamic Republic of */ IR, /** * Iceland */ IS, /** * Italy */ IT, /** * Jersey */ JE, /** * Jamaica */ JM, /** * Jordan */ JO, /** * Japan */ JP, /** * Kenya */ KE, /** * Kyrgyzstan */ KG, /** * Cambodia */ KH, /** * Kiribati */ KI, /** * Comoros */ KM, /** * Saint Kitts and Nevis */ KN, /** * Korea, Democratic People's Republic of */ KP, /** * Korea, Republic of */ KR, /** * Kuwait */ KW, /** * Cayman Islands */ KY, /** * Kazakhstan */ KZ, /** * Lao People's Democratic Republic */ LA, /** * Lebanon */ LB, /** * Saint Lucia */ LC, /** * Liechtenstein */ LI, /** * Sri Lanka */ LK, /** * Liberia */ LR, /** * Lesotho */ LS, /** * Lithuania */ LT, /** * Luxembourg */ LU, /** * Latvia */ LV, /** * Libya */ LY, /** * Morocco */ MA, /** * Monaco */ MC, /** * Moldova, Republic of */ MD, /** * Montenegro */ ME, /** * Saint Martin (French part) */ MF, /** * Madagascar */ MG, /** * Marshall Islands */ MH, /** * Macedonia, the former Yugoslav Republic of */ MK, /** * Mali */ ML, /** * Myanmar */ MM, /** * Mongolia */ MN, /** * Macao */ MO, /** * Northern Mariana Islands */ MP, /** * Martinique */ MQ, /** * Mauritania */ MR, /** * Montserrat */ MS, /** * Malta */ MT, /** * Mauritius */ MU, /** * Maldives */ MV, /** * Malawi */ MW, /** * Mexico */ MX, /** * Malaysia */ MY, /** * Mozambique */ MZ, /** * Namibia */ NA, /** * New Caledonia */ NC, /** * Niger */ NE, /** * Norfolk Island */ NF, /** * Nigeria */ NG, /** * Nicaragua */ NI, /** * Netherlands */ NL, /** * Norway */ NO, /** * Nepal */ NP, /** * Nauru */ NR, /** * Niue */ NU, /** * New Zealand */ NZ, /** * Oman */ OM, /** * Panama */ PA, /** * Peru */ PE, /** * French Polynesia */ PF, /** * Papua New Guinea */ PG, /** * Philippines */ PH, /** * Pakistan */ PK, /** * Poland */ PL, /** * Saint Pierre and Miquelon */ PM, /** * Pitcairn */ PN, /** * Puerto Rico */ PR, /** * Palestine, State of */ PS, /** * Portugal */ PT, /** * Palau */ PW, /** * Paraguay */ PY, /** * Qatar */ QA, RE, /** * Romania */ RO, /** * Serbia */ RS, /** * Russian Federation */ RU, /** * Rwanda */ RW, /** * Saudi Arabia */ SA, /** * Solomon Islands */ SB, /** * Seychelles */ SC, /** * Sudan */ SD, /** * Sweden */ SE, /** * Singapore */ SG, /** * Saint Helena, Ascension and Tristan da Cunha */ SH, /** * Slovenia */ SI, /** * Svalbard and Jan Mayen */ SJ, /** * Slovakia */ SK, /** * Sierra Leone */ SL, /** * San Marino */ SM, /** * Senegal */ SN, /** * Somalia */ SO, /** * Suriname */ SR, /** * South Sudan */ SS, /** * Sao Tome and Principe */ ST, /** * El Salvador */ SV, /** * Sint Maarten (Dutch part) */ SX, /** * Syrian Arab Republic */ SY, /** * Swaziland */ SZ, /** * Turks and Caicos Islands */ TC, /** * Chad */ TD, /** * French Southern Territories */ TF, /** * Togo */ TG, /** * Thailand */ TH, /** * Tajikistan */ TJ, /** * Tokelau */ TK, /** * Timor-Leste */ TL, /** * Turkmenistan */ TM, /** * Tunisia */ TN, /** * Tonga */ TO, /** * Turkey */ TR, /** * Trinidad and Tobago */ TT, /** * Tuvalu */ TV, /** * Taiwan, Province of China */ TW, /** * Tanzania, United Republic of */ TZ, /** * Ukraine */ UA, /** * Uganda */ UG, /** * United States Minor Outlying Islands */ UM, /** * United States */ US, /** * Uruguay */ UY, /** * Uzbekistan */ UZ, /** * Holy See (Vatican City State) */ VA, /** * Saint Vincent and the Grenadines */ VC, /** * Venezuela, Bolivarian Republic of */ VE, /** * Virgin Islands, British */ VG, /** * Virgin Islands, U.S. */ VI, /** * Viet Nam */ VN, /** * Vanuatu */ VU, /** * Wallis and Futuna */ WF, /** * Samoa */ WS, /** * Yemen */ YE, /** * Mayotte */ YT, /** * South Africa */ ZA, /** * Zambia */ ZM, /** * Zimbabwe */ ZW }
package com.orange.oss.cloudfoundry.cscpi; import static java.util.concurrent.TimeUnit.SECONDS; import static org.jclouds.util.Predicates2.retry; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.UUID; import org.jclouds.cloudstack.CloudStackApi; import org.jclouds.cloudstack.domain.AsyncCreateResponse; import org.jclouds.cloudstack.domain.DiskOffering; import org.jclouds.cloudstack.domain.NIC; import org.jclouds.cloudstack.domain.Network; import org.jclouds.cloudstack.domain.NetworkOffering; import org.jclouds.cloudstack.domain.OSType; import org.jclouds.cloudstack.domain.ServiceOffering; import org.jclouds.cloudstack.domain.Tag; import org.jclouds.cloudstack.domain.Template; import org.jclouds.cloudstack.domain.TemplateMetadata; import org.jclouds.cloudstack.domain.VirtualMachine; import org.jclouds.cloudstack.domain.VirtualMachine.State; import org.jclouds.cloudstack.domain.Volume; import org.jclouds.cloudstack.domain.Volume.Type; import org.jclouds.cloudstack.domain.Zone; import org.jclouds.cloudstack.features.VolumeApi; import org.jclouds.cloudstack.options.CreateSnapshotOptions; import org.jclouds.cloudstack.options.CreateTagsOptions; import org.jclouds.cloudstack.options.CreateTemplateOptions; import org.jclouds.cloudstack.options.DeleteTemplateOptions; import org.jclouds.cloudstack.options.DeployVirtualMachineOptions; import org.jclouds.cloudstack.options.ListDiskOfferingsOptions; import org.jclouds.cloudstack.options.ListNetworkOfferingsOptions; import org.jclouds.cloudstack.options.ListNetworksOptions; import org.jclouds.cloudstack.options.ListServiceOfferingsOptions; import org.jclouds.cloudstack.options.ListTagsOptions; import org.jclouds.cloudstack.options.ListTemplatesOptions; import org.jclouds.cloudstack.options.ListVirtualMachinesOptions; import org.jclouds.cloudstack.options.ListVolumesOptions; import org.jclouds.cloudstack.options.ListZonesOptions; import org.jclouds.cloudstack.options.RegisterTemplateOptions; import org.jclouds.cloudstack.predicates.JobComplete; import org.jclouds.http.HttpResponseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.util.Assert; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableMap; import com.orange.oss.cloudfoundry.cscpi.boshregistry.BoshRegistryClient; import com.orange.oss.cloudfoundry.cscpi.domain.NetworkType; import com.orange.oss.cloudfoundry.cscpi.domain.Networks; import com.orange.oss.cloudfoundry.cscpi.domain.ResourcePool; import com.orange.oss.cloudfoundry.cscpi.exceptions.VMCreationFailedException; import com.orange.oss.cloudfoundry.cscpi.webdav.WebdavServerAdapter; public class CPIImpl implements CPI{ private static final String CPI_VM_PREFIX = "cpivm-"; private static final String CPI_PERSISTENT_DISK_PREFIX = "cpi-disk-"; private static final String CPI_EPHEMERAL_DISK_PREFIX = "cpi-ephemeral-disk-"; private static Logger logger=LoggerFactory.getLogger(CPIImpl.class); @Value("${cloudstack.state_timeout}") int state_timeout; @Value("${cloudstack.state_timeout_volume}") int state_timeout_volume; @Value("${cloudstack.stemcell_public_visibility}") boolean stemcell_public_visibility; @Value("${cloudstack.default_zone}") String default_zone; @Value("${cpi.mock_create_stemcell}") boolean mockCreateStemcell; //initial preexisting template (to mock stemcell upload before template generation) @Value("${cpi.existing_template_name}") String existingTemplateName; private Predicate<String> jobComplete; @Autowired private CloudStackApi api; @Autowired UserDataGenerator userDataGenerator; @Autowired VmSettingGenerator vmSettingGenerator; @Autowired private WebdavServerAdapter webdav; @Autowired private BoshRegistryClient boshRegistry; /** * creates a vm. * take the stemcell_id as cloudstack template name. * create the vm on the correct network configuration * static * vip * floating * create an "ephemeral disk" and attach it the the vm * * @param agent_id * @param stemcell_id * @param resource_pool * @param networks * @param disk_locality * @param env * @return * @throws VMCreationFailedException */ public String create_vm(String agent_id, String stemcell_id, ResourcePool resource_pool, Networks networks, List<String> disk_locality, Map<String,String> env) throws VMCreationFailedException { String compute_offering=resource_pool.compute_offering; Assert.isTrue(compute_offering!=null,"Must provide compute offering in vm ressource pool"); String vmName=CPI_VM_PREFIX+UUID.randomUUID().toString(); logger.info("now creating cloudstack vm"); //cloudstack userdata generation for bootstrap String userData=this.userDataGenerator.userMetadata(vmName,networks); this.vmCreation(stemcell_id, compute_offering, networks, vmName,agent_id,userData); //TODO: create ephemeral disk, read the disk size from properties, attach it to the vm. //NB: if base ROOT disk is large enough, bosh agent can use it to hold swap / ephemeral data. CPI forces an external vol for ephemeral String ephemeralDiskServiceOfferingName=resource_pool.ephemeral_disk_offering; Assert.isTrue(ephemeralDiskServiceOfferingName!=null,"create_vm: must specify ephemeral_disk_offering attribute in cloud properties"); logger.debug("ephemeral disk offering is {}",ephemeralDiskServiceOfferingName); logger.info("now creating ephemeral disk"); int ephemeralDiskSize=resource_pool.disk/1024; //cloudstack size api is Go String name=CPI_EPHEMERAL_DISK_PREFIX+UUID.randomUUID().toString(); String ephemeralDiskName=this.diskCreate(name,ephemeralDiskSize,ephemeralDiskServiceOfferingName); //NOW attache the ephemeral disk to the vm (need reboot ?) //FIXME : placement constraint local disk offering / vm logger.info("now attaching ephemaral disk {} to cloudstack vm {}",ephemeralDiskName,vmName); this.diskAttachment(vmName, ephemeralDiskName); //FIXME: registry feeding in vmCreation method. refactor here ? return vmName; } /** * Cloudstack vm creation. * @param stemcell_id * @param compute_offering * @param networks * @param vmName * @throws VMCreationFailedException */ private void vmCreation(String stemcell_id, String compute_offering, Networks networks, String vmName,String agent_id,String userData) throws VMCreationFailedException { Set<Template> matchingTemplates=api.getTemplateApi().listTemplates(ListTemplatesOptions.Builder.name(stemcell_id)); Assert.isTrue(matchingTemplates.size()==1,"Did not find a single template with name "+stemcell_id); Template stemCellTemplate=matchingTemplates.iterator().next(); String csTemplateId=stemCellTemplate.getId(); logger.info("found cloudstack template {} matching name / stemcell_id {}",csTemplateId,stemcell_id ); String csZoneId = findZoneId(); //find compute offering Set<ServiceOffering> computeOfferings = api.getOfferingApi().listServiceOfferings(ListServiceOfferingsOptions.Builder.name(compute_offering)); Assert.isTrue(computeOfferings.size()>0, "Unable to find compute offering "+compute_offering); ServiceOffering so=computeOfferings.iterator().next(); //parse network from cloud_properties Assert.isTrue(networks.networks.size()==1, "CPI currenly only support 1 network / nic per VM"); String directorNetworkName=networks.networks.keySet().iterator().next(); //NB: directorName must be usefull for vm provisioning ? com.orange.oss.cloudfoundry.cscpi.domain.Network directorNetwork=networks.networks.values().iterator().next(); String network_name=directorNetwork.cloud_properties.get("name"); //find the network with the provided name Network network=null; Set<Network> listNetworks = api.getNetworkApi().listNetworks(ListNetworksOptions.Builder.zoneId(csZoneId)); for (Network n:listNetworks){ if (n.getName().equals(network_name)){ network=n; } } Assert.notNull(network,"Could not find network "+network_name); Set<NetworkOffering> listNetworkOfferings = api.getOfferingApi().listNetworkOfferings(ListNetworkOfferingsOptions.Builder.zoneId(csZoneId).id(network.getNetworkOfferingId())); NetworkOffering networkOffering=listNetworkOfferings.iterator().next(); //Requirements, check the provided network, must have a correct prerequisite in offering // service offering need dhcp (if same bootstrap as openstack) // need metadata service for userData // need dns ? logger.info("associated Network Offering is {}", networkOffering.getName()); NetworkType netType=directorNetwork.type; DeployVirtualMachineOptions options=null; switch (netType) { case vip: case dynamic: logger.debug("dynamic ip vm creation"); options=DeployVirtualMachineOptions.Builder .name(vmName) .networkId(network.getId()) .userData(userData.getBytes()) //.dataDiskSize(dataDiskSize) ; break; case manual: logger.debug("static / manual ip vm creation"); options=DeployVirtualMachineOptions.Builder .name(vmName) .networkId(network.getId()) .userData(userData.getBytes()) //.dataDiskSize(dataDiskSize) .ipOnDefaultNetwork(directorNetwork.ip) ; break; } logger.info("Now launching VM {} creation !",vmName); try { AsyncCreateResponse job = api.getVirtualMachineApi().deployVirtualMachineInZone(csZoneId, so.getId(), csTemplateId, options); jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS); jobComplete.apply(job.getJobId()); } catch (HttpResponseException hjce){ int statusCode=hjce.getResponse().getStatusCode(); String message=hjce.getResponse().getMessage(); logger.error("Error while creating vm. Status code {}, Message : {} ",statusCode,message); throw new VMCreationFailedException("Error while creating vm",hjce); } VirtualMachine vm = api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name(vmName)).iterator().next(); if (! vm.getState().equals(State.RUNNING)) { throw new RuntimeException("Not in expected running state:" + vm.getState()); } //list NICS, check macs. NIC nic=vm.getNICs().iterator().next(); logger.info("generated NIC : "+nic.toString()); //FIXME: move bosh registry in create_vm (no need of registry for stemcell generation work vms) //populate bosh registry logger.info("add vm {} to registry", vmName ); String settings=this.vmSettingGenerator.createsettingForVM(agent_id,vmName,vm,networks); this.boshRegistry.put(vmName, settings); logger.info("vm creation completed, now running ! {}"); } @Override @Deprecated public String current_vm_id() { logger.info("current_vm_id"); //FIXME : deprecated API //must keep state in CPI with latest changed / created vm ?? Or find current vm running cpi ? by IP / hostname ? // ==> use local vm meta data server to identify. // see http://cloudstack-administration.readthedocs.org/en/latest/api.html#user-data-and-meta-data return null; } /** * * first try : create a vm from an existing template, stop it, create template from vm, delete work vm * * @param image_path * @param cloud_properties * @return */ @Override public String create_stemcell(String image_path, Map<String, String> cloud_properties) { logger.info("create_stemcell"); //mock mode enables tests with an existing template (copied as a new template) if (this.mockCreateStemcell){ logger.warn("USING MOCK STEMCELL TRANSFORMATION TO CLOUDSTAK TEMPLATE)"); String stemcellId; try { stemcellId = mockTemplateGeneration(); } catch (VMCreationFailedException e) { throw new RuntimeException(e); } return stemcellId; } //TODO : template name limited to 32 chars, UUID is longer. use Random for now Random randomGenerator=new Random(); String stemcellId="cpitemplate-"+randomGenerator.nextInt(100000); logger.info("Starting to upload stemcell to webdav"); Assert.isTrue(image_path!=null,"create_stemcell: Image Path must not be Null"); File f=new File(image_path); Assert.isTrue(f.exists(), "create_stemcell: Image Path does not exist :"+image_path); Assert.isTrue(f.isFile(), "create_stemcell: Image Path exist but is not a file :"+image_path); String webDavUrl=null; try { webDavUrl=this.webdav.pushFile(new FileInputStream(f), stemcellId+".vhd"); } catch (FileNotFoundException e) { logger.error("Unable to read file"); throw new RuntimeException("Unable to read file",e); } logger.debug("template pushed to webdav, url {}",webDavUrl); //FIXME: find correct os type (PVM 64 bits) OSType osType=null; for (OSType ost:api.getGuestOSApi().listOSTypes()){ if (ost.getDescription().equals("Other PV (64-bit)")) osType=ost; } Assert.notNull(osType, "Unable to find OsType"); TemplateMetadata templateMetadata=TemplateMetadata.builder() .name(stemcellId) .osTypeId(osType.getId()) .displayText(stemcellId+" : cpi stemcell template") .build(); RegisterTemplateOptions options=RegisterTemplateOptions.Builder .bits(64) .isExtractable(true) //.isPublic(false) //true is KO //.isFeatured(false) //.domainId(domainId) ; //TODO: get from cloud properties ie from stemcell MANIFEST file ? String hypervisor="XenServer"; String format="VHD"; // QCOW2, RAW, and VHD. Set<Template> registredTemplates = api.getTemplateApi().registerTemplate(templateMetadata, format, hypervisor, webDavUrl, findZoneId(), options); for (Template t: registredTemplates){ logger.debug("registred template "+t.toString()); } //FIXME: wait for the template to be ready logger.info("Template successfully registred ! {} - {}",stemcellId); logger.info("done registering cloudstack template for stemcell {}",stemcellId); return stemcellId; } /** * Mocktemplate generation : use existing template and copy it as another * * @return */ private String mockTemplateGeneration() throws VMCreationFailedException { //String instance_type="Ultra Tiny"; String instance_type="CO1 - Small STD"; //FIXME : should parameter the network offering String network_name="DefaultIsolatedNetworkOfferingWithSourceNatService"; logger.info("CREATING work vm for template generation"); //map stemcell to cloudstack template concept. String workVmName="cpi-stemcell-work-"+UUID.randomUUID(); //FIXME : temporay network config (dynamic) Networks fakeDirectorNetworks=new Networks(); com.orange.oss.cloudfoundry.cscpi.domain.Network net=new com.orange.oss.cloudfoundry.cscpi.domain.Network(); net.type=NetworkType.dynamic; net.cloud_properties.put("name", "3112 - preprod - back"); net.dns.add("10.234.50.180"); net.dns.add("10.234.71.124"); fakeDirectorNetworks.networks.put("default",net); this.vmCreation(existingTemplateName, instance_type, fakeDirectorNetworks, workVmName,"fakeagent","fakeuserdata"); VirtualMachine m=api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name(workVmName)).iterator().next(); logger.info("STOPPING work vm for template generation"); String stopJob=api.getVirtualMachineApi().stopVirtualMachine(m.getId()); jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS); jobComplete.apply(stopJob); logger.info("Work vm stopped. now creating template from it its ROOT Volume"); Volume rootVolume=api.getVolumeApi().listVolumes(ListVolumesOptions.Builder.virtualMachineId(m.getId()).type(Type.ROOT)).iterator().next(); //hopefully, fist volume is ROOT ? //FIXME : template name limited to 32 chars, UUID is longer. use Random Random randomGenerator=new Random(); String stemcellId="cpitemplate-"+randomGenerator.nextInt(100000); //FIXME: find correct os type (PVM 64 bits) OSType osType=null; for (OSType ost:api.getGuestOSApi().listOSTypes()){ if (ost.getDescription().equals("Other PV (64-bit)")) osType=ost; } Assert.notNull(osType, "Unable to find OsType"); TemplateMetadata templateMetadata=TemplateMetadata.builder() .name(stemcellId) .osTypeId(osType.getId()) .volumeId(rootVolume.getId()) .displayText("generated cpi stemcell template") .build(); CreateTemplateOptions options=CreateTemplateOptions.Builder .isPublic(true) .isFeatured(true); AsyncCreateResponse asyncTemplateCreateJob =api.getTemplateApi().createTemplate(templateMetadata, options); jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS); jobComplete.apply(asyncTemplateCreateJob.getJobId()); logger.info("Template successfully created ! {} - {}",stemcellId); logger.info("now cleaning work vm"); String jobId=api.getVirtualMachineApi().destroyVirtualMachine(m.getId()); jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS); jobComplete.apply(jobId); logger.info("work vm cleaned work vm"); return stemcellId; } @Override public void delete_stemcell(String stemcell_id) { logger.info("delete_stemcell"); //FIXME: assert stemcell_id template exists and is unique Set<Template> listTemplates = api.getTemplateApi().listTemplates(ListTemplatesOptions.Builder.name(stemcell_id)); Assert.isTrue(listTemplates.size()>0,"Could not find any CloudStack Template matching stemcell id "+stemcell_id); Assert.isTrue(listTemplates.size()==1,"Found multiple CloudStack templates matching stemcell_id "+stemcell_id); String csTemplateId=listTemplates.iterator().next().getId(); String zoneId=findZoneId(); DeleteTemplateOptions options=DeleteTemplateOptions.Builder.zoneId(zoneId); AsyncCreateResponse asyncTemplateDeleteJob =api.getTemplateApi().deleteTemplate(csTemplateId, options); jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS); jobComplete.apply(asyncTemplateDeleteJob.getJobId()); logger.info("stemcell {} successfully deleted",stemcell_id); } @Override public void delete_vm(String vm_id) { logger.info("delete_vm"); Set<VirtualMachine> vms = api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name(vm_id)); if (vms.size()==0) { logger.warn("Vm to delete does not exist {}. OK ...",vm_id); return; } Assert.isTrue(vms.size()==1, "delete_vm : Found multiple VMs with name "+vm_id); String csVmId=vms.iterator().next().getId(); String jobId=api.getVirtualMachineApi().destroyVirtualMachine(csVmId); jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS); jobComplete.apply(jobId); //FIXME : should force expunge VM (bosh usually recreates a vm shortly, expunge is necessary to avoid ip / vols reuse conflicts). //remove vm_id /settings from bosh registry logger.info("remove vm {} from registry", vm_id ); this.boshRegistry.delete(vm_id); //delete ephemeral disk !! Unmount then delete. Set<Volume> vols=api.getVolumeApi().listVolumes(ListVolumesOptions.Builder.type(Type.DATADISK).virtualMachineId(csVmId)); if (vols.size()==0){ logger.warn("No ephemeral disk found while deleting vm {}. Ignoring ...",vm_id); return; } Assert.isTrue(vols.size()==1,"Should have a single data disk mounted (ephemeral disk), found "+vols.size()); Volume ephemeralVol=vols.iterator().next(); Assert.isTrue(ephemeralVol.getName().startsWith(CPI_EPHEMERAL_DISK_PREFIX),"mounted disk is not ephemeral disk. Name is "+ephemeralVol.getName()); //detach disk AsyncCreateResponse resp=api.getVolumeApi().detachVolume(ephemeralVol.getId()); jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS); jobComplete.apply(resp.getJobId()); //delete disk api.getVolumeApi().deleteVolume(ephemeralVol.getName()); logger.info("deleted successfully vm {} and ephemeral disk {}",vm_id,ephemeralVol.getName()); } @Override public boolean has_vm(String vm_id) { logger.info("has_vm ?"); Set<VirtualMachine> listVirtualMachines = api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name(vm_id)); if (listVirtualMachines.size()==0) return false; return true; } @Override public boolean has_disk(String disk_id) { logger.info("has_disk ?"); Set<Volume> vols=api.getVolumeApi().listVolumes(ListVolumesOptions.Builder.name(disk_id).type(Type.DATADISK)); if (vols.size()==0) return false; logger.debug("disk {} found in cloudstack", disk_id); return true; } @Override public void reboot_vm(String vm_id) { logger.info("reboot_vm"); VirtualMachine vm=api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name(vm_id)).iterator().next(); String rebootJob=api.getVirtualMachineApi().rebootVirtualMachine(vm.getId()); jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS); jobComplete.apply(rebootJob); logger.info("done rebooting vm {}",vm_id); } /** * add metadata to the VM. CPI should not rely on the presence of specific ket */ @Override public void set_vm_metadata(String vm_id, Map<String, String> metadata) { logger.info("set vm metadata"); VirtualMachine vm=api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name(vm_id)).iterator().next(); //set metadatas setVmMetada(vm_id, metadata, vm); } /** * * adapter method to cloudstack User Tag API * @param vm_id cloudstack vm id * @param metadata map of tag name / value * @param vm cloudstack VirtualMachine */ private void setVmMetada(String vm_id, Map<String, String> metadata, VirtualMachine vm) { //NB: must merge with preexisting user tags. delete previous tag ListTagsOptions listTagOptions=ListTagsOptions.Builder.resourceId(vm.getId()).resourceType(Tag.ResourceType.USER_VM); Set<Tag> existingTags=api.getTagApi().listTags(listTagOptions); if (existingTags.size()>0) { //FIXME: merge change existing tags logger.warn("VM metadata already set on vm {}.Metadata change not yet implemented by CPI"); return; } ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); Map<String, String> tags = builder.putAll(metadata).build(); logger.debug(">> adding tags %s to virtualmachine(%s)", tags, vm.getId()); CreateTagsOptions tagOptions = CreateTagsOptions.Builder.resourceIds(vm.getId()).resourceType(Tag.ResourceType.USER_VM).tags(tags); AsyncCreateResponse tagJob = api.getTagApi().createTags(tagOptions); jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS); jobComplete.apply(tagJob.getJobId()); logger.info("done settings metadata on vm ",vm_id); } /** * Modify the VM network configuration * NB: throws NotSupported error for now. => The director will delete the VM and recreate a new One with the desired target conf * @throws com.orange.oss.cloudfoundry.cscpi.exceptions.NotSupportedException */ @Override public void configure_networks(String vm_id, JsonNode networks) throws com.orange.oss.cloudfoundry.cscpi.exceptions.NotSupportedException { logger.info("configure network"); throw new com.orange.oss.cloudfoundry.cscpi.exceptions.NotSupportedException("CPI does not support modifying network yet"); } @Override public String create_disk(Integer size, Map<String, String> cloud_properties) { String diskOfferingName=cloud_properties.get("disk_offering"); Assert.isTrue(diskOfferingName!=null, "no disk_offering attribute specified for disk creation !"); String name=CPI_PERSISTENT_DISK_PREFIX+UUID.randomUUID().toString(); return this.diskCreate(name,size,diskOfferingName); } /** * @param diskOfferingName * @return */ private String diskCreate(String name,int size,String diskOfferingName) { logger.info("create_disk {} on offering {}",name,diskOfferingName); //find disk offering Set<DiskOffering> listDiskOfferings = api.getOfferingApi().listDiskOfferings(ListDiskOfferingsOptions.Builder.name(diskOfferingName)); Assert.isTrue(listDiskOfferings.size()>0, "Unknown Service Offering ! : "+diskOfferingName); DiskOffering csDiskOffering = listDiskOfferings.iterator().next(); String diskOfferingId=csDiskOffering.getId(); String zoneId=this.findZoneId(); AsyncCreateResponse resp=null; if (csDiskOffering.isCustomized()){ logger.info("creating disk with specified size (custom size offering)"); resp=api.getVolumeApi().createVolumeFromCustomDiskOfferingInZone(name, diskOfferingId, zoneId, size); } else { logger.info("creating disk - ignoring specified size {} (fixed by offering : {} )",size,csDiskOffering.getDiskSize()); resp=api.getVolumeApi().createVolumeFromDiskOfferingInZone(name, diskOfferingId, zoneId); } jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS); jobComplete.apply(resp.getJobId()); logger.info("disk {} successfully created ",name); return name; } @Override public void delete_disk(String disk_id) { logger.info("delete_disk"); //FIXME; check disk exists String csDiskId=api.getVolumeApi().listVolumes(ListVolumesOptions.Builder.name(disk_id).type(Type.DATADISK)).iterator().next().getId(); api.getVolumeApi().deleteVolume(csDiskId); } @Override public void attach_disk(String vm_id, String disk_id) { logger.info("attach disk"); this.diskAttachment(vm_id, disk_id); //now update registry String previousSetting=this.boshRegistry.getRaw(vm_id); String newSetting=this.vmSettingGenerator.updateVmSettingForAttachDisk(previousSetting, disk_id); this.boshRegistry.put(vm_id, newSetting); logger.info("==> attach disk updated in bosh registry"); } /** * Cloudstack Attachement. * Used for persistent disks and ephemeral disk * @param vm_id * @param disk_id */ private void diskAttachment(String vm_id, String disk_id) { //FIXME; check disk exists //FIXME: check vm exists Set<Volume> volumes = api.getVolumeApi().listVolumes(ListVolumesOptions.Builder.name(disk_id).type(Type.DATADISK)); Assert.isTrue(volumes.size()<2,"attach_disk: Fatal, Found multiple volume with name "+disk_id); Assert.isTrue(volumes.size()==1,"attach_disk: Unable to find volume "+disk_id); String csDiskId=volumes.iterator().next().getId(); Set<VirtualMachine> vms = api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name(vm_id)); Assert.isTrue(vms.size()==1, "attach_disk: Unable to find vm "+vm_id); String csVmId=vms.iterator().next().getId(); VolumeApi vol = this.api.getVolumeApi(); AsyncCreateResponse resp=vol.attachVolume(csDiskId, csVmId); //TODO: need to restart vm ? jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS); jobComplete.apply(resp.getJobId()); logger.info("==> attach disk successfull"); } @Override public String snapshot_disk(String disk_id, Map<String, String> metadata) { logger.info("snapshot disk"); String csDiskId=api.getVolumeApi().getVolume(disk_id).getId(); AsyncCreateResponse async = api.getSnapshotApi().createSnapshot(csDiskId,CreateSnapshotOptions.Builder.domainId("domain")); jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS); jobComplete.apply(async.getJobId()); //FIXME return null; } @Override public void delete_snapshot(String snapshot_id) { logger.info("delete snapshot"); //TODO } @Override public void detach_disk(String vm_id, String disk_id) { logger.info("detach disk"); String csDiskId=api.getVolumeApi().listVolumes(ListVolumesOptions.Builder.name(disk_id).type(Type.DATADISK)).iterator().next().getId(); AsyncCreateResponse resp=api.getVolumeApi().detachVolume(csDiskId); jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS); jobComplete.apply(resp.getJobId()); logger.info("==> detach disk successfull"); //now update registry String previousSetting=this.boshRegistry.getRaw(vm_id); String newSetting=this.vmSettingGenerator.updateVmSettingForDetachDisk(previousSetting, disk_id); this.boshRegistry.put(vm_id, newSetting); logger.info("==> attach disk updated in bosh registry"); } @Override public List<String> get_disks(String vm_id) { logger.info("get_disks"); VirtualMachine vm=api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name(vm_id)).iterator().next(); VolumeApi vol = this.api.getVolumeApi(); Set<Volume> vols=vol.listVolumes(ListVolumesOptions.Builder.virtualMachineId(vm.getId())); ArrayList<String> disks = new ArrayList<String>(); Iterator<Volume> it=vols.iterator(); while (it.hasNext()){ Volume v=it.next(); //only DATA disk - persistent disk. No ROOT disk,no ephemeral disk ? if ((v.getType()==Type.DATADISK) && (v.getName().startsWith(CPI_PERSISTENT_DISK_PREFIX))){ String disk_id=v.getName(); disks.add(disk_id); } } return disks; } /** * utility to retrieve cloudstack zoneId * @return */ private String findZoneId() { //TODO: select the exact zone if multiple available ListZonesOptions zoneOptions=ListZonesOptions.Builder.available(true); Set<Zone> zones = api.getZoneApi().listZones(zoneOptions); Assert.notEmpty(zones, "No Zone available"); Zone zone=zones.iterator().next(); String zoneId = zone.getId(); Assert.isTrue(zone.getName().equals(this.default_zone)); return zoneId; } }
package com.samczsun.skype4j.internal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.samczsun.skype4j.formatting.Message; import org.apache.commons.lang3.StringEscapeUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.parser.Parser; import com.eclipsesource.json.JsonObject; import com.samczsun.skype4j.chat.Chat; import com.samczsun.skype4j.chat.ChatMessage; import com.samczsun.skype4j.events.chat.ChatJoinedEvent; import com.samczsun.skype4j.events.chat.TopicChangeEvent; import com.samczsun.skype4j.events.chat.message.MessageEditedByOtherEvent; import com.samczsun.skype4j.events.chat.message.MessageEditedEvent; import com.samczsun.skype4j.events.chat.message.MessageReceivedEvent; import com.samczsun.skype4j.events.chat.user.MultiUserAddEvent; import com.samczsun.skype4j.events.chat.user.RoleUpdateEvent; import com.samczsun.skype4j.events.chat.user.UserAddEvent; import com.samczsun.skype4j.events.chat.user.UserRemoveEvent; import com.samczsun.skype4j.exceptions.SkypeException; import com.samczsun.skype4j.formatting.RichText; import com.samczsun.skype4j.user.User; import com.samczsun.skype4j.user.User.Role; public enum MessageType { UNKNOWN("Unknown") { @Override public void handle(SkypeImpl skype, JsonObject resource) { } }, TEXT("Text") { @Override public void handle(SkypeImpl skype, JsonObject resource) throws SkypeException { MessageType.RICH_TEXT.handle(skype, resource); } }, RICH_TEXT("RichText") { @Override public void handle(SkypeImpl skype, JsonObject resource) throws SkypeException { if (resource.get("clientmessageid") != null) { // New message String clientId = resource.get("clientmessageid").asString(); String id = resource.get("id").asString(); String content = resource.get("content").asString(); String from = resource.get("from").asString(); String url = resource.get("conversationLink").asString(); Chat c = getChat(url, skype); User u = getUser(from, c); ChatMessage m = ChatMessageImpl.createMessage(c, u, id, clientId, System.currentTimeMillis(), Message.fromHtml(stripMetadata(content))); ((ChatImpl) c).onMessage(m); MessageReceivedEvent evnt = new MessageReceivedEvent(m); skype.getEventDispatcher().callEvent(evnt); } else if (resource.get("skypeeditedid") != null) { // Edited // message String url = resource.get("conversationLink").asString(); String from = resource.get("from").asString(); final Chat c = getChat(url, skype); final User u = getUser(from, c); // If not original sender, then // fake final String clientId = resource.get("skypeeditedid").asString(); final String id = resource.get("id").asString(); String content = resource.get("content").asString(); content = stripMetadata(content); boolean faker = false; if (content.startsWith("Edited previous message: ")) { content = content.substring("Edited previous message: ".length()); ChatMessage m = u.getMessageById(clientId); if (m != null) { MessageEditedEvent evnt = new MessageEditedEvent(m, content); skype.getEventDispatcher().callEvent(evnt); ((ChatMessageImpl) m).setContent(Message.fromHtml(content)); } else { faker = true; } } else { faker = true; } if (faker) { Message originalContent = null; for (User user : c.getAllUsers()) { if (user.getMessageById(clientId) != null) { originalContent = user.getMessageById(clientId).getMessage(); } } final Message finalOriginalContent = originalContent; MessageEditedByOtherEvent event = new MessageEditedByOtherEvent(new ChatMessage() { public String getClientId() { return clientId; } public Message getMessage() { return finalOriginalContent; } public long getTime() { return System.currentTimeMillis(); } public User getSender() { return u; } public void edit(Message newMessage) throws SkypeException { throw new UnsupportedOperationException(); } public void delete() throws SkypeException { throw new UnsupportedOperationException(); } public Chat getChat() { return c; } public String getId() { return id; } }, content, u); skype.getEventDispatcher().callEvent(event); } } else { throw new SkypeException("Had no id"); } } }, RICH_TEXT_CONTACTS("RichText/Contacts") { @Override public void handle(SkypeImpl skype, JsonObject resource) { } }, RICH_TEXT_FILES("RichText/Files") { @Override public void handle(SkypeImpl skype, JsonObject resource) { } }, RICH_TEXT_SMS("RichText/Sms") { @Override public void handle(SkypeImpl skype, JsonObject resource) { } }, RICH_TEXT_LOCATION("RichText/Location") { @Override public void handle(SkypeImpl skype, JsonObject resource) { } }, RICH_TEXT_URI_OBJECT("RichText/UriObject") { @Override public void handle(SkypeImpl skype, JsonObject resource) { } }, RICH_TEXT_MEDIA_FLIK_MSG("RichText/Media_FlikMsg") { @Override public void handle(SkypeImpl skype, JsonObject resource) { } }, EVENT_SKYPE_VIDEO_MESSAGE("Event/SkypeVideoMessage") { @Override public void handle(SkypeImpl skype, JsonObject resource) { } }, THREAD_ACTIVITY_ADD_MEMBER("ThreadActivity/AddMember") { @Override public void handle(SkypeImpl skype, JsonObject resource) throws SkypeException { String url = resource.get("conversationLink").asString(); Chat c = getChat(url, skype); List<User> usersAdded = new ArrayList<>(); Document xml = Jsoup.parse(resource.get("content").asString(), "", Parser.xmlParser()); User initiator = c.getUser(xml.getElementsByTag("initiator").get(0).text()); for (Element e : xml.getElementsByTag("target")) { String username = e.text().substring(2); if (username.equals(skype.getUsername())) { ChatJoinedEvent event = new ChatJoinedEvent(c); skype.getEventDispatcher().callEvent(event); } else { usersAdded.add(c.getUser(username)); } ((ChatImpl) c).addUser(username); } UserAddEvent event = null; if (usersAdded.size() == 1) { event = new UserAddEvent(usersAdded.get(0), initiator); } else { event = new MultiUserAddEvent(usersAdded, initiator); } skype.getEventDispatcher().callEvent(event); } }, THREAD_ACTIVITY_DELETE_MEMBER("ThreadActivity/DeleteMember") { @Override public void handle(SkypeImpl skype, JsonObject resource) throws SkypeException { String url = resource.get("conversationLink").asString(); Chat c = getChat(url, skype); List<User> usersRemoved = new ArrayList<>(); Document xml = Jsoup.parse(resource.get("content").asString(), "", Parser.xmlParser()); User initiator = c.getUser(xml.getElementsByTag("initiator").get(0).text()); for (Element e : xml.getElementsByTag("target")) { String username = e.text().substring(2); usersRemoved.add(c.getUser(username)); ((ChatImpl) c).removeUser(username); } UserRemoveEvent event = null; if (usersRemoved.size() == 1) { event = new UserRemoveEvent(usersRemoved.get(0), initiator); } else { throw new SkypeException("More than one user removed?"); } skype.getEventDispatcher().callEvent(event); } }, THREAD_ACTIVITY_ROLE_UPDATE("ThreadActivity/RoleUpdate") { @Override public void handle(SkypeImpl skype, JsonObject resource) throws SkypeException { String url = resource.get("conversationLink").asString(); Chat c = getChat(url, skype); Document xml = Jsoup.parse(resource.get("content").asString(), "", Parser.xmlParser()); User target = c.getUser(xml.getElementsByTag("id").get(0).text().substring(2)); Role role = Role.getByName(xml.getElementsByTag("role").get(0).text()); target.setRole(role); RoleUpdateEvent e = new RoleUpdateEvent(target); skype.getEventDispatcher().callEvent(e); } }, THREAD_ACTIVITY_TOPIC_UPDATE("ThreadActivity/TopicUpdate") { @Override public void handle(SkypeImpl skype, JsonObject resource) { String url = resource.get("conversationLink").asString(); Chat c = getChat(url, skype); Document xml = Jsoup.parse(resource.get("content").asString(), "", Parser.xmlParser()); if (xml.getElementsByTag("value").size() > 0) { ((ChatGroup) c).updateTopic(StringEscapeUtils.unescapeHtml4(xml.getElementsByTag("value").get(0).text())); } else { ((ChatGroup) c).updateTopic(""); } TopicChangeEvent e = new TopicChangeEvent(c); skype.getEventDispatcher().callEvent(e); } }, THREAD_ACTIVITY_PICTURE_UPDATE("ThreadActivity/PictureUpdate") { @Override public void handle(SkypeImpl skype, JsonObject resource) { } }, THREAD_ACTIVITY_HISTORY_DISCLOSED_UPDATE("ThreadActivity/HistoryDisclosedUpdate") { @Override public void handle(SkypeImpl skype, JsonObject resource) { } }, THREAD_ACTIVITY_JOINING_ENABLED_UPDATE("ThreadActivity/JoiningEnabledUpdate") { @Override public void handle(SkypeImpl skype, JsonObject resource) { } }, THREAD_ACTIVITY_LEGACY_MEMBER_ADDED("ThreadActivity/LegacyMemberAdded") { @Override public void handle(SkypeImpl skype, JsonObject resource) { } }, THREAD_ACTIVITY_LEGACY_MEMBER_UPGRADED("ThreadActivity/LegacyMemberUpgraded") { @Override public void handle(SkypeImpl skype, JsonObject resource) { } }, EVENT_CALL("Event/Call") { @Override public void handle(SkypeImpl skype, JsonObject resource) { } }, CONTROL_TYPING("Control/Typing") { @Override public void handle(SkypeImpl skype, JsonObject resource) { } }, CONTROL_CLEAR_TYPING("Control/ClearTyping") { @Override public void handle(SkypeImpl skype, JsonObject resource) { } }, CONTROL_LIVE_STATE("Control/LiveState") { @Override public void handle(SkypeImpl skype, JsonObject resource) { } }; private static final Map<String, MessageType> byValue = new HashMap<>(); private static final Pattern URL_PATTERN = Pattern.compile("conversations/(.*)"); private static final Pattern USER_PATTERN = Pattern.compile("8:(.*)"); private static final Pattern STRIP_EDIT_PATTERN = Pattern.compile("</?[e_m][^<>]+>"); private static final Pattern STRIP_QUOTE_PATTERN = Pattern.compile("(<(?:/?)(?:quote|legacyquote)[^>]*>)", Pattern.CASE_INSENSITIVE); private static final Pattern STRIP_EMOTICON_PATTERN = Pattern.compile("(<(?:/?)(?:ss)[^>]*>)", Pattern.CASE_INSENSITIVE); private final String value; MessageType(String value) { this.value = value; } public String getValue() { return this.value; } public abstract void handle(SkypeImpl skype, JsonObject resource) throws SkypeException; static { for (MessageType type : values()) { byValue.put(type.getValue(), type); } } public static MessageType getByName(String messageType) { return byValue.get(messageType); } private static Chat getChat(String url, SkypeImpl skype) { Matcher m = URL_PATTERN.matcher(url); if (m.find()) { return skype.getChat(m.group(1)); } return null; } private static User getUser(String url, Chat c) { Matcher m = USER_PATTERN.matcher(url); if (m.find()) { return c.getUser(m.group(1)); } return null; } private static String stripMetadata(String message) { return STRIP_EMOTICON_PATTERN.matcher(STRIP_QUOTE_PATTERN.matcher(STRIP_EDIT_PATTERN.matcher(message).replaceAll("")).replaceAll("")).replaceAll(""); } }
package com.sandwell.JavaSimulation3D; import static com.sandwell.JavaSimulation.Util.formatNumber; import java.util.ArrayList; import java.util.HashMap; import com.jaamsim.input.InputAgent; import com.jaamsim.math.Color4d; import com.sandwell.JavaSimulation.BooleanInput; import com.sandwell.JavaSimulation.BooleanListInput; import com.sandwell.JavaSimulation.BooleanVector; import com.sandwell.JavaSimulation.ColourInput; import com.sandwell.JavaSimulation.DoubleInput; import com.sandwell.JavaSimulation.DoubleListInput; import com.sandwell.JavaSimulation.DoubleVector; import com.sandwell.JavaSimulation.EntityInput; import com.sandwell.JavaSimulation.EntityListInput; import com.sandwell.JavaSimulation.ErrorException; import com.sandwell.JavaSimulation.FileEntity; import com.sandwell.JavaSimulation.Input; import com.sandwell.JavaSimulation.InputErrorException; import com.sandwell.JavaSimulation.IntegerVector; import com.sandwell.JavaSimulation.Keyword; import com.sandwell.JavaSimulation.ProbabilityDistribution; import com.sandwell.JavaSimulation.Process; import com.sandwell.JavaSimulation.Tester; import com.sandwell.JavaSimulation.Vector; /** * Class ModelEntity - JavaSimulation3D */ public class ModelEntity extends DisplayEntity { // Breakdowns @Keyword(desc = "Reliability is defined as:\n" + " 100% - (plant breakdown time / total operation time)\n " + "or\n " + "(Operational Time)/(Breakdown + Operational Time)", example = "Object1 Reliability { 0.95 }") private final DoubleInput availability; protected double hoursForNextFailure; // The number of working hours required before the next breakdown protected double iATFailure; // inter arrival time between failures protected boolean breakdownPending; // true when a breakdown is to occur protected boolean brokendown; // true => entity is presently broken down protected boolean maintenance; // true => entity is presently in maintenance protected boolean associatedBreakdown; // true => entity is presently in Associated Breakdown protected boolean associatedMaintenance; // true => entity is presently in Associated Maintenance protected double breakdownStartTime; // Start time of the most recent breakdown protected double breakdownEndTime; // End time of the most recent breakdown // Breakdown Probability Distributions @Keyword(desc = "A ProbabilityDistribution object that governs the duration of breakdowns (in hours).", example = "Object1 DowntimeDurationDistribution { BreakdownProbDist1 }") private final EntityInput<ProbabilityDistribution> downtimeDurationDistribution; @Keyword(desc = "A ProbabilityDistribution object that governs when breakdowns occur (in hours).", example = "Object1 DowntimeIATDistribution { BreakdownProbDist1 }") private final EntityInput<ProbabilityDistribution> downtimeIATDistribution; // Maintenance @Keyword(desc = "The simulation time for the start of the first maintenance for each maintenance cycle.", example = "Object1 FirstMaintenanceTime { 24 h }") protected DoubleListInput firstMaintenanceTimes; @Keyword(desc = "The time between maintenance activities for each maintenance cycle", example = "Object1 MaintenanceInterval { 168 h }") protected DoubleListInput maintenanceIntervals; @Keyword(desc = "The durations of a single maintenance event for each maintenance cycle.", example = "Object1 MaintenanceDuration { 336 h }") protected DoubleListInput maintenanceDurations; protected IntegerVector maintenancePendings; // Number of maintenance periods that are due @Keyword(desc = "A Boolean value. Allows scheduled maintenances to be skipped if it overlaps " + "with another planned maintenance event.", example = "Object1 SkipMaintenanceIfOverlap { TRUE }") protected BooleanListInput skipMaintenanceIfOverlap; @Keyword(desc = "A list of objects that share the maintenance schedule with this object. " + "In order for the maintenance to start, all objects on this list must be available." + "This keyword is for Handlers and Signal Blocks only.", example = "Block1 SharedMaintenance { Block2 Block2 }") private final EntityListInput<ModelEntity> sharedMaintenanceList; protected ModelEntity masterMaintenanceEntity; // The entity that has maintenance information protected boolean performMaintenanceAfterShipDelayPending; // maintenance needs to be done after shipDelay // Maintenance based on hours of operations @Keyword(desc = "Working time for the start of the first maintenance for each maintenance cycle", example = "Object1 FirstMaintenanceOperatingHours { 1000 2500 h }") private final DoubleListInput firstMaintenanceOperatingHours; @Keyword(desc = "Working time between one maintenance event and the next for each maintenance cycle", example = "Object1 MaintenanceOperatingHoursIntervals { 2000 5000 h }") private final DoubleListInput maintenanceOperatingHoursIntervals; @Keyword(desc = "Duration of maintenance events based on working hours for each maintenance cycle", example = "Ship1 MaintenanceOperatingHoursDurations { 24 48 h }") private final DoubleListInput maintenanceOperatingHoursDurations; protected IntegerVector maintenanceOperatingHoursPendings; // Number of maintenance periods that are due protected DoubleVector hoursForNextMaintenanceOperatingHours; protected double maintenanceStartTime; // Start time of the most recent maintenance protected double maintenanceEndTime; // End time of the most recent maintenance protected DoubleVector nextMaintenanceTimes; // next start time for each maintenance protected double nextMaintenanceDuration; // duration for next maintenance protected DoubleVector lastScheduledMaintenanceTimes; @Keyword(desc = "If maintenance has been deferred by the DeferMaintenanceLookAhead keyword " + "for longer than this time, the maintenance will start even if " + "there is an object within the lookahead. There must be one entry for each " + "defined maintenance schedule if DeferMaintenanceLookAhead is used. This" + "keyword is only used for signal blocks.", example = "Object1 DeferMaintenanceLimit { 50 50 h }") private final DoubleListInput deferMaintenanceLimit; @Keyword(desc = "If the duration of the downtime is longer than this time, equipment will be released", example = "Object1 DowntimeToReleaseEquipment { 1.0 h }") protected final DoubleInput downtimeToReleaseEquipment; @Keyword(desc = "A list of Boolean values corresponding to the maintenance cycles. If a value is TRUE, " + "then routes/tasks are released before performing the maintenance in the cycle.", example = "Object1 ReleaseEquipment { TRUE FALSE FALSE }") protected final BooleanListInput releaseEquipment; @Keyword(desc = "A list of Boolean values corresponding to the maintenance cycles. If a value is " + "TRUE, then maintenance in the cycle can start even if the equipment is presently " + "working.", example = "Object1 ForceMaintenance { TRUE FALSE FALSE }") protected final BooleanListInput forceMaintenance; // Statistics @Keyword(desc = "If TRUE, then statistics for this object are " + "included in the main output report.", example = "Object1 PrintToReport { TRUE }") private final BooleanInput printToReport; // States private static Vector stateList = new Vector( 11, 1 ); // List of valid states private final HashMap<String, StateRecord> stateMap; protected double workingHours; // Accumulated working time spent in working states private static class StateRecord { String stateName; int index; double initializationHours; double totalHours; double completedCycleHours; double currentCycleHours; double lastStartTimeInState; double secondLastStartTimeInState; public StateRecord(String state, int i) { stateName = state; index = i; } public int getIndex() { return index; } public String getStateName() { return stateName; } public double getTotalHours() { return totalHours; } public double getCompletedCycleHours() { return completedCycleHours; } public double getCurrentCycleHours() { return currentCycleHours; } public double getLastStartTimeInState() { return lastStartTimeInState; } public double getSecondLastStartTimeInState() { return secondLastStartTimeInState; } public void setInitializationHours(double init) { initializationHours = init; } public void setTotalHours(double total) { totalHours = total; } public void setCompletedCycleHours(double hours) { completedCycleHours = hours; } public void setCurrentCycleHours(double hours) { currentCycleHours = hours; } @Override public String toString() { return getStateName(); } public void clearReportStats() { totalHours = 0.0d; completedCycleHours = 0.0d; } public void clearCurrentCycleHours() { currentCycleHours = 0.0d; } } private double timeOfLastStateChange; private int numberOfCompletedCycles; protected double lastHistogramUpdateTime; // Last time at which a histogram was updated for this entity protected double secondToLastHistogramUpdateTime; // Second to last time at which a histogram was updated for this entity private StateRecord presentState; // The present state of the entity protected FileEntity stateReportFile; // The file to store the state information private String finalLastState = ""; // The final state of the entity (in a sequence of transitional states) private double timeOfLastPrintedState = 0; // The time that the last state printed in the trace state file // Graphics protected final static Color4d breakdownColor = ColourInput.DARK_RED; // Color of the entity in breaking down protected final static Color4d maintenanceColor = ColourInput.RED; // Color of the entity in maintenance static { stateList.addElement( "Idle" ); stateList.addElement( "Working" ); stateList.addElement( "Breakdown" ); stateList.addElement( "Maintenance" ); } { maintenanceDurations = new DoubleListInput("MaintenanceDurations", "Maintenance", new DoubleVector()); maintenanceDurations.setValidRange(0.0d, Double.POSITIVE_INFINITY); maintenanceDurations.setUnits("h"); this.addInput(maintenanceDurations, true, "MaintenanceDuration"); maintenanceIntervals = new DoubleListInput("MaintenanceIntervals", "Maintenance", new DoubleVector()); maintenanceIntervals.setValidRange(0.0d, Double.POSITIVE_INFINITY); maintenanceIntervals.setUnits("h"); this.addInput(maintenanceIntervals, true, "MaintenanceInterval"); firstMaintenanceTimes = new DoubleListInput("FirstMaintenanceTimes", "Maintenance", new DoubleVector()); firstMaintenanceTimes.setValidRange(0.0d, Double.POSITIVE_INFINITY); firstMaintenanceTimes.setUnits("h"); this.addInput(firstMaintenanceTimes, true, "FirstMaintenanceTime"); forceMaintenance = new BooleanListInput("ForceMaintenance", "Maintenance", null); this.addInput(forceMaintenance, true); releaseEquipment = new BooleanListInput("ReleaseEquipment", "Maintenance", null); this.addInput(releaseEquipment, true); availability = new DoubleInput("Reliability", "Breakdowns", 1.0d, 0.0d, 1.0d); this.addInput(availability, true); downtimeIATDistribution = new EntityInput<ProbabilityDistribution>(ProbabilityDistribution.class, "DowntimeIATDistribution", "Breakdowns", null); this.addInput(downtimeIATDistribution, true); downtimeDurationDistribution = new EntityInput<ProbabilityDistribution>(ProbabilityDistribution.class, "DowntimeDurationDistribution", "Breakdowns", null); this.addInput(downtimeDurationDistribution, true); downtimeToReleaseEquipment = new DoubleInput("DowntimeToReleaseEquipment", "Breakdowns", 0.0d, 0.0d, Double.POSITIVE_INFINITY); this.addInput(downtimeToReleaseEquipment, true); skipMaintenanceIfOverlap = new BooleanListInput("SkipMaintenanceIfOverlap", "Maintenance", new BooleanVector()); this.addInput(skipMaintenanceIfOverlap, true); deferMaintenanceLimit = new DoubleListInput("DeferMaintenanceLimit", "Maintenance", null); deferMaintenanceLimit.setValidRange(0.0d, Double.POSITIVE_INFINITY); deferMaintenanceLimit.setUnits("h"); this.addInput(deferMaintenanceLimit, true); sharedMaintenanceList = new EntityListInput<ModelEntity>(ModelEntity.class, "SharedMaintenance", "Maintenance", new ArrayList<ModelEntity>(0)); this.addInput(sharedMaintenanceList, true); firstMaintenanceOperatingHours = new DoubleListInput("FirstMaintenanceOperatingHours", "Maintenance", new DoubleVector()); firstMaintenanceOperatingHours.setValidRange(0.0d, Double.POSITIVE_INFINITY); firstMaintenanceOperatingHours.setUnits("h"); this.addInput(firstMaintenanceOperatingHours, true); maintenanceOperatingHoursDurations = new DoubleListInput("MaintenanceOperatingHoursDurations", "Maintenance", new DoubleVector()); maintenanceOperatingHoursDurations.setValidRange(1e-15, Double.POSITIVE_INFINITY); maintenanceOperatingHoursDurations.setUnits("h"); this.addInput(maintenanceOperatingHoursDurations, true); maintenanceOperatingHoursIntervals = new DoubleListInput("MaintenanceOperatingHoursIntervals", "Maintenance", new DoubleVector()); maintenanceOperatingHoursIntervals.setValidRange(1e-15, Double.POSITIVE_INFINITY); maintenanceOperatingHoursIntervals.setUnits("h"); this.addInput(maintenanceOperatingHoursIntervals, true); printToReport = new BooleanInput("PrintToReport", "Report", true); this.addInput(printToReport, true); } public ModelEntity() { lastHistogramUpdateTime = 0.0; secondToLastHistogramUpdateTime = 0.0; hoursForNextFailure = 0.0; iATFailure = 0.0; maintenancePendings = new IntegerVector( 1, 1 ); maintenanceOperatingHoursPendings = new IntegerVector( 1, 1 ); hoursForNextMaintenanceOperatingHours = new DoubleVector( 1, 1 ); performMaintenanceAfterShipDelayPending = false; lastScheduledMaintenanceTimes = new DoubleVector(); breakdownStartTime = 0.0; breakdownEndTime = Double.POSITIVE_INFINITY; breakdownPending = false; brokendown = false; associatedBreakdown = false; maintenanceStartTime = 0.0; maintenanceEndTime = Double.POSITIVE_INFINITY; maintenance = false; associatedMaintenance = false; workingHours = 0.0; stateMap = new HashMap<String, StateRecord>(); StateRecord idle = new StateRecord("Idle", 0); stateMap.put("idle" , idle); presentState = idle; timeOfLastStateChange = getCurrentTime(); idle.lastStartTimeInState = getCurrentTime(); idle.secondLastStartTimeInState = getCurrentTime(); initStateMap(); } /** * Clear internal properties */ public void clearInternalProperties() { hoursForNextFailure = 0.0; performMaintenanceAfterShipDelayPending = false; breakdownPending = false; brokendown = false; associatedBreakdown = false; maintenance = false; associatedMaintenance = false; workingHours = 0.0; } @Override public void validate() throws InputErrorException { super.validate(); this.validateMaintenance(); Input.validateIndexedLists(firstMaintenanceOperatingHours.getValue(), maintenanceOperatingHoursIntervals.getValue(), "FirstMaintenanceOperatingHours", "MaintenanceOperatingHoursIntervals"); Input.validateIndexedLists(firstMaintenanceOperatingHours.getValue(), maintenanceOperatingHoursDurations.getValue(), "FirstMaintenanceOperatingHours", "MaintenanceOperatingHoursDurations"); if( getAvailability() < 1.0 ) { if( getDowntimeDurationDistribution() == null ) { throw new InputErrorException("When availability is less than one you must define downtimeDurationDistribution in your input file!"); } } if( downtimeIATDistribution.getValue() != null ) { if( getDowntimeDurationDistribution() == null ) { throw new InputErrorException("When DowntimeIATDistribution is set, DowntimeDurationDistribution must also be set."); } } if( skipMaintenanceIfOverlap.getValue().size() > 0 ) Input.validateIndexedLists(firstMaintenanceTimes.getValue(), skipMaintenanceIfOverlap.getValue(), "FirstMaintenanceTimes", "SkipMaintenanceIfOverlap"); if( releaseEquipment.getValue() != null ) Input.validateIndexedLists(firstMaintenanceTimes.getValue(), releaseEquipment.getValue(), "FirstMaintenanceTimes", "ReleaseEquipment"); if( forceMaintenance.getValue() != null ) { Input.validateIndexedLists(firstMaintenanceTimes.getValue(), forceMaintenance.getValue(), "FirstMaintenanceTimes", "ForceMaintenance"); } if(downtimeDurationDistribution.getValue() != null && downtimeDurationDistribution.getValue().getMinimumValue() < 0) throw new InputErrorException("DowntimeDurationDistribution cannot allow negative values"); if(downtimeIATDistribution.getValue() != null && downtimeIATDistribution.getValue().getMinimumValue() < 0) throw new InputErrorException("DowntimeIATDistribution cannot allow negative values"); } @Override public void earlyInit() { super.earlyInit(); if( downtimeDurationDistribution.getValue() != null ) { downtimeDurationDistribution.getValue().initialize(); } if( downtimeIATDistribution.getValue() != null ) { downtimeIATDistribution.getValue().initialize(); } } /** * Runs after initialization period */ public void collectInitializationStats() { for ( StateRecord each : stateMap.values() ) { each.setInitializationHours( getTotalHoursFor(each) ); each.clearReportStats(); if (each == presentState) each.setCurrentCycleHours( getCurrentCycleHoursFor(each) ); } if ( this.isWorking() ) workingHours += getCurrentTime() - timeOfLastStateChange; timeOfLastStateChange = getCurrentTime(); numberOfCompletedCycles = 0; } /** * Runs when cycle is finished */ public void collectCycleStats() { // finalize cycle for each state record for ( StateRecord each : stateMap.values() ) { double hour = each.getCompletedCycleHours(); hour += getCurrentCycleHoursFor(each); each.setCompletedCycleHours(hour); each.clearCurrentCycleHours(); if (each == presentState) each.setTotalHours( getTotalHoursFor(each) ); } if ( this.isWorking() ) workingHours += getCurrentTime() - timeOfLastStateChange; timeOfLastStateChange = getCurrentTime(); numberOfCompletedCycles++; } /** * Runs after each report interval */ public void clearReportStats() { // clear totalHours for each state record for ( StateRecord each : stateMap.values() ) { each.clearReportStats(); } numberOfCompletedCycles = 0; } public int getNumberOfCompletedCycles() { return numberOfCompletedCycles; } /** * Clear the current cycle hours */ protected void clearCurrentCycleHours() { // clear current cycle hours for each state record for ( StateRecord each : stateMap.values() ) { if (each == presentState) each.setTotalHours( getTotalHoursFor(each) ); each.clearCurrentCycleHours(); } if ( this.isWorking() ) workingHours += getCurrentTime() - timeOfLastStateChange; timeOfLastStateChange = getCurrentTime(); } public void initStateMap() { // Populate the hash map for the states and StateRecord StateRecord idle = getStateRecordFor("Idle"); stateMap.clear(); for (int i = 0; i < getStateList().size(); i++) { String state = (String)getStateList().get(i); if ( state.equals("Idle") ) { idle.index = i; continue; } StateRecord stateRecord = new StateRecord(state, i); stateMap.put(state.toLowerCase() , stateRecord); } stateMap.put("idle", idle); timeOfLastStateChange = getCurrentTime(); } private StateRecord getStateRecordFor(String state) { return stateMap.get(state.toLowerCase()); } private StateRecord getStateRecordFor(int index) { String state = (String)getStateList().get(index); return getStateRecordFor(state); } public double getCompletedCycleHoursFor(String state) { return getStateRecordFor(state).getCompletedCycleHours(); } public double getCompletedCycleHoursFor(int index) { return getStateRecordFor(index).getCompletedCycleHours(); } public double getCompletedCycleHours() { double total = 0.0d; for (int i = 0; i < getStateList().size(); i ++) total += getStateRecordFor(i).getCompletedCycleHours(); return total; } public double getTotalHoursFor(int index) { return getTotalHoursFor( (String) getStateList().get(index) ); } public double getTotalHoursFor(String state) { StateRecord rec = getStateRecordFor(state); return getTotalHoursFor(rec); } public double getTotalHoursFor(StateRecord state) { double hours = state.getTotalHours(); if (presentState == state) hours += getCurrentTime() - timeOfLastStateChange; return hours; } public double getTotalHours() { double total = getCurrentTime() - timeOfLastStateChange; for (int i = 0; i < getNumberOfStates(); i++) total += getStateRecordFor(i).getTotalHours(); return total; } // INPUT public void validateMaintenance() { Input.validateIndexedLists(firstMaintenanceTimes.getValue(), maintenanceIntervals.getValue(), "FirstMaintenanceTimes", "MaintenanceIntervals"); Input.validateIndexedLists(firstMaintenanceTimes.getValue(), maintenanceDurations.getValue(), "FirstMaintenanceTimes", "MaintenanceDurations"); for( int i = 0; i < maintenanceIntervals.getValue().size(); i++ ) { if( maintenanceIntervals.getValue().get( i ) < maintenanceDurations.getValue().get( i ) ) { throw new InputErrorException("MaintenanceInterval should be greater than MaintenanceDuration (%f) <= (%f)", maintenanceIntervals.getValue().get(i), maintenanceDurations.getValue().get(i)); } } } // INITIALIZATION METHODS public void clearStatistics() { for( int i = 0; i < getMaintenanceOperatingHoursIntervals().size(); i++ ) { hoursForNextMaintenanceOperatingHours.set( i, hoursForNextMaintenanceOperatingHours.get( i ) - this.getWorkingHours() ); } // Determine the time for the first breakdown event /*if ( downtimeIATDistribution == null ) { if( breakdownSeed != 0 ) { breakdownRandGen.initialiseWith( breakdownSeed ); hoursForNextFailure = breakdownRandGen.getUniformFrom_To( 0.5*iATFailure, 1.5*iATFailure ); } else { hoursForNextFailure = getNextBreakdownIAT(); } } else { hoursForNextFailure = getNextBreakdownIAT(); }*/ } /** * *!*!*!*! OVERLOAD !*!*!*!* * Initialize statistics */ public void initialize() { brokendown = false; maintenance = false; associatedBreakdown = false; associatedMaintenance = false; // Create state trace file if required if (testFlag(FLAG_TRACESTATE)) { String fileName = InputAgent.getReportDirectory() + InputAgent.getRunName() + "-" + this.getName() + ".trc"; stateReportFile = new FileEntity( fileName, FileEntity.FILE_WRITE, false ); } workingHours = 0.0; // Calculate the average downtime duration if distributions are used double average = 0.0; if(getDowntimeDurationDistribution() != null) average = getDowntimeDurationDistribution().getExpectedValue(); // Calculate the average downtime inter-arrival time if( (getAvailability() == 1.0 || average == 0.0) ) { iATFailure = 10.0E10; } else { if( getDowntimeIATDistribution() != null ) { iATFailure = getDowntimeIATDistribution().getExpectedValue(); // Adjust the downtime inter-arrival time to get the specified availability if( ! Tester.equalCheckTolerance( iATFailure, ( (average / (1.0 - getAvailability())) - average ) ) ) { getDowntimeIATDistribution().setValueFactor_For( ( (average / (1.0 - getAvailability())) - average) / iATFailure, this ); iATFailure = getDowntimeIATDistribution().getExpectedValue(); } } else { iATFailure = ( (average / (1.0 - getAvailability())) - average ); } } // Determine the time for the first breakdown event hoursForNextFailure = getNextBreakdownIAT(); int ind = this.indexOfState( "Idle" ); if( ind != -1 ) { this.setPresentState( "Idle" ); } brokendown = false; // Start the maintenance network if( firstMaintenanceTimes.getValue().size() != 0 ) { maintenancePendings.fillWithEntriesOf( firstMaintenanceTimes.getValue().size(), 0 ); lastScheduledMaintenanceTimes.fillWithEntriesOf( firstMaintenanceTimes.getValue().size(), Double.POSITIVE_INFINITY ); this.doMaintenanceNetwork(); } // calculate hours for first operating hours breakdown for ( int i = 0; i < getMaintenanceOperatingHoursIntervals().size(); i++ ) { hoursForNextMaintenanceOperatingHours.add( firstMaintenanceOperatingHours.getValue().get( i ) ); maintenanceOperatingHoursPendings.add( 0 ); } } // ACCESSOR METHODS /** * Return the time at which the most recent maintenance is scheduled to end */ public double getMaintenanceEndTime() { return maintenanceEndTime; } /** * Return the time at which a the most recent breakdown is scheduled to end */ public double getBreakdownEndTime() { return breakdownEndTime; } public double getTimeOfLastStateChange() { return timeOfLastStateChange; } /** * Returns the availability proportion. */ public double getAvailability() { return availability.getValue(); } public DoubleListInput getFirstMaintenanceTimes() { return firstMaintenanceTimes; } public boolean getPrintToReport() { return printToReport.getValue(); } public boolean isBrokendown() { return brokendown; } public boolean isBreakdownPending() { return breakdownPending; } public boolean isInAssociatedBreakdown() { return associatedBreakdown; } public boolean isInMaintenance() { return maintenance; } public boolean isInAssociatedMaintenance() { return associatedMaintenance; } public boolean isInService() { return ( brokendown || maintenance || associatedBreakdown || associatedMaintenance ); } public void setBrokendown( boolean bool ) { brokendown = bool; this.setPresentState(); } public void setMaintenance( boolean bool ) { maintenance = bool; this.setPresentState(); } public void setAssociatedBreakdown( boolean bool ) { associatedBreakdown = bool; } public void setAssociatedMaintenance( boolean bool ) { associatedMaintenance = bool; } public ProbabilityDistribution getDowntimeDurationDistribution() { return downtimeDurationDistribution.getValue(); } public double getDowntimeToReleaseEquipment() { return downtimeToReleaseEquipment.getValue(); } public boolean hasServiceDefined() { return( maintenanceDurations.getValue().size() > 0 || getDowntimeDurationDistribution() != null ); } // HOURS AND STATES /** * Return true if the entity is working */ public boolean isWorking() { return false; } /** * Returns the present status. */ public String getPresentState() { return presentState.getStateName(); } public boolean presentStateEquals(String state) { return getPresentState().equals(state); } public boolean presentStateMatches(String state) { return getPresentState().equalsIgnoreCase(state); } public boolean presentStateStartsWith(String prefix) { return getPresentState().startsWith(prefix); } public boolean presentStateEndsWith(String suffix) { return getPresentState().endsWith(suffix); } protected int getPresentStateIndex() { return presentState.getIndex(); } public void setPresentState() {} /** * Updates the statistics, then sets the present status to be the specified value. */ public void setPresentState( String state ) { if (traceFlag) { this.trace("setState( " + state + " )"); this.traceLine(" Old State = " + getPresentState()); } if (presentStateEquals(state)) return; if (testFlag(FLAG_TRACESTATE)) this.printStateTrace(state); double curTime = getCurrentTime(); double duration = curTime - timeOfLastStateChange; StateRecord nextState = this.getStateRecordFor(state); if (nextState == null) throw new ErrorException(this + " Specified state: " + state + " was not found in the StateList: " + this.getStateList()); if (duration > 0.0d) { presentState.totalHours += duration; presentState.currentCycleHours += duration; if (this.isWorking()) workingHours += duration; } timeOfLastStateChange = curTime; presentState = nextState; presentState.secondLastStartTimeInState = presentState.getLastStartTimeInState(); presentState.lastStartTimeInState = curTime; } /** * Print that state information on the trace state log file */ public void printStateTrace( String state ) { // First state ever if( finalLastState.equals("") ) { finalLastState = state; stateReportFile.putString(String.format("%.5f %s.setState( \"%s\" ) dt = %s\n", 0.0d, this.getName(), getPresentState(), formatNumber(getCurrentTime()))); stateReportFile.flush(); timeOfLastPrintedState = getCurrentTime(); } else { // The final state in a sequence from the previous state change (one step behind) if ( ! Tester.equalCheckTimeStep( timeOfLastPrintedState, getCurrentTime() ) ) { stateReportFile.putString(String.format("%.5f %s.setState( \"%s\" ) dt = %s\n", timeOfLastPrintedState, this.getName(), finalLastState, formatNumber(getCurrentTime() - timeOfLastPrintedState))); // for( int i = 0; i < stateTraceRelatedModelEntities.size(); i++ ) { // ModelEntitiy each = (ModelEntitiy) stateTraceRelatedModelEntities.get( i ); // putString( ) stateReportFile.flush(); timeOfLastPrintedState = getCurrentTime(); } finalLastState = state; } } /** * Returns the amount of time spent in the specified status. */ public double getCurrentCycleHoursFor( String state ) { StateRecord rec = getStateRecordFor(state); return getCurrentCycleHoursFor(rec); } /** * Return spent hours for a given state at the index in stateList */ public double getCurrentCycleHoursFor(int index) { StateRecord rec = getStateRecordFor(index); return getCurrentCycleHoursFor(rec); } public double getCurrentCycleHoursFor(StateRecord state) { double hours = state.getCurrentCycleHours(); if (presentState == state) hours += getCurrentTime() - timeOfLastStateChange; return hours; } /** * Set the last time a histogram was updated for this entity */ public void setLastHistogramUpdateTime( double time ) { secondToLastHistogramUpdateTime = lastHistogramUpdateTime; lastHistogramUpdateTime = time; } /** * Returns the time from the start of the start state to the start of the end state */ public double getTimeFromStartState_ToEndState( String startState, String endState) { // Determine the index of the start state StateRecord startStateRec = this.getStateRecordFor(startState); if (startStateRec == null) { throw new ErrorException("Specified state: %s was not found in the StateList.", startState); } // Determine the index of the end state StateRecord endStateRec = this.getStateRecordFor(endState); if (endStateRec == null) { throw new ErrorException("Specified state: %s was not found in the StateList.", endState); } // Is the start time of the end state greater or equal to the start time of the start state? if (endStateRec.getLastStartTimeInState() >= startStateRec.getLastStartTimeInState()) { // If either time was not in the present cycle, return NaN if (endStateRec.getLastStartTimeInState() <= lastHistogramUpdateTime || startStateRec.getLastStartTimeInState() <= lastHistogramUpdateTime ) { return Double.NaN; } // Return the time from the last start time of the start state to the last start time of the end state return endStateRec.getLastStartTimeInState() - startStateRec.getLastStartTimeInState(); } else { // If either time was not in the present cycle, return NaN if (endStateRec.getLastStartTimeInState() <= lastHistogramUpdateTime || startStateRec.getSecondLastStartTimeInState() <= secondToLastHistogramUpdateTime ) { return Double.NaN; } // Return the time from the second to last start time of the start date to the last start time of the end state return endStateRec.getLastStartTimeInState() - startStateRec.getSecondLastStartTimeInState(); } } /** * Return the commitment */ public double getCommitment() { return 1.0 - this.getFractionOfTimeForState( "Idle" ); } /** * Return the fraction of time for the given status */ public double getFractionOfTimeForState( String aState ) { if( getTotalHours() > 0.0 ) { return ((this.getTotalHoursFor( aState ) / getTotalHours()) ); } else { return 0.0; } } /** * Return the percentage of time for the given status */ public double getPercentageOfTimeForState( String aState ) { if( getTotalHours() > 0.0 ) { return ((this.getTotalHoursFor( aState ) / getTotalHours()) * 100.0); } else { return 0.0; } } /** * Returns the number of hours the entity is in use. * *!*!*!*! OVERLOAD !*!*!*!* */ public double getWorkingHours() { double hours = 0.0d; if ( this.isWorking() ) hours = getCurrentTime() - timeOfLastStateChange; return workingHours + hours; } public Vector getStateList() { return stateList; } public int indexOfState( String state ) { StateRecord stateRecord = stateMap.get( state.toLowerCase() ); if (stateRecord != null) return stateRecord.getIndex(); return -1; } /** * Return total number of states */ public int getNumberOfStates() { return stateMap.size(); } /** * Return the total hours in current cycle for all the states */ public double getCurrentCycleHours() { double total = getCurrentTime() - timeOfLastStateChange; for (int i = 0; i < getNumberOfStates(); i++) { total += getStateRecordFor(i).getCurrentCycleHours(); } return total; } // MAINTENANCE METHODS /** * Perform tasks required before a maintenance period */ public void doPreMaintenance() { //@debug@ cr 'Entity should be overloaded' print } /** * Start working again following a breakdown or maintenance period */ public void restart() { //@debug@ cr 'Entity should be overloaded' print } /** * Disconnect routes, release truck assignments, etc. when performing maintenance or breakdown */ public void releaseEquipment() {} public boolean releaseEquipmentForMaintenanceSchedule( int index ) { if( releaseEquipment.getValue() == null ) return true; return releaseEquipment.getValue().get( index ); } public boolean forceMaintenanceSchedule( int index ) { if( forceMaintenance.getValue() == null ) return false; return forceMaintenance.getValue().get( index ); } /** * Perform all maintenance schedules that are due */ public void doMaintenance() { // scheduled maintenance for( int index = 0; index < maintenancePendings.size(); index++ ) { if( this.getMaintenancePendings().get( index ) > 0 ) { if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index ); this.doMaintenance(index); } } // Operating hours maintenance for( int index = 0; index < maintenanceOperatingHoursPendings.size(); index++ ) { if( this.getWorkingHours() > hoursForNextMaintenanceOperatingHours.get( index ) ) { hoursForNextMaintenanceOperatingHours.set(index, this.getWorkingHours() + getMaintenanceOperatingHoursIntervals().get( index )); maintenanceOperatingHoursPendings.addAt( 1, index ); this.doMaintenanceOperatingHours(index); } } } /** * Perform all the planned maintenance that is due for the given schedule */ public void doMaintenance( int index ) { double wait; if( masterMaintenanceEntity != null ) { wait = masterMaintenanceEntity.getMaintenanceDurations().getValue().get( index ); } else { wait = this.getMaintenanceDurations().getValue().get( index ); } if( wait > 0.0 && maintenancePendings.get( index ) != 0 ) { if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- start of maintenance" ); // Keep track of the start and end of maintenance times maintenanceStartTime = getCurrentTime(); if( masterMaintenanceEntity != null ) { maintenanceEndTime = maintenanceStartTime + ( maintenancePendings.get( index ) * masterMaintenanceEntity.getMaintenanceDurations().getValue().get( index ) ); } else { maintenanceEndTime = maintenanceStartTime + ( maintenancePendings.get( index ) * maintenanceDurations.getValue().get( index ) ); } this.setPresentState( "Maintenance" ); maintenance = true; this.doPreMaintenance(); // Release equipment if necessary if( this.releaseEquipmentForMaintenanceSchedule( index ) ) { this.releaseEquipment(); } while( maintenancePendings.get( index ) != 0 ) { maintenancePendings.subAt( 1, index ); scheduleWait( wait ); // If maintenance pending goes negative, something is wrong if( maintenancePendings.get( index ) < 0 ) { this.error( "ModelEntity.doMaintenance_Wait()", "Maintenace pending should not be negative", "maintenacePending = "+maintenancePendings.get( index ) ); } } if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- end of maintenance" ); // The maintenance is over this.setPresentState( "Idle" ); maintenance = false; this.restart(); } } /** * Perform all the planned maintenance that is due */ public void doMaintenanceOperatingHours( int index ) { if(maintenanceOperatingHoursPendings.get( index ) == 0 ) return; if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- start of maintenance" ); // Keep track of the start and end of maintenance times maintenanceStartTime = getCurrentTime(); maintenanceEndTime = maintenanceStartTime + (maintenanceOperatingHoursPendings.get( index ) * getMaintenanceOperatingHoursDurationFor(index)); this.setPresentState( "Maintenance" ); maintenance = true; this.doPreMaintenance(); while( maintenanceOperatingHoursPendings.get( index ) != 0 ) { //scheduleWait( maintenanceDurations.get( index ) ); scheduleWait( maintenanceEndTime - maintenanceStartTime ); maintenanceOperatingHoursPendings.subAt( 1, index ); // If maintenance pending goes negative, something is wrong if( maintenanceOperatingHoursPendings.get( index ) < 0 ) { this.error( "ModelEntity.doMaintenance_Wait()", "Maintenace pending should not be negative", "maintenacePending = "+maintenanceOperatingHoursPendings.get( index ) ); } } if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- end of maintenance" ); // The maintenance is over maintenance = false; this.setPresentState( "Idle" ); this.restart(); } /** * Check if a maintenance is due. if so, try to perform the maintenance */ public boolean checkMaintenance() { if( traceFlag ) this.trace( "checkMaintenance()" ); if( checkOperatingHoursMaintenance() ) { return true; } // List of all entities going to maintenance ArrayList<ModelEntity> sharedMaintenanceEntities; // This is not a master maintenance entity if( masterMaintenanceEntity != null ) { sharedMaintenanceEntities = masterMaintenanceEntity.getSharedMaintenanceList(); } // This is a master maintenance entity else { sharedMaintenanceEntities = getSharedMaintenanceList(); } // If this entity is in shared maintenance relation with a group of entities if( sharedMaintenanceEntities.size() > 0 || masterMaintenanceEntity != null ) { // Are all entities in the group ready for maintenance if( this.areAllEntitiesAvailable() ) { // For every entity in the shared maintenance list plus the master maintenance entity for( int i=0; i <= sharedMaintenanceEntities.size(); i++ ) { ModelEntity aModel; // Locate master maintenance entity( after all entity in shared maintenance list have been taken care of ) if( i == sharedMaintenanceEntities.size() ) { // This entity is manster maintenance entity if( masterMaintenanceEntity == null ) { aModel = this; } // This entity is on the shared maintenannce list of the master maintenance entity else { aModel = masterMaintenanceEntity; } } // Next entity in the shared maintenance list else { aModel = sharedMaintenanceEntities.get( i ); } // Check for aModel maintenances for( int index = 0; index < maintenancePendings.size(); index++ ) { if( aModel.getMaintenancePendings().get( index ) > 0 ) { if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index ); aModel.startProcess("doMaintenance", index); } } } return true; } else { return false; } } // This block is maintained indipendently else { // Check for maintenances for( int i = 0; i < maintenancePendings.size(); i++ ) { if( maintenancePendings.get( i ) > 0 ) { if( this.canStartMaintenance( i ) ) { if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + i ); this.startProcess("doMaintenance", i); return true; } } } } return false; } /** * Determine how many hours of maintenance is scheduled between startTime and endTime */ public double getScheduledMaintenanceHoursForPeriod( double startTime, double endTime ) { if( traceFlag ) this.trace("Handler.getScheduledMaintenanceHoursForPeriod( "+startTime+", "+endTime+" )" ); double totalHours = 0.0; double firstTime = 0.0; // Add on hours for all pending maintenance for( int i=0; i < maintenancePendings.size(); i++ ) { totalHours += maintenancePendings.get( i ) * maintenanceDurations.getValue().get( i ); } if( traceFlag ) this.traceLine( "Hours of pending maintenances="+totalHours ); // Add on hours for all maintenance scheduled to occur in the given period from startTime to endTime for( int i=0; i < maintenancePendings.size(); i++ ) { // Find the first time that maintenance is scheduled after startTime firstTime = firstMaintenanceTimes.getValue().get( i ); while( firstTime < startTime ) { firstTime += maintenanceIntervals.getValue().get( i ); } if( traceFlag ) this.traceLine(" first time maintenance "+i+" is scheduled after startTime= "+firstTime ); // Now have the first maintenance start time after startTime // Add all maintenances that lie in the given interval while( firstTime < endTime ) { if( traceFlag ) this.traceLine(" Checking for maintenances for period:"+firstTime+" to "+endTime ); // Add the maintenance totalHours += maintenanceDurations.getValue().get( i ); // Update the search period endTime += maintenanceDurations.getValue().get( i ); // Look for next maintenance in new interval firstTime += maintenanceIntervals.getValue().get( i ); if( traceFlag ) this.traceLine(" Adding Maintenance duration = "+maintenanceDurations.getValue().get( i ) ); } } // Return the total hours of maintenance scheduled from startTime to endTime if( traceFlag ) this.traceLine( "Maintenance hours to add= "+totalHours ); return totalHours; } public boolean checkOperatingHoursMaintenance() { if( traceFlag ) this.trace("checkOperatingHoursMaintenance()"); // Check for maintenances for( int i = 0; i < getMaintenanceOperatingHoursIntervals().size(); i++ ) { // If the entity is not available, maintenance cannot start if( ! this.canStartMaintenance( i ) ) continue; if( this.getWorkingHours() > hoursForNextMaintenanceOperatingHours.get( i ) ) { hoursForNextMaintenanceOperatingHours.set(i, (this.getWorkingHours() + getMaintenanceOperatingHoursIntervals().get( i ))); maintenanceOperatingHoursPendings.addAt( 1, i ); if( traceFlag ) this.trace( "Starting Maintenance Operating Hours Schedule : " + i ); this.startProcess("doMaintenanceOperatingHours", i); return true; } } return false; } /** * Wrapper method for doMaintenance_Wait. */ public void doMaintenanceNetwork() { this.startProcess("doMaintenanceNetwork_Wait"); } /** * Network for planned maintenance. * This method should be called in the initialize method of the specific entity. */ public void doMaintenanceNetwork_Wait() { // Initialize schedules for( int i=0; i < maintenancePendings.size(); i++ ) { maintenancePendings.set( i, 0 ); } nextMaintenanceTimes = new DoubleVector(firstMaintenanceTimes.getValue()); nextMaintenanceDuration = 0; // Find the next maintenance event int index = 0; double earliestTime = Double.POSITIVE_INFINITY; for( int i=0; i < nextMaintenanceTimes.size(); i++ ) { double time = nextMaintenanceTimes.get( i ); if( Tester.lessCheckTolerance( time, earliestTime ) ) { earliestTime = time; index = i; nextMaintenanceDuration = maintenanceDurations.getValue().get( i ); } } // Make sure that maintenance for entities on the shared list are being called after those entities have been initialize (AT TIME ZERO) scheduleLastLIFO(); while( true ) { double dt = earliestTime - getCurrentTime(); // Wait for the maintenance check time if( dt > Process.getEventTolerance() ) { scheduleWait( dt ); } // Increment the number of maintenances due for the entity maintenancePendings.addAt( 1, index ); // If this is a master maintenance entity if (getSharedMaintenanceList().size() > 0) { // If all the entities on the shared list are ready for maintenance if( this.areAllEntitiesAvailable() ) { // Put this entity to maintenance if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index ); this.startProcess("doMaintenance", index); } } // If this entity is maintained independently else { // Do maintenance if possible if( ! this.isInService() && this.canStartMaintenance( index ) ) { // if( traceFlag ) this.trace( "doMaintenanceNetwork_Wait: Starting Maintenance. PresentState = "+presentState+" IsAvailable? = "+this.isAvailable() ); if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index ); this.startProcess("doMaintenance", index); } // Keep track of the time the maintenance was attempted else { lastScheduledMaintenanceTimes.set( index, getCurrentTime() ); // If skipMaintenance was defined, cancel the maintenance if( this.shouldSkipMaintenance( index ) ) { // if a different maintenance is due, cancel this maintenance boolean cancelMaintenance = false; for( int i=0; i < maintenancePendings.size(); i++ ) { if( i != index ) { if( maintenancePendings.get( i ) > 0 ) { cancelMaintenance = true; break; } } } if( cancelMaintenance || this.isInMaintenance() ) { maintenancePendings.subAt( 1, index ); } } // Do a check after the limit has expired if( this.getDeferMaintenanceLimit( index ) > 0.0 ) { this.startProcess( "scheduleCheckMaintenance", this.getDeferMaintenanceLimit( index ) ); } } } // Determine the next maintenance time nextMaintenanceTimes.addAt( maintenanceIntervals.getValue().get( index ), index ); // Find the next maintenance event index = 0; earliestTime = Double.POSITIVE_INFINITY; for( int i=0; i < nextMaintenanceTimes.size(); i++ ) { double time = nextMaintenanceTimes.get( i ); if( Tester.lessCheckTolerance( time, earliestTime ) ) { earliestTime = time; index = i; nextMaintenanceDuration = maintenanceDurations.getValue().get( i ); } } } } public double getDeferMaintenanceLimit( int index ) { if( deferMaintenanceLimit.getValue() == null ) return 0.0d; return deferMaintenanceLimit.getValue().get( index ); } public void scheduleCheckMaintenance( double wait ) { scheduleWait( wait ); this.checkMaintenance(); } public boolean shouldSkipMaintenance( int index ) { if( skipMaintenanceIfOverlap.getValue().size() == 0 ) return false; return skipMaintenanceIfOverlap.getValue().get( index ); } /** * Return TRUE if there is a pending maintenance for any schedule */ public boolean isMaintenancePending() { for( int i = 0; i < maintenancePendings.size(); i++ ) { if( maintenancePendings.get( i ) > 0 ) { return true; } } for( int i = 0; i < hoursForNextMaintenanceOperatingHours.size(); i++ ) { if( this.getWorkingHours() > hoursForNextMaintenanceOperatingHours.get( i ) ) { return true; } } return false; } public boolean isForcedMaintenancePending() { if( forceMaintenance.getValue() == null ) return false; for( int i = 0; i < maintenancePendings.size(); i++ ) { if( maintenancePendings.get( i ) > 0 && forceMaintenance.getValue().get(i) ) { return true; } } return false; } public ArrayList<ModelEntity> getSharedMaintenanceList () { return sharedMaintenanceList.getValue(); } public IntegerVector getMaintenancePendings () { return maintenancePendings; } public DoubleListInput getMaintenanceDurations() { return maintenanceDurations; } /** * Return the start of the next scheduled maintenance time if not in maintenance, * or the start of the current scheduled maintenance time if in maintenance */ public double getNextMaintenanceStartTime() { if( nextMaintenanceTimes == null ) return Double.POSITIVE_INFINITY; else return nextMaintenanceTimes.getMin(); } /** * Return the duration of the next maintenance event (assuming only one pending) */ public double getNextMaintenanceDuration() { return nextMaintenanceDuration; } // Shows if an Entity would ever go on service public boolean hasServiceScheduled() { if( firstMaintenanceTimes.getValue().size() != 0 || masterMaintenanceEntity != null ) { return true; } return false; } public void setMasterMaintenanceBlock( ModelEntity aModel ) { masterMaintenanceEntity = aModel; } // BREAKDOWN METHODS /** * No Comments Given. */ public void calculateTimeOfNextFailure() { hoursForNextFailure = (this.getWorkingHours() + this.getNextBreakdownIAT()); } /** * Activity Network for Breakdowns. */ public void doBreakdown() { } /** * Prints the header for the entity's state list. * @return bottomLine contains format for each column of the bottom line of the group report */ public IntegerVector printUtilizationHeaderOn( FileEntity anOut ) { IntegerVector bottomLine = new IntegerVector(); if( getStateList().size() != 0 ) { anOut.putStringTabs( "Name", 1 ); bottomLine.add( ReportAgent.BLANK ); int doLoop = getStateList().size(); for( int x = 0; x < doLoop; x++ ) { String state = (String)getStateList().get( x ); anOut.putStringTabs( state, 1 ); bottomLine.add( ReportAgent.AVERAGE_PCT_ONE_DEC ); } anOut.newLine(); } return bottomLine; } /** * Print the entity's name and percentage of hours spent in each state. * @return columnValues are the values for each column in the group report (0 if the value is a String) */ public DoubleVector printUtilizationOn( FileEntity anOut ) { double total; DoubleVector columnValues = new DoubleVector(); if( getNumberOfStates() != 0 ) { total = getTotalHours(); if( !(total == 0.0) ) { anOut.putStringTabs( getName(), 1 ); columnValues.add( 0.0 ); for( int i = 0; i < getNumberOfStates(); i++ ) { double value = getTotalHoursFor( i ) / total; anOut.putDoublePercentWithDecimals( value, 1 ); anOut.putTabs( 1 ); columnValues.add( value ); } anOut.newLine(); } } return columnValues; } /** * This method must be overridden in any subclass of ModelEntity. */ public boolean isAvailable() { throw new ErrorException( "Must override isAvailable in any subclass of ModelEntity." ); } /** * This method must be overridden in any subclass of ModelEntity. */ public boolean canStartMaintenance( int index ) { return isAvailable(); } /** * This method must be overridden in any subclass of ModelEntity. */ public boolean canStartForcedMaintenance() { return isAvailable(); } /** * This method must be overridden in any subclass of ModelEntity. */ public boolean areAllEntitiesAvailable() { throw new ErrorException( "Must override areAllEntitiesAvailable in any subclass of ModelEntity." ); } /** * Return the time of the next breakdown duration */ public double getBreakdownDuration() { // if( traceFlag ) this.trace( "getBreakdownDuration()" ); // If a distribution was specified, then select a duration randomly from the distribution if ( getDowntimeDurationDistribution() != null ) { return getDowntimeDurationDistribution().nextValue(); } else { return 0.0; } } /** * Return the time of the next breakdown IAT */ public double getNextBreakdownIAT() { if( getDowntimeIATDistribution() != null ) { return getDowntimeIATDistribution().nextValue(); } else { return iATFailure; } } public double getHoursForNextFailure() { return hoursForNextFailure; } public void setHoursForNextFailure( double hours ) { hoursForNextFailure = hours; } /** Returns a vector of strings describing the ModelEntity. Override to add details @return Vector - tab delimited strings describing the DisplayEntity **/ @Override public Vector getInfo() { Vector info = super.getInfo(); if ( presentStateEquals("") ) info.addElement( "Present State\t<no state>" ); else info.addElement( "Present State" + "\t" + getPresentState() ); return info; } protected DoubleVector getMaintenanceOperatingHoursIntervals() { return maintenanceOperatingHoursIntervals.getValue(); } protected double getMaintenanceOperatingHoursDurationFor(int index) { return maintenanceOperatingHoursDurations.getValue().get(index); } protected ProbabilityDistribution getDowntimeIATDistribution() { return downtimeIATDistribution.getValue(); } }
package com.springapp.mvc.model; import org.apache.commons.lang.StringUtils; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.core.StopFilter; import org.apache.lucene.analysis.en.PorterStemFilter; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.analysis.standard.StandardTokenizer; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.analysis.tokenattributes.OffsetAttribute; import org.apache.lucene.analysis.util.CharArraySet; import org.apache.lucene.document.Document; import org.apache.lucene.index.*; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopScoreDocCollector; import org.apache.lucene.store.Directory; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.Version; import org.apache.poi.openxml4j.exceptions.OpenXML4JException; import org.apache.xmlbeans.XmlException; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; public class LuceneIndexReader { private final Directory indexDir; private IndexReader indexReader; private Fields fields; private final StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_42); public LuceneIndexReader(Directory indexDir) throws IOException { this.indexDir = indexDir; //noinspection deprecation this.indexReader = IndexReader.open(this.indexDir); this.fields = MultiFields.getFields(this.indexReader); } public long getTotalDocs() { return this.indexReader.numDocs(); } long getTermFreq(Term term) throws IOException { return this.indexReader.totalTermFreq(term); } public Map<String,String> searchIndex(String searchString, int totalResult) throws IOException, XmlException, OpenXML4JException, ParserConfigurationException, SAXException { Query q = null; IndexReader reader = null; Map<String, String> result = null; try { q = new QueryParser(Version.LUCENE_42, "word", analyzer).parse(tokenizeStopStem(searchString)); //noinspection deprecation reader = IndexReader.open(this.indexDir); IndexSearcher searcher = new IndexSearcher(reader); TopScoreDocCollector collector = TopScoreDocCollector.create(totalResult, true); searcher.search(q, collector); ScoreDoc[] hits = collector.topDocs().scoreDocs; result = new HashMap<String, String>(); for (int i = 0; i < hits.length; i++) { Document doc = searcher.doc(hits[i].doc); int indexOfLastSlash = doc.get("fullpath").lastIndexOf('/'); String fileName = doc.get("fullpath").substring(indexOfLastSlash + 1); result.put(fileName, getPreview(doc.get("fullpath"), searchString.replaceAll("[^a-zA-Z0-9\\s]", ""))); } } catch (org.apache.lucene.queryparser.classic.ParseException e) { e.printStackTrace(); } finally { reader.close(); } return new TreeMap<String, String>(result).descendingMap(); } //This will return indexed word and its doc frequency public HashMap<String, Object> getAllWords() throws IOException { HashMap<String, Object> indexedWord = new HashMap<String, Object>(); Fields fields = MultiFields.getFields(this.indexReader); Terms terms = fields.terms("word"); TermsEnum iterator = terms.iterator(null); BytesRef byteRef; Term term; while ((byteRef = iterator.next()) != null) { String word = new String(byteRef.bytes, byteRef.offset, byteRef.length); term = new Term("word", word); indexedWord.put(word, getTermFreq(term)); } return indexedWord; } private String getPreview (String filePath, String keyword) throws OpenXML4JException, XmlException, IOException, SAXException, ParserConfigurationException { DocParser docParser = new DocParser(); String content = docParser.parseDocument(filePath); int indexOfKeyword = getKeywordIndex(content, keyword); if(indexOfKeyword > -1){ int startOfPreview = indexOfKeyword - 100 > 0 ? indexOfKeyword - 100 : indexOfKeyword; int endOfPreview = content.length() < indexOfKeyword + 300 ? content.length() : indexOfKeyword + 300; return content.substring(startOfPreview, endOfPreview); } return "Sorry for system cannot show preview for non-standard query"; } private int getKeywordIndex(String content, String keyword) { //Dirty way to trick the case sensitive of indexOf method int indexOfKeyword = content.indexOf(keyword); if(indexOfKeyword < 0){ indexOfKeyword = content.indexOf(StringUtils.capitalize(keyword)); if(indexOfKeyword < 0){ indexOfKeyword = content.indexOf(keyword.toLowerCase()); if(indexOfKeyword < 0){ indexOfKeyword = content.indexOf(keyword.toUpperCase()); if (indexOfKeyword < 0) { indexOfKeyword = -1; } } } } return indexOfKeyword; } public String tokenizeStopStem(String input) { if(input.indexOf("=") < 0){ return input; } input = input.replaceAll("=", ""); TokenStream tokenStream = new StandardTokenizer(Version.LUCENE_42, new StringReader(input)); CharArraySet stop_word_set = new CharArraySet(Version.LUCENE_42, 1, true); tokenStream = new StopFilter(Version.LUCENE_42, tokenStream, stop_word_set); tokenStream = new PorterStemFilter(tokenStream); StringBuilder sb = new StringBuilder(); OffsetAttribute offsetAttribute = tokenStream.addAttribute(OffsetAttribute.class); CharTermAttribute charTermAttr = tokenStream.getAttribute(CharTermAttribute.class); try{ tokenStream.reset(); while (tokenStream.incrementToken()) { if (sb.length() > 0) { sb.append(" "); } sb.append(charTermAttr.toString()); } } catch (IOException e){ System.out.println(e.getMessage()); } return sb.toString(); } public IndexReader getIndexReader() { return indexReader; } }
package com.upplication.s3fs; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.s3.model.*; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.upplication.s3fs.util.FileTypeDetector; import com.upplication.s3fs.util.IOUtils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.nio.ByteBuffer; import java.nio.channels.SeekableByteChannel; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.FileAttributeView; import java.nio.file.attribute.FileTime; import java.nio.file.spi.FileSystemProvider; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import static com.google.common.collect.Sets.difference; import static java.lang.String.format; public class S3FileSystemProvider extends FileSystemProvider { public static final String ACCESS_KEY = "access_key"; public static final String SECRET_KEY = "secret_key"; final AtomicReference<S3FileSystem> fileSystem = new AtomicReference<>(); private final FileTypeDetector fileTypeDetector = new com.upplication.s3fs.util.FileTypeDetector(); @Override public String getScheme() { return "s3"; } @Override public FileSystem newFileSystem(URI uri, Map<String, ?> env) throws IOException { Preconditions.checkNotNull(uri, "uri is null"); Preconditions.checkArgument(uri.getScheme().equals("s3"), "uri scheme must be 's3': '%s'", uri); // first try to load amazon props Properties props = loadAmazonProperties(); Object accessKey = props.getProperty(ACCESS_KEY); Object secretKey = props.getProperty(SECRET_KEY); // but can overload by envs vars if (env.get(ACCESS_KEY) != null){ accessKey = env.get(ACCESS_KEY); } if (env.get(SECRET_KEY) != null){ secretKey = env.get(SECRET_KEY); } Preconditions.checkArgument((accessKey == null && secretKey == null) || (accessKey != null && secretKey != null), "%s and %s should both be provided or should both be omitted", ACCESS_KEY, SECRET_KEY); S3FileSystem result = createFileSystem(uri, accessKey, secretKey); // if this instance already has a S3FileSystem, throw exception // otherwise set if (!fileSystem.compareAndSet(null, result)) { throw new FileSystemAlreadyExistsException( "S3 filesystem already exists. Use getFileSystem() instead"); } return result; } @Override public FileSystem getFileSystem(URI uri) { FileSystem fileSystem = this.fileSystem.get(); if (fileSystem == null) { throw new FileSystemNotFoundException( String.format("S3 filesystem not yet created. Use newFileSystem() instead")); } return fileSystem; } /** * Deviation from spec: throws FileSystemNotFoundException if FileSystem * hasn't yet been initialized. Call newFileSystem() first. * Need credentials. Maybe set credentials after? how? */ @Override public Path getPath(URI uri) { Preconditions.checkArgument(uri.getScheme().equals(getScheme()), "URI scheme must be %s", getScheme()); if (uri.getHost() != null && !uri.getHost().isEmpty() && !uri.getHost().equals(fileSystem.get().getEndpoint())) { throw new IllegalArgumentException(format( "only empty URI host or URI host that matching the current fileSystem: %s", fileSystem.get().getEndpoint())); // TODO } /** * TODO: set as a list. one s3FileSystem by region */ return getFileSystem(uri).getPath(uri.getPath()); } @Override public DirectoryStream<Path> newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter) throws IOException { Preconditions.checkArgument(dir instanceof S3Path, "path must be an instance of %s", S3Path.class.getName()); final S3Path s3Path = (S3Path) dir; return new DirectoryStream<Path>() { @Override public void close() throws IOException { // nothing to do here } @Override public Iterator<Path> iterator() { return new S3Iterator(s3Path.getFileSystem(), s3Path.getBucket(), s3Path.getKey() + "/"); } }; } @Override public InputStream newInputStream(Path path, OpenOption... options) throws IOException { Preconditions.checkArgument(options.length == 0, "OpenOptions not yet supported: %s", ImmutableList.copyOf(options)); // TODO Preconditions.checkArgument(path instanceof S3Path, "path must be an instance of %s", S3Path.class.getName()); S3Path s3Path = (S3Path) path; Preconditions.checkArgument(!s3Path.getKey().equals(""), "cannot create InputStream for root directory: %s", s3Path); InputStream res = s3Path.getFileSystem().getClient() .getObject(s3Path.getBucket(), s3Path.getKey()) .getObjectContent(); if (res == null){ throw new IOException("path is a directory"); } else{ return res; } } @Override public OutputStream newOutputStream(Path path, OpenOption... options) throws IOException { Preconditions.checkArgument(path instanceof S3Path, "path must be an instance of %s", S3Path.class.getName()); return super.newOutputStream(path, options); } @Override public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException { Preconditions.checkArgument(path instanceof S3Path, "path must be an instance of %s", S3Path.class.getName()); final S3Path s3Path = (S3Path) path; // we resolve to a file inside the temp folder with the s3path name final Path tempFile = createTempDir().resolve(path.getFileName().toString()); if (Files.exists(path)){ InputStream is = s3Path.getFileSystem() .getClient() .getObject(s3Path.getBucket(), s3Path.getKey()).getObjectContent(); Files.write(tempFile, IOUtils.toByteArray(is)); } // and we can use the File SeekableByteChannel implementation final SeekableByteChannel seekable = Files .newByteChannel(tempFile, options); return new SeekableByteChannel() { @Override public boolean isOpen() { return seekable.isOpen(); } @Override public void close() throws IOException { seekable.close(); // upload the content where the seekable ends (close) if (Files.exists(tempFile)){ ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(Files.size(tempFile)); // FIXME: #20 ServiceLoader cant load com.upplication.s3fs.util.FileTypeDetector when this library is used inside a ear :( metadata.setContentType(fileTypeDetector.probeContentType(tempFile)); try (InputStream stream = Files.newInputStream(tempFile)){ /* FIXME: if the stream is {@link InputStream#markSupported()} i can reuse the same stream and evict the close and open methods of probeContentType. By this way: metadata.setContentType(new Tika().detect(stream, tempFile.getFileName().toString())); */ s3Path.getFileSystem() .getClient() .putObject(s3Path.getBucket(), s3Path.getKey(), stream, metadata); } } else { // delete: check option delete_on_close s3Path.getFileSystem(). getClient().deleteObject(s3Path.getBucket(), s3Path.getKey()); } // and delete the temp dir Files.deleteIfExists(tempFile); Files.deleteIfExists(tempFile.getParent()); } @Override public int write(ByteBuffer src) throws IOException { return seekable.write(src); } @Override public SeekableByteChannel truncate(long size) throws IOException { return seekable.truncate(size); } @Override public long size() throws IOException { return seekable.size(); } @Override public int read(ByteBuffer dst) throws IOException { return seekable.read(dst); } @Override public SeekableByteChannel position(long newPosition) throws IOException { return seekable.position(newPosition); } @Override public long position() throws IOException { return seekable.position(); } }; } /** * Deviations from spec: Does not perform atomic check-and-create. Since a * directory is just an S3 object, all directories in the hierarchy are * created or it already existed. */ @Override public void createDirectory(Path dir, FileAttribute<?>... attrs) throws IOException { // FIXME: throw exception if the same key already exists at amazon s3 S3Path s3Path = (S3Path) dir; Preconditions.checkArgument(attrs.length == 0, "attrs not yet supported: %s", ImmutableList.copyOf(attrs)); // TODO ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(0); String keyName = s3Path.getKey() + (s3Path.getKey().endsWith("/") ? "" : "/"); s3Path.getFileSystem() .getClient() .putObject(s3Path.getBucket(), keyName, new ByteArrayInputStream(new byte[0]), metadata); } @Override public void delete(Path path) throws IOException { Preconditions.checkArgument(path instanceof S3Path, "path must be an instance of %s", S3Path.class.getName()); S3Path s3Path = (S3Path) path; if (Files.notExists(path)){ throw new NoSuchFileException("the path: " + path + " not exists"); } if (Files.isDirectory(path)){ try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)){ if (stream.iterator().hasNext()){ throw new DirectoryNotEmptyException("the path: " + path + " is a directory and is not empty"); } } } // we delete the two objects (sometimes exists the key '/' and sometimes not) s3Path.getFileSystem().getClient() .deleteObject(s3Path.getBucket(), s3Path.getKey()); s3Path.getFileSystem().getClient() .deleteObject(s3Path.getBucket(), s3Path.getKey() + "/"); } @Override public void copy(Path source, Path target, CopyOption... options) throws IOException { Preconditions.checkArgument(source instanceof S3Path, "source must be an instance of %s", S3Path.class.getName()); Preconditions.checkArgument(target instanceof S3Path, "target must be an instance of %s", S3Path.class.getName()); if (isSameFile(source, target)) { return; } S3Path s3Source = (S3Path) source; S3Path s3Target = (S3Path) target; /* * Preconditions.checkArgument(!s3Source.isDirectory(), * "copying directories is not yet supported: %s", source); // TODO * Preconditions.checkArgument(!s3Target.isDirectory(), * "copying directories is not yet supported: %s", target); // TODO */ ImmutableSet<CopyOption> actualOptions = ImmutableSet.copyOf(options); verifySupportedOptions(EnumSet.of(StandardCopyOption.REPLACE_EXISTING), actualOptions); if (!actualOptions.contains(StandardCopyOption.REPLACE_EXISTING)) { if (exists(s3Target)) { throw new FileAlreadyExistsException(format( "target already exists: %s", target)); } } s3Source.getFileSystem() .getClient() .copyObject(s3Source.getBucket(), s3Source.getKey(), s3Target.getBucket(), s3Target.getKey()); } @Override public void move(Path source, Path target, CopyOption... options) throws IOException { throw new UnsupportedOperationException(); } @Override public boolean isSameFile(Path path1, Path path2) throws IOException { return path1.isAbsolute() && path2.isAbsolute() && path1.equals(path2); } @Override public boolean isHidden(Path path) throws IOException { return false; } @Override public FileStore getFileStore(Path path) throws IOException { throw new UnsupportedOperationException(); } @Override public void checkAccess(Path path, AccessMode... modes) throws IOException { S3Path s3Path = (S3Path) path; Preconditions.checkArgument(s3Path.isAbsolute(), "path must be absolute: %s", s3Path); AmazonS3Client client = s3Path.getFileSystem().getClient(); // get ACL and check if the file exists as a side-effect AccessControlList acl = getAccessControl(s3Path); for (AccessMode accessMode : modes) { switch (accessMode) { case EXECUTE: throw new AccessDeniedException(s3Path.toString(), null, "file is not executable"); case READ: if (!hasPermissions(acl, client.getS3AccountOwner(), EnumSet.of(Permission.FullControl, Permission.Read))) { throw new AccessDeniedException(s3Path.toString(), null, "file is not readable"); } break; case WRITE: if (!hasPermissions(acl, client.getS3AccountOwner(), EnumSet.of(Permission.FullControl, Permission.Write))) { throw new AccessDeniedException(s3Path.toString(), null, format("bucket '%s' is not writable", s3Path.getBucket())); } break; } } } private boolean hasPermissions(AccessControlList acl, Owner owner, EnumSet<Permission> permissions) { boolean result = false; for (Grant grant : acl.getGrants()) { if (grant.getGrantee().getIdentifier().equals(owner.getId()) && permissions.contains(grant.getPermission())) { result = true; break; } } return result; } @Override public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) { throw new UnsupportedOperationException(); } @Override public <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options) throws IOException { Preconditions.checkArgument(path instanceof S3Path, "path must be an instance of %s", S3Path.class.getName()); S3Path s3Path = (S3Path) path; if (type == BasicFileAttributes.class) { S3ObjectSummary objectSummary = getFirstObjectSummary(s3Path); // parse the data to BasicFileAttributes. FileTime lastModifiedTime = FileTime.from(objectSummary.getLastModified().getTime(), TimeUnit.MILLISECONDS); long size = objectSummary.getSize(); boolean directory = false; boolean regularFile = false; String key = objectSummary.getKey(); // check if is a directory and exists the key of this directory at amazon s3 if (objectSummary.getKey().equals(s3Path.getKey() + "/") && objectSummary.getKey().endsWith("/")) { directory = true; } // is a directory but not exists at amazon s3 else if (!objectSummary.getKey().equals(s3Path.getKey()) && objectSummary.getKey().startsWith(s3Path.getKey())){ directory = true; // no metadata, we fake one size = 0; // delete extra part key = s3Path.getKey() + "/"; } // is a file: else { regularFile = true; } return type.cast(new S3FileAttributes(key, lastModifiedTime, size, directory, regularFile)); } else { throw new UnsupportedOperationException(format("only %s supported", BasicFileAttributes.class)); } } @Override public Map<String, Object> readAttributes(Path path, String attributes, LinkOption... options) throws IOException { throw new UnsupportedOperationException(); } @Override public void setAttribute(Path path, String attribute, Object value, LinkOption... options) throws IOException { throw new UnsupportedOperationException(); } /** * Create the fileSystem * @param uri URI * @param accessKey Object maybe null for anonymous authentication * @param secretKey Object maybe null for anonymous authentication * @return S3FileSystem never null */ protected S3FileSystem createFileSystem(URI uri, Object accessKey, Object secretKey) { AmazonS3Client client; if (accessKey == null && secretKey == null) { client = new AmazonS3Client(new com.amazonaws.services.s3.AmazonS3Client()); } else { client = new AmazonS3Client(new com.amazonaws.services.s3.AmazonS3Client(new BasicAWSCredentials( accessKey.toString(), secretKey.toString()))); } if (uri.getHost() != null) { client.setEndpoint(uri.getHost()); } S3FileSystem result = new S3FileSystem(this, client, uri.getHost()); return result; } /** * find /amazon.properties in the classpath * @return Properties amazon.properties */ protected Properties loadAmazonProperties() { Properties props = new Properties(); try(InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("amazon.properties")){ if (in != null){ props.load(in); } } catch (IOException e) {} return props; } private <T> void verifySupportedOptions(Set<? extends T> allowedOptions, Set<? extends T> actualOptions) { Sets.SetView<? extends T> unsupported = difference(actualOptions, allowedOptions); Preconditions.checkArgument(unsupported.isEmpty(), "the following options are not supported: %s", unsupported); } /** * check that the paths exists or not * @param path S3Path * @return true if exists */ private boolean exists(S3Path path) { try { getFirstObjectSummary(path); return true; } catch(NoSuchFileException e) { return false; } } /** * Get the {@link S3ObjectSummary} that represent this Path or her first child if this path not exists * @param s3Path {@link S3Path} * @return {@link S3ObjectSummary} * @throws NoSuchFileException if not found the path and any child */ private S3ObjectSummary getFirstObjectSummary(S3Path s3Path) throws NoSuchFileException{ AmazonS3Client client = s3Path.getFileSystem().getClient(); ListObjectsRequest request = new ListObjectsRequest(); request.setBucketName(s3Path.getBucket()); request.setPrefix(s3Path.getKey()); request.setMaxKeys(1); List<S3ObjectSummary> query = client.listObjects(request).getObjectSummaries(); if (!query.isEmpty()) { return query.get(0); } else { throw new NoSuchFileException(s3Path.toString()); } } /** * Get the Control List, if the path not exists * (because the path is a directory and this key isnt created at amazon s3) * then return the ACL of the first child. * * @param path {@link S3Path} * @return AccessControlList * @throws NoSuchFileException if not found the path and any child */ private AccessControlList getAccessControl(S3Path path) throws NoSuchFileException{ S3ObjectSummary obj = getFirstObjectSummary(path); // check first for file: return path.getFileSystem().getClient().getObjectAcl(obj.getBucketName(), obj.getKey()); } /** * create a temporal directory to create streams * @return Path temporal folder * @throws IOException */ protected Path createTempDir() throws IOException { return Files.createTempDirectory("temp-s3-"); } }
package de.bmoth.backend.z3; import com.microsoft.z3.*; import de.bmoth.backend.SubstitutionOptions; import de.bmoth.backend.TranslationOptions; import de.bmoth.parser.ast.nodes.*; import de.bmoth.parser.ast.visitors.SubstitutionVisitor; import java.util.*; import static de.bmoth.backend.TranslationOptions.PRIMED_0; import static de.bmoth.backend.TranslationOptions.UNPRIMED; public class MachineToZ3Translator { private final MachineNode machineNode; private final Context z3Context; private final SubstitutionToZ3TranslatorVisitor visitor; private final Z3TypeInference z3TypeInference; private final Expr[] originalVariables; public MachineToZ3Translator(MachineNode machineNode, Context ctx) { this.machineNode = machineNode; this.z3Context = ctx; this.visitor = new SubstitutionToZ3TranslatorVisitor(); this.z3TypeInference = new Z3TypeInference(); this.originalVariables = getVariables().stream().map(this::getVariable).toArray(Expr[]::new); z3TypeInference.visitMachineNode(machineNode); } private List<BoolExpr> visitOperations(SubstitutionOptions ops) { List<BoolExpr> results = new ArrayList<>(); // if there's at least one operation... if (!machineNode.getOperations().isEmpty()) { // ... then for every operation ... for (OperationNode operationNode : this.machineNode.getOperations()) { // ... translate it's substitution BoolExpr substitution = visitor.visitSubstitutionNode(operationNode.getSubstitution(), ops); // for unassigned variables add a dummy assignment, e.g. x' = x Set<DeclarationNode> set = new HashSet<>(this.getVariables()); set.removeAll(operationNode.getSubstitution().getAssignedVariables()); List<BoolExpr> dummyAssignments = createDummyAssignment(set, ops); dummyAssignments.add(0, substitution); BoolExpr[] array = dummyAssignments.toArray(new BoolExpr[dummyAssignments.size()]); results.add(z3Context.mkAnd(array)); } } // if there's no operation... else { // ... add dummy assignments for all variables Set<DeclarationNode> set = new HashSet<>(this.getVariables()); List<BoolExpr> dummyAssignments = createDummyAssignment(set, ops); BoolExpr[] array = dummyAssignments.toArray(new BoolExpr[dummyAssignments.size()]); results.add(z3Context.mkAnd(array)); } return results; } protected List<BoolExpr> createDummyAssignment(Set<DeclarationNode> unassignedVariables, SubstitutionOptions ops) { List<BoolExpr> list = new ArrayList<>(); for (DeclarationNode node : unassignedVariables) { BoolExpr mkEq = z3Context.mkEq(getPrimedVariable(node, ops.getLhs()), getPrimedVariable(node, ops.getRhs())); list.add(mkEq); } return list; } public List<DeclarationNode> getVariables() { return machineNode.getVariables(); } public List<DeclarationNode> getConstants() { return machineNode.getConstants(); } public Expr getVariableAsZ3Expression(DeclarationNode node) { Sort type = z3TypeInference.getZ3Sort(node, z3Context); return z3Context.mkConst(node.getName(), type); } public Expr getVariable(DeclarationNode node) { Sort type = z3TypeInference.getZ3Sort(node, z3Context); return z3Context.mkConst(node.getName(), type); } public Expr getPrimedVariable(DeclarationNode node, TranslationOptions ops) { String primedName = getPrimedName(node.getName(), ops); Sort type = z3TypeInference.getZ3Sort(node, z3Context); return z3Context.mkConst(primedName, type); } public BoolExpr getInitialValueConstraint(TranslationOptions ops) { BoolExpr initialization = null; BoolExpr properties = null; if (machineNode.getInitialisation() != null) { initialization = visitor.visitSubstitutionNode(machineNode.getInitialisation(), new SubstitutionOptions(ops, UNPRIMED)); } if (machineNode.getProperties() != null) { properties = FormulaToZ3Translator.translatePredicate(machineNode.getProperties(), z3Context, z3TypeInference); } if (initialization != null && properties != null) { return z3Context.mkAnd(initialization, properties); } else if (initialization != null) { return initialization; } else { return properties; } } public BoolExpr getInitialValueConstraint() { return getInitialValueConstraint(PRIMED_0); } private BoolExpr translatePredicate(PredicateNode predicateNode, TranslationOptions ops) { BoolExpr predicate = FormulaToZ3Translator.translatePredicate(predicateNode, z3Context, ops, z3TypeInference); return substituteWithPrimedIfNecessary(predicate, ops); } private BoolExpr substituteWithPrimedIfNecessary(BoolExpr boolExpr, TranslationOptions ops) { if (ops.isHasPrimeLevel()) { Expr[] primedVariables = getVariables().stream().map(var -> getPrimedVariable(var, ops)).toArray(Expr[]::new); return (BoolExpr) boolExpr.substitute(originalVariables, primedVariables); } else { return boolExpr; } } public BoolExpr getInvariantConstraint(TranslationOptions ops) { PredicateNode invariantPredicate = machineNode.getInvariant(); if (invariantPredicate != null) { return translatePredicate(invariantPredicate, ops); } else { return z3Context.mkTrue(); } } public BoolExpr getInvariantConstraint() { return getInvariantConstraint(UNPRIMED); } public List<BoolExpr> getOperationConstraints(SubstitutionOptions ops) { return visitOperations(ops); } public List<BoolExpr> getOperationConstraints() { return visitOperations(new SubstitutionOptions(PRIMED_0, UNPRIMED)); } public BoolExpr getCombinedOperationConstraint(SubstitutionOptions ops) { BoolExpr[] operations = visitOperations(ops).toArray(new BoolExpr[0]); switch (operations.length) { case 0: return z3Context.mkTrue(); case 1: return operations[0]; default: return z3Context.mkOr(operations); } } public BoolExpr getCombinedOperationConstraint() { return getCombinedOperationConstraint(new SubstitutionOptions(PRIMED_0, UNPRIMED)); } public Map<String, Expr> getVarMapFromModel(Model model, TranslationOptions ops) { HashMap<String, Expr> map = new HashMap<>(); for (DeclarationNode declNode : getVariables()) { Expr expr = getPrimedVariable(declNode, ops); Expr value = model.eval(expr, true); map.put(declNode.getName(), value); } for (DeclarationNode declarationNode : getConstants()) { Expr expr = getVariable(declarationNode); Expr value = model.eval(expr, true); map.put(declarationNode.getName(), value); } return map; } class SubstitutionToZ3TranslatorVisitor implements SubstitutionVisitor<BoolExpr, SubstitutionOptions> { private static final String CURRENTLY_NOT_SUPPORTED = "Currently not supported"; @Override public BoolExpr visitAnySubstitution(AnySubstitutionNode node, SubstitutionOptions ops) { Expr[] parameters = new Expr[node.getParameters().size()]; for (int i = 0; i < parameters.length; i++) { parameters[i] = getVariableAsZ3Expression(node.getParameters().get(i)); } BoolExpr parameterConstraints = FormulaToZ3Translator.translatePredicate(node.getWherePredicate(), z3Context, z3TypeInference); BoolExpr transition = visitSubstitutionNode(node.getThenSubstitution(), ops); BoolExpr existsBody = z3Context.mkAnd(parameterConstraints, transition); return z3Context.mkExists(parameters, existsBody, parameters.length, null, null, null, null); } @Override public BoolExpr visitSelectSubstitutionNode(SelectSubstitutionNode node, SubstitutionOptions ops) { if (node.getConditions().size() > 1 || node.getElseSubstitution() != null) { throw new AssertionError(CURRENTLY_NOT_SUPPORTED); } BoolExpr condition = translatePredicate(node.getConditions().get(0), ops.getRhs()); BoolExpr substitution = visitSubstitutionNode(node.getSubstitutions().get(0), ops); return z3Context.mkAnd(condition, substitution); } @Override public BoolExpr visitSingleAssignSubstitution(SingleAssignSubstitutionNode node, SubstitutionOptions ops) { String name = getPrimedName(node.getIdentifier().getName(), ops.getLhs()); BoolExpr assignment = FormulaToZ3Translator.translateVariableEqualToExpr(name, node.getValue(), z3Context, z3TypeInference); return substituteWithPrimedIfNecessary(assignment, ops.getRhs()); } @Override public BoolExpr visitParallelSubstitutionNode(ParallelSubstitutionNode node, SubstitutionOptions ops) { List<SubstitutionNode> substitutions = node.getSubstitutions(); BoolExpr boolExpr = null; for (SubstitutionNode substitutionNode : substitutions) { BoolExpr temp = visitSubstitutionNode(substitutionNode, ops); if (boolExpr == null) { boolExpr = temp; } else { boolExpr = z3Context.mkAnd(boolExpr, temp); } } return boolExpr; } @Override public BoolExpr visitConditionSubstitutionNode(ConditionSubstitutionNode node, SubstitutionOptions ops) { // PRE and ASSERT BoolExpr condition = translatePredicate(node.getCondition(), ops.getRhs()); BoolExpr substitution = visitSubstitutionNode(node.getSubstitution(), ops); return z3Context.mkAnd(condition, substitution); } @Override public BoolExpr visitBecomesElementOfSubstitutionNode(BecomesElementOfSubstitutionNode node, SubstitutionOptions ops) { if (node.getIdentifiers().size() > 1) { throw new AssertionError(CURRENTLY_NOT_SUPPORTED); } IdentifierExprNode identifierExprNode = node.getIdentifiers().get(0); String name = getPrimedName(identifierExprNode.getName(), ops.getLhs()); return FormulaToZ3Translator.translateVariableElementOfSetExpr(name, identifierExprNode.getDeclarationNode(), node.getExpression(), z3Context, UNPRIMED, z3TypeInference); } @Override public BoolExpr visitBecomesSuchThatSubstitutionNode(BecomesSuchThatSubstitutionNode node, SubstitutionOptions ops) { throw new AssertionError(CURRENTLY_NOT_SUPPORTED); } @Override public BoolExpr visitIfSubstitutionNode(IfSubstitutionNode node, SubstitutionOptions ops) { if (node.getConditions().size() > 1) { // ELSIF THEN ... throw new AssertionError(CURRENTLY_NOT_SUPPORTED); } BoolExpr condition = translatePredicate(node.getConditions().get(0), ops.getRhs()); BoolExpr substitution = visitSubstitutionNode(node.getSubstitutions().get(0), ops); List<BoolExpr> ifThenList = new ArrayList<>(); ifThenList.add(condition); ifThenList.add(substitution); Set<DeclarationNode> set = new HashSet<>(node.getAssignedVariables()); set.removeAll(node.getSubstitutions().get(0).getAssignedVariables()); ifThenList.addAll(createDummyAssignment(set, ops)); BoolExpr ifThen = z3Context.mkAnd(ifThenList.toArray(new BoolExpr[ifThenList.size()])); BoolExpr elseExpr = null; List<BoolExpr> elseList = new ArrayList<>(); elseList.add(z3Context.mkNot(condition)); if (null == node.getElseSubstitution()) { elseList.addAll(createDummyAssignment(node.getAssignedVariables(), ops)); } else { elseList.add(visitSubstitutionNode(node.getElseSubstitution(), ops)); Set<DeclarationNode> elseDummies = new HashSet<>(node.getAssignedVariables()); elseDummies.removeAll(node.getElseSubstitution().getAssignedVariables()); elseList.addAll(createDummyAssignment(elseDummies, ops)); } elseExpr = z3Context.mkAnd(elseList.toArray(new BoolExpr[elseList.size()])); return z3Context.mkOr(ifThen, elseExpr); } @Override public BoolExpr visitSkipSubstitutionNode(SkipSubstitutionNode node, SubstitutionOptions ops) { return z3Context.mkBool(true); } } private String getPrimedName(String name, TranslationOptions ops) { if (ops.isHasPrimeLevel()) { return name + "'" + ops.getPrimeLevel(); } else { return name; } } }
package de.dhbw.humbuch.viewmodel; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import com.google.inject.Inject; import de.davherrmann.mvvm.ActionHandler; import de.davherrmann.mvvm.BasicState; import de.davherrmann.mvvm.State; import de.davherrmann.mvvm.annotations.AfterVMBinding; import de.davherrmann.mvvm.annotations.HandlesAction; import de.davherrmann.mvvm.annotations.ProvidesState; import de.dhbw.humbuch.model.DAO; import de.dhbw.humbuch.model.entity.BorrowedMaterial; import de.dhbw.humbuch.model.entity.Grade; import de.dhbw.humbuch.model.entity.SchoolYear; import de.dhbw.humbuch.model.entity.SchoolYear.Term; import de.dhbw.humbuch.model.entity.Student; import de.dhbw.humbuch.model.entity.TeachingMaterial; public class ReturnViewModel { public interface GenerateStudentReturnList extends ActionHandler {} public interface SetBorrowedMaterialsReturned extends ActionHandler {} public interface RefreshStudents extends ActionHandler {} public interface ReturnListStudent extends State<Map<Grade, Map<Student, List<BorrowedMaterial>>>> {} @ProvidesState(ReturnListStudent.class) public State<Map<Grade, Map<Student, List<BorrowedMaterial>>>> returnListStudent = new BasicState<>(Map.class); private DAO<Grade> daoGrade; private DAO<BorrowedMaterial> daoBorrowedMaterial; private DAO<SchoolYear> daoSchoolYear; private DAO<Student> daoStudents; private SchoolYear recentlyActiveSchoolYear; /** * Constructor * * @param daoGrade * @param daoBorrowedMaterial * @param daoSchoolYear * @param daoStudents */ @Inject public ReturnViewModel(DAO<Grade> daoGrade, DAO<BorrowedMaterial> daoBorrowedMaterial, DAO<SchoolYear> daoSchoolYear, DAO<Student> daoStudents) { this.daoGrade = daoGrade; this.daoBorrowedMaterial = daoBorrowedMaterial; this.daoSchoolYear = daoSchoolYear; this.daoStudents = daoStudents; } @AfterVMBinding public void refresh() { updateSchoolYear(); updateReturnList(); } /** * Generates "list" of all {@link BorrowedMaterial}s that have to returned by a {@link Student}.<br> * the "list" is returned as {@code Map<Grade, Map<Student, List<BorrowedMaterial>>>} in the state {@link ReturnListStudent} * */ @HandlesAction(GenerateStudentReturnList.class) public void generateStudentReturnList() { Map<Grade, Map<Student, List<BorrowedMaterial>>> toReturn = new TreeMap<Grade, Map<Student,List<BorrowedMaterial>>>(); for(Grade grade : daoGrade.findAll()) { Map<Student, List<BorrowedMaterial>> studentWithUnreturnedBorrowedMaterials = new TreeMap<Student, List<BorrowedMaterial>>(); for(Student student : grade.getStudents()) { List<BorrowedMaterial> unreturnedBorrowedMaterials = new ArrayList<BorrowedMaterial>(); for (BorrowedMaterial borrowedMaterial : student.getReceivedBorrowedMaterials()) { Term recentlyActiveTerm = recentlyActiveSchoolYear.getRecentlyActiveTerm(); Date borrowUntilDate = borrowedMaterial.getBorrowUntil(); boolean isAfterCurrentTerm = recentlyActiveSchoolYear.getEndOf(recentlyActiveTerm).before(new Date()); boolean notNeededNextTerm = borrowedMaterial.getReturnDate() == null && !isNeededNextTerm(borrowedMaterial); boolean borrowUntilExceeded = borrowUntilDate == null ? false : borrowUntilDate.before(new Date()); boolean isManualLended = borrowUntilDate == null ? false : true; if(!isManualLended && notNeededNextTerm && (borrowedMaterial.getTeachingMaterial().getToTerm() != recentlyActiveTerm ? true : isAfterCurrentTerm)) { unreturnedBorrowedMaterials.add(borrowedMaterial); } else if (!borrowedMaterial.isReturned() && borrowUntilExceeded) { unreturnedBorrowedMaterials.add(borrowedMaterial); } } if(!unreturnedBorrowedMaterials.isEmpty()) { Collections.sort(unreturnedBorrowedMaterials); studentWithUnreturnedBorrowedMaterials.put(student, unreturnedBorrowedMaterials); } } if(!studentWithUnreturnedBorrowedMaterials.isEmpty()) { toReturn.put(grade, studentWithUnreturnedBorrowedMaterials); } } returnListStudent.set(toReturn); } /** * Marks the given {@link BorrowedMaterial}s as {@code returned} * * @param borrowedMaterials that should be marked as {@code returned} */ @HandlesAction(SetBorrowedMaterialsReturned.class) public void setBorrowedMaterialsReturned(Collection<BorrowedMaterial> borrowedMaterials) { for (BorrowedMaterial borrowedMaterial : borrowedMaterials) { borrowedMaterial.setReturnDate(new Date()); daoBorrowedMaterial.update(borrowedMaterial); } updateReturnList(); } @HandlesAction(RefreshStudents.class) public void refreshStudents() { daoStudents.findAll(); } /** * Checks if the given {@link BorrowedMaterial} is needed in the next {@link Term}. * * @param borrowedMaterial * @return <code>true</code> if needed, <code>false</code> otherwise */ private boolean isNeededNextTerm(BorrowedMaterial borrowedMaterial) { TeachingMaterial teachingMaterial = borrowedMaterial.getTeachingMaterial(); Integer toGrade = teachingMaterial.getToGrade(); int currentGrade = borrowedMaterial.getStudent().getGrade().getGrade(); Term toTerm = teachingMaterial.getToTerm(); Term currentTerm = recentlyActiveSchoolYear.getRecentlyActiveTerm(); if(toGrade == null) return false; return (toGrade > currentGrade || (toGrade == currentGrade && (toTerm.compareTo(currentTerm) > 0))); } private void updateReturnList() { generateStudentReturnList(); } /** * Updates the recently actice {@link SchoolYear} */ private void updateSchoolYear() { recentlyActiveSchoolYear = daoSchoolYear.findSingleWithCriteria( Order.desc("toDate"), Restrictions.le("fromDate", new Date())); } }
package de.slackspace.openkeepass; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import java.util.zip.GZIPInputStream; import org.bouncycastle.util.encoders.Base64; import de.slackspace.openkeepass.crypto.Decrypter; import de.slackspace.openkeepass.crypto.ProtectedStringCrypto; import de.slackspace.openkeepass.crypto.Salsa20; import de.slackspace.openkeepass.crypto.Sha256; import de.slackspace.openkeepass.domain.CompressionAlgorithm; import de.slackspace.openkeepass.domain.CrsAlgorithm; import de.slackspace.openkeepass.domain.KeePassFile; import de.slackspace.openkeepass.domain.KeePassHeader; import de.slackspace.openkeepass.domain.KeyFile; import de.slackspace.openkeepass.exception.KeePassDatabaseUnreadable; import de.slackspace.openkeepass.parser.KeePassDatabaseXmlParser; import de.slackspace.openkeepass.parser.KeyFileXmlParser; import de.slackspace.openkeepass.stream.HashedBlockInputStream; import de.slackspace.openkeepass.util.ByteUtils; import de.slackspace.openkeepass.util.StreamUtils; /** * A KeePassDatabase is the central API class to read a KeePass database file. * <p> * Currently the following KeePass files are supported: * * <ul> * <li>KeePass Database V2 with password</li> * <li>KeePass Database V2 with keyfile</li> * </ul> * * A typical use-case should use the following idiom: * <pre> * // open database * KeePassFile database = KeePassDatabase.getInstance("keePassDatabasePath").openDatabase("secret"); * * // get password entries * List&lt;Entry&gt; entries = database.getEntries(); * ... * </pre> * * If the database could not be opened a <tt>RuntimeException</tt> will be thrown. * * @see KeePassFile * */ public class KeePassDatabase { // KeePass 2.x signature private static final int DATABASE_V2_FILE_SIGNATURE_1 = 0x9AA2D903 & 0xFF; private static final int DATABASE_V2_FILE_SIGNATURE_2 = 0xB54BFB67 & 0xFF; // KeePass 1.x signature private static final int OLD_DATABASE_V1_FILE_SIGNATURE_1 = 0x9AA2D903 & 0xFF; private static final int OLD_DATABASE_V1_FILE_SIGNATURE_2 = 0xB54BFB65 & 0xFF; // KeePass version signature length in bytes public static final int VERSION_SIGNATURE_LENGTH = 12; private KeePassHeader keepassHeader = new KeePassHeader(); private byte[] keepassFile; protected Decrypter decrypter = new Decrypter(); protected KeePassDatabaseXmlParser keePassDatabaseXmlParser = new KeePassDatabaseXmlParser(); protected KeyFileXmlParser keyFileXmlParser = new KeyFileXmlParser(); private KeePassDatabase(InputStream inputStream) { try { keepassFile = StreamUtils.toByteArray(inputStream); } catch (IOException e) { throw new RuntimeException(e); } } /** * Retrieves a KeePassDatabase instance. The instance returned is based on the given database filename and tries to parse the database header of it. * * @param keePassDatabaseFile a KeePass database filename, must not be NULL * @return a KeePassDatabase */ public static KeePassDatabase getInstance(String keePassDatabaseFile) { return getInstance(new File(keePassDatabaseFile)); } /** * Retrieves a KeePassDatabase instance. The instance returned is based on the given database file and tries to parse the database header of it. * * @param keePassDatabaseFile a KeePass database file, must not be NULL * @return a KeePassDatabase */ public static KeePassDatabase getInstance(File keePassDatabaseFile) { if(keePassDatabaseFile == null) { throw new IllegalArgumentException("You must provide a valid KeePass database file."); } InputStream keePassDatabaseStream = null; try { keePassDatabaseStream = new FileInputStream(keePassDatabaseFile); return getInstance(keePassDatabaseStream); } catch (FileNotFoundException e) { throw new IllegalArgumentException("The KeePass database file could not be found. You must provide a valid KeePass database file."); } finally { if (keePassDatabaseStream != null) { try { keePassDatabaseStream.close(); } catch (IOException e) { // Ignore } } } } /** * Retrieves a KeePassDatabase instance. The instance returned is based on the given input stream and tries to parse the database header of it. * * @param keePassDatabaseStream an input stream of a KeePass database, must not be NULL * @return a KeePassDatabase */ public static KeePassDatabase getInstance(InputStream keePassDatabaseStream) { if(keePassDatabaseStream == null) { throw new IllegalArgumentException("You must provide a non-empty KeePass database stream."); } KeePassDatabase reader = new KeePassDatabase(keePassDatabaseStream); try { reader.checkVersionSupport(); reader.readHeader(); return reader; } catch(IOException e) { throw new RuntimeException("Could not read input stream", e); } } private void checkVersionSupport() throws IOException { BufferedInputStream bufferedInputStream = new BufferedInputStream(new ByteArrayInputStream(keepassFile)); byte[] signature = new byte[VERSION_SIGNATURE_LENGTH]; bufferedInputStream.read(signature); ByteBuffer signatureBuffer = ByteBuffer.wrap(signature); signatureBuffer.order(ByteOrder.LITTLE_ENDIAN); int signaturePart1 = ByteUtils.toUnsignedInt(signatureBuffer.getInt()); int signaturePart2 = ByteUtils.toUnsignedInt(signatureBuffer.getInt()); if(signaturePart1 == DATABASE_V2_FILE_SIGNATURE_1 && signaturePart2 == DATABASE_V2_FILE_SIGNATURE_2) { return; } else if(signaturePart1 == OLD_DATABASE_V1_FILE_SIGNATURE_1 && signaturePart2 == OLD_DATABASE_V1_FILE_SIGNATURE_2) { throw new UnsupportedOperationException("The provided KeePass database file seems to be from KeePass 1.x which is not supported!"); } else { throw new UnsupportedOperationException("The provided file seems to be no KeePass database file!"); } } private void readHeader() throws IOException { BufferedInputStream bufferedInputStream = new BufferedInputStream(new ByteArrayInputStream(keepassFile)); bufferedInputStream.skip(VERSION_SIGNATURE_LENGTH); // skip version while(true) { try { int fieldId = bufferedInputStream.read(); byte[] fieldLength = new byte[2]; bufferedInputStream.read(fieldLength); ByteBuffer fieldLengthBuffer = ByteBuffer.wrap(fieldLength); fieldLengthBuffer.order(ByteOrder.LITTLE_ENDIAN); int fieldLengthInt = ByteUtils.toUnsignedInt(fieldLengthBuffer.getShort()); if(fieldLengthInt > 0) { byte[] data = new byte[fieldLengthInt]; bufferedInputStream.read(data); keepassHeader.setValue(fieldId, data); keepassHeader.increaseHeaderSize(fieldLengthInt + 3); } if(fieldId == 0) { break; } } catch (IOException e) { throw new RuntimeException("Could not read header input", e); } } } /** * Opens a KeePass database with the given password and returns the KeePassFile for further processing. * <p> * If the database cannot be decrypted with the provided password an exception will be thrown. * * @param password the password to open the database * @return a KeePassFile * @see KeePassFile */ public KeePassFile openDatabase(String password) { if(password == null) { throw new IllegalArgumentException("The password for the database must not be null. Please provide a valid password."); } try { byte[] passwordBytes = password.getBytes("UTF-8"); byte[] hashedPassword = Sha256.hash(passwordBytes); return decryptAndParseDatabase(hashedPassword); } catch (UnsupportedEncodingException e) { throw new UnsupportedOperationException("The encoding UTF-8 is not supported"); } } /** * Opens a KeePass database with the given password and returns the KeePassFile for further processing. * <p> * If the database cannot be decrypted with the provided password an exception will be thrown. * * @param keyFile the password to open the database * @return a KeePassFile the keyfile to open the database * @see KeePassFile */ public KeePassFile openDatabase(File keyFile) { if(keyFile == null) { throw new IllegalArgumentException("You must provide a valid KeePass keyfile."); } try { return openDatabase(new FileInputStream(keyFile)); } catch (FileNotFoundException e) { throw new IllegalArgumentException("The KeePass keyfile could not be found. You must provide a valid KeePass keyfile."); } } /** * Opens a KeePass database with the given keyfile stream and returns the KeePassFile for further processing. * <p> * If the database cannot be decrypted with the provided keyfile an exception will be thrown. * * @param keyFileStream the keyfile to open the database as stream * @return a KeePassFile * @see KeePassFile */ public KeePassFile openDatabase(InputStream keyFileStream) { if(keyFileStream == null) { throw new IllegalArgumentException("You must provide a non-empty KeePass keyfile stream."); } try { KeyFile keyFile = keyFileXmlParser.parse(keyFileStream); byte[] protectedBuffer = Base64.decode(keyFile.getKey().getData().getBytes("UTF-8")); return decryptAndParseDatabase(protectedBuffer); } catch (UnsupportedEncodingException e) { throw new UnsupportedOperationException("The encoding UTF-8 is not supported"); } } private KeePassFile decryptAndParseDatabase(byte[] key) { try { byte[] aesDecryptedDbFile = decrypter.decryptDatabase(key, keepassHeader, keepassFile); byte[] startBytes = new byte[32]; ByteArrayInputStream decryptedStream = new ByteArrayInputStream(aesDecryptedDbFile); decryptedStream.read(startBytes); // compare startBytes if(!Arrays.equals(keepassHeader.getStreamStartBytes(), startBytes)) { throw new KeePassDatabaseUnreadable("The keepass database file seems to be corrupt or cannot be decrypted."); } HashedBlockInputStream hashedBlockInputStream = new HashedBlockInputStream(decryptedStream); byte[] hashedBlockBytes = StreamUtils.toByteArray(hashedBlockInputStream); byte[] decompressed = hashedBlockBytes; // unzip if necessary if(keepassHeader.getCompression().equals(CompressionAlgorithm.Gzip)) { GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(hashedBlockBytes)); decompressed = StreamUtils.toByteArray(gzipInputStream); } ProtectedStringCrypto protectedStringCrypto; if(keepassHeader.getCrsAlgorithm().equals(CrsAlgorithm.Salsa20)) { protectedStringCrypto = Salsa20.createInstance(keepassHeader.getProtectedStreamKey()); } else { throw new UnsupportedOperationException("Only Salsa20 is supported as CrsAlgorithm at the moment!"); } return keePassDatabaseXmlParser.parse(new ByteArrayInputStream(decompressed), protectedStringCrypto); } catch (IOException e) { throw new RuntimeException("Could not open database file", e); } } /** * Gets the KeePassDatabase header. * * @return the database header */ public KeePassHeader getHeader() { return keepassHeader; } }
package edu.harvard.iq.dataverse; import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser; import java.io.Serializable; import java.sql.Timestamp; import java.text.SimpleDateFormat; import javax.persistence.Entity; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Transient; /** * * @author xyang */ @Entity public class UserNotification implements Serializable { public enum Type { CREATEDV, CREATEDS, CREATEACC, MAPLAYERUPDATED, SUBMITTEDDS, RETURNEDDS, PUBLISHEDDS, REQUESTFILEACCESS, GRANTFILEACCESS, REJECTFILEACCESS }; private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne private AuthenticatedUser user; private Timestamp sendDate; private boolean readNotification; @Enumerated private Type type; private Long objectId; @Transient private boolean displayAsRead; private boolean emailed; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public AuthenticatedUser getUser() { return user; } public void setUser(AuthenticatedUser user) { this.user = user; } public String getSendDate() { return new SimpleDateFormat("MMMM d, yyyy h:mm a z").format(sendDate); } public void setSendDate(Timestamp sendDate) { this.sendDate = sendDate; } public boolean isReadNotification() { return readNotification; } public void setReadNotification(boolean readNotification) { this.readNotification = readNotification; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public Long getObjectId() { return objectId; } public void setObjectId(Long objectId) { this.objectId = objectId; } public boolean isDisplayAsRead() { return displayAsRead; } public void setDisplayAsRead(boolean displayAsRead) { this.displayAsRead = displayAsRead; } public boolean isEmailed() { return emailed; } public void setEmailed(boolean emailed) { this.emailed = emailed; } }
package edu.howest.breakout.game.entity; import edu.howest.breakout.game.Game; import edu.howest.breakout.game.info.Direction; import edu.howest.breakout.game.info.Wall; import edu.howest.breakout.game.powerup.PowerUpManager; import java.awt.*; import java.util.EnumSet; import static edu.howest.breakout.game.info.Wall.*; public class EntityPad extends EntityBlock { private Wall wall; private EnumSet<Wall> ballWalls; private Direction MovementDirection; private EntityBall ball; private boolean hasBall; private boolean ballLess; private PowerUpManager powerUpManager; private Game game; public EntityPad(Wall wall, Color color, int width, int height, Game game, boolean ballLess) { super(0, 0, width, height, color); this.game = game; this.ballLess = ballLess; this.powerUpManager = new PowerUpManager(); int x = 0; int y = 0; this.wall = wall; this.ballWalls = EnumSet.of(wall); this.MovementDirection = Direction.none; switch (wall){ case bottom: x = 50; y = (int) game.getDimension().getHeight() - height - 10; break; case top: x = 50; y = height + 10; break; } setX(x); setY(y); if (!ballLess) newBall(); } public EntityPad(Wall wall, Color color, int width, int height, Game game, EnumSet<Wall> BallWalls){ this(wall, color, width, height, game, false); this.ballWalls = BallWalls; newBall(); } @Override public void tick(Game game) { int motion = getSpeed(); if (MovementDirection != Direction.none) { if (MovementDirection == Direction.left) motion *= -1; if (this.wall == bottom || this.wall == top) setX(getX() + motion); } if(getX()<0){ setX(0); } if(getX()+getWidth()>game.getDimension().width-1){ setX(game.getDimension().width-getWidth()-1); } if (hasBall) { ball.setX(getX() + getWidth()/2 - ball.getWidth()/2); switch (wall) { case top: ball.setY(getY() + 10 + getHeight()); break; case bottom: ball.setY(getY() - getHeight() - 10); } } } @Override public void DoAction(Game game, Entity entity){ System.out.println("bouncy bouncy"); } public void setMovement(Direction direction){ this.MovementDirection = direction; } public void launchBall(Game game){ if (hasBall && !ballLess) { ball.setSpeed(game.getDifficulty().getBallSpeed()); ball.setAngle(180); hasBall = false; } } public Wall getWall() { return wall; } public void newBall() { hasBall = true; ball = new EntityBall(this, ballWalls); game.add(ball); } public PowerUpManager getPowerUpManager() { return powerUpManager; } }
package edu.yu.einstein.wasp.taglib; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.BodyTagSupport; import javax.servlet.jsp.tagext.Tag; import org.apache.commons.beanutils.MethodUtils; import org.apache.log4j.Logger; import org.springframework.util.StringUtils; import edu.yu.einstein.wasp.model.MetaAttribute; /* * Initializes request attributes selectItems,itemValue and itemLabel request attributes * based on MetaAttribute.Control object * * Used to build dropdown lists off meta field values. * * @Author Sasha Levchuk */ public class MetaSelectTag extends BodyTagSupport { Logger log=Logger.getLogger(MetaSelectTag.class); private MetaAttribute.Control control; public void setControl(MetaAttribute.Control control) { this.control = control; } @Override public int doStartTag() throws javax.servlet.jsp.JspException { if (control==null) return Tag.EVAL_PAGE; if (control.getItems()==null) { this.pageContext.getRequest().setAttribute("selectItems",control.getOptions()); this.pageContext.getRequest().setAttribute("itemValue","value"); this.pageContext.getRequest().setAttribute("itemLabel","label"); return Tag.EVAL_PAGE; } this.pageContext.getRequest().setAttribute("itemValue",control.getItemValue()); this.pageContext.getRequest().setAttribute("itemLabel",control.getItemLabel()); if (control.getItems().indexOf('.')==-1) { this.pageContext.getRequest().setAttribute("selectItems",this.pageContext.getRequest().getAttribute(control.getItems())); return Tag.EVAL_PAGE; } String str=control.getItems(); if (str.indexOf(".")==-1 || str.indexOf("(")==-1 || str.indexOf(")")==-1) { throw new JspException(control.getItems()+" should match ${beanName} or ${beanName.method(param)} pattern"); } String[] pair=StringUtils.tokenizeToStringArray(str, ".", true, true); String beanName=pair[0]; String [] method=pair[1].split("[\\(\\)]"); String methodName=method[0]; Object bean= this.pageContext.getRequest().getAttribute(beanName); if (bean==null) throw new JspException("No bean under name "+beanName+" exist in request attributes"); Object[] args; if (method.length==2) { args=new Object[1]; args[0]=method[1]; } else { args=new Object[0]; } try { Object result = MethodUtils.invokeMethod(bean, methodName, args); this.pageContext.getRequest().setAttribute("selectItems", result); } catch (Throwable e) { throw new IllegalStateException("Can't invoke method to get dropdown options beanName: "+beanName+",methodName: "+methodName+", argument:"+(args.length==0?"none":args[0]),e); } return Tag.EVAL_PAGE; } }
package eml.studio.server.rpc; import eml.studio.client.rpc.CategoryService; import eml.studio.client.util.Constants; import eml.studio.server.db.SecureDao; import eml.studio.shared.model.Category; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import java.util.List; /** * Specific methods in Category modules' related RemoteServiceServlet */ public class CategoryServiceImpl extends RemoteServiceServlet implements CategoryService { private static final long serialVersionUID = 1L; /** * Get the quantity of all valid Accounts */ @Override public int getSize() throws Exception { int size = 0; List<Category> categories; try { Category query = new Category(); categories = SecureDao.listAll(query, "and level != 1"); size = categories.size(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); throw e; } return size; } /** * Get the category of Programs from database * * @return category group list */ @Override public List<Category> getCategory() throws Exception { List<Category> categories = null; try{ Category query = new Category(); query.setLevel("1"); categories = SecureDao.listAll( query, "order by level, type asc"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); throw e; } return categories; } /** * Get the category of id from database * @param id category id * @return category object * @throws Exception */ @Override public Category getCategory(String id) throws Exception { Category category = null; try{ Category query = new Category(); query.setId(id); category = SecureDao.getObject(query); } catch (Exception e) { e.printStackTrace(); throw e; } return category; } /** * Get the category list searched by start and size * @param start * @param size * @return category list * @throws Exception */ @Override public List<Category> getCategory(int start, int size) throws Exception{ List<Category> categories = null; try{ Category query = new Category(); categories = SecureDao.listAll( query, "and level != 1 order by level, type limit "+ start + ", " + size); } catch (Exception e) { e.printStackTrace(); throw e; } return categories; } /** * Get one category's info from database * * @param category category * @param str category string */ @Override public List<Category> getCategory(Category category, String str) throws Exception { List<Category> categories; try{ categories = SecureDao.listAll(category, str); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); throw e; } return categories; } /** * Insert category to database * @param category * @return success or error string */ @Override public String insertCategory(Category category){ Category insert_query = null; Category update_query = null; try{ Category tmp = new Category(); //Queries whether the directory with the same name exists under the same path tmp.setName(category.getName()); tmp.setPath(category.getPath()); if(SecureDao.getObject(tmp) != null){ return Constants.adminUIMsg.alert6() + tmp.getName() + Constants.adminUIMsg.alert7(); }else{ Category update = new Category(); //Update its parent node haschild field to true int index = category.getPath().lastIndexOf(">"); String fathPath = category.getPath().substring(0, index); if("my program".equals(fathPath.toLowerCase())){ update.setPath("My Program"); }else if("shared program".equals(fathPath.toLowerCase())){ update.setPath("Shared Program"); }else if("system program".equals(fathPath.toLowerCase())){ update.setPath("System Program"); }else if("my data".equals(fathPath.toLowerCase())){ update.setPath("My Data"); }else if("shared data".equals(fathPath.toLowerCase())){ update.setPath("Shared Data"); }else if("system data".equals(fathPath.toLowerCase())){ update.setPath("System Data"); }else update.setPath(fathPath); update.setHaschild(true); String[] setFields = { "haschild"}; String[] condFields = { "path" }; SecureDao.update(update, setFields, condFields); update_query = SecureDao.getObject(update); //Haschild update success is the implementation of the insert operation will be added to the table insert table if(update_query != null){ int level = Integer.parseInt(update_query.getLevel())+1; category.setLevel(Integer.toString(level)); category.setFatherid(update_query.getId()); SecureDao.insert(category); insert_query = SecureDao.getObject(category); if(insert_query != null){ return "success"; }else{ Category back = new Category(); back.setPath(category.getPath().substring(0, index)); back.setHaschild(false); SecureDao.update(update, setFields, condFields); return "insert failed"; } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** * Delete a category * * @param category target category * @return category */ @Override public Category deleteCategory(Category category) { Category query = new Category(); query.setId(category.getId()); try{ SecureDao.delete(query); if(SecureDao.getObject(query) == null){ return null; }else return SecureDao.getObject(query); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
package eu.djakarta.tsEarthquake; import java.io.File; import java.io.IOException; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; public class XmlEventDatabase implements EventDatabase { private File file; public XmlEventDatabase(File file) { this.file = file; } public XmlEventDatabase(String fileName) { this(new File(fileName)); } @Override public List<Event> getEventList() { /* TODO implement getEventList */ SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser; try { saxParser = factory.newSAXParser(); } catch (ParserConfigurationException | SAXException e) { throw new RuntimeException(e); } EventXmlHandler eventXmlHandler = new EventXmlHandler(); try { saxParser.parse(this.file, eventXmlHandler); } catch (SAXException | IOException e) { throw new RuntimeException(e); } List<Event> list = eventXmlHandler.getEventList(); return list; } }
package treesPackage; public class Prob12IsBST { // Version 1 public static boolean isBST1(Node root) { if (root == null) return true; // So if the max of the left subtree is greater than the current node's value, we return false if (root.getLeftChild() != null && root.getData() < maxValue(root.getLeftChild())) return false; // So if the max of the right subtree is less than the current node's value, we return false if (root.getRightChild() != null && root.getData() > minValue(root.getRightChild())) return false; // in a BST, both the left and right subtrees must also be binary search trees. // So we check that the subtrees themselves are ok by making a recursive call on them return (isBst1(root.getLeftChild()) && isBst1(root.getRightChild())); } /* Version 1 above runs slowly since it traverses over some parts of the tree many times. A better solution looks at each node only once. The trick is to write a utility helper function isBST2(Node root, int min, int max) that traverses down the tree keeping track of the narrowing min and max allowed values as it goes, looking at each node only once. The initial values for min and max should be Integer.MIN_VALUE and int Integer.MAX_VALUE -- they narrow from there. */ // Version 2: public static boolean isBST2(Node root) { return isBST2(root, Integer.MIN_VALUE, Integer.MAX_VALUE); } public static boolean isBST2(Node node, int min, int max) { // an empty tree is a BST if (node == null) return true; // if node violates the min/max constraints, we return false if (node.getData() < min || node.getData() > max) return false; // left subtree should be in the range of min...node.getData() // and right subtree in the range of node.getData+1...max return isBST2(node.getLeftChild(), min, node.getData()) && isBST2(node.getRightChild(), node.getData()+1, max); } }
package owltools.cli; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import org.apache.log4j.Logger; import org.semanticweb.owlapi.model.AddImport; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLClassExpression; import org.semanticweb.owlapi.model.OWLDataFactory; import org.semanticweb.owlapi.model.OWLDisjointClassesAxiom; import org.semanticweb.owlapi.model.OWLImportsDeclaration; import org.semanticweb.owlapi.model.OWLObject; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyManager; import org.semanticweb.owlapi.model.OWLSubClassOfAxiom; import owltools.cli.tools.CLIMethod; import owltools.gaf.inference.ClassTaxonMatrix; import owltools.gaf.inference.TaxonConstraintsEngine; import owltools.graph.OWLGraphEdge; import owltools.io.OWLPrettyPrinter; /** * Command-line module for taxon constraints. */ public class TaxonCommandRunner extends GafCommandRunner { private static final Logger LOG = Logger.getLogger(TaxonCommandRunner.class); @CLIMethod("--make-class-taxon-matrix") public void makeClassTaxonMatrix(Opts opts) throws Exception { opts.info("[-o|--output OUTPUT-FILE] [--query-taxa QUERY_TAXA_ONTOLOGY_IRI] [TAXON ...]", "Specifiy relevant taxa either as list or as separate taxon ontology (Load via an IRI)" + "\nOptional parameter: OUTPUT-FILE (if not specified system out is used)" + "\nHINT: To create a class taxon load first the ontology with merged taxa."); Set<OWLClass> taxa = new HashSet<OWLClass>(); File outputFile = null; while (opts.hasArgs()) { if (opts.nextEq("-o") || opts.nextEq("--output")) { outputFile = new File(opts.nextOpt()); } else if(opts.nextEq("--query-taxa")) { OWLOntology queryTaxaOntology = pw.parse(opts.nextOpt()); taxa.addAll(queryTaxaOntology.getClassesInSignature()); } else if (opts.hasOpts()) { break; } else { taxa.add((OWLClass)resolveEntity(opts)); } } if (taxa.isEmpty()) { LOG.warn("No taxa for matrix selected"); return; } // set output writer final BufferedWriter writer; if (outputFile == null) { writer = new BufferedWriter(new PrintWriter(System.out)); } else { writer = new BufferedWriter(new FileWriter(outputFile)); } // create matrix ClassTaxonMatrix matrix = ClassTaxonMatrix.create(g, g.getSourceOntology().getClassesInSignature(), taxa); // write matrix ClassTaxonMatrix.write(matrix, g, writer); writer.close(); } @CLIMethod("--make-taxon-set") public void makeTaxonSet(Opts opts) throws Exception { opts.info("[-s] TAXON","Lists all classes that are applicable for a specified taxon"); String idspace = null; if (opts.nextEq("-s")) idspace = opts.nextOpt(); OWLPrettyPrinter owlpp = getPrettyPrinter(); TaxonConstraintsEngine tce = new TaxonConstraintsEngine(g); OWLClass tax = (OWLClass)this.resolveEntity(opts); Set<OWLObject> taxAncs = g.getAncestorsReflexive(tax); LOG.info("Tax ancs: "+taxAncs); Set<OWLClass> taxSet = new HashSet<OWLClass>(); for (OWLClass c : g.getSourceOntology().getClassesInSignature()) { String cid = g.getIdentifier(c); if (idspace != null && !cid.startsWith(idspace+":")) continue; Set<OWLGraphEdge> edges = g.getOutgoingEdgesClosure(c); boolean isExcluded = !tce.isClassApplicable(c, tax, edges, taxAncs); if (isExcluded) { LOG.info("excluding: "+owlpp.render(c)); } else { taxSet.add(c); System.out.println(cid); } } } @CLIMethod("--create-taxon-disjoint-over-in-taxon") public void createTaxonDisjointOverInTaxon(Opts opts) throws Exception { String outputFile = "taxslim-disjoint-over-in-taxon.owl"; String ontologyIRI = "http://purl.obolibrary.org/obo/ncbitaxon/subsets/taxslim-disjoint-over-in-taxon.owl"; List<String> imports = Arrays.asList("http://purl.obolibrary.org/obo/ncbitaxon/subsets/taxslim.owl", "http://purl.obolibrary.org/obo/ro.owl"); OWLClass root = null; if (opts.nextEq("-r|--root")) { String s = opts.nextOpt(); root = g.getOWLClassByIdentifier(s); if (root == null) { throw new RuntimeException("No class was found for the specified identifier: "+s); } } else { throw new RuntimeException("No root identifier specified."); } // Task: create disjoint axioms for all siblings in the slim // avoid functional recursion // create new disjoint ontology OWLOntologyManager m = g.getManager(); OWLDataFactory f = m.getOWLDataFactory(); OWLOntology disjointOntology = m.createOntology(IRI.create(ontologyIRI)); // setup imports for(String importIRI : imports) { OWLImportsDeclaration decl = f.getOWLImportsDeclaration(IRI.create(importIRI)); m.applyChange(new AddImport(disjointOntology, decl)); } // add disjoints Queue<OWLClass> queue = new LinkedList<OWLClass>(); queue.add(root); Set<OWLClass> done = new HashSet<OWLClass>(); final OWLOntology ont = g.getSourceOntology(); int axiomCount = 0; while (queue.isEmpty() == false) { OWLClass current = queue.remove(); if (done.add(current)) { Set<OWLSubClassOfAxiom> axioms = ont.getSubClassAxiomsForSuperClass(current); Set<OWLClass> siblings = new HashSet<OWLClass>(); for (OWLSubClassOfAxiom ax : axioms) { OWLClassExpression ce = ax.getSubClass(); if (ce.isAnonymous() == false) { OWLClass subCls = ce.asOWLClass(); siblings.add(subCls); queue.add(subCls); } } if (siblings.size() > 1) { Set<OWLDisjointClassesAxiom> disjointAxioms = new HashSet<OWLDisjointClassesAxiom>(); for (OWLClass sibling1 : siblings) { for (OWLClass sibling2 : siblings) { if (sibling1 != sibling2) { disjointAxioms.add(f.getOWLDisjointClassesAxiom(sibling1, sibling2)); } } } m.addAxioms(disjointOntology, disjointAxioms); axiomCount += disjointAxioms.size(); } } } LOG.info("Created "+axiomCount+" disjoint axioms."); // save to file m.saveOntology(disjointOntology, new FileOutputStream(outputFile)); } }
package water; import java.io.IOException; import water.init.NetworkInit; import water.util.Log; /** * A UDP Rebooted packet: this node recently rebooted * * @author <a href="mailto:cliffc@0xdata.com"></a> * @version 1.0 */ class UDPRebooted extends UDP { static enum T { none, reboot, shutdown, oom, error, locked, mismatch; void send(H2ONode target) { assert this != none; new AutoBuffer(target).putUdp(udp.rebooted).put1(ordinal()).close(); } void broadcast() { send(H2O.SELF); } } static void checkForSuicide(int first_byte, AutoBuffer ab) { if( first_byte != UDP.udp.rebooted.ordinal() ) return; int type = ab.get1(); suicide( T.values()[type], ab._h2o); } static void suicide( T cause, H2ONode killer ) { String m; switch( cause ) { case none: return; case reboot: return; case shutdown: closeAll(); Log.info("Orderly shutdown command from "+killer); H2O.exit(0); return; case oom: m = "Out of Memory and no swap space left"; break; case error: m = "Error leading to a cloud kill"; break; case locked: m = "Attempting to join an H2O cloud that is no longer accepting new H2O nodes"; break; case mismatch: m = "Attempting to join an H2O cloud with a different H2O version (is H2O already running?)"; break; default: m = "Received kill " + cause; break; } closeAll(); Log.err(m+" from "+killer); H2O.die("Exiting."); } @Override AutoBuffer call(AutoBuffer ab) { if( ab._h2o != null ) ab._h2o.rebooted(); return ab; } // Try to gracefully close/shutdown all i/o channels. static void closeAll() { try { NetworkInit._udpSocket.close(); } catch( IOException ignore ) { } try { NetworkInit._apiSocket.close(); } catch( IOException ignore ) { } try { TCPReceiverThread.SOCK.close(); } catch( IOException ignore ) { } } // Pretty-print bytes 1-15; byte 0 is the udp_type enum @Override String print16( AutoBuffer ab ) { ab.getPort(); return T.values()[ab.get1()].toString(); } }
package edu.cmu.minorthird.text; import edu.cmu.minorthird.text.mixup.*; import org.apache.log4j.*; import java.util.*; import java.io.*; /** * Analogous to a ClassLoader, this finds annotators by name, * so they can be applied to a set of labels. */ public abstract class AnnotatorLoader { private static Logger log = Logger.getLogger(AnnotatorLoader.class); private static Properties redirectionProps = new Properties(); static { InputStream s = ClassLoader.getSystemResourceAsStream("annotators.config"); if (s==null) log.warn("can't find annotators.config"); else { try { redirectionProps.load(s); } catch (IOException e) { log.warn("error trying to load annotators.config: "+e); } } } /** Find the named resource file - usually a dictionary or trie for mixup. */ abstract public InputStream findFileResource(String fileName); /** Find the named resource class - usually an annotator. */ abstract public Class findClassResource(String className); /** Find an annotator for the given annotationType, from the listed * source. If the source is non-null, it attempted to be located via * findFileResource and if it does not find it there it uses the * findClassResource. If the source is null, the following rules are * followed, in order, to find the source. * <ol> * <li>If the classpath contains a file "annotation.properties" that * defines the annotator source for 'foo' to be 'bar', follow the * rules above for source 'bar' (i.e., find a file resource 'bar' * if 'bar' ends in .mixup, and a class resource otherwise.) * <li>If one can find a file resource "foo.mixup", use that as the source. * <li>Use 'foo' as a class name. * </ol> */ final public Annotator findAnnotator(String annotationType, String source) { Annotator ann = null; String redirect; InputStream s; log.info("finding annotator for "+annotationType+" source="+source); // First we check based on the provided source if (source != null) { // We treat mixup programs special. They must end in ".mixup" if (source.endsWith(".mixup")) { log.debug("non-null mixup"); return findMixupAnnotatorFromStream(source,findFileResource(source)); } // If the source is not a mixup, then it is either part of an encapsulated annotator // or is a class that needs to be loaded natively by java. else { log.debug("non-null non-mixup"); // First check to see if the saved annotator is being served as a object from a // stream such as if the annotator is encapsulated inside another annotator. ann = findSavedAnnotatorFromStream(source, findFileResource(source)); if (ann == null) // Otherwise find the native annotator for the provided source. ann = findNativeAnnotatorFromString(source); return ann; } } // If the source does not lead us to the annotator check the annotation type else { // Check to see if the annotation type specifies a redirection redirect = redirectionProps.getProperty(annotationType); if (redirect != null) { log.debug("redirected to "+redirect); return findAnnotator(annotationType,redirect); } // Now check to see if the annotation type specifies a mixup file to load. if ((s = findFileResource(annotationType+".mixup"))!=null) { log.debug("file resource "+s+" for "+annotationType+".mixup"); return findMixupAnnotatorFromStream(annotationType+".mixup",s); } // If all else fails attempt to load the annotation type as a class log.debug("trying as class "+annotationType); return findNativeAnnotatorFromString(annotationType); } } // This method attempts to locate an annotator named as provided using the supplied input stream final private Annotator findSavedAnnotatorFromStream(String annotatorName, InputStream s) { log.info("finding saved Annotator "+annotatorName+" in stream "+s); if (s != null) { try { byte[] buf = new byte[s.available()]; s.read(buf); ByteArrayInputStream input = new ByteArrayInputStream(buf); ObjectInputStream objInput = new ObjectInputStream(input); return (Annotator)objInput.readObject(); } catch (IOException e) { log.warn("error loading "+annotatorName+": "+e); return null; } catch (ClassNotFoundException e) { log.warn("annotator "+annotatorName+" not found: "+e); return null; } } log.warn("Couldn't find annotator "+annotatorName+" using "+this); return null; } final private Annotator findMixupAnnotatorFromStream(String fileName,InputStream s) { log.info("finding MixupProgram "+fileName+" in stream "+s); if (s==null) { log.warn("couldn't find mixup program "+fileName+" using "+this); return null; } try { byte[] buf = new byte[s.available()]; s.read(buf); MixupProgram p = new MixupProgram(new String(buf)); return new MixupAnnotator(p); } catch (Mixup.ParseException e) { log.warn("error parsing "+fileName+": "+e); return null; } catch (IOException e) { log.warn("error loading "+fileName+": "+e); return null; } } final private Annotator findNativeAnnotatorFromString(String className) { try { Class c = findClassResource(className); Object o = c.newInstance(); if (o instanceof Annotator) return (Annotator)o; else log.warn(c+", found from "+className+" via "+this+", is not an instance of Annotator"); } catch (Exception e) { log.warn(this+" can't find class named "+className+": "+e); } return null; } }
package actions.backend; import bl.beans.ServicePlaceBean; import bl.constants.BusTieConstant; import bl.exceptions.MiServerException; import bl.instancepool.SingleBusinessPoolManager; import bl.mongobus.ServicePlaceBusiness; import com.opensymphony.xwork2.ActionSupport; import org.apache.commons.beanutils.BeanUtils; import org.bson.types.ObjectId; import util.ServerContext; import vo.table.TableHeaderVo; import vo.table.TableInitVo; import vo.table.TableQueryVo; import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; public class BackendServicePlaceAction extends BaseBackendAction<ServicePlaceBusiness> { List<ServicePlaceBean> servicePlaces = null; ServicePlaceBean servicePlace = null; ServicePlaceBusiness sp = (ServicePlaceBusiness) SingleBusinessPoolManager.getBusObj(BusTieConstant.BUS_CPATH_SERVICEPLACE); private int type = 0; private String[] serviceicons = null; private List<ServicePlaceBean> innerHospital = null; public List<ServicePlaceBean> getInnerHospital() { return innerHospital; } public void setInnerHospital(List<ServicePlaceBean> innerHospital) { this.innerHospital = innerHospital; } public String[] getServiceicons() { return serviceicons; } public void setServiceicons(String[] serviceicons) { this.serviceicons = serviceicons; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String servicePlaceList() { HashMap<String,Integer> filterByType = new HashMap<String,Integer>(); filterByType.put("type",this.type); this.servicePlaces = (List<ServicePlaceBean>) sp.queryDataByCondition(filterByType, null); return ActionSupport.SUCCESS; } public String servicePlaceDelete() { if (this.getId() != null) { sp.deleteLeaf(this.getId()); } return ActionSupport.SUCCESS; } public String servicePlaceAddEdit() { //read file list File iconList = new File(ServerContext.getValue("realserviceplacedirectory")); if(iconList.isDirectory() && iconList.exists()){ String[] list = iconList.list(); //convert to virtual path within tomcat service. serviceicons = new String[list.length]; String vitual = ServerContext.getValue("vitualserviceiplacedirectory"); for (int i = 0; i < list.length; i++) { serviceicons[i] = vitual+ list[i]; } } if (this.getId() != null) { String id = this.getId(); this.servicePlace = (ServicePlaceBean) this.sp.getLeaf(id).getResponseData(); } Map<String,String> filterMap = new HashMap<String,String>(); filterMap.put("area_=","0"); filterMap.put("type_=","1"); filterMap.put("isDeleted","false"); this.innerHospital = sp.queryDataByCondition(filterMap,null); return ActionSupport.SUCCESS; } public String servicePlaceSubmit() throws Exception{ String id = this.servicePlace.getId(); try { if (id != null && !id.isEmpty()) { ServicePlaceBean originalBean = (ServicePlaceBean) this.sp.getLeaf(id).getResponseData(); ServicePlaceBean newBean = (ServicePlaceBean) originalBean.clone(); BeanUtils.copyProperties(newBean, this.servicePlace); sp.updateLeaf(originalBean, newBean); } else { this.servicePlace.set_id(ObjectId.get()); this.sp.createLeaf(this.servicePlace); } } catch (MiServerException miEx) { //read file list File iconList = new File(ServerContext.getValue("realserviceplacedirectory")); if (iconList.isDirectory() && iconList.exists()) { String[] list = iconList.list(); //convert to virtual path within tomcat service. serviceicons = new String[list.length]; String vitual = ServerContext.getValue("vitualserviceiplacedirectory"); for (int i = 0; i < list.length; i++) { serviceicons[i] = vitual + list[i]; } } Map<String, String> filterMap = new HashMap<String, String>(); filterMap.put("area_=", "0"); filterMap.put("type_=", "1"); filterMap.put("isDeleted", "false"); this.innerHospital = sp.queryDataByCondition(filterMap, null); throw miEx; } return ActionSupport.SUCCESS; } @Override public String getActionPrex() { return getRequest().getContextPath() + "/backend/serviceplace"; } @Override public String getCustomJs() { return super.getCustomJs(); //return getRequest().getContextPath() + "/js/serviceplace.js"; } @Override public TableInitVo getTableInit() { TableInitVo init = new TableInitVo(); init.getAoColumns().add(new TableHeaderVo("sequence", "").enableSearch()); init.getAoColumns().add(new TableHeaderVo("code", "").enableSearch()); init.getAoColumns().add(new TableHeaderVo("name", "").enableSearch()); return init; } @Override public TableQueryVo getModel() { TableQueryVo model = super.getModel(); model.getFilter().put("type", this.type + ""); return model; } @Override public String getAddButtonParameter(){ return "type="+this.type; } public List<ServicePlaceBean> getServicePlaces() { return servicePlaces; } public void setServicePlaces(List<ServicePlaceBean> servicePlaces) { this.servicePlaces = servicePlaces; } public ServicePlaceBean getServicePlace() { return servicePlace; } public void setServicePlace(ServicePlaceBean servicePlace) { this.servicePlace = servicePlace; } @Override public String getTableTitle() { if (this.type == 0) return "<ul class=\"breadcrumb\"><li></li><li class=\"active\"></li></ul>"; else return "<ul class=\"breadcrumb\"><li></li><li class=\"active\"></li></ul>"; } }
// This file is part of OpenTSDB. // This program is free software: you can redistribute it and/or modify it // option) any later version. This program is distributed in the hope that it // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser package net.opentsdb.core; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import com.stumbleupon.async.Callback; import com.stumbleupon.async.Deferred; import com.stumbleupon.async.DeferredGroupException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.hbase.async.Bytes; import org.hbase.async.Bytes.ByteMap; import org.hbase.async.ClientStats; import org.hbase.async.DeleteRequest; import org.hbase.async.GetRequest; import org.hbase.async.HBaseClient; import org.hbase.async.HBaseException; import org.hbase.async.KeyValue; import org.hbase.async.PutRequest; import net.opentsdb.tree.TreeBuilder; import net.opentsdb.tsd.RTPublisher; import net.opentsdb.tsd.RpcPlugin; import net.opentsdb.uid.NoSuchUniqueName; import net.opentsdb.uid.UniqueId; import net.opentsdb.uid.UniqueId.UniqueIdType; import net.opentsdb.utils.Config; import net.opentsdb.utils.DateTime; import net.opentsdb.utils.PluginLoader; import net.opentsdb.meta.Annotation; import net.opentsdb.meta.TSMeta; import net.opentsdb.meta.UIDMeta; import net.opentsdb.search.SearchPlugin; import net.opentsdb.search.SearchQuery; import net.opentsdb.stats.Histogram; import net.opentsdb.stats.StatsCollector; /** * Thread-safe implementation of the TSDB client. * <p> * This class is the central class of OpenTSDB. You use it to add new data * points or query the database. */ public final class TSDB { private static final Logger LOG = LoggerFactory.getLogger(TSDB.class); static final byte[] FAMILY = { 't' }; /** Charset used to convert Strings to byte arrays and back. */ private static final Charset CHARSET = Charset.forName("ISO-8859-1"); private static final String METRICS_QUAL = "metrics"; private static final short METRICS_WIDTH = 3; private static final String TAG_NAME_QUAL = "tagk"; private static final short TAG_NAME_WIDTH = 3; private static final String TAG_VALUE_QUAL = "tagv"; private static final short TAG_VALUE_WIDTH = 3; /** Client for the HBase cluster to use. */ final HBaseClient client; /** Name of the table in which timeseries are stored. */ final byte[] table; /** Name of the table in which UID information is stored. */ final byte[] uidtable; /** Name of the table where tree data is stored. */ final byte[] treetable; /** Name of the table where meta data is stored. */ final byte[] meta_table; /** Unique IDs for the metric names. */ final UniqueId metrics; /** Unique IDs for the tag names. */ final UniqueId tag_names; /** Unique IDs for the tag values. */ final UniqueId tag_values; /** Configuration object for all TSDB components */ final Config config; /** * Row keys that need to be compacted. * Whenever we write a new data point to a row, we add the row key to this * set. Every once in a while, the compaction thread will go through old * row keys and will read re-compact them. */ private final CompactionQueue compactionq; /** Search indexer to use if configure */ private SearchPlugin search = null; /** Optional real time pulblisher plugin to use if configured */ private RTPublisher rt_publisher = null; /** List of activated RPC plugins */ private List<RpcPlugin> rpc_plugins = null; /** * Constructor * @param client An initialized HBase client object * @param config An initialized configuration object * @since 2.1 */ public TSDB(final HBaseClient client, final Config config) { this.config = config; this.client = client; this.client.setFlushInterval(config.getShort("tsd.storage.flush_interval")); table = config.getString("tsd.storage.hbase.data_table").getBytes(CHARSET); uidtable = config.getString("tsd.storage.hbase.uid_table").getBytes(CHARSET); treetable = config.getString("tsd.storage.hbase.tree_table").getBytes(CHARSET); meta_table = config.getString("tsd.storage.hbase.meta_table").getBytes(CHARSET); metrics = new UniqueId(client, uidtable, METRICS_QUAL, METRICS_WIDTH); tag_names = new UniqueId(client, uidtable, TAG_NAME_QUAL, TAG_NAME_WIDTH); tag_values = new UniqueId(client, uidtable, TAG_VALUE_QUAL, TAG_VALUE_WIDTH); compactionq = new CompactionQueue(this); if (config.hasProperty("tsd.core.timezone")) { DateTime.setDefaultTimezone(config.getString("tsd.core.timezone")); } if (config.enable_realtime_ts() || config.enable_realtime_uid()) { // this is cleaner than another constructor and defaults to null. UIDs // will be refactored with DAL code anyways metrics.setTSDB(this); tag_names.setTSDB(this); tag_values.setTSDB(this); } if (config.getBoolean("tsd.core.preload_uid_cache")) { final ByteMap<UniqueId> uid_cache_map = new ByteMap<UniqueId>(); uid_cache_map.put(METRICS_QUAL.getBytes(CHARSET), metrics); uid_cache_map.put(TAG_NAME_QUAL.getBytes(CHARSET), tag_names); uid_cache_map.put(TAG_VALUE_QUAL.getBytes(CHARSET), tag_values); UniqueId.preloadUidCache(this, uid_cache_map); } LOG.debug(config.dumpConfiguration()); } /** * Constructor * @param config An initialized configuration object * @since 2.0 */ public TSDB(final Config config) { this(new HBaseClient(config.getString("tsd.storage.hbase.zk_quorum"), config.getString("tsd.storage.hbase.zk_basedir")), config); } /** @return The data point column family name */ public static byte[] FAMILY() { return FAMILY; } public void initializePlugins(final boolean init_rpcs) { final String plugin_path = config.getString("tsd.core.plugin_path"); if (plugin_path != null && !plugin_path.isEmpty()) { try { PluginLoader.loadJARs(plugin_path); } catch (Exception e) { LOG.error("Error loading plugins from plugin path: " + plugin_path, e); throw new RuntimeException("Error loading plugins from plugin path: " + plugin_path, e); } } // load the search plugin if enabled if (config.getBoolean("tsd.search.enable")) { search = PluginLoader.loadSpecificPlugin( config.getString("tsd.search.plugin"), SearchPlugin.class); if (search == null) { throw new IllegalArgumentException("Unable to locate search plugin: " + config.getString("tsd.search.plugin")); } try { search.initialize(this); } catch (Exception e) { throw new RuntimeException("Failed to initialize search plugin", e); } LOG.info("Successfully initialized search plugin [" + search.getClass().getCanonicalName() + "] version: " + search.version()); } else { search = null; } // load the real time publisher plugin if enabled if (config.getBoolean("tsd.rtpublisher.enable")) { rt_publisher = PluginLoader.loadSpecificPlugin( config.getString("tsd.rtpublisher.plugin"), RTPublisher.class); if (rt_publisher == null) { throw new IllegalArgumentException( "Unable to locate real time publisher plugin: " + config.getString("tsd.rtpublisher.plugin")); } try { rt_publisher.initialize(this); } catch (Exception e) { throw new RuntimeException( "Failed to initialize real time publisher plugin", e); } LOG.info("Successfully initialized real time publisher plugin [" + rt_publisher.getClass().getCanonicalName() + "] version: " + rt_publisher.version()); } else { rt_publisher = null; } if (init_rpcs && config.hasProperty("tsd.rpc.plugins")) { final String[] plugins = config.getString("tsd.rpc.plugins").split(","); for (final String plugin : plugins) { final RpcPlugin rpc = PluginLoader.loadSpecificPlugin(plugin.trim(), RpcPlugin.class); if (rpc == null) { throw new IllegalArgumentException( "Unable to locate RPC plugin: " + plugin.trim()); } try { rpc.initialize(this); } catch (Exception e) { throw new RuntimeException( "Failed to initialize RPC plugin", e); } if (rpc_plugins == null) { rpc_plugins = new ArrayList<RpcPlugin>(1); } rpc_plugins.add(rpc); LOG.info("Successfully initialized RPC plugin [" + rpc.getClass().getCanonicalName() + "] version: " + rpc.version()); } } } /** * Returns the configured HBase client * @return The HBase client * @since 2.0 */ public final HBaseClient getClient() { return this.client; } /** * Getter that returns the configuration object * @return The configuration object * @since 2.0 */ public final Config getConfig() { return this.config; } public Deferred<String> getUidName(final UniqueIdType type, final byte[] uid) { if (uid == null) { throw new IllegalArgumentException("Missing UID"); } switch (type) { case METRIC: return this.metrics.getNameAsync(uid); case TAGK: return this.tag_names.getNameAsync(uid); case TAGV: return this.tag_values.getNameAsync(uid); default: throw new IllegalArgumentException("Unrecognized UID type"); } } public byte[] getUID(final UniqueIdType type, final String name) { if (name == null || name.isEmpty()) { throw new IllegalArgumentException("Missing UID name"); } switch (type) { case METRIC: return this.metrics.getId(name); case TAGK: return this.tag_names.getId(name); case TAGV: return this.tag_values.getId(name); default: throw new IllegalArgumentException("Unrecognized UID type"); } } /** * Verifies that the data and UID tables exist in HBase and optionally the * tree and meta data tables if the user has enabled meta tracking or tree * building * @return An ArrayList of objects to wait for * @throws TableNotFoundException * @since 2.0 */ public Deferred<ArrayList<Object>> checkNecessaryTablesExist() { final ArrayList<Deferred<Object>> checks = new ArrayList<Deferred<Object>>(2); checks.add(client.ensureTableExists( config.getString("tsd.storage.hbase.data_table"))); checks.add(client.ensureTableExists( config.getString("tsd.storage.hbase.uid_table"))); if (config.enable_tree_processing()) { checks.add(client.ensureTableExists( config.getString("tsd.storage.hbase.tree_table"))); } if (config.enable_realtime_ts() || config.enable_realtime_uid() || config.enable_tsuid_incrementing()) { checks.add(client.ensureTableExists( config.getString("tsd.storage.hbase.meta_table"))); } return Deferred.group(checks); } /** Number of cache hits during lookups involving UIDs. */ public int uidCacheHits() { return (metrics.cacheHits() + tag_names.cacheHits() + tag_values.cacheHits()); } /** Number of cache misses during lookups involving UIDs. */ public int uidCacheMisses() { return (metrics.cacheMisses() + tag_names.cacheMisses() + tag_values.cacheMisses()); } /** Number of cache entries currently in RAM for lookups involving UIDs. */ public int uidCacheSize() { return (metrics.cacheSize() + tag_names.cacheSize() + tag_values.cacheSize()); } /** * Collects the stats and metrics tracked by this instance. * @param collector The collector to use. */ public void collectStats(final StatsCollector collector) { final byte[][] kinds = { METRICS_QUAL.getBytes(CHARSET), TAG_NAME_QUAL.getBytes(CHARSET), TAG_VALUE_QUAL.getBytes(CHARSET) }; try { final Map<String, Long> used_uids = UniqueId.getUsedUIDs(this, kinds) .joinUninterruptibly(); collectUidStats(metrics, collector); collector.record("uid.ids-used", used_uids.get(METRICS_QUAL), "kind=" + METRICS_QUAL); collector.record("uid.ids-available", (metrics.maxPossibleId() - used_uids.get(METRICS_QUAL)), "kind=" + METRICS_QUAL); collectUidStats(tag_names, collector); collector.record("uid.ids-used", used_uids.get(TAG_NAME_QUAL), "kind=" + TAG_NAME_QUAL); collector.record("uid.ids-available", (tag_names.maxPossibleId() - used_uids.get(TAG_NAME_QUAL)), "kind=" + TAG_NAME_QUAL); collectUidStats(tag_values, collector); collector.record("uid.ids-used", used_uids.get(TAG_VALUE_QUAL), "kind=" + TAG_VALUE_QUAL); collector.record("uid.ids-available", (tag_values.maxPossibleId() - used_uids.get(TAG_VALUE_QUAL)), "kind=" + TAG_VALUE_QUAL); } catch (Exception e) { throw new RuntimeException("Shouldn't be here", e); } { final Runtime runtime = Runtime.getRuntime(); collector.record("jvm.ramfree", runtime.freeMemory()); collector.record("jvm.ramused", runtime.totalMemory()); } collector.addExtraTag("class", "IncomingDataPoints"); try { collector.record("hbase.latency", IncomingDataPoints.putlatency, "method=put"); } finally { collector.clearExtraTag("class"); } collector.addExtraTag("class", "TsdbQuery"); try { collector.record("hbase.latency", TsdbQuery.scanlatency, "method=scan"); } finally { collector.clearExtraTag("class"); } final ClientStats stats = client.stats(); collector.record("hbase.root_lookups", stats.rootLookups()); collector.record("hbase.meta_lookups", stats.uncontendedMetaLookups(), "type=uncontended"); collector.record("hbase.meta_lookups", stats.contendedMetaLookups(), "type=contended"); collector.record("hbase.rpcs", stats.atomicIncrements(), "type=increment"); collector.record("hbase.rpcs", stats.deletes(), "type=delete"); collector.record("hbase.rpcs", stats.gets(), "type=get"); collector.record("hbase.rpcs", stats.puts(), "type=put"); collector.record("hbase.rpcs", stats.rowLocks(), "type=rowLock"); collector.record("hbase.rpcs", stats.scannersOpened(), "type=openScanner"); collector.record("hbase.rpcs", stats.scans(), "type=scan"); collector.record("hbase.rpcs.batched", stats.numBatchedRpcSent()); collector.record("hbase.flushes", stats.flushes()); collector.record("hbase.connections.created", stats.connectionsCreated()); collector.record("hbase.nsre", stats.noSuchRegionExceptions()); collector.record("hbase.nsre.rpcs_delayed", stats.numRpcDelayedDueToNSRE()); compactionq.collectStats(collector); // Collect Stats from Plugins if (rt_publisher != null) { try { collector.addExtraTag("plugin", "publish"); rt_publisher.collectStats(collector); } finally { collector.clearExtraTag("plugin"); } } if (search != null) { try { collector.addExtraTag("plugin", "search"); search.collectStats(collector); } finally { collector.clearExtraTag("plugin"); } } if (rpc_plugins != null) { try { collector.addExtraTag("plugin", "rpc"); for(RpcPlugin rpc: rpc_plugins) { rpc.collectStats(collector); } } finally { collector.clearExtraTag("plugin"); } } } /** Returns a latency histogram for Put RPCs used to store data points. */ public Histogram getPutLatencyHistogram() { return IncomingDataPoints.putlatency; } /** Returns a latency histogram for Scan RPCs used to fetch data points. */ public Histogram getScanLatencyHistogram() { return TsdbQuery.scanlatency; } /** * Collects the stats for a {@link UniqueId}. * @param uid The instance from which to collect stats. * @param collector The collector to use. */ private static void collectUidStats(final UniqueId uid, final StatsCollector collector) { collector.record("uid.cache-hit", uid.cacheHits(), "kind=" + uid.kind()); collector.record("uid.cache-miss", uid.cacheMisses(), "kind=" + uid.kind()); collector.record("uid.cache-size", uid.cacheSize(), "kind=" + uid.kind()); } /** @return the width, in bytes, of metric UIDs */ public static short metrics_width() { return METRICS_WIDTH; } /** @return the width, in bytes, of tagk UIDs */ public static short tagk_width() { return TAG_NAME_WIDTH; } /** @return the width, in bytes, of tagv UIDs */ public static short tagv_width() { return TAG_VALUE_WIDTH; } /** * Returns a new {@link Query} instance suitable for this TSDB. */ public Query newQuery() { return new TsdbQuery(this); } /** * Returns a new {@link WritableDataPoints} instance suitable for this TSDB. * <p> * If you want to add a single data-point, consider using {@link #addPoint} * instead. */ public WritableDataPoints newDataPoints() { return new IncomingDataPoints(this); } public Deferred<Object> addPoint(final String metric, final long timestamp, final long value, final Map<String, String> tags) { final byte[] v; if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE) { v = new byte[] { (byte) value }; } else if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE) { v = Bytes.fromShort((short) value); } else if (Integer.MIN_VALUE <= value && value <= Integer.MAX_VALUE) { v = Bytes.fromInt((int) value); } else { v = Bytes.fromLong(value); } final short flags = (short) (v.length - 1); // Just the length. return addPointInternal(metric, timestamp, v, tags, flags); } public Deferred<Object> addPoint(final String metric, final long timestamp, final double value, final Map<String, String> tags) { if (Double.isNaN(value) || Double.isInfinite(value)) { throw new IllegalArgumentException("value is NaN or Infinite: " + value + " for metric=" + metric + " timestamp=" + timestamp); } final short flags = Const.FLAG_FLOAT | 0x7; // A float stored on 8 bytes. return addPointInternal(metric, timestamp, Bytes.fromLong(Double.doubleToRawLongBits(value)), tags, flags); } public Deferred<Object> addPoint(final String metric, final long timestamp, final float value, final Map<String, String> tags) { if (Float.isNaN(value) || Float.isInfinite(value)) { throw new IllegalArgumentException("value is NaN or Infinite: " + value + " for metric=" + metric + " timestamp=" + timestamp); } final short flags = Const.FLAG_FLOAT | 0x3; // A float stored on 4 bytes. return addPointInternal(metric, timestamp, Bytes.fromInt(Float.floatToRawIntBits(value)), tags, flags); } private Deferred<Object> addPointInternal(final String metric, final long timestamp, final byte[] value, final Map<String, String> tags, final short flags) { // we only accept positive unix epoch timestamps in seconds or milliseconds if (timestamp < 0 || ((timestamp & Const.SECOND_MASK) != 0 && timestamp > 9999999999999L)) { throw new IllegalArgumentException((timestamp < 0 ? "negative " : "bad") + " timestamp=" + timestamp + " when trying to add value=" + Arrays.toString(value) + '/' + flags + " to metric=" + metric + ", tags=" + tags); } IncomingDataPoints.checkMetricAndTags(metric, tags); final byte[] row = IncomingDataPoints.rowKeyTemplate(this, metric, tags); final long base_time; final byte[] qualifier = Internal.buildQualifier(timestamp, flags); if ((timestamp & Const.SECOND_MASK) != 0) { // drop the ms timestamp to seconds to calculate the base timestamp base_time = ((timestamp / 1000) - ((timestamp / 1000) % Const.MAX_TIMESPAN)); } else { base_time = (timestamp - (timestamp % Const.MAX_TIMESPAN)); } Bytes.setInt(row, (int) base_time, metrics.width()); scheduleForCompaction(row, (int) base_time); final PutRequest point = new PutRequest(table, row, FAMILY, qualifier, value); // TODO(tsuna): Add a callback to time the latency of HBase and store the // timing in a moving Histogram (once we have a class for this). Deferred<Object> result = client.put(point); if (!config.enable_realtime_ts() && !config.enable_tsuid_incrementing() && !config.enable_tsuid_tracking() && rt_publisher == null) { return result; } final byte[] tsuid = UniqueId.getTSUIDFromKey(row, METRICS_WIDTH, Const.TIMESTAMP_BYTES); // for busy TSDs we may only enable TSUID tracking, storing a 1 in the // counter field for a TSUID with the proper timestamp. If the user would // rather have TSUID incrementing enabled, that will trump the PUT if (config.enable_tsuid_tracking() && !config.enable_tsuid_incrementing()) { final PutRequest tracking = new PutRequest(meta_table, tsuid, TSMeta.FAMILY(), TSMeta.COUNTER_QUALIFIER(), Bytes.fromLong(1)); client.put(tracking); } else if (config.enable_tsuid_incrementing() || config.enable_realtime_ts()) { TSMeta.incrementAndGetCounter(TSDB.this, tsuid); } if (rt_publisher != null) { rt_publisher.sinkDataPoint(metric, timestamp, value, tags, tsuid, flags); } return result; } /** * Forces a flush of any un-committed in memory data including left over * compactions. * <p> * For instance, any data point not persisted will be sent to HBase. * @return A {@link Deferred} that will be called once all the un-committed * data has been successfully and durably stored. The value of the deferred * object return is meaningless and unspecified, and can be {@code null}. * @throws HBaseException (deferred) if there was a problem sending * un-committed data to HBase. Please refer to the {@link HBaseException} * hierarchy to handle the possible failures. Some of them are easily * recoverable by retrying, some are not. */ public Deferred<Object> flush() throws HBaseException { final class HClientFlush implements Callback<Object, ArrayList<Object>> { public Object call(final ArrayList<Object> args) { return client.flush(); } public String toString() { return "flush HBase client"; } } return config.enable_compactions() && compactionq != null ? compactionq.flush().addCallback(new HClientFlush()) : client.flush(); } /** * Gracefully shuts down this TSD instance. * <p> * The method must call {@code shutdown()} on all plugins as well as flush the * compaction queue. * @return A {@link Deferred} that will be called once all the un-committed * data has been successfully and durably stored, and all resources used by * this instance have been released. The value of the deferred object * return is meaningless and unspecified, and can be {@code null}. * @throws HBaseException (deferred) if there was a problem sending * un-committed data to HBase. Please refer to the {@link HBaseException} * hierarchy to handle the possible failures. Some of them are easily * recoverable by retrying, some are not. */ public Deferred<Object> shutdown() { final ArrayList<Deferred<Object>> deferreds = new ArrayList<Deferred<Object>>(); final class HClientShutdown implements Callback<Object, ArrayList<Object>> { public Object call(final ArrayList<Object> args) { return client.shutdown(); } public String toString() { return "shutdown HBase client"; } } final class ShutdownErrback implements Callback<Object, Exception> { public Object call(final Exception e) { final Logger LOG = LoggerFactory.getLogger(ShutdownErrback.class); if (e instanceof DeferredGroupException) { final DeferredGroupException ge = (DeferredGroupException) e; for (final Object r : ge.results()) { if (r instanceof Exception) { LOG.error("Failed to shutdown the TSD", (Exception) r); } } } else { LOG.error("Failed to shutdown the TSD", e); } return client.shutdown(); } public String toString() { return "shutdown HBase client after error"; } } final class CompactCB implements Callback<Object, ArrayList<Object>> { public Object call(ArrayList<Object> compactions) throws Exception { return null; } } if (config.enable_compactions()) { LOG.info("Flushing compaction queue"); deferreds.add(compactionq.flush().addCallback(new CompactCB())); } if (search != null) { LOG.info("Shutting down search plugin: " + search.getClass().getCanonicalName()); deferreds.add(search.shutdown()); } if (rt_publisher != null) { LOG.info("Shutting down RT plugin: " + rt_publisher.getClass().getCanonicalName()); deferreds.add(rt_publisher.shutdown()); } if (rpc_plugins != null && !rpc_plugins.isEmpty()) { for (final RpcPlugin rpc : rpc_plugins) { LOG.info("Shutting down RPC plugin: " + rpc.getClass().getCanonicalName()); deferreds.add(rpc.shutdown()); } } // wait for plugins to shutdown before we close the client return deferreds.size() > 0 ? Deferred.group(deferreds).addCallbacks(new HClientShutdown(), new ShutdownErrback()) : client.shutdown(); } /** * Given a prefix search, returns a few matching metric names. * @param search A prefix to search. */ public List<String> suggestMetrics(final String search) { return metrics.suggest(search); } /** * Given a prefix search, returns matching metric names. * @param search A prefix to search. * @param max_results Maximum number of results to return. * @since 2.0 */ public List<String> suggestMetrics(final String search, final int max_results) { return metrics.suggest(search, max_results); } /** * Given a prefix search, returns a few matching tag names. * @param search A prefix to search. */ public List<String> suggestTagNames(final String search) { return tag_names.suggest(search); } /** * Given a prefix search, returns matching tagk names. * @param search A prefix to search. * @param max_results Maximum number of results to return. * @since 2.0 */ public List<String> suggestTagNames(final String search, final int max_results) { return tag_names.suggest(search, max_results); } /** * Given a prefix search, returns a few matching tag values. * @param search A prefix to search. */ public List<String> suggestTagValues(final String search) { return tag_values.suggest(search); } /** * Given a prefix search, returns matching tag values. * @param search A prefix to search. * @param max_results Maximum number of results to return. * @since 2.0 */ public List<String> suggestTagValues(final String search, final int max_results) { return tag_values.suggest(search, max_results); } /** * Discards all in-memory caches. * @since 1.1 */ public void dropCaches() { metrics.dropCaches(); tag_names.dropCaches(); tag_values.dropCaches(); } public byte[] assignUid(final String type, final String name) { Tags.validateString(type, name); if (type.toLowerCase().equals("metric")) { try { final byte[] uid = this.metrics.getId(name); throw new IllegalArgumentException("Name already exists with UID: " + UniqueId.uidToString(uid)); } catch (NoSuchUniqueName nsue) { return this.metrics.getOrCreateId(name); } } else if (type.toLowerCase().equals("tagk")) { try { final byte[] uid = this.tag_names.getId(name); throw new IllegalArgumentException("Name already exists with UID: " + UniqueId.uidToString(uid)); } catch (NoSuchUniqueName nsue) { return this.tag_names.getOrCreateId(name); } } else if (type.toLowerCase().equals("tagv")) { try { final byte[] uid = this.tag_values.getId(name); throw new IllegalArgumentException("Name already exists with UID: " + UniqueId.uidToString(uid)); } catch (NoSuchUniqueName nsue) { return this.tag_values.getOrCreateId(name); } } else { LOG.warn("Unknown type name: " + type); throw new IllegalArgumentException("Unknown type name"); } } /** @return the name of the UID table as a byte array for client requests */ public byte[] uidTable() { return this.uidtable; } /** @return the name of the data table as a byte array for client requests */ public byte[] dataTable() { return this.table; } /** @return the name of the tree table as a byte array for client requests */ public byte[] treeTable() { return this.treetable; } /** @return the name of the meta table as a byte array for client requests */ public byte[] metaTable() { return this.meta_table; } /** * Index the given timeseries meta object via the configured search plugin * @param meta The meta data object to index * @since 2.0 */ public void indexTSMeta(final TSMeta meta) { if (search != null) { search.indexTSMeta(meta).addErrback(new PluginError()); } } /** * Delete the timeseries meta object from the search index * @param tsuid The TSUID to delete * @since 2.0 */ public void deleteTSMeta(final String tsuid) { if (search != null) { search.deleteTSMeta(tsuid).addErrback(new PluginError()); } } /** * Index the given UID meta object via the configured search plugin * @param meta The meta data object to index * @since 2.0 */ public void indexUIDMeta(final UIDMeta meta) { if (search != null) { search.indexUIDMeta(meta).addErrback(new PluginError()); } } /** * Delete the UID meta object from the search index * @param meta The UID meta object to delete * @since 2.0 */ public void deleteUIDMeta(final UIDMeta meta) { if (search != null) { search.deleteUIDMeta(meta).addErrback(new PluginError()); } } /** * Index the given Annotation object via the configured search plugin * @param note The annotation object to index * @since 2.0 */ public void indexAnnotation(final Annotation note) { if (search != null) { search.indexAnnotation(note).addErrback(new PluginError()); } if( rt_publisher != null ) { rt_publisher.publishAnnotation(note); } } /** * Delete the annotation object from the search index * @param note The annotation object to delete * @since 2.0 */ public void deleteAnnotation(final Annotation note) { if (search != null) { search.deleteAnnotation(note).addErrback(new PluginError()); } } /** * Processes the TSMeta through all of the trees if configured to do so * @param meta The meta data to process * @since 2.0 */ public Deferred<Boolean> processTSMetaThroughTrees(final TSMeta meta) { if (config.enable_tree_processing()) { return TreeBuilder.processAllTrees(this, meta); } return Deferred.fromResult(false); } public Deferred<SearchQuery> executeSearch(final SearchQuery query) { if (search == null) { throw new IllegalStateException( "Searching has not been enabled on this TSD"); } return search.executeQuery(query); } /** * Simply logs plugin errors when they're thrown by attaching as an errorback. * Without this, exceptions will just disappear (unless logged by the plugin) * since we don't wait for a result. */ final class PluginError implements Callback<Object, Exception> { @Override public Object call(final Exception e) throws Exception { LOG.error("Exception from Search plugin indexer", e); return null; } } // Compaction helpers // final KeyValue compact(final ArrayList<KeyValue> row, List<Annotation> annotations) { return compactionq.compact(row, annotations); } /** * Schedules the given row key for later re-compaction. * Once this row key has become "old enough", we'll read back all the data * points in that row, write them back to HBase in a more compact fashion, * and delete the individual data points. * @param row The row key to re-compact later. Will not be modified. * @param base_time The 32-bit unsigned UNIX timestamp. */ final void scheduleForCompaction(final byte[] row, final int base_time) { if (config.enable_compactions()) { compactionq.add(row); } } // HBase operations helpers // /** Gets the entire given row from the data table. */ final Deferred<ArrayList<KeyValue>> get(final byte[] key) { return client.get(new GetRequest(table, key)); } /** Puts the given value into the data table. */ final Deferred<Object> put(final byte[] key, final byte[] qualifier, final byte[] value) { return client.put(new PutRequest(table, key, FAMILY, qualifier, value)); } /** Deletes the given cells from the data table. */ final Deferred<Object> delete(final byte[] key, final byte[][] qualifiers) { return client.delete(new DeleteRequest(table, key, FAMILY, qualifiers)); } }
package com.openxc; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import com.openxc.sinks.DataSinkException; import android.app.Service; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.os.Binder; import android.os.IBinder; import android.os.RemoteException; import android.preference.PreferenceManager; import android.util.Log; import com.google.common.base.Objects; import com.openxc.measurements.AcceleratorPedalPosition; import com.openxc.measurements.BaseMeasurement; import com.openxc.measurements.BrakePedalStatus; import com.openxc.measurements.EngineSpeed; import com.openxc.measurements.FineOdometer; import com.openxc.measurements.FuelConsumed; import com.openxc.measurements.FuelLevel; import com.openxc.measurements.HeadlampStatus; import com.openxc.measurements.HighBeamStatus; import com.openxc.measurements.IgnitionStatus; import com.openxc.measurements.Latitude; import com.openxc.measurements.Longitude; import com.openxc.measurements.Measurement; import com.openxc.measurements.Odometer; import com.openxc.measurements.ParkingBrakeStatus; import com.openxc.measurements.SteeringWheelAngle; import com.openxc.measurements.TorqueAtTransmission; import com.openxc.measurements.TransmissionGearPosition; import com.openxc.measurements.UnrecognizedMeasurementTypeException; import com.openxc.measurements.VehicleButtonEvent; import com.openxc.measurements.VehicleDoorStatus; import com.openxc.measurements.VehicleSpeed; import com.openxc.measurements.WindshieldWiperStatus; import com.openxc.measurements.TurnSignalStatus; import com.openxc.NoValueException; import com.openxc.remote.RawMeasurement; import com.openxc.remote.VehicleServiceException; import com.openxc.remote.VehicleServiceInterface; import com.openxc.sinks.FileRecorderSink; import com.openxc.sinks.MeasurementListenerSink; import com.openxc.sinks.MockedLocationSink; import com.openxc.sinks.UploaderSink; import com.openxc.sinks.VehicleDataSink; import com.openxc.sources.NativeLocationSource; import com.openxc.sources.RemoteListenerSource; import com.openxc.sources.SourceCallback; import com.openxc.sources.VehicleDataSource; import com.openxc.sources.usb.UsbVehicleDataSource; import com.openxc.util.AndroidFileOpener; /** * The VehicleManager is an in-process Android service and the primary entry * point into the OpenXC library. * * An OpenXC application should bind to this service and request vehicle * measurements through it either synchronously or asynchronously. The service * will shut down when no more clients are bound to it. * * Synchronous measurements are obtained by passing the type of the desired * measurement to the get method. Asynchronous measurements are obtained by * defining a Measurement.Listener object and passing it to the service via the * addListener method. * * The sources of data and any post-processing that happens is controlled by * modifying a list of "sources" and "sinks". When a message is received from a * data source, it is passed to any and all registered message "sinks" - these * receivers conform to the {@link com.openxc.sinks.VehicleDataSinkInterface}. * There will always be at least one sink that stores the latest messages and * handles passing on data to users of the VehicleManager class. Other possible * sinks include the {@link com.openxc.sinks.FileRecorderSink} which records a * trace of the raw OpenXC measurements to a file and a web streaming sink * (which streams the raw data to a web application). Other possible sources * include the {@link com.openxc.sources.TraceVehicleDataSource} which reads a * previously recorded vehicle data trace file and plays back the measurements * in real-time. */ public class VehicleManager extends Service implements SourceCallback { public final static String VEHICLE_LOCATION_PROVIDER = MockedLocationSink.VEHICLE_LOCATION_PROVIDER; private final static String TAG = "VehicleManager"; private boolean mIsBound; private Lock mRemoteBoundLock; private Condition mRemoteBoundCondition; private PreferenceListener mPreferenceListener; private SharedPreferences mPreferences; private IBinder mBinder = new VehicleBinder(); private VehicleServiceInterface mRemoteService; private DataPipeline mPipeline; private RemoteListenerSource mRemoteSource; private VehicleDataSink mFileRecorder; private VehicleDataSource mNativeLocationSource; private VehicleDataSink mUploader; private MeasurementListenerSink mNotifier; // The DataPipeline in this class must only have 1 source - the special // RemoteListenerSource that receives measurements from the // VehicleService and propagates them to all of the user-registered // sinks. Any user-registered sources must live in a separate array, // unfortunately, so they don't try to circumvent the VehicleService // and send their values directly to the in-process sinks (otherwise no // other applications could receive updates from that source). For most // applications that might be fine, but since we want to control trace // playback from the Enabler, it needs to be able to inject those into the // RVS. TODO actually, maybe that's the only case. If there are no other // cases where a user application should be able to inject source data for // all other apps to share, we should reconsider this and special case the // trace source. private CopyOnWriteArrayList<VehicleDataSource> mSources; // TODO I've tried really hard to avoid doing this - requiring that all // measurements classes be registered somewhere. There doesn't seem to be a // good way to enumerate all of the classes without reading the filesystem. // The problem is that we need to be able to map from a measurement's ID to // its class and vice versa. We need *someone* to refer to to Class in Java // before we can load its ID. Since we reworked the sources and sinks to be // in application space, and the file trace recorder and uploader need to // receive all measurements regardless of if someone has actually registered // to receive callbacks for that measurement or not, we need to pre-load the // name mapping cache before doing anything. private static List<Class<? extends Measurement>> MEASUREMENT_TYPES = new ArrayList<Class<? extends Measurement>>(); static { MEASUREMENT_TYPES.add(AcceleratorPedalPosition.class); MEASUREMENT_TYPES.add(BrakePedalStatus.class); MEASUREMENT_TYPES.add(EngineSpeed.class); MEASUREMENT_TYPES.add(FineOdometer.class); MEASUREMENT_TYPES.add(FuelConsumed.class); MEASUREMENT_TYPES.add(FuelLevel.class); MEASUREMENT_TYPES.add(HeadlampStatus.class); MEASUREMENT_TYPES.add(HighBeamStatus.class); MEASUREMENT_TYPES.add(IgnitionStatus.class); MEASUREMENT_TYPES.add(Latitude.class); MEASUREMENT_TYPES.add(Longitude.class); MEASUREMENT_TYPES.add(Odometer.class); MEASUREMENT_TYPES.add(ParkingBrakeStatus.class); MEASUREMENT_TYPES.add(TorqueAtTransmission.class); MEASUREMENT_TYPES.add(SteeringWheelAngle.class); MEASUREMENT_TYPES.add(TransmissionGearPosition.class); MEASUREMENT_TYPES.add(VehicleButtonEvent.class); MEASUREMENT_TYPES.add(VehicleDoorStatus.class); MEASUREMENT_TYPES.add(VehicleSpeed.class); MEASUREMENT_TYPES.add(WindshieldWiperStatus.class); MEASUREMENT_TYPES.add(TurnSignalStatus.class); for(Class<? extends Measurement> measurementType : MEASUREMENT_TYPES) { try { BaseMeasurement.getIdForClass(measurementType); } catch(UnrecognizedMeasurementTypeException e) { Log.w(TAG, "Unable to initialize list of measurements", e); } } } /** * Binder to connect IBinder in a ServiceConnection with the VehicleManager. * * This class is used in the onServiceConnected method of a * ServiceConnection in a client of this service - the IBinder given to the * application can be cast to the VehicleBinder to retrieve the * actual service instance. This is required to actaully call any of its * methods. */ public class VehicleBinder extends Binder { /* * Return this Binder's parent VehicleManager instance. * * @return an instance of VehicleManager. */ public VehicleManager getService() { return VehicleManager.this; } } /** * Block until the VehicleManager is alive and can return measurements. * * Most applications don't need this and don't wait this method, but it can * be useful for testing when you need to make sure you will get a * measurement back from the system. */ public void waitUntilBound() { mRemoteBoundLock.lock(); Log.i(TAG, "Waiting for the VehicleService to bind to " + this); while(!mIsBound) { try { mRemoteBoundCondition.await(); } catch(InterruptedException e) {} } Log.i(TAG, mRemoteService + " is now bound"); mRemoteBoundLock.unlock(); } @Override public void onCreate() { super.onCreate(); Log.i(TAG, "Service starting"); mRemoteBoundLock = new ReentrantLock(); mRemoteBoundCondition = mRemoteBoundLock.newCondition(); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); mPreferenceListener = watchPreferences(mPreferences); mPipeline = new DataPipeline(); mNotifier = new MeasurementListenerSink(); mPipeline.addSink(mNotifier); mSources = new CopyOnWriteArrayList<VehicleDataSource>(); bindRemote(); } @Override public void onDestroy() { super.onDestroy(); Log.i(TAG, "Service being destroyed"); if(mPipeline != null) { mPipeline.stop(); } unwatchPreferences(mPreferences, mPreferenceListener); unbindRemote(); } @Override public IBinder onBind(Intent intent) { Log.i(TAG, "Service binding in response to " + intent); bindRemote(); return mBinder; } /** * Retrieve the most current value of a measurement. * * Regardless of if a measurement is available or not, return a * Measurement instance of the specified type. The measurement can be * checked to see if it has a value. * * @param measurementType The class of the requested Measurement * (e.g. VehicleSpeed.class) * @return An instance of the requested Measurement which may or may * not have a value. * @throws UnrecognizedMeasurementTypeException if passed a measurementType * that does not extend Measurement * @throws NoValueException if no value has yet been received for this * measurementType * @see BaseMeasurement */ public Measurement get( Class<? extends Measurement> measurementType) throws UnrecognizedMeasurementTypeException, NoValueException { if(mRemoteService == null) { Log.w(TAG, "Not connected to the VehicleService "throwing a NoValueException"); throw new NoValueException(); } Log.d(TAG, "Looking up measurement for " + measurementType); try { RawMeasurement rawMeasurement = mRemoteService.get( BaseMeasurement.getIdForClass(measurementType)); return BaseMeasurement.getMeasurementFromRaw(measurementType, rawMeasurement); } catch(RemoteException e) { Log.w(TAG, "Unable to get value from remote vehicle service", e); throw new NoValueException(); } } /** * Send a command back to the vehicle. * * This fails silently if it is unable to connect to the remote vehicle * service. * * @param command The desired command to send to the vehicle. */ public void set(Measurement command) throws UnrecognizedMeasurementTypeException { if(mRemoteService == null) { Log.w(TAG, "Not connected to the VehicleService"); return; } Log.d(TAG, "Sending command " + command); try { // TODO measurement should know how to convert itself back to raw... // or maybe we don't even need raw in this case. oh wait, we can't // send templated class over AIDL so we do. RawMeasurement rawCommand = new RawMeasurement(command.getGenericName(), command.getSerializedValue(), command.getSerializedEvent()); mRemoteService.set(rawCommand); } catch(RemoteException e) { Log.w(TAG, "Unable to send command to remote vehicle service", e); } } /** * Register to receive async updates for a specific Measurement type. * * Use this method to register an object implementing the * Measurement.Listener interface to receive real-time updates * whenever a new value is received for the specified measurementType. * * @param measurementType The class of the Measurement * (e.g. VehicleSpeed.class) the listener was listening for * @param listener An Measurement.Listener instance that was * previously registered with addListener * @throws VehicleServiceException if the listener is unable to be * unregistered with the library internals - an exceptional situation * that shouldn't occur. * @throws UnrecognizedMeasurementTypeException if passed a measurementType * not extend Measurement */ public void addListener( Class<? extends Measurement> measurementType, Measurement.Listener listener) throws VehicleServiceException, UnrecognizedMeasurementTypeException { Log.i(TAG, "Adding listener " + listener + " to " + measurementType); mNotifier.register(measurementType, listener); } /** * Reset vehicle service to use only the default vehicle sources. * * The default vehicle data source is USB. If a USB CAN translator is not * connected, there will be no more data. * * @throws VehicleServiceException if the listener is unable to be * unregistered with the library internals - an exceptional situation * that shouldn't occur. */ public void initializeDefaultSources() throws VehicleServiceException { Log.i(TAG, "Resetting data sources"); if(mRemoteService != null) { try { mRemoteService.initializeDefaultSources(); } catch(RemoteException e) { throw new VehicleServiceException( "Unable to reset data sources"); } } else { Log.w(TAG, "Can't reset data sources "not connected to remote service yet"); } } public void clearSources() throws VehicleServiceException { Log.i(TAG, "Clearing all data sources"); if(mRemoteService != null) { try { mRemoteService.clearSources(); } catch(RemoteException e) { throw new VehicleServiceException( "Unable to clear data sources"); } } else { Log.w(TAG, "Can't clear all data sources "not connected to remote service yet"); } mSources.clear(); } /** * Unregister a previously reigstered Measurement.Listener instance. * * When an application is no longer interested in received measurement * updates (e.g. when it's pausing or exiting) it should unregister all * previously registered listeners to save on CPU. * * @param measurementType The class of the requested Measurement * (e.g. VehicleSpeed.class) * @param listener An object implementing the Measurement.Listener * interface that should be called with any new measurements. * @throws VehicleServiceException if the listener is unable to be * registered with the library internals - an exceptional situation * that shouldn't occur. * @throws UnrecognizedMeasurementTypeException if passed a class that does * not extend Measurement */ public void removeListener(Class<? extends Measurement> measurementType, Measurement.Listener listener) throws VehicleServiceException { Log.i(TAG, "Removing listener " + listener + " from " + measurementType); mNotifier.unregister(measurementType, listener); } /** * Add a new data source to the vehicle service. * * For example, to use the trace data source to playback a trace file, call * the addSource method after binding with VehicleManager: * * service.addSource(new TraceVehicleDataSource( * new URI("/sdcard/openxc/trace.json")))); * * The {@link UsbVehicleDataSource} exists by default with the default USB * device ID. To clear all existing sources, use the {@link #clearSources()} * method. To revert back to the default set of sources, use * {@link #initializeDefaultSources}. * * @param source an instance of a VehicleDataSource */ public void addSource(VehicleDataSource source) { Log.i(TAG, "Adding data source " + source); source.setCallback(this); mSources.add(source); } /** * Remove a previously registered source from the data pipeline. */ public void removeSource(VehicleDataSource source) { if(source != null) { mSources.remove(source); source.stop(); } } /** * Add a new data sink to the vehicle service. * * A data sink added with this method will receive all new measurements as * they arrive from registered data sources. For example, to use the trace * file recorder sink, call the addSink method after binding with * VehicleManager: * * service.addSink(new FileRecorderSink( * new AndroidFileOpener("openxc", this))); * * @param sink an instance of a VehicleDataSink */ public void addSink(VehicleDataSink sink) { Log.i(TAG, "Adding data sink " + sink); mPipeline.addSink(sink); } /** * Remove a previously registered sink from the data pipeline. */ public void removeSink(VehicleDataSink sink) { if(sink != null) { mPipeline.removeSink(sink); sink.stop(); } } /** * Enable or disable uploading of a vehicle trace to a remote web server. * * The URL of the web server to upload the trace to is read from the shared * preferences. * * @param enabled true if uploading should be enabled * @throws VehicleServiceException if the listener is unable to be * unregistered with the library internals - an exceptional situation * that shouldn't occur. */ public void enableUploading(boolean enabled) throws VehicleServiceException { Log.i(TAG, "Setting uploading to " + enabled); if(enabled) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); String path = preferences.getString( getString(R.string.uploading_path_key), null); String error = "Target URL in preferences not valid " + "-- not starting uploading a trace"; if(!UploaderSink.validatePath(path)) { Log.w(TAG, error); } else { try { mUploader = mPipeline.addSink(new UploaderSink(this, path)); } catch(java.net.URISyntaxException e) { Log.w(TAG, error, e); } } } else { mPipeline.removeSink(mUploader); } } /** * Enable or disable recording of a trace file. * * @param enabled true if recording should be enabled * @throws VehicleServiceException if the listener is unable to be * unregistered with the library internals - an exceptional * situation that shouldn't occur. */ public void enableRecording(boolean enabled) throws VehicleServiceException { Log.i(TAG, "Setting recording to " + enabled); if(enabled) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); String directory = preferences.getString( getString(R.string.recording_directory_key), null); try { mFileRecorder = mPipeline.addSink(new FileRecorderSink( new AndroidFileOpener(this, directory))); } catch(DataSinkException e) { Log.w(TAG, "Unable to start trace recording", e); } } else { mPipeline.removeSink(mFileRecorder); } } /** * Enable or disable reading GPS from the native Android stack. * * @param enabled true if native GPS should be passed through * @throws VehicleServiceException if the listener is unable to be * unregistered with the library internals - an exceptional situation * that shouldn't occur. */ public void enableNativeGpsPassthrough(boolean enabled) throws VehicleServiceException { Log.i(TAG, "Setting native GPS to " + enabled); if(enabled) { mNativeLocationSource = mPipeline.addSource( new NativeLocationSource(this)); } else if(mNativeLocationSource != null) { mPipeline.removeSource(mNativeLocationSource); mNativeLocationSource = null; } } /** * Read the number of messages received by the vehicle service. * * @throws VehicleServiceException if the listener is unable to be * unregistered with the library internals - an exceptional situation * that shouldn't occur. */ public int getMessageCount() throws VehicleServiceException { if(mRemoteService != null) { try { return mRemoteService.getMessageCount(); } catch(RemoteException e) { throw new VehicleServiceException( "Unable to retrieve message count", e); } } else { throw new VehicleServiceException( "Unable to retrieve message count"); } } @Override public String toString() { return Objects.toStringHelper(this) .add("bound", mIsBound) .toString(); } public void receive(RawMeasurement measurement) { if(mRemoteService != null) { try { mRemoteService.receive(measurement); } catch(RemoteException e) { Log.d(TAG, "Unable to send message to remote service", e); } } } private void setUploadingStatus() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); boolean uploadingEnabled = preferences.getBoolean( getString(R.string.uploading_checkbox_key), false); try { enableUploading(uploadingEnabled); } catch(VehicleServiceException e) { Log.w(TAG, "Unable to set uploading status after binding", e); } } private void setRecordingStatus() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); boolean recordingEnabled = preferences.getBoolean( getString(R.string.recording_checkbox_key), false); try { enableRecording(recordingEnabled); } catch(VehicleServiceException e) { Log.w(TAG, "Unable to set recording status after binding", e); } } private void setNativeGpsStatus() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); boolean nativeGpsEnabled = preferences.getBoolean( getString(R.string.native_gps_checkbox_key), false); try { enableNativeGpsPassthrough(nativeGpsEnabled); } catch(VehicleServiceException e) { Log.w(TAG, "Unable to set native GPS status after binding", e); } } private void unwatchPreferences(SharedPreferences preferences, PreferenceListener listener) { if(preferences != null && listener != null) { preferences.unregisterOnSharedPreferenceChangeListener(listener); } } private PreferenceListener watchPreferences(SharedPreferences preferences) { if(preferences != null) { PreferenceListener listener = new PreferenceListener(); preferences.registerOnSharedPreferenceChangeListener( listener); return listener; } return null; } private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { Log.i(TAG, "Bound to VehicleService"); mRemoteService = VehicleServiceInterface.Stub.asInterface( service); mRemoteSource = new RemoteListenerSource(mRemoteService); mPipeline.addSource(mRemoteSource); setUploadingStatus(); setRecordingStatus(); setNativeGpsStatus(); mRemoteBoundLock.lock(); mIsBound = true; mRemoteBoundCondition.signal(); mRemoteBoundLock.unlock(); } public void onServiceDisconnected(ComponentName className) { Log.w(TAG, "VehicleService disconnected unexpectedly"); mRemoteService = null; mIsBound = false; mPipeline.removeSource(mRemoteSource); } }; private void bindRemote() { Log.i(TAG, "Binding to VehicleService"); Intent intent = new Intent( VehicleServiceInterface.class.getName()); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } private void unbindRemote() { if(mRemoteBoundLock != null) { mRemoteBoundLock.lock(); } if(mIsBound) { Log.i(TAG, "Unbinding from VehicleService"); unbindService(mConnection); mIsBound = false; } if(mRemoteBoundLock != null) { mRemoteBoundLock.unlock(); } } private class PreferenceListener implements SharedPreferences.OnSharedPreferenceChangeListener { public void onSharedPreferenceChanged(SharedPreferences preferences, String key) { if(key.equals(getString(R.string.recording_checkbox_key))) { setRecordingStatus(); } else if(key.equals(getString(R.string.native_gps_checkbox_key))) { setNativeGpsStatus(); } else if(key.equals(getString(R.string.uploading_checkbox_key))) { setUploadingStatus(); } } } }
package br.com.luvva.epolisher.control; import javax.swing.*; import java.io.*; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.*; /** * @author Lima Filho, A. L. - amsterdam@luvva.com.br */ public class Main { private static final String CD_I = "A Criação de Deus (Volume I)"; private static final String CD_III = "A Criação de Deus (Volume III)"; private static final String IJ = "A Infância de Jesus"; private static final String MP = "Mensagens do Pai"; private static final String EXP = "Explicações de Textos das Escrituras Sagradas"; private static final String RB_II = "Roberto Blum (Volume II)"; public static void main (String[] args) { Path oebpsPath = getOEBPSPath(args); if (oebpsPath != null) { File tocFile = getTocFile(oebpsPath); if (tocFile != null) { String bookTitle; try { bookTitle = getBookTitle(tocFile); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error getting bookTitle name: " + e.getMessage()); return; } try { switch (bookTitle) { case CD_I: addChapterNumbersCD_I(tocFile); break; case CD_III: addChapterNumbersCD_III(tocFile); break; case EXP: fixIndex(tocFile); fixAllPageTitles(oebpsPath, "EXP-epub"); break; case IJ: addChapterNumbersInfancia(tocFile); break; case MP: fixIndex(tocFile); fixAllPageTitles(oebpsPath, "MP-epub"); break; case RB_II: addChapterNumbersBlumII(tocFile); break; default: addChapterNumbers(tocFile); } } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error editing toc file: " + e.getMessage()); } } try { FootnoteFileVisitor visitor = new FootnoteFileVisitor(); Files.walkFileTree(oebpsPath, visitor); int footnoteCount = 0; List<Path> sortedPaths = visitor.getSortedPaths(); for (Path sortedPath : sortedPaths) { footnoteCount = polishFootnote(sortedPath, footnoteCount); } } catch (IOException e) { JOptionPane.showMessageDialog(null, "Error editing footnotes: " + e.getMessage()); } } } private static void fixAllPageTitles (Path oebpsPath, String id) { try (DirectoryStream<Path> stream = Files.newDirectoryStream(oebpsPath)) { for (Path chapterFile : stream) { if (chapterFile.getFileName().toString().startsWith(id)) { String inputLine; StringBuilder sb = new StringBuilder(); FileInputStream fis = new FileInputStream(chapterFile.toFile()); try (BufferedReader in = new BufferedReader(new InputStreamReader(fis, "UTF8"))) { while ((inputLine = in.readLine()) != null) { if (inputLine.contains("Epub-TitCapIndice")) { StringBuilder sb1 = new StringBuilder(); boolean reachedATag = false; boolean reachedSecondTrace = false; boolean reachedFirstTrace = false; for (int i = 0; i < inputLine.length(); i++) { String currentChar = inputLine.substring(i, i + 1); if (reachedATag && Objects.equals("/", currentChar)) { sb1.append("/a></p>"); break; } if (reachedATag && !Objects.equals("/", currentChar)) { sb1.append(currentChar); continue; } if (reachedSecondTrace && Objects.equals("<", currentChar)) { sb1.append(currentChar); reachedATag = true; continue; } if (reachedSecondTrace && !Objects.equals("<", currentChar)) { continue; } if (Objects.equals("–", currentChar)) { if (reachedFirstTrace) { reachedSecondTrace = true; sb1.append(currentChar); } else { reachedFirstTrace = true; sb1.append(currentChar); } } else { sb1.append(currentChar); } } sb.append(sb1).append("\n"); } else { sb.append(inputLine).append("\n"); } } } try (BufferedWriter bw = Files.newBufferedWriter(chapterFile)) { bw.write(sb.toString()); } } } } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage()); } } private static String getBookTitle (File tocFile) throws Exception { String inputLine; try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(tocFile), "UTF8"))) { while ((inputLine = in.readLine()) != null) { if (inputLine.matches("\t\t<title>.+</title>")) { return inputLine.replace("</title>", "").replace("<title>", "").replace("\t", ""); } } } throw new NullPointerException("Could not find book's title!"); } private static Path getOEBPSPath (String[] args) { if (args.length == 0) { JOptionPane.showMessageDialog(null, "Specify Epub directory for polishment!"); } else { File epubDirectory = new File(args[0]); if (!epubDirectory.exists()) { JOptionPane.showMessageDialog(null, "Specified Epub directory does not exist!"); } else if (!epubDirectory.isDirectory()) { JOptionPane.showMessageDialog(null, "Choose Epub directory, not a file!"); } else { Path oebps = epubDirectory.toPath().resolve("OEBPS"); File oebpsFile = oebps.toFile(); if (!(oebpsFile.exists() && oebpsFile.isDirectory())) { JOptionPane.showMessageDialog(null, "OEBPS directory could not be resolved!"); } else { return oebps; } } } return null; } private static File getTocFile (Path oebps) { File tocFile = oebps.resolve("toc.xhtml").toFile(); if (!(tocFile.exists() && tocFile.isFile())) { JOptionPane.showMessageDialog(null, "toc.xhtml file could not be resolved!"); } else { return tocFile; } return null; } private static void addChapterNumbersCD_I (File tocFile) throws Exception { String inputLine; StringBuilder sb = new StringBuilder(); int cap = 1; try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(tocFile), "UTF8"))) { while ((inputLine = in.readLine()) != null) { if (inputLine.contains("idParaDest") && !inputLine.contains("PRÓLOGO DO SENHOR") && !inputLine .contains("APÊNDICE")) { sb.append(inputLine.replaceAll("idParaDest-([0-9]+)\">", "idParaDest\\-$1\">" + String.valueOf (cap++) + ". ")) .append("\n"); } else { sb.append(inputLine).append("\n"); } } } try (BufferedWriter bw = Files.newBufferedWriter(tocFile.toPath())) { bw.write(sb.toString()); } } private static void addChapterNumbersCD_III (File tocFile) throws Exception { String inputLine; StringBuilder sb = new StringBuilder(); int cap = 1; try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(tocFile), "UTF8"))) { while ((inputLine = in.readLine()) != null) { if (inputLine.contains("idParaDest") && !inputLine.contains("ANEXO – A FORMAÇÃO")) { sb.append(inputLine.replaceAll("idParaDest-([0-9]+)\">", "idParaDest\\-$1\">" + String.valueOf (cap++) + ". ")) .append("\n"); } else { sb.append(inputLine).append("\n"); } } } try (BufferedWriter bw = Files.newBufferedWriter(tocFile.toPath())) { bw.write(sb.toString()); } } private static void fixIndex (File tocFile) throws Exception { String inputLine; StringBuilder sb = new StringBuilder(); try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(tocFile), "UTF8"))) { while ((inputLine = in.readLine()) != null) { if (inputLine.contains("idParaDest")) { sb.append(inputLine.replaceAll(">– ([0-9]+) –", ">$1. ")).append("\n"); } else { sb.append(inputLine).append("\n"); } } } try (BufferedWriter bw = Files.newBufferedWriter(tocFile.toPath())) { bw.write(sb.toString()); } } private static void addChapterNumbersInfancia (File tocFile) throws Exception { String inputLine; StringBuilder sb = new StringBuilder(); int cap = 1; try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(tocFile), "UTF8"))) { while ((inputLine = in.readLine()) != null) { if (inputLine.contains("idParaDest") && !inputLine.contains("Preâmbulo")) { sb.append(inputLine.replaceAll("idParaDest-([0-9]+)\">", "idParaDest\\-$1\">" + String.valueOf (cap++) + ". ")) .append("\n"); } else { sb.append(inputLine).append("\n"); } } } try (BufferedWriter bw = Files.newBufferedWriter(tocFile.toPath())) { bw.write(sb.toString()); } } private static void addChapterNumbersBlumII (File tocFile) throws Exception { String inputLine; StringBuilder sb = new StringBuilder(); int cap = 151; try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(tocFile), "UTF8"))) { while ((inputLine = in.readLine()) != null) { if (inputLine.contains("idParaDest")) { sb.append(inputLine.replaceAll("idParaDest-([0-9]+)\">", "idParaDest\\-$1\">" + String.valueOf (cap++) + ". ")) .append("\n"); } else { sb.append(inputLine).append("\n"); } } } try (BufferedWriter bw = Files.newBufferedWriter(tocFile.toPath())) { bw.write(sb.toString()); } } private static void addChapterNumbers (File tocFile) throws Exception { String inputLine; StringBuilder sb = new StringBuilder(); try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(tocFile), "UTF8"))) { while ((inputLine = in.readLine()) != null) { if (inputLine.contains("idParaDest")) { sb.append( inputLine.replaceAll("idParaDest-([0-9]+)\">", "idParaDest\\-$1\">$1. ")) .append("\n"); } else { sb.append(inputLine).append("\n"); } } } try (BufferedWriter bw = Files.newBufferedWriter(tocFile.toPath())) { bw.write(sb.toString()); } } private static class FootnoteFileVisitor extends SimpleFileVisitor<Path> { private final List<Path> paths = new ArrayList<>(); @Override public FileVisitResult visitFile (Path path, BasicFileAttributes attrs) throws IOException { if (!attrs.isDirectory() && path.toString().toLowerCase().endsWith(".xhtml")) { paths.add(path); } return FileVisitResult.CONTINUE; } private List<Path> getSortedPaths () { Collections.sort(paths, new ChapterFileSorter()); return paths; } } private static class ChapterFileSorter implements Comparator<Path> { @Override public int compare (Path o1, Path o2) { return Integer.compare(getIndexFromPath(o1), getIndexFromPath(o2)); } private int getIndexFromPath (Path path) { String name = path.toFile().getName(); name = name.replace(".xhtml", ""); if (name.matches(".+-[0-9]+")) { return Integer.valueOf(name.substring(name.lastIndexOf('-') + 1)); } return 0; } } private static int polishFootnote (Path path, int footNoteCount) throws IOException { String inputLine; StringBuilder sb = new StringBuilder(); try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(path.toFile()), "UTF8"))) { while ((inputLine = in.readLine()) != null) { if (inputLine.contains("<div class=\"_idFootnotes\">")) { sb.append(inputLine).append("\n"); sb.append("\t\t\t\t<aside class=\"_idFootnote\" epub:type=\"footnote\">\n"); sb.append("\t\t\t\t\t<p class=\"Epub-texto\"> sb.append("\t\t\t\t</aside>\n"); } else if (inputLine.contains("class=\"Epub-rodape\"")) { if (inputLine.contains("</a>. ")) { sb.append(inputLine.replace("</a>", "</a>" + String.valueOf(++footNoteCount))).append("\n"); } else { sb.append(inputLine.replace("</a>", "</a>" + String.valueOf(++footNoteCount) + ". ")).append ("\n"); } } else { sb.append(inputLine).append("\n"); } } } try (BufferedWriter bw = Files.newBufferedWriter(path)) { bw.write(sb.toString()); } return footNoteCount; } }
package eu.rekawek.coffeegb.memory.cart.type; import eu.rekawek.coffeegb.AddressSpace; import eu.rekawek.coffeegb.memory.cart.battery.Battery; import eu.rekawek.coffeegb.memory.cart.CartridgeType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Mbc1 implements AddressSpace { private static final Logger LOG = LoggerFactory.getLogger(Mbc1.class); private static int[] NINTENDO_LOGO = { 0xCE, 0xED, 0x66, 0x66, 0xCC, 0x0D, 0x00, 0x0B, 0x03, 0x73, 0x00, 0x83, 0x00, 0x0C, 0x00, 0x0D, 0x00, 0x08, 0x11, 0x1F, 0x88, 0x89, 0x00, 0x0E, 0xDC, 0xCC, 0x6E, 0xE6, 0xDD, 0xDD, 0xD9, 0x99, 0xBB, 0xBB, 0x67, 0x63, 0x6E, 0x0E, 0xEC, 0xCC, 0xDD, 0xDC, 0x99, 0x9F, 0xBB, 0xB9, 0x33, 0x3E }; private final CartridgeType type; private final int romBanks; private final int ramBanks; private final int[] cartridge; private final int[] ram; private final Battery battery; private final boolean multicart; private int selectedRamBank; private int selectedRomBank = 1; private int memoryModel; private boolean ramWriteEnabled; private int cachedRomBankFor0x0000 = -1; private int cachedRomBankFor0x4000 = -1; public Mbc1(int[] cartridge, CartridgeType type, Battery battery, int romBanks, int ramBanks) { this.multicart = romBanks == 64 && isMulticart(cartridge); this.cartridge = cartridge; this.ramBanks = ramBanks; this.romBanks = romBanks; this.ram = new int[0x2000 * this.ramBanks]; for (int i = 0; i < ram.length; i++) { ram[i] = 0xff; } this.type = type; this.battery = battery; battery.loadRam(ram); } @Override public boolean accepts(int address) { return (address >= 0x0000 && address < 0x8000) || (address >= 0xa000 && address < 0xc000); } @Override public void setByte(int address, int value) { if (address >= 0x0000 && address < 0x2000) { ramWriteEnabled = (value & 0b1010) != 0; if (!ramWriteEnabled) { battery.saveRam(ram); } LOG.trace("RAM write: {}", ramWriteEnabled); } else if (address >= 0x2000 && address < 0x4000) { LOG.trace("Low 5 bits of ROM bank: {}", (value & 0b00011111)); int bank = selectedRomBank & 0b01100000; bank = bank | (value & 0b00011111); selectRomBank(bank); cachedRomBankFor0x0000 = cachedRomBankFor0x4000 = -1; } else if (address >= 0x4000 && address < 0x6000 && memoryModel == 0) { LOG.trace("High 2 bits of ROM bank: {}", ((value & 0b11) << 5)); int bank = selectedRomBank & 0b00011111; bank = bank | ((value & 0b11) << 5); selectRomBank(bank); cachedRomBankFor0x0000 = cachedRomBankFor0x4000 = -1; } else if (address >= 0x4000 && address < 0x6000 && memoryModel == 1) { LOG.trace("RAM bank: {}", (value & 0b11)); int bank = value & 0b11; selectedRamBank = bank; cachedRomBankFor0x0000 = cachedRomBankFor0x4000 = -1; } else if (address >= 0x6000 && address < 0x8000) { LOG.trace("Memory mode: {}", (value & 1)); memoryModel = value & 1; cachedRomBankFor0x0000 = cachedRomBankFor0x4000 = -1; } else if (address >= 0xa000 && address < 0xc000 && ramWriteEnabled) { int ramAddress = getRamAddress(address); if (ramAddress < ram.length) { ram[ramAddress] = value; } } } private void selectRomBank(int bank) { selectedRomBank = bank; LOG.trace("Selected ROM bank: {}", selectedRomBank); } @Override public int getByte(int address) { if (address >= 0x0000 && address < 0x4000) { return getRomByte(getRomBankFor0x0000(), address); } else if (address >= 0x4000 && address < 0x8000) { return getRomByte(getRomBankFor0x4000(), address - 0x4000); } else if (address >= 0xa000 && address < 0xc000) { if (ramWriteEnabled) { int ramAddress = getRamAddress(address); if (ramAddress < ram.length) { return ram[ramAddress]; } else { return 0xff; } } else { return 0xff; } } else { throw new IllegalArgumentException(Integer.toHexString(address)); } } private int getRomBankFor0x0000() { if (cachedRomBankFor0x0000 == -1) { if (memoryModel == 0) { cachedRomBankFor0x0000 = 0; } else { int bank = (selectedRamBank << 5); if (multicart) { bank >>= 1; } bank %= romBanks; cachedRomBankFor0x0000 = bank; } } return cachedRomBankFor0x0000; } private int getRomBankFor0x4000() { if (cachedRomBankFor0x4000 == -1) { int bank = selectedRomBank; if (bank % 0x20 == 0) { bank++; } if (memoryModel == 1) { bank &= 0b00011111; bank |= (selectedRamBank << 5); } if (multicart) { bank = ((bank >> 1) & 0x30) | (bank & 0x0f); } bank %= romBanks; cachedRomBankFor0x4000 = bank; } return cachedRomBankFor0x4000; } private int getRomByte(int bank, int address) { int cartOffset = bank * 0x4000 + address; if (cartOffset < cartridge.length) { return cartridge[cartOffset]; } else { return 0xff; } } private int getRamAddress(int address) { if (memoryModel == 0) { return address - 0xa000; } else { return (selectedRamBank % ramBanks) * 0x2000 + (address - 0xa000); } } private static boolean isMulticart(int[] rom) { int logoCount = 0; for (int i = 0; i < rom.length; i += 0x4000) { boolean logoMatches = true; for (int j = 0; j < NINTENDO_LOGO.length; j++) { if (rom[i + 0x104 + j] != NINTENDO_LOGO[j]) { logoMatches = false; break; } } if (logoMatches) { logoCount++; } } return logoCount > 1; } }
package org.usfirst.frc.team847.robot; import edu.wpi.first.wpilibj.CANTalon; import edu.wpi.first.wpilibj.Victor; public class DriveTrain implements RobotMap { Victor backMotor; Victor leftMotor; Victor rightMotor; CANTalon turnMotor; GamePad gamePad1; GamePad ferrariWheel; double speedLeft; double speedRight; double speedBack; double radianDirection; double rightRadius; double backRadius; double leftRadius; boolean driveToggleAlreadyPressed; int posDif; public DriveTrain(GamePad driverPad, GamePad steeringWheel) { gamePad1 = driverPad; ferrariWheel = steeringWheel; backMotor = new Victor(BACK_MOTOR); leftMotor = new Victor(LEFT_MOTOR); rightMotor = new Victor(RIGHT_MOTOR); turnMotor = new CANTalon(TURN_MOTOR); leftMotor.setInverted(true); backMotor.set(0); leftMotor.set(0); rightMotor.set(0); driveToggleAlreadyPressed = false; } public void driveController() { double feedsd = gamePad1.quadraticLY(); double feeddir = ferrariWheel.quadraticLX(); //System.out.println("wheel: "+ feeddir); if(ferrariWheel.lBumper()){ if(!driveToggleAlreadyPressed){ feedsd *= -1; feeddir *= -1; } driveToggleAlreadyPressed = true; } else driveToggleAlreadyPressed = false; turnWheel(feeddir); driveWheels(feedsd); } public void testMotor(){ turnMotor.set(0.5); } //This was for testing stuff but it now is dead X |D //ORCAS WILL NEVER DIE :) ORCAS!!!!!!!!!! // NOT This part under it though //"Software Turn" stuff for the Back wheel changing angle public void turnWheel(double direction){ if(direction <= 0) posDif = START_POSITION - MIN_POSITION; else posDif = MAX_POSITION - START_POSITION; int turn = (int)(direction * posDif) + START_POSITION; //System.out.println("turnpot: " + turnMotor.getAnalogInRaw()); moveToTarget(turn); } private void moveToTarget(int targetPosition){ double speed = 0; int currentPosition = turnMotor.getAnalogInRaw(); int distanceToTarget = Math.abs(targetPosition - currentPosition); if(distanceToTarget > 100) speed = 0.5; else if(distanceToTarget > 50) speed = 0.4; else if(distanceToTarget > 30) speed = 0.3; else if(distanceToTarget > 15) speed = 0.2; else if(distanceToTarget > 2) speed = 0.1; else speed = 0; if (currentPosition > targetPosition) speed *= -1; //System.out.println("tspeed: " + speed); turnMotor.set(speed); } public void driveWheels(double speed){ radianDirection = (turnMotor.getAnalogInRaw() - START_POSITION) * Math.PI / (posDif * 2); // Drive Straight code if(Math.abs(radianDirection) <= 0.004){ speedLeft = speed; speedRight = speed; speedBack = speed; } //"Right Turn Code" // gets the wheel speed to change depending on how fast and sharp of a turn you want while turning right else if( radianDirection < 0){ backRadius = FRAME_LENGTH / (Math.sin(Math.abs(radianDirection))); leftRadius = (backRadius * Math.cos(Math.abs(radianDirection))) - (FRAME_WIDTH / 2); rightRadius = (leftRadius + FRAME_WIDTH); } //"Left turn Code" //It dosent change much from the Right turn code else { backRadius = FRAME_LENGTH / (Math.sin(Math.abs(radianDirection))); rightRadius = (backRadius * Math.cos(Math.abs(radianDirection))) - (FRAME_WIDTH / 2); leftRadius = (rightRadius + FRAME_WIDTH); } // Find the maximum radius. This should be the fastest wheel double maxRadius = backRadius; if(Math.abs(maxRadius) < Math.abs(leftRadius)) maxRadius = leftRadius; if(Math.abs(maxRadius) < Math.abs(rightRadius)) maxRadius = rightRadius; // Scale the slower wheels based on the fastest speedBack = speed * (backRadius / maxRadius); speedLeft = speed * (leftRadius / maxRadius); speedRight = speed * (rightRadius / maxRadius); backMotor.set(speedBack); leftMotor.set(speedLeft); rightMotor.set(speedRight); } public void pivot() { if(gamePad1.backB()) { //backMotor.setPosition(-1400); } else if(gamePad1.startB()) { //backMotor.setPosition(1400); } } }
package slavetest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import org.junit.After; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.NotFoundException; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.Transaction; import org.neo4j.helpers.collection.MapUtil; import org.neo4j.kernel.Config; import org.neo4j.kernel.EmbeddedGraphDatabase; import org.neo4j.kernel.HighlyAvailableGraphDatabase; import org.neo4j.kernel.ha.Broker; import org.neo4j.kernel.ha.FakeMasterBroker; import org.neo4j.kernel.ha.FakeSlaveBroker; import org.neo4j.kernel.ha.MasterImpl; public class SingleJvmTest extends AbstractHaTest { private MasterImpl master; private List<GraphDatabaseService> haDbs; protected GraphDatabaseService getSlave( int nr ) { return haDbs.get( nr ); } @Override protected int addDb( Map<String, String> config, boolean awaitStarted ) { haDbs = haDbs != null ? haDbs : new ArrayList<GraphDatabaseService>(); int machineId = haDbs.size()+1; haDbs.add( null ); startDb( machineId, config, awaitStarted ); return machineId; } @Override protected void startDb( int machineId, Map<String, String> config, boolean awaitStarted ) { haDbs = haDbs != null ? haDbs : new ArrayList<GraphDatabaseService>(); File slavePath = dbPath( machineId ); PlaceHolderGraphDatabaseService placeHolderDb = new PlaceHolderGraphDatabaseService( slavePath.getAbsolutePath() ); Broker broker = makeSlaveBroker( master, 0, machineId, placeHolderDb ); Map<String,String> cfg = new HashMap<String, String>(config); cfg.put( HighlyAvailableGraphDatabase.CONFIG_KEY_HA_MACHINE_ID, Integer.toString(machineId) ); cfg.put( Config.KEEP_LOGICAL_LOGS, "true" ); HighlyAvailableGraphDatabase db = new HighlyAvailableGraphDatabase( slavePath.getAbsolutePath(), cfg, wrapBrokerAndSetPlaceHolderDb( placeHolderDb, broker ) ); placeHolderDb.setDb( db ); haDbs.set( machineId-1, db ); } @Override protected void awaitAllStarted() throws Exception { } @Override protected void shutdownDb( int machineId ) { haDbs.get( machineId-1 ).shutdown(); } @Override protected void startUpMaster( Map<String, String> extraConfig ) throws Exception { int masterId = 0; Map<String, String> config = MapUtil.stringMap( extraConfig, HighlyAvailableGraphDatabase.CONFIG_KEY_HA_MACHINE_ID, String.valueOf( masterId ) ); String path = dbPath( 0 ).getAbsolutePath(); PlaceHolderGraphDatabaseService placeHolderDb = new PlaceHolderGraphDatabaseService( path ); Broker broker = makeMasterBroker( master, masterId, placeHolderDb ); HighlyAvailableGraphDatabase db = new HighlyAvailableGraphDatabase( path, config, wrapBrokerAndSetPlaceHolderDb( placeHolderDb, broker ) ); placeHolderDb.setDb( db ); // db.newMaster( null, new Exception() ); master = new MasterImpl( db ); } protected Broker makeMasterBroker( MasterImpl master, int masterId, GraphDatabaseService graphDb ) { return new FakeMasterBroker( masterId, graphDb ); } protected Broker makeSlaveBroker( MasterImpl master, int masterId, int id, GraphDatabaseService graphDb ) { return new FakeSlaveBroker( master, masterId, id, graphDb ); } protected MasterImpl getMaster() { return master; } @Override protected void shutdownDbs() { for ( GraphDatabaseService haDb : haDbs ) { haDb.shutdown(); } master.getGraphDb().shutdown(); } @After public void verifyAndShutdownDbs() { try { verify( master.getGraphDb(), haDbs.toArray( new GraphDatabaseService[haDbs.size()] ) ); } finally { shutdownDbs(); } if ( !shouldDoVerificationAfterTests() ) { return; } GraphDatabaseService masterOfflineDb = new EmbeddedGraphDatabase( dbPath( 0 ).getAbsolutePath() ); GraphDatabaseService[] slaveOfflineDbs = new GraphDatabaseService[haDbs.size()]; for ( int i = 1; i <= haDbs.size(); i++ ) { slaveOfflineDbs[i-1] = new EmbeddedGraphDatabase( dbPath( i ).getAbsolutePath() ); } try { verify( masterOfflineDb, slaveOfflineDbs ); } finally { masterOfflineDb.shutdown(); for ( GraphDatabaseService db : slaveOfflineDbs ) { db.shutdown(); } } } @Override protected <T> T executeJob( Job<T> job, int slave ) throws Exception { return job.execute( haDbs.get( slave ) ); } @Override protected <T> T executeJobOnMaster( Job<T> job ) throws Exception { return job.execute( master.getGraphDb() ); } @Override protected void pullUpdates( int... ids ) { if ( ids.length == 0 ) { for ( GraphDatabaseService db : haDbs ) { ((HighlyAvailableGraphDatabase) db).pullUpdates(); } } else { for ( int id : ids ) { ((HighlyAvailableGraphDatabase) haDbs.get( id )).pullUpdates(); } } } @Test public void testMixingEntitiesFromWrongDbs() throws Exception { initializeDbs( 1 ); GraphDatabaseService haDb1 = haDbs.get( 0 ); GraphDatabaseService mDb = master.getGraphDb(); Transaction tx = mDb.beginTx(); Node masterNode; try { masterNode = mDb.createNode(); mDb.getReferenceNode().createRelationshipTo( masterNode, CommonJobs.REL_TYPE ); tx.success(); } finally { tx.finish(); } tx = haDb1.beginTx(); // try throw in node that does not exist and no tx on mdb try { Node node = haDb1.createNode(); mDb.getReferenceNode().createRelationshipTo( node, CommonJobs.KNOWS ); fail( "Should throw not found exception" ); } catch ( NotFoundException e ) { // good } finally { tx.finish(); } } @Override protected CommonJobs.ShutdownDispatcher getMasterShutdownDispatcher() { return new CommonJobs.ShutdownDispatcher() { public void doShutdown() { master.getGraphDb().shutdown(); } }; } @Override protected Fetcher<DoubleLatch> getDoubleLatch() { return new Fetcher<DoubleLatch>() { private final DoubleLatch latch = new DoubleLatch() { private final CountDownLatch first = new CountDownLatch( 1 ); private final CountDownLatch second = new CountDownLatch( 1 ); public void countDownSecond() { second.countDown(); } public void countDownFirst() { first.countDown(); } public void awaitSecond() { await( second ); } public void awaitFirst() { await( first ); } private void await( CountDownLatch latch ) { try { latch.await(); } catch ( InterruptedException e ) { Thread.interrupted(); e.printStackTrace(); } } }; public DoubleLatch fetch() { return latch; } public void close() { } }; } @Test public void slaveWriteThatOnlyModifyRelationshipRecordsCanUpdateCachedNodeOnMaster() throws Exception { initializeDbs( 1, MapUtil.stringMap( Config.CACHE_TYPE, "strong" ) ); HighlyAvailableGraphDatabase sDb = (HighlyAvailableGraphDatabase) haDbs.get( 0 ); HighlyAvailableGraphDatabase mDb = (HighlyAvailableGraphDatabase) master.getGraphDb(); long relId; Node node; Transaction tx = mDb.beginTx(); try { node = mDb.createNode(); // "pad" the relationship so that removing it doesn't update the node record node.createRelationshipTo( mDb.createNode(), REL_TYPE ); relId = node.createRelationshipTo( mDb.createNode(), REL_TYPE ).getId(); node.createRelationshipTo( mDb.createNode(), REL_TYPE ); tx.success(); } finally { tx.finish(); } // update the slave to make getRelationshipById() work sDb.pullUpdates(); // remove the relationship on the slave tx = sDb.beginTx(); try { sDb.getRelationshipById( relId ).delete(); tx.success(); } finally { tx.finish(); } // verify that the removed relationship is gone from the master int relCount = 0; for ( Relationship rel : node.getRelationships() ) { rel.getOtherNode( node ); relCount++; } assertEquals( "wrong number of relationships", 2, relCount ); } }
package eu.fthevenet.binjr; import eu.fthevenet.util.logging.Profiler; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.stage.Stage; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.awt.*; /** * The entry point fo the application. * * @author Frederic Thevenet */ public class Main extends Application { private static final Logger logger = LogManager.getLogger(Main.class); @Override public void start(Stage primaryStage) throws Exception { logger.info(() -> "Starting binjr"); Parent root = FXMLLoader.load(getClass().getResource("/views/MainView.fxml")); primaryStage.setTitle("binjr"); primaryStage.getIcons().addAll( new Image(getClass().getResourceAsStream("/icons/binjr_16.png")), new Image(getClass().getResourceAsStream("/icons/binjr_32.png")), new Image(getClass().getResourceAsStream("/icons/binjr_48.png")), new Image(getClass().getResourceAsStream("/icons/binjr_128.png")), new Image(getClass().getResourceAsStream("/icons/binjr_256.png"))); try (Profiler p = Profiler.start("Set scene", logger::trace)) { primaryStage.setScene(new Scene(root)); // Application.setUserAgentStylesheet(STYLESHEET_CASPIAN); } try (Profiler p = Profiler.start("show", logger::trace)) { primaryStage.show(); } SplashScreen splash = SplashScreen.getSplashScreen(); if (splash != null) { splash.close(); } } /** * The entry point fo the application. * * @param args the command line arguments */ public static void main(String[] args) { // Disabling accessibility support could work around hanging issue on Windows 10 // System.setProperty("glass.accessible.force", "false"); launch(args); } }
package android.game.guessmynumber; import java.util.Random; import android.app.ActionBar; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.NavUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; public class ResultActivity extends Activity { String []result = new String[4]; TextView mode , userinput , userinputdate , message , highscore , highscoredate; String msg; Settings S; String cardMode; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_result); S = new Settings(getApplicationContext()); mode = (TextView)findViewById(R.id.TextViewMode); userinput = (TextView)findViewById(R.id.TextViewScore); userinputdate = (TextView)findViewById(R.id.TextViewScoreDate); message = (TextView)findViewById(R.id.TextViewMessage); highscore = (TextView)findViewById(R.id.TextViewHighScore); highscoredate = (TextView)findViewById(R.id.TextViewHighScoreDate); cardMode = S.getCardMode(); Bundle extras = getIntent().getExtras(); if (extras != null) { result = extras.getStringArray("result"); } if(cardMode.equals("0")){ Random random = new Random(); int randomNum = random.nextInt((10 - 1) + 1) + 1; if(randomNum < 7){ result[0] = Integer.toString(Integer.parseInt(result[0]) + randomNum); } mode.setText("App Guess"); message.setText("The Secret Number is " + result[0].toString()); userinput.setVisibility(View.GONE); userinputdate.setVisibility(View.GONE); highscore.setVisibility(View.GONE); highscoredate.setVisibility(View.GONE); } else{ mode.setText("User Guess"); userinputdate.setText(result[3].toString()); if(result[1] == null){ msg = "The secret number is " + result[0].toString(); userinput.setText("You didnot enter any answer but took " + result[2].toString() + " Sec"); } else{ userinput.setText("You Entered " + result[1].toString() + " in " + result[2].toString() + " Sec"); if(result[1].toString().equals(result[0].toString())){ msg = "You input " + result[1].toString() + " and secret number is " + result[0].toString()+"\nYou Win"; } else{ msg = "You input " + result[1].toString() + " and secret number is " + result[0].toString()+"\nBetter luck next time"; } } message.setText(msg); highscore.setText("HighScore: 23 Sec"); highscoredate.setText(result[3].toString()); } } @Override /**Diaplay back button only**/ public boolean onCreateOptionsMenu(Menu menu) { ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { // TODO Auto-generated method stub switch(item.getItemId()){ case android.R.id.home: //Intent upIntent = new Intent(this, MainActivity.class); NavUtils.navigateUpFromSameTask(this); return true; } return super.onMenuItemSelected(featureId, item); } }
package com.openxc; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.Set; import com.google.common.base.Objects; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimaps; import com.google.common.collect.Multimap; import com.openxc.measurements.UnrecognizedMeasurementTypeException; import com.openxc.measurements.VehicleMeasurement; import com.openxc.remote.RawMeasurement; import com.openxc.remote.RawMeasurement; import com.openxc.remote.RemoteVehicleServiceException; import com.openxc.remote.RemoteVehicleServiceInterface; import com.openxc.remote.RemoteVehicleServiceListenerInterface; import android.content.Context; import android.app.Service; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Binder; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; /** * The VehicleService is an in-process Android service and the primary entry * point into the OpenXC library. * * An OpenXC application should bind to this service and request vehicle * measurements through it either synchronously or asynchronously. The service * will shut down when no more clients are bound to it. * * Synchronous measurements are obtained by passing the type of the desired * measurement to the get method. * * Asynchronous measurements are obtained by defining a * VehicleMeasurement.Listener object and passing it to the service via the * addListener method. */ public class VehicleService extends Service { private final static String TAG = "VehicleService"; private boolean mIsBound; private Lock mRemoteBoundLock; private Condition mRemoteBoundCondition; private IBinder mBinder = new VehicleServiceBinder(); private RemoteVehicleServiceInterface mRemoteService; private Multimap<Class<? extends VehicleMeasurement>, VehicleMeasurement.Listener> mListeners; private BiMap<String, Class<? extends VehicleMeasurement>> mMeasurementIdToClass; private BiMap<Class<? extends VehicleMeasurement>, String> mMeasurementClassToId; /** * Binder to connect IBinder in a ServiceConnection with the VehicleService. * * This class is used in the onServiceConnected method of a * ServiceConnection in a client of this service - the IBinder given to the * application can be cast to the VehicleServiceBinder to retrieve the * actual service instance. This is required to actaully call any of its * methods. */ public class VehicleServiceBinder extends Binder { /* * Return this Binder's parent VehicleService instance. * * @return an instance of VehicleService. */ public VehicleService getService() { return VehicleService.this; } } /** * Block until the VehicleService is alive and can return measurements. * * Most applications don't need this and don't wait this method, but it can * be useful for testing when you need to make sure you will get a * measurement back from the system. */ public void waitUntilBound() { mRemoteBoundLock.lock(); Log.i(TAG, "Waiting for the RemoteVehicleService to bind to " + this); while(!mIsBound) { try { mRemoteBoundCondition.await(); } catch(InterruptedException e) {} } Log.i(TAG, mRemoteService + " is now bound"); mRemoteBoundLock.unlock(); } @Override public void onCreate() { super.onCreate(); Log.i(TAG, "Service starting"); mRemoteBoundLock = new ReentrantLock(); mRemoteBoundCondition = mRemoteBoundLock.newCondition(); mListeners = HashMultimap.create(); mListeners = Multimaps.synchronizedMultimap(mListeners); mMeasurementIdToClass = HashBiMap.create(); mMeasurementClassToId = HashBiMap.create(); } @Override public void onDestroy() { super.onDestroy(); Log.i(TAG, "Service being destroyed"); unbindRemote(); } @Override public IBinder onBind(Intent intent) { Log.i(TAG, "Service binding in response to " + intent); bindRemote(intent); return mBinder; } /** * Retrieve a VehicleMeasurement from the current data source. * * Regardless of if a measurement is available or not, return a * VehicleMeasurement instance of the specified type. The measurement can be * checked to see if it has a value. * * @param measurementType The class of the requested VehicleMeasurement * (e.g. VehicleSpeed.class) * @return An instance of the requested VehicleMeasurement which may or may * not have a value. * @throws UnrecognizedMeasurementTypeException if passed a measurementType * that does not extend VehicleMeasurement * @see VehicleMeasurement */ public VehicleMeasurement get( Class<? extends VehicleMeasurement> measurementType) throws UnrecognizedMeasurementTypeException { cacheMeasurementId(measurementType); if(mRemoteService == null) { Log.w(TAG, "Not connected to the RemoteVehicleService "returning an empty measurement"); return constructBlankMeasurement(measurementType); } Log.d(TAG, "Looking up measurement for " + measurementType); try { RawMeasurement rawMeasurement = mRemoteService.get( mMeasurementClassToId.get(measurementType)); return getMeasurementFromRaw(measurementType, rawMeasurement); } catch(RemoteException e) { Log.w(TAG, "Unable to get value from remote vehicle service", e); return constructBlankMeasurement(measurementType); } } /** * Register to receive async updates for a specific VehicleMeasurement type. * * Use this method to register an object implementing the * VehicleMeasurement.Listener interface to receive real-time updates * whenever a new value is received for the specified measurementType. * * @param measurementType The class of the VehicleMeasurement * (e.g. VehicleSpeed.class) the listener was listening for * @param listener An VehicleMeasurement.Listener instance that was * previously registered with addListener * @throws RemoteVehicleServiceException if the listener is unable to be * unregistered with the library internals - an exceptional situation * that shouldn't occur. * @throws UnrecognizedMeasurementTypeException if passed a measurementType * not extend VehicleMeasurement */ public void addListener( Class<? extends VehicleMeasurement> measurementType, VehicleMeasurement.Listener listener) throws RemoteVehicleServiceException, UnrecognizedMeasurementTypeException { Log.i(TAG, "Adding listener " + listener + " to " + measurementType); cacheMeasurementId(measurementType); mListeners.put(measurementType, listener); if(mRemoteService != null) { try { mRemoteService.addListener( mMeasurementClassToId.get(measurementType), mRemoteListener); } catch(RemoteException e) { throw new RemoteVehicleServiceException( "Unable to register listener with remote vehicle " + "service", e); } } } /** * Unregister a previously reigstered VehicleMeasurement.Listener instance. * * When an application is no longer interested in received measurement updates (e.g. when it's pausing or exiting) * it should unregister all previously registered listeners to save on CPU. * * @param measurementType The class of the requested VehicleMeasurement * (e.g. VehicleSpeed.class) * @param listener An object implementing the VehicleMeasurement.Listener * interface that should be called with any new measurements. * @throws RemoteVehicleServiceException if the listener is unable to be * registered with the library internals - an exceptional situation that * shouldn't occur. * @throws UnrecognizedMeasurementTypeException if passed a class that does * not extend VehicleMeasurement */ public void removeListener(Class<? extends VehicleMeasurement> measurementType, VehicleMeasurement.Listener listener) throws RemoteVehicleServiceException { Log.i(TAG, "Removing listener " + listener + " from " + measurementType); mListeners.remove(measurementType, listener); if(mRemoteService != null) { try { mRemoteService.removeListener( mMeasurementClassToId.get(measurementType), mRemoteListener); } catch(RemoteException e) { throw new RemoteVehicleServiceException( "Unable to unregister listener from remote " + "vehicle service", e); } } } @Override public String toString() { return Objects.toStringHelper(this) .add("bound", mIsBound) .add("numListeners", mListeners.size()) .toString(); } private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { Log.i(TAG, "Bound to RemoteVehicleService"); mRemoteService = RemoteVehicleServiceInterface.Stub.asInterface( service); mRemoteBoundLock.lock(); mIsBound = true; mRemoteBoundCondition.signal(); mRemoteBoundLock.unlock(); // in case we had listeners registered before the remote service was // connected, sync up here. Set<Class<? extends VehicleMeasurement>> listenerKeys = mListeners.keySet(); for(Class<? extends VehicleMeasurement> key : listenerKeys) { try { mRemoteService.addListener( mMeasurementClassToId.get(key), mRemoteListener); Log.i(TAG, "Added listener " + key + " to remote vehicle service after it started up"); } catch(RemoteException e) { Log.w(TAG, "Unable to register listener with remote " + "vehicle service", e); } } } public void onServiceDisconnected(ComponentName className) { Log.w(TAG, "RemoteVehicleService disconnected unexpectedly"); mRemoteService = null; mIsBound = false; } }; private void cacheMeasurementId( Class<? extends VehicleMeasurement> measurementType) throws UnrecognizedMeasurementTypeException { String measurementId; try { measurementId = (String) measurementType.getField("ID").get( measurementType); mMeasurementIdToClass.put(measurementId, measurementType); } catch(NoSuchFieldException e) { throw new UnrecognizedMeasurementTypeException( measurementType + " doesn't have an ID field", e); } catch(IllegalAccessException e) { throw new UnrecognizedMeasurementTypeException( measurementType + " has an inaccessible ID", e); } mMeasurementClassToId = mMeasurementIdToClass.inverse(); } private RemoteVehicleServiceListenerInterface mRemoteListener = new RemoteVehicleServiceListenerInterface.Stub() { public void receive(String measurementId, RawMeasurement value) { Class<? extends VehicleMeasurement> measurementClass = mMeasurementIdToClass.get(measurementId); VehicleMeasurement measurement; try { measurement = getMeasurementFromRaw(measurementClass, value); } catch(UnrecognizedMeasurementTypeException e) { Log.w(TAG, "Received notification for a malformed " + "measurement type: " + measurementClass, e); return; } // TODO we may want to dump these in a queue handled by another // thread or post runnables to the main handler, sort of like we // do in the RemoteVehicleService. If the listener's receive // blocks...actually it might be OK. // we do this in RVS because the data source would block waiting // for the receive to return before handling another. // in this case we're being called from the handler thread in // RVS...so yeah, we don't want to block. // AppLink posts runnables, but that might create a ton of // objects and be a lot of overhead. the queue method might be // fine, and if we use that we should see if the queue+notifying // thread setup can be abstracted and shared by the two // services. notifyListeners(measurementClass, measurement); } }; private void notifyListeners( Class<? extends VehicleMeasurement> measurementType, VehicleMeasurement measurement) { synchronized(mListeners) { for(VehicleMeasurement.Listener listener : mListeners.get(measurementType)) { listener.receive(measurement); } } } private void bindRemote(Intent triggeringIntent) { Log.i(TAG, "Binding to RemoteVehicleService"); Intent intent = new Intent( RemoteVehicleServiceInterface.class.getName()); intent.putExtras(triggeringIntent); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } private void unbindRemote() { if(mRemoteBoundLock != null) { mRemoteBoundLock.lock(); } if(mIsBound) { Log.i(TAG, "Unbinding from RemoteVehicleService"); unbindService(mConnection); mIsBound = false; } if(mRemoteBoundLock != null) { mRemoteBoundLock.unlock(); } } private VehicleMeasurement constructBlankMeasurement( Class<? extends VehicleMeasurement> measurementType) throws UnrecognizedMeasurementTypeException { try { return measurementType.newInstance(); } catch(InstantiationException e) { throw new UnrecognizedMeasurementTypeException( "No default constructor on given measurement type", e); } catch(IllegalAccessException e) { throw new UnrecognizedMeasurementTypeException( "Default constructor not public on measurement type", e); } } private VehicleMeasurement getMeasurementFromRaw( Class<? extends VehicleMeasurement> measurementType, RawMeasurement rawMeasurement) throws UnrecognizedMeasurementTypeException{ Constructor<? extends VehicleMeasurement> constructor; try { constructor = measurementType.getConstructor(Double.class, Double.class); } catch(NoSuchMethodException e) { constructor = null; } if(constructor == null) { try { constructor = measurementType.getConstructor(Double.class); } catch(NoSuchMethodException e) { throw new UnrecognizedMeasurementTypeException(measurementType + " doesn't have a numerical constructor", e); } } if(rawMeasurement.isValid()) { try { if(rawMeasurement.hasEvent()) { return constructor.newInstance(rawMeasurement.getValue(), rawMeasurement.getEvent()); } else { return constructor.newInstance(rawMeasurement.getValue()); } } catch(InstantiationException e) { throw new UnrecognizedMeasurementTypeException( measurementType + " is abstract", e); } catch(IllegalAccessException e) { throw new UnrecognizedMeasurementTypeException( measurementType + " has a private constructor", e); } catch(InvocationTargetException e) { throw new UnrecognizedMeasurementTypeException( measurementType + "'s constructor threw an exception", e); } } else { Log.d(TAG, rawMeasurement + " isn't valid -- returning a blank measurement"); } return constructBlankMeasurement(measurementType); } }
package br.org.mj.sislegis.app.model; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import javax.xml.bind.annotation.XmlRootElement; import br.org.mj.sislegis.app.enumerated.TipoTarefa; @Entity @Table(name = "tarefa") @XmlRootElement public class Tarefa implements AbstractEntity { private static final long serialVersionUID = -806063711060116952L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", updatable = false, nullable = false) private Long id; @Column(name = "data") @Temporal(TemporalType.TIMESTAMP) private Date data; @Column @Enumerated(EnumType.ORDINAL) private TipoTarefa tipoTarefa; private boolean isFinalizada; @OneToOne(fetch = FetchType.EAGER) private EncaminhamentoProposicao encaminhamentoProposicao; @ManyToOne(fetch = FetchType.EAGER) private Usuario usuario; @Transient private Long idProposicao; public Long getId() { return this.id; } public void setId(final Long id) { this.id = id; } public Date getData() { return data; } public void setData(Date data) { this.data = data; } public TipoTarefa getTipoTarefa() { return tipoTarefa; } public void setTipoTarefa(TipoTarefa tipoTarefa) { this.tipoTarefa = tipoTarefa; } public boolean isFinalizada() { return isFinalizada; } public void setFinalizada(boolean isFinalizada) { this.isFinalizada = isFinalizada; } public EncaminhamentoProposicao getEncaminhamentoProposicao() { return encaminhamentoProposicao; } public void setEncaminhamentoProposicao( EncaminhamentoProposicao encaminhamentoProposicao) { this.encaminhamentoProposicao = encaminhamentoProposicao; } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public Long getIdProposicao() { return idProposicao; } public void setIdProposicao(Long idProposicao) { this.idProposicao = idProposicao; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Tarefa)) { return false; } Tarefa other = (Tarefa) obj; if (id != null) { if (!id.equals(other.id)) { return false; } } return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } }
package hudson.plugins.disk_usage; import hudson.Extension; import hudson.FilePath; import hudson.Util; import hudson.matrix.MatrixProject; import hudson.maven.MavenBuild; import hudson.maven.MavenModuleSet; import hudson.maven.MavenModuleSetBuild; import hudson.model.AsyncPeriodicWork; import hudson.model.Item; import hudson.model.ItemGroup; import hudson.model.TaskListener; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Hudson; import hudson.remoting.Callable; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; /** * A Thread responsible for gathering disk usage information * * @author dvrzalik */ @Extension public class DiskUsageThread extends AsyncPeriodicWork { //trigger disk usage thread each 6 hours public static final int COUNT_INTERVAL_MINUTES = 60*6; public static final int WORKSPACE_TIMEOUT = 1000*60*5; public DiskUsageThread() { super("Project disk usage"); } public long getRecurrencePeriod() { return 1000*60*COUNT_INTERVAL_MINUTES; } @Override protected void execute(TaskListener listener) throws IOException, InterruptedException { List<Item> items = new ArrayList<Item>(); ItemGroup<? extends Item> itemGroup = Hudson.getInstance(); addAllItems(itemGroup, items); for (Object item : items) { if (item instanceof AbstractProject) { AbstractProject project = (AbstractProject) item; //well, this is not absolutely thread-safe, but in the worst case we get invalid result for one build //(which will be rewritten next time) if (!project.isBuilding()) { List<AbstractBuild> builds = project.getBuilds(); Iterator<AbstractBuild> buildIterator = builds.iterator(); try { while (buildIterator.hasNext()) { calculateDiskUsageForBuild(buildIterator.next()); } //Assign workspace size to the last build calculateWorkspaceDiskUsage(project); } catch (Exception ex) { logger.log(Level.WARNING, "Error when recording disk usage for " + project.getName(), ex); } } } } } /** * Recursively add items form itemGroup */ public List<Item> addAllItems(ItemGroup<? extends Item> itemGroup, List<Item> items) { for (Item item : itemGroup.getItems()) { if (item instanceof MatrixProject || item instanceof MavenModuleSet) { items.add(item); } else if (item instanceof ItemGroup) { addAllItems((ItemGroup) item, items); } else { items.add(item); } } return items; } protected static void calculateDiskUsageForBuild(AbstractBuild build) throws IOException { //Build disk usage has to be always recalculated to be kept up-to-date //- artifacts might be kept only for the last build and users sometimes delete files manually as well. long buildSize = DiskUsageCallable.getFileSize(build.getRootDir()); if (build instanceof MavenModuleSetBuild) { Collection<List<MavenBuild>> builds = ((MavenModuleSetBuild) build).getModuleBuilds().values(); for (List<MavenBuild> mavenBuilds : builds) { for (MavenBuild mavenBuild : mavenBuilds) { calculateDiskUsageForBuild(mavenBuild); } } } BuildDiskUsageAction action = build.getAction(BuildDiskUsageAction.class); boolean updateBuild = false; if (action == null) { action = new BuildDiskUsageAction(build, 0, buildSize); build.addAction(action); updateBuild = true; } else { if (( action.diskUsage.buildUsage <= 0 ) || ( Math.abs(action.diskUsage.buildUsage - buildSize) > 1024 )) { action.diskUsage.buildUsage = buildSize; updateBuild = true; } } if ( updateBuild ) { build.save(); } } private static void calculateWorkspaceDiskUsage(AbstractProject project) throws IOException, InterruptedException { AbstractBuild lastBuild = (AbstractBuild) project.getLastBuild(); if (lastBuild != null) { BuildDiskUsageAction bdua = lastBuild.getAction(BuildDiskUsageAction.class); //also recalculate workspace - deleting workspace by e.g. scripts is also quite common boolean updateWs = false; if (bdua == null) { bdua = new BuildDiskUsageAction(lastBuild, 0, 0); lastBuild.addAction(bdua); updateWs = true; } FilePath workspace = project.getSomeWorkspace(); //slave might be offline...or have been deleted - set to 0 if (workspace != null) { long oldWsUsage = bdua.diskUsage.wsUsage; try{ bdua.diskUsage.wsUsage = workspace.getChannel().callAsync(new DiskUsageCallable(workspace)).get(WORKSPACE_TIMEOUT, TimeUnit.MILLISECONDS); if (Math.abs(bdua.diskUsage.wsUsage - oldWsUsage) > 1024 ) { updateWs = true; } }catch(Exception ex){ Logger.getLogger(DiskUsageThread.class.getName()).log(Level.WARNING, "Disk usage fails to calculate workspace for job " + project.getDisplayName() + " through channel " + workspace.getChannel(),ex); } } else{ bdua.diskUsage.wsUsage = 0; //workspace have been delete or is not reachable } if(updateWs){ lastBuild.save(); } } } /** * A {@link Callable} which computes disk usage of remote file object */ public static class DiskUsageCallable implements Callable<Long, IOException> { public static final Logger LOGGER = Logger .getLogger(DiskUsageCallable.class.getName()); private FilePath path; public DiskUsageCallable(FilePath filePath) { this.path = filePath; } public Long call() throws IOException { File f = new File(path.getRemote()); return getFileSize(f); } public static Long getFileSize(File f) throws IOException { long size = 0; if (f.isDirectory() && !Util.isSymlink(f)) { File[] fileList = f.listFiles(); if (fileList != null) { for (File child : fileList) { size += getFileSize(child); } } else { LOGGER.info("Failed to list files in " + f.getPath() + " - ignoring"); } } return size + f.length(); } } }
package org.epics.pvmanager.data; import org.epics.pvmanager.util.TimeStamp; import java.text.NumberFormat; import java.util.List; import java.util.Set; import org.epics.util.time.Timestamp; /** * Factory class for all concrete implementation of the types. * <p> * The factory methods do not do anything in terms of defensive copy and * immutability to the objects, which they are passed as they are. It's the * client responsibility to prepare them appropriately, which is automatically * done anyway for all objects except collections. * * @author carcassi */ public class ValueFactory { private static Timestamp toTimestamp(TimeStamp timeStamp) { if (timeStamp == null) return null; return timeStamp.asTimestamp(); } public static VString newVString(String value, AlarmSeverity alarmSeverity, AlarmStatus alarmStatus, TimeStamp timeStamp, Integer timeUserTag) { return new IVString(value, alarmSeverity, alarmStatus, toTimestamp(timeStamp), timeUserTag, true); } public static VMultiDouble newVMultiDouble(List<VDouble> values, AlarmSeverity alarmSeverity, AlarmStatus alarmStatus, TimeStamp timeStamp, Integer timeUserTag, Double lowerDisplayLimit, Double lowerCtrlLimit, Double lowerAlarmLimit, Double lowerWarningLimit, String units, NumberFormat format, Double upperWarningLimit, Double upperAlarmLimit, Double upperCtrlLimit, Double upperDisplayLimit) { return new IVMultiDouble(values, alarmSeverity, alarmStatus, toTimestamp(timeStamp), timeUserTag, true, lowerDisplayLimit, lowerCtrlLimit, lowerAlarmLimit, lowerWarningLimit, units, format, upperWarningLimit, upperAlarmLimit, upperCtrlLimit, upperDisplayLimit); } /** * Creates new immutable VInt. */ @Deprecated public static VInt newVInt(final Integer value, final AlarmSeverity alarmSeverity, final AlarmStatus alarmStatus, final TimeStamp timeStamp, final Integer timeUserTag, final Double lowerDisplayLimit, final Double lowerAlarmLimit, final Double lowerWarningLimit, final String units, final NumberFormat numberFormat, final Double upperWarningLimit, final Double upperAlarmLimit, final Double upperDisplayLimit, final Double lowerCtrlLimit, final Double upperCtrlLimit) { return new IVInt(value, alarmSeverity, alarmStatus, toTimestamp(timeStamp), timeUserTag, true, lowerDisplayLimit, lowerCtrlLimit, lowerAlarmLimit, lowerWarningLimit, units, numberFormat, upperWarningLimit, upperAlarmLimit, upperCtrlLimit, upperDisplayLimit); } /** * Creates new immutable VInt. */ public static VInt newVInt(final Integer value, final Alarm alarm, final Time time, final Display display) { return new IVInt(value, alarm.getAlarmSeverity(), alarm.getAlarmStatus(), time.getTimestamp(), time.getTimeUserTag(), time.isTimeValid(), display.getLowerDisplayLimit(), display.getLowerCtrlLimit(), display.getLowerAlarmLimit(), display.getLowerWarningLimit(), display.getUnits(), display.getFormat(), display.getLowerWarningLimit(), display.getUpperAlarmLimit(), display.getUpperCtrlLimit(), display.getUpperDisplayLimit()); } public static Alarm newAlarm(final AlarmSeverity alarmSeverity, final AlarmStatus alarmStatus) { return new Alarm() { @Override public AlarmSeverity getAlarmSeverity() { return alarmSeverity; } @Override public AlarmStatus getAlarmStatus() { return alarmStatus; } }; } public static Alarm alarmNone() { return newAlarm(AlarmSeverity.NONE, AlarmStatus.NONE); } public static Time newTime(final Timestamp timestamp, final Integer timeUserTag, final boolean timeValid) { return new Time() { @Override public TimeStamp getTimeStamp() { return TimeStamp.timestampOf(timestamp); } @Override public Timestamp getTimestamp() { return timestamp; } @Override public Integer getTimeUserTag() { return timeUserTag; } @Override public boolean isTimeValid() { return timeValid; } }; } public static Time newTime(final Timestamp timestamp) { return newTime(timestamp, null, true); } public static Time timeNow() { return newTime(Timestamp.now(), null, true); } public static Display newDisplay(final Double lowerDisplayLimit, final Double lowerAlarmLimit, final Double lowerWarningLimit, final String units, final NumberFormat numberFormat, final Double upperWarningLimit, final Double upperAlarmLimit, final Double upperDisplayLimit, final Double lowerCtrlLimit, final Double upperCtrlLimit) { return new Display() { @Override public Double getLowerCtrlLimit() { return lowerCtrlLimit; } @Override public Double getUpperCtrlLimit() { return upperCtrlLimit; } @Override public Double getLowerDisplayLimit() { return lowerDisplayLimit; } @Override public Double getLowerAlarmLimit() { return lowerAlarmLimit; } @Override public Double getLowerWarningLimit() { return lowerWarningLimit; } @Override public String getUnits() { return units; } @Override public NumberFormat getFormat() { return numberFormat; } @Override public Double getUpperWarningLimit() { return upperWarningLimit; } @Override public Double getUpperAlarmLimit() { return upperAlarmLimit; } @Override public Double getUpperDisplayLimit() { return upperDisplayLimit; } }; } public static Display displayNone() { return newDisplay(null, null, null, null, null, null, null, null, null, null); } /** * Creates new immutable VDouble. */ public static VDouble newVDouble(final Double value, final Alarm alarm, final Time time, final Display display) { return new IVDouble(value, alarm.getAlarmSeverity(), alarm.getAlarmStatus(), time.getTimestamp(), time.getTimeUserTag(), time.isTimeValid(), display.getLowerDisplayLimit(), display.getLowerCtrlLimit(), display.getLowerAlarmLimit(), display.getLowerWarningLimit(), display.getUnits(), display.getFormat(), display.getLowerWarningLimit(), display.getUpperAlarmLimit(), display.getUpperCtrlLimit(), display.getUpperDisplayLimit()); } /** * Creates new immutable VDouble. */ @Deprecated public static VDouble newVDouble(final Double value, final AlarmSeverity alarmSeverity, final AlarmStatus alarmStatus, final TimeStamp timeStamp, final Integer timeUserTag, final Double lowerDisplayLimit, final Double lowerAlarmLimit, final Double lowerWarningLimit, final String units, final NumberFormat numberFormat, final Double upperWarningLimit, final Double upperAlarmLimit, final Double upperDisplayLimit, final Double lowerCtrlLimit, final Double upperCtrlLimit) { return new VDouble() { @Override public Double getLowerCtrlLimit() { return lowerCtrlLimit; } @Override public Double getUpperCtrlLimit() { return upperCtrlLimit; } @Override public Double getLowerDisplayLimit() { return lowerDisplayLimit; } @Override public Double getLowerAlarmLimit() { return lowerAlarmLimit; } @Override public Double getLowerWarningLimit() { return lowerWarningLimit; } @Override public String getUnits() { return units; } @Override public NumberFormat getFormat() { return numberFormat; } @Override public Double getUpperWarningLimit() { return upperWarningLimit; } @Override public Double getUpperAlarmLimit() { return upperAlarmLimit; } @Override public Double getUpperDisplayLimit() { return upperDisplayLimit; } @Override public Integer getTimeUserTag() { return timeUserTag; } @Override public TimeStamp getTimeStamp() { return timeStamp; } @Override public Timestamp getTimestamp() { return toTimestamp(timeStamp); } @Override public AlarmSeverity getAlarmSeverity() { return alarmSeverity; } @Override public AlarmStatus getAlarmStatus() { return alarmStatus; } @Override public Double getValue() { return value; } @Override public boolean isTimeValid() { return true; } }; } /** * Creates new immutable new VDouble by using the metadata from the old value. */ @Deprecated public static VDouble newVDouble(final Double value, final AlarmSeverity alarmSeverity, final AlarmStatus alarmStatus, final Integer timeUserTag, final TimeStamp timeStamp, Display display) { return newVDouble(value, alarmSeverity, alarmStatus, timeStamp, timeUserTag, display.getLowerDisplayLimit(), display.getLowerAlarmLimit(), display.getLowerWarningLimit(), display.getUnits(), display.getFormat(), display.getUpperWarningLimit(), display.getUpperAlarmLimit(), display.getUpperDisplayLimit(), display.getLowerCtrlLimit(), display.getUpperCtrlLimit()); } /** * Creates new immutable VDouble by using the metadata from the old value, * and computing the alarm from the metadata range. * * @param value new numeric value * @param timeStamp time stamp * @param display metadata * @return new value */ @Deprecated public static VDouble newVDouble(double value, TimeStamp timeStamp, Display display) { // Calculate new AlarmSeverity, using oldValue ranges AlarmSeverity severity = AlarmSeverity.NONE; AlarmStatus status = AlarmStatus.NONE; if (value <= display.getLowerAlarmLimit() || value >= display.getUpperAlarmLimit()) { status = AlarmStatus.RECORD; severity = AlarmSeverity.MAJOR; } else if (value <= display.getLowerWarningLimit() || value >= display.getUpperWarningLimit()) { status = AlarmStatus.RECORD; severity = AlarmSeverity.MINOR; } return ValueFactory.newVDouble(value, severity, status, null, timeStamp, display); } /** * Creates new immutable VDouble by using metadata from the old value, * now as timestamp and computing alarm from the metadata range. * * @param value new numeric value * @param display metadata * @return new value */ public static VDouble newVDouble(double value, Display display) { return newVDouble(value, TimeStamp.now(), display); } /** * Creates a new immutable VStatistics. */ public static VStatistics newVStatistics(final double average, final double stdDev, final double min, final double max, final int nSamples, final AlarmSeverity alarmSeverity, final AlarmStatus alarmStatus, final TimeStamp timeStamp, final Integer timeUserTag, final Double lowerDisplayLimit, final Double lowerAlarmLimit, final Double lowerWarningLimit, final String units, final NumberFormat numberFormat, final Double upperWarningLimit, final Double upperAlarmLimit, final Double upperDisplayLimit, final Double lowerCtrlLimit, final Double upperCtrlLimit) { return new IVStatistics(average, stdDev, min, max, nSamples, alarmSeverity, alarmStatus, toTimestamp(timeStamp), timeUserTag, true, lowerDisplayLimit, lowerCtrlLimit, lowerAlarmLimit, lowerWarningLimit, units, numberFormat, upperWarningLimit, upperAlarmLimit, upperCtrlLimit, upperDisplayLimit); } /** * Creates a new VStatistics by taking the metadata from a VDouble. */ public static VStatistics newVStatistics(final double average, final double stdDev, final double min, final double max, final int nSamples, final AlarmSeverity alarmSeverity, final AlarmStatus alarmStatus, final Integer timeUserTag, final TimeStamp timeStamp, VDouble aValue) { return newVStatistics(average, stdDev, min, max, nSamples, alarmSeverity, alarmStatus, timeStamp, timeUserTag, aValue.getLowerDisplayLimit(), aValue.getLowerAlarmLimit(), aValue.getLowerWarningLimit(), aValue.getUnits(), aValue.getFormat(), aValue.getUpperWarningLimit(), aValue.getUpperAlarmLimit(), aValue.getUpperDisplayLimit(), aValue.getLowerCtrlLimit(), aValue.getUpperCtrlLimit()); } /** * Creates new immutable VInt. */ public static VInt newEInt(final Integer value, final AlarmSeverity alarmSeverity, final AlarmStatus alarmStatus, final TimeStamp timeStamp, final Integer timeUserTag, final Double lowerDisplayLimit, final Double lowerAlarmLimit, final Double lowerWarningLimit, final String units, final NumberFormat numberFormat, final Double upperWarningLimit, final Double upperAlarmLimit, final Double upperDisplayLimit, final Double lowerCtrlLimit, final Double upperCtrlLimit) { return new IVInt(value, alarmSeverity, alarmStatus, toTimestamp(timeStamp), timeUserTag, true, lowerDisplayLimit, lowerCtrlLimit, lowerAlarmLimit, lowerWarningLimit, units, numberFormat, upperWarningLimit, upperAlarmLimit, upperCtrlLimit, upperDisplayLimit); } /** * Creates new immutable newDbrCtrlInt by using the metadata from the old value. */ public static VInt newEInt(final Integer value, final AlarmSeverity alarmSeverity, final AlarmStatus alarmStatus, final Integer timeUserTag, final TimeStamp timeStamp, VInt oldValue) { return newEInt(value, alarmSeverity, alarmStatus, timeStamp, timeUserTag, oldValue.getLowerDisplayLimit(), oldValue.getLowerAlarmLimit(), oldValue.getLowerWarningLimit(), oldValue.getUnits(), oldValue.getFormat(), oldValue.getUpperWarningLimit(), oldValue.getUpperAlarmLimit(), oldValue.getUpperDisplayLimit(), oldValue.getLowerCtrlLimit(), oldValue.getUpperCtrlLimit()); } public static VDoubleArray newVDoubleArray(final double[] values, final List<Integer> sizes, final AlarmSeverity alarmSeverity, final AlarmStatus alarmStatus, final TimeStamp timeStamp, final Integer timeUserTag, final Double lowerDisplayLimit, final Double lowerAlarmLimit, final Double lowerWarningLimit, final String units, final NumberFormat numberFormat, final Double upperWarningLimit, final Double upperAlarmLimit, final Double upperDisplayLimit, final Double lowerCtrlLimit, final Double upperCtrlLimit) { return new IVDoubleArray(values, sizes, alarmSeverity, alarmStatus, toTimestamp(timeStamp), timeUserTag, true, lowerDisplayLimit, lowerCtrlLimit, lowerAlarmLimit, lowerWarningLimit, units, numberFormat, upperWarningLimit, upperAlarmLimit, upperCtrlLimit, upperDisplayLimit); } public static VImage newVImage(int height, int width, byte[] data) { return new IVImage(height, width, data); } static VIntArray newVIntArray(final int[] values, final List<Integer> sizes, final AlarmSeverity alarmSeverity, final AlarmStatus alarmStatus, final TimeStamp timeStamp, final Integer timeUserTag, final Double lowerDisplayLimit, final Double lowerAlarmLimit, final Double lowerWarningLimit, final String units, final NumberFormat numberFormat, final Double upperWarningLimit, final Double upperAlarmLimit, final Double upperDisplayLimit, final Double lowerCtrlLimit, final Double upperCtrlLimit) { return new IVIntArray(values, sizes, alarmSeverity, alarmStatus, toTimestamp(timeStamp), timeUserTag, true, lowerDisplayLimit, lowerCtrlLimit, lowerAlarmLimit, lowerWarningLimit, units, numberFormat, upperWarningLimit, upperAlarmLimit, upperCtrlLimit, upperDisplayLimit); } }
package de.onyxbits.bureauengine.screen; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.utils.TimeUtils; import com.badlogic.gdx.assets.AssetDescriptor; import com.badlogic.gdx.audio.Music; import de.onyxbits.bureauengine.BureauGame; import de.onyxbits.bureauengine.audio.NullMusic; import de.onyxbits.bureauengine.audio.MuteListener; /** * A screen of the game. <code>BureauScreen</code>S are heavyweight objects that usually * have a large amount of assets (music, textures, sfx) bound to them. Their purpose is * to break the game down into seperate working sets of "art units", so large games * can be written without the need to hold all assets in memory at all time. * <p> * <code>BureauScreen</code>S are not meant to be recycled. Once they are hidden, they * must not be shown again. */ public abstract class BureauScreen<T extends BureauGame> implements Screen, MuteListener { /** * <code>Stage</code> of this screen. Will be rendered automatically. */ protected Stage stage; /** * Reference to the game object. */ protected T game; /** * Music playing on this screen. May be null, will not be disposed of automatically if * not loaded via an <code>AssetManager</code>. */ protected Music music; /** * Instantiate a new screen. Note: instantiation must usually happen fast and on the * UI thread (e.g. whne the player hits an "exit" button). Put all your real construction * work in the <code>readyScreen()</code> method. * @param game callback reference to the main game object */ public BureauScreen(T game) { this.game=game; } /** * Register all assets declared by <code>getAssets()</code> with the <code>AssetManager</code>. * This method must be called before <code>readyScreen()</code> may be called. Note: this is a * two step process because asset loading (at least as far as textures are concerned) must be * done on the UI thread which will cause a noticable pause in game play. Some games may want * to handle that pause differently than others. * @param finishLoading true to also call <code>AssetManager.finishLoading()</code>. */ public void prepareAssets(boolean finishLoading) { AssetDescriptor ad[] = getAssets(); for (AssetDescriptor tmp: ad) { game.assetManager.load(tmp); } if (finishLoading) game.assetManager.finishLoading(); } /** * Declare assets that are to be automatically loaded/unloaded. * @return The assets, this <code>Screen</code> depends on. */ protected AssetDescriptor[] getAssets() { return new AssetDescriptor[0]; } @Override public void dispose() { if (stage!=null) stage.dispose(); AssetDescriptor ad[] = getAssets(); for (AssetDescriptor tmp: ad) { game.assetManager.unload(tmp.fileName); } } /** * Showing the screen will register the stage as an inputprocessor, register * the screen as a <code>MuteListener</code> and start playing music. */ @Override public void show() { Gdx.input.setInputProcessor(stage); game.muteManager.addMuteListener(this); if (music!=null && !game.muteManager.isMusicMuted()) { music.play(); } } @Override public void hide() { game.muteManager.removeMuteListener(this); if (Gdx.input.getInputProcessor()==stage) { Gdx.input.setInputProcessor(null); } } @Override public void resume() { game.assetManager.finishLoading(); } @Override public void pause() { } @Override public void resize(int w, int h) {} /** * Subclasses should override this method if they wish to do any drawing below the * stage. Default implementation just clears the screen to a solid color. * @param delta time diff */ public void renderBackground(float delta) { Gdx.gl.glClearColor(0.0f, 0.0f, 0.0f, 1); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); } /** * Default implementation pauses/resumes music */ @Override public void muteMusic(boolean mute) { if (music==null) return; if (mute) { music.pause(); } else { music.play(); } } /** * Default implementation does nothing */ @Override public void muteSound(boolean mute) {} @Override public void render(float delta) { renderBackground(delta); stage.act(delta); stage.draw(); } /** * Actually construct the screen object. Subclasses should override this method. * The default implementation just constructs a <code>Stage</code>. */ public void readyScreen() { this.stage = new Stage(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false,game.spriteBatch); } }
package edu.jhu.thrax.hadoop.jobs; import java.io.IOException; import java.util.ArrayList; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; import edu.jhu.thrax.extraction.Labeling; import edu.jhu.thrax.util.FormatUtils; import edu.jhu.thrax.util.Vocabulary; public class VocabularyJob extends ThraxJob { public VocabularyJob() {} public Job getJob(Configuration conf) throws IOException { Job job = new Job(conf, "vocabulary"); job.setJarByClass(VocabularyJob.class); job.setMapperClass(VocabularyJob.Map.class); job.setReducerClass(VocabularyJob.Reduce.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(NullWritable.class); job.setOutputKeyClass(IntWritable.class); job.setOutputValueClass(Text.class); job.setSortComparatorClass(Text.Comparator.class); job.setOutputFormatClass(SequenceFileOutputFormat.class); FileInputFormat.setInputPaths(job, new Path(conf.get("thrax.input-file"))); int maxSplitSize = conf.getInt("thrax.max-split-size", 0); if (maxSplitSize != 0) FileInputFormat.setMaxInputSplitSize(job, maxSplitSize); FileOutputFormat.setOutputPath(job, new Path(conf.get("thrax.work-dir") + "vocabulary")); job.setNumReduceTasks(1); return job; } public String getOutputSuffix() { return "vocabulary"; } @Override public String getName() { return "vocabulary"; } private static class Map extends Mapper<LongWritable, Text, Text, NullWritable> { private boolean sourceParsed; private boolean targetParsed; private Labeling labeling; protected void setup(Context context) { Configuration conf = context.getConfiguration(); sourceParsed = conf.getBoolean("thrax.source-is-parsed", false); targetParsed = conf.getBoolean("thrax.target-is-parsed", false); if (conf.get("thrax.grammar", "hiero").equalsIgnoreCase("samt")) { labeling = Labeling.SYNTAX; } else if (conf.get("thrax.grammar", "hiero").equalsIgnoreCase("manual")) { labeling = Labeling.MANUAL; } else { labeling = Labeling.HIERO; } } protected void map(LongWritable key, Text input, Context context) throws IOException, InterruptedException { String[] parts = FormatUtils.P_DELIM.split(input.toString()); if (parts.length < 3) return; if (sourceParsed) extractTokensFromParsed(parts[0], (labeling != Labeling.SYNTAX), context); else extractTokens(parts[0], context); if (targetParsed) extractTokensFromParsed(parts[1], (labeling != Labeling.SYNTAX), context); else extractTokens(parts[1], context); if (labeling == Labeling.MANUAL && parts.length > 3) { String[] labels = FormatUtils.P_SPACE.split(parts[3].trim()); for (String label : labels) context.write(new Text("[" + label), NullWritable.get()); } } protected void extractTokens(String input, Context context) throws IOException, InterruptedException { if (input == null || input.isEmpty()) return; String[] tokens = FormatUtils.P_SPACE.split(input); for (String token : tokens) if (!token.isEmpty()) context.write(new Text(token), NullWritable.get()); } protected void extractTokensFromParsed(String input, boolean terminals_only, Context context) throws IOException, InterruptedException { int from = 0, to = 0; boolean seeking = true; boolean nonterminal = false; char current; if (input == null || input.isEmpty() || input.charAt(0) != '(') return; // Run through entire (potentially parsed) sentence. while (from < input.length() && to < input.length()) { if (seeking) { // Seeking mode: looking for the start of the next symbol. current = input.charAt(from); if (current == '(' || current == ')' || current == ' ') { // We skip brackets and spaces. ++from; } else { // Found a non spacing symbol, go into word filling mode. to = from + 1; seeking = false; nonterminal = (input.charAt(from - 1) == '('); } } else { // Word filling mode. Advance to until we hit the end or spacing. current = input.charAt(to); if (current == ' ' || current == ')' || current == '(') { // Word ended. if (terminals_only) { if (!nonterminal) context.write(new Text(input.substring(from, to)), NullWritable.get()); } else { if (nonterminal) { String nt = input.substring(from, to); if (nt.equals(",")) nt = "COMMA"; context.write(new Text("[" + nt), NullWritable.get()); } else { context.write(new Text(input.substring(from, to)), NullWritable.get()); } } from = to + 1; seeking = true; } else { ++to; } } } } } private static class Reduce extends Reducer<Text, NullWritable, IntWritable, Text> { private ArrayList<String> nonterminals; private boolean allowConstituent = true; private boolean allowCCG = true; private boolean allowConcat = true; private boolean allowDoubleConcat = true; protected void setup(Context context) throws IOException, InterruptedException { Configuration conf = context.getConfiguration(); nonterminals = new ArrayList<String>(); allowConstituent = conf.getBoolean("thrax.allow-constituent-label", true); allowCCG = conf.getBoolean("thrax.allow-ccg-label", true); allowConcat = conf.getBoolean("thrax.allow-concat-label", true); allowDoubleConcat = conf.getBoolean("thrax.allow-double-plus", true); } protected void reduce(Text key, Iterable<NullWritable> values, Context context) throws IOException, InterruptedException { String token = key.toString(); if (token == null || token.isEmpty()) throw new RuntimeException("Unexpected empty token."); if (token.charAt(0) == '[') nonterminals.add(token); else Vocabulary.id(token); context.progress(); } protected void cleanup(Context context) throws IOException, InterruptedException { Configuration conf = context.getConfiguration(); combineNonterminals(conf); int size = Vocabulary.size(); for (int i = 1; i < size; ++i) context.write(new IntWritable(i), new Text(Vocabulary.word(i))); } private void combineNonterminals(Configuration conf) { if (allowConstituent) addNonterminals(nonterminals); if (allowConcat) { ArrayList<String> concatenated = joinNonterminals("+", nonterminals); addNonterminals(concatenated); } if (allowCCG) { ArrayList<String> forward = joinNonterminals("/", nonterminals); addNonterminals(forward); ArrayList<String> backward = joinNonterminals("\\", nonterminals); addNonterminals(backward); } if (allowDoubleConcat) { ArrayList<String> concat = joinNonterminals("+", nonterminals); ArrayList<String> double_concat = joinNonterminals("+", concat); addNonterminals(double_concat); } Vocabulary.id(FormatUtils.markup(conf.get("thrax.default-nt", "X"))); Vocabulary.id(FormatUtils.markup(conf.get("thrax.full-sentence-nt", "_S"))); } private ArrayList<String> joinNonterminals(String glue, ArrayList<String> prefixes) { ArrayList<String> joined = new ArrayList<String>(); for (String prefix : prefixes) for (String nt : nonterminals) joined.add(prefix + glue + nt.substring(1)); return joined; } private static void addNonterminals(ArrayList<String> nts) { for (String nt : nts) Vocabulary.id(nt + "]"); } } }
package android.palharini.myhealth.entity; public class Usuario { String nome; String dataNascimento; String altura; String peso; public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getDataNascimento() { return dataNascimento; } public void setDataNascimento(String dataNascimento) { this.dataNascimento = dataNascimento; } public String getAltura() { return altura; } public void setAltura(String altura) { this.altura = altura; } public String getPeso() { return peso; } public void setPeso(String peso) { this.peso = peso; } }
package org.postgresql.test.jdbc2; import org.postgresql.test.JDBC2Tests; import junit.framework.TestCase; import java.sql.*; /* * TestCase to test the internal functionality of org.postgresql.jdbc2.DatabaseMetaData * * PS: Do you know how difficult it is to type on a train? ;-) * * $Id: DatabaseMetaDataTest.java,v 1.10 2002/07/30 13:22:38 davec Exp $ */ public class DatabaseMetaDataTest extends TestCase { private Connection con; /* * Constructor */ public DatabaseMetaDataTest(String name) { super(name); } protected void setUp() throws Exception { con = JDBC2Tests.openDB(); JDBC2Tests.createTable( con, "testmetadata", "id int4, name text, updated timestamp" ); } protected void tearDown() throws Exception { JDBC2Tests.dropTable( con, "testmetadata" ); JDBC2Tests.closeDB( con ); } /* * The spec says this may return null, but we always do! */ public void testGetMetaData() { try { DatabaseMetaData dbmd = con.getMetaData(); assertNotNull(dbmd); ResultSet rs = dbmd.getTables( null, null, "test%", new String[] {"TABLE"}); assertTrue( rs.next() ); String tableName = rs.getString("TABLE_NAME"); assertTrue( tableName.equals("testmetadata") ); rs.close(); rs = dbmd.getColumns("", "", "test%", "%" ); assertTrue( rs.next() ); assertTrue( rs.getString("TABLE_NAME").equals("testmetadata") ); assertTrue( rs.getString("COLUMN_NAME").equals("id") ); assertTrue( rs.getInt("DATA_TYPE") == java.sql.Types.INTEGER ); assertTrue( rs.next() ); assertTrue( rs.getString("TABLE_NAME").equals("testmetadata") ); assertTrue( rs.getString("COLUMN_NAME").equals("name") ); assertTrue( rs.getInt("DATA_TYPE") == java.sql.Types.VARCHAR ); assertTrue( rs.next() ); assertTrue( rs.getString("TABLE_NAME").equals("testmetadata") ); assertTrue( rs.getString("COLUMN_NAME").equals("updated") ); assertTrue( rs.getInt("DATA_TYPE") == java.sql.Types.TIMESTAMP ); } catch (SQLException ex) { fail(ex.getMessage()); } } /* * Test default capabilities */ public void testCapabilities() { try { DatabaseMetaData dbmd = con.getMetaData(); assertNotNull(dbmd); assertTrue(dbmd.allProceduresAreCallable()); assertTrue(dbmd.allTablesAreSelectable()); // not true all the time // This should always be false for postgresql (at least for 7.x) assertTrue(!dbmd.isReadOnly()); // does the backend support this yet? The protocol does... assertTrue(!dbmd.supportsMultipleResultSets()); // yes, as multiple backends can have transactions open assertTrue(dbmd.supportsMultipleTransactions()); assertTrue(dbmd.supportsMinimumSQLGrammar()); assertTrue(!dbmd.supportsCoreSQLGrammar()); assertTrue(!dbmd.supportsExtendedSQLGrammar()); assertTrue(dbmd.supportsANSI92EntryLevelSQL()); assertTrue(!dbmd.supportsANSI92IntermediateSQL()); assertTrue(!dbmd.supportsANSI92FullSQL()); assertTrue(!dbmd.supportsIntegrityEnhancementFacility()); } catch (SQLException ex) { fail(ex.getMessage()); } } public void testJoins() { try { DatabaseMetaData dbmd = con.getMetaData(); assertNotNull(dbmd); assertTrue(dbmd.supportsOuterJoins()); assertTrue(dbmd.supportsFullOuterJoins()); assertTrue(dbmd.supportsLimitedOuterJoins()); } catch (SQLException ex) { fail(ex.getMessage()); } } public void testCursors() { try { DatabaseMetaData dbmd = con.getMetaData(); assertNotNull(dbmd); assertTrue(!dbmd.supportsPositionedDelete()); assertTrue(!dbmd.supportsPositionedUpdate()); } catch (SQLException ex) { fail(ex.getMessage()); } } public void testNulls() { try { DatabaseMetaData dbmd = con.getMetaData(); assertNotNull(dbmd); // We need to type cast the connection to get access to the // PostgreSQL-specific method haveMinimumServerVersion(). // This is not available through the java.sql.Connection interface. assertTrue( con instanceof org.postgresql.PGConnection ); assertTrue(!dbmd.nullsAreSortedAtStart()); assertTrue( dbmd.nullsAreSortedAtEnd() != ((org.postgresql.jdbc2.AbstractJdbc2Connection)con).haveMinimumServerVersion("7.2")); assertTrue( dbmd.nullsAreSortedHigh() == ((org.postgresql.jdbc2.AbstractJdbc2Connection)con).haveMinimumServerVersion("7.2")); assertTrue(!dbmd.nullsAreSortedLow()); assertTrue(dbmd.nullPlusNonNullIsNull()); assertTrue(dbmd.supportsNonNullableColumns()); } catch (SQLException ex) { fail(ex.getMessage()); } } public void testLocalFiles() { try { DatabaseMetaData dbmd = con.getMetaData(); assertNotNull(dbmd); assertTrue(!dbmd.usesLocalFilePerTable()); assertTrue(!dbmd.usesLocalFiles()); } catch (SQLException ex) { fail(ex.getMessage()); } } public void testIdentifiers() { try { DatabaseMetaData dbmd = con.getMetaData(); assertNotNull(dbmd); assertTrue(!dbmd.supportsMixedCaseIdentifiers()); // always false assertTrue(dbmd.supportsMixedCaseQuotedIdentifiers()); // always true assertTrue(!dbmd.storesUpperCaseIdentifiers()); // always false assertTrue(dbmd.storesLowerCaseIdentifiers()); // always true assertTrue(!dbmd.storesUpperCaseQuotedIdentifiers()); // always false assertTrue(!dbmd.storesLowerCaseQuotedIdentifiers()); // always false assertTrue(!dbmd.storesMixedCaseQuotedIdentifiers()); // always false assertTrue(dbmd.getIdentifierQuoteString().equals("\"")); } catch (SQLException ex) { fail(ex.getMessage()); } } public void testCrossReference() { try { Connection con1 = JDBC2Tests.openDB(); JDBC2Tests.createTable( con1, "vv", "a int not null, b int not null, primary key ( a, b )" ); JDBC2Tests.createTable( con1, "ww", "m int not null, n int not null, primary key ( m, n ), foreign key ( m, n ) references vv ( a, b )" ); DatabaseMetaData dbmd = con.getMetaData(); assertNotNull(dbmd); ResultSet rs = dbmd.getCrossReference(null, "", "vv", null, "", "ww" ); for (int j=1; rs.next(); j++ ) { String pkTableName = rs.getString( "PKTABLE_NAME" ); assertTrue ( pkTableName.equals("vv") ); String pkColumnName = rs.getString( "PKCOLUMN_NAME" ); assertTrue( pkColumnName.equals("a") || pkColumnName.equals("b")); String fkTableName = rs.getString( "FKTABLE_NAME" ); assertTrue( fkTableName.equals( "ww" ) ); String fkColumnName = rs.getString( "FKCOLUMN_NAME" ); assertTrue( fkColumnName.equals( "m" ) || fkColumnName.equals( "n" ) ) ; String fkName = rs.getString( "FK_NAME" ); assertTrue( fkName.equals( "<unnamed>") ); String pkName = rs.getString( "PK_NAME" ); assertTrue( pkName.equals("vv_pkey") ); int keySeq = rs.getInt( "KEY_SEQ" ); assertTrue( keySeq == j ); } JDBC2Tests.dropTable( con1, "vv" ); JDBC2Tests.dropTable( con1, "ww" ); } catch (SQLException ex) { fail(ex.getMessage()); } } public void testForeignKeys() { try { Connection con1 = JDBC2Tests.openDB(); JDBC2Tests.createTable( con1, "people", "id int4 primary key, name text" ); JDBC2Tests.createTable( con1, "policy", "id int4 primary key, name text" ); JDBC2Tests.createTable( con1, "users", "id int4 primary key, people_id int4, policy_id int4,"+ "CONSTRAINT people FOREIGN KEY (people_id) references people(id),"+ "constraint policy FOREIGN KEY (policy_id) references policy(id)" ); DatabaseMetaData dbmd = con.getMetaData(); assertNotNull(dbmd); ResultSet rs = dbmd.getImportedKeys(null, "", "users" ); int j = 0; for (; rs.next(); j++ ) { String pkTableName = rs.getString( "PKTABLE_NAME" ); assertTrue ( pkTableName.equals("people") || pkTableName.equals("policy") ); String pkColumnName = rs.getString( "PKCOLUMN_NAME" ); assertTrue( pkColumnName.equals("id") ); String fkTableName = rs.getString( "FKTABLE_NAME" ); assertTrue( fkTableName.equals( "users" ) ); String fkColumnName = rs.getString( "FKCOLUMN_NAME" ); assertTrue( fkColumnName.equals( "people_id" ) || fkColumnName.equals( "policy_id" ) ) ; String fkName = rs.getString( "FK_NAME" ); assertTrue( fkName.equals( "people") || fkName.equals( "policy" ) ); String pkName = rs.getString( "PK_NAME" ); assertTrue( pkName.equals( "people_pkey") || pkName.equals( "policy_pkey" ) ); } assertTrue ( j== 2 ); rs = dbmd.getExportedKeys( null, "", "people" ); // this is hacky, but it will serve the purpose assertTrue ( rs.next() ); assertTrue( rs.getString( "PKTABLE_NAME" ).equals( "people" ) ); assertTrue( rs.getString( "PKCOLUMN_NAME" ).equals( "id" ) ); assertTrue( rs.getString( "FKTABLE_NAME" ).equals( "users" ) ); assertTrue( rs.getString( "FKCOLUMN_NAME" ).equals( "people_id" ) ); assertTrue( rs.getString( "FK_NAME" ).equals( "people" ) ); JDBC2Tests.dropTable( con1, "users" ); JDBC2Tests.dropTable( con1, "people" ); JDBC2Tests.dropTable( con1, "policy" ); } catch (SQLException ex) { fail(ex.getMessage()); } } public void testTables() { try { DatabaseMetaData dbmd = con.getMetaData(); assertNotNull(dbmd); // we can add columns assertTrue(dbmd.supportsAlterTableWithAddColumn()); // we can't drop columns (yet) assertTrue(!dbmd.supportsAlterTableWithDropColumn()); } catch (SQLException ex) { fail(ex.getMessage()); } } public void testSelect() { try { DatabaseMetaData dbmd = con.getMetaData(); assertNotNull(dbmd); // yes we can?: SELECT col a FROM a; assertTrue(dbmd.supportsColumnAliasing()); // yes we can have expressions in ORDERBY assertTrue(dbmd.supportsExpressionsInOrderBy()); // Yes, an ORDER BY clause can contain columns that are not in the // SELECT clause. assertTrue(dbmd.supportsOrderByUnrelated()); assertTrue(dbmd.supportsGroupBy()); assertTrue(dbmd.supportsGroupByUnrelated()); assertTrue(dbmd.supportsGroupByBeyondSelect()); // needs checking } catch (SQLException ex) { fail(ex.getMessage()); } } public void testDBParams() { try { DatabaseMetaData dbmd = con.getMetaData(); assertNotNull(dbmd); assertTrue(dbmd.getURL().equals(JDBC2Tests.getURL())); assertTrue(dbmd.getUserName().equals(JDBC2Tests.getUser())); } catch (SQLException ex) { fail(ex.getMessage()); } } public void testDbProductDetails() { try { assertTrue(con instanceof org.postgresql.PGConnection); org.postgresql.jdbc2.AbstractJdbc2Connection pc = (org.postgresql.jdbc2.AbstractJdbc2Connection) con; DatabaseMetaData dbmd = con.getMetaData(); assertNotNull(dbmd); assertTrue(dbmd.getDatabaseProductName().equals("PostgreSQL")); //The test below doesn't make sense to me, it tests that //the version of the driver = the version of the database it is connected to //since the driver should be backwardly compatible this test is commented out //assertTrue(dbmd.getDatabaseProductVersion().startsWith( // Integer.toString(pc.getDriver().getMajorVersion()) // + Integer.toString(pc.getDriver().getMinorVersion()))); assertTrue(dbmd.getDriverName().equals("PostgreSQL Native Driver")); } catch (SQLException ex) { fail(ex.getMessage()); } } public void testDriverVersioning() { try { assertTrue(con instanceof org.postgresql.PGConnection); org.postgresql.jdbc2.AbstractJdbc2Connection pc = (org.postgresql.jdbc2.AbstractJdbc2Connection) con; DatabaseMetaData dbmd = con.getMetaData(); assertNotNull(dbmd); assertTrue(dbmd.getDriverVersion().equals(pc.getDriver().getVersion())); assertTrue(dbmd.getDriverMajorVersion() == pc.getDriver().getMajorVersion()); assertTrue(dbmd.getDriverMinorVersion() == pc.getDriver().getMinorVersion()); } catch (SQLException ex) { fail(ex.getMessage()); } } }
package info.gameboxx.gameboxx.options; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.List; public abstract class ListOption extends Option { protected List<SingleOption> value = new ArrayList<>(); protected Object defaultValue = null; public ListOption() {} public ListOption(String name) { super(name); } public ListOption(String name, Object defaultValues) { super(name); this.defaultValue = defaultValues; } /** * Reset the option. * It will reset the error message and the list with values. * Use this when you want to parse a new list of objects. */ public void reset() { error = ""; value = new ArrayList<>(); } /** * Get the cached list with values. * The list may contain default values if the parsing failed. * @return The cached list with values. (May be empty) */ public List<SingleOption> getOptions() { return value; } /** * Get the default value. * This value will be added to the list when parsing of a value failed. * @return The default value. (May be {@code null}!) */ public Object getDefault() { return defaultValue; } /** * Set the default value to use when parsing fails. * The value must of the same type as the raw class type of the single option. So a IntList can only have an integer as default option here. * @param defaultValue The default value. (This value will be added to the list when parsing of a value failed.) * @return The option instance. */ public ListOption setDefault(Object defaultValue) { if (defaultValue == null || !defaultValue.getClass().equals(getSingleOption().getRawClass())) { this.defaultValue = null; } else { this.defaultValue = defaultValue; for (SingleOption option : value) { option.setDefault(defaultValue); } } return this; } public boolean parse(boolean ignoreErrors, Object... input) { if (input == null || input.length == 0) { error = "Missing input value."; return false; } for (int i = 0; i < input.length; i++) { Object obj = input[i]; SingleOption option = getSingleOption(); option.parse(obj); if (option.hasError() && (!ignoreErrors || !option.hasValue())) { error = option.getError() + " [index:" + i + "]"; return false; } if (!option.hasValue()) { error = "Unknown parsing error. [index:" + i + "]"; return false; } value.add(option); } return true; } public boolean parse(boolean ignoreErrors, String... input) { return parse(ignoreErrors, null, input); } public boolean parse(boolean ignoreErrors, Player player, String... input) { reset(); if (input == null || input.length == 0) { error = "Missing input value."; return false; } for (int i = 0; i < input.length; i++) { String str = input[i]; SingleOption option = getSingleOption(); option.parse(player, str); if (option.hasError() && (!ignoreErrors || !option.hasValue())) { error = option.getError() + " [index:" + i + "]"; return false; } if (!option.hasValue()) { error = "Unknown parsing error. [index:" + i + "]"; return false; } value.add(option); } return true; } public boolean parse(int index, Object input) { if (index >= value.size()) { value.add(getSingleOption()); index = value.size()-1; } SingleOption option = value.get(index); boolean result = option.parse(input); error = option.getError(); return result; } public boolean parse(int index, String input) { return parse(null, index, input); } public boolean parse(Player player, int index, String input) { if (index >= value.size()) { value.add(getSingleOption()); index = value.size()-1; } SingleOption option = value.get(index); boolean result = option.parse(player, input); error = option.getError(); return result; } public boolean hasError(int index) { if (index >= value.size()) { throw new IndexOutOfBoundsException(); } if (value.get(index) == null) { return true; } return value.get(index).hasError(); } public String getError(int index) { if (index >= value.size()) { throw new IndexOutOfBoundsException(); } if (value.get(index) == null) { return "Missing value for index " + index + "."; } return value.get(index).getError(); } public boolean hasValue(int index) { if (index >= value.size()) { throw new IndexOutOfBoundsException(); } if (value.get(index) == null) { return false; } return value.get(index).hasValue(); } public boolean success(int index) { if (index >= value.size()) { throw new IndexOutOfBoundsException(); } if (value.get(index) == null) { return false; } return value.get(index).success(); } protected Object getValueOrDefault(int index) { if (index >= value.size()) { throw new IndexOutOfBoundsException(); } if (value.get(index) == null) { return null; } return value.get(index).getValueOrDefault(); } public List<String> serialize() { List<String> values = new ArrayList<>(); for (SingleOption option : value) { values.add(option.serialize()); } return values; } public String serialize(int index) { if (index >= value.size()) { throw new IndexOutOfBoundsException(); } if (value.get(index) == null) { return null; } return value.get(index).serialize(); } public List<String> getDisplayValues() { List<String> values = new ArrayList<>(); for (SingleOption option : value) { values.add(option.getDisplayValue()); } return values; } public String getDisplayValue(int index) { if (index >= value.size()) { throw new IndexOutOfBoundsException(); } if (value.get(index) == null) { return null; } return value.get(index).getDisplayValue(); } public abstract List<?> getValues(); public abstract Object getValue(int index); public abstract SingleOption getSingleOption(); }
package de.sebhn.algorithm.excercise2; import java.math.BigInteger; public class Quaternstrings { public static void main(String[] args) { Quaternstrings.calculate(3); } public static void calculate(int n) { int radix = 4; BigInteger maxNumber = new BigInteger("4").pow(n); BigInteger counter = BigInteger.ZERO; System.out.println("maxnbr " + maxNumber); for (BigInteger i = BigInteger.ZERO; i.compareTo(maxNumber) < 0; i = i.add(BigInteger.ONE)) { String numberAsRadix4 = i.toString(radix); if (canBePrinted(numberAsRadix4)) { counter = counter.add(BigInteger.ONE); // System.out.println(numberAsRadix4); } } System.out.println("Amount of possibleNumbers " + counter); } // TODO: make following code faster private static boolean canBePrinted(String numberAsRadix4) { boolean print = true; char[] numbers = numberAsRadix4.toCharArray(); for (int j = 0; j < numbers.length; j++) { char currentChar = numbers[j]; int nextIndex = j + 1; if (hasNextIndex(numbers, nextIndex)) { char nextChar = numbers[nextIndex]; int currentCharAsNumber = currentChar; int nextCharAsNumber = nextChar; if (nextCharAsNumber == currentCharAsNumber + 1) { print = false; break; } } } return print; } private static boolean hasNextIndex(char[] numbers, int nextIndex) { return nextIndex < numbers.length; } }
package com.redhat.ceylon.dist.osgi; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.osgi.framework.Bundle; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.Version; import org.osgi.framework.wiring.BundleWire; import org.osgi.framework.wiring.BundleWiring; import com.redhat.ceylon.cmr.api.ArtifactResult; import com.redhat.ceylon.cmr.api.ArtifactResultType; import com.redhat.ceylon.cmr.api.ImportType; import com.redhat.ceylon.cmr.api.PathFilter; import com.redhat.ceylon.cmr.api.RepositoryException; import com.redhat.ceylon.cmr.api.VisibilityType; import com.redhat.ceylon.compiler.java.runtime.metamodel.Metamodel; import com.redhat.ceylon.compiler.loader.ContentAwareArtifactResult; public class Activator implements BundleActivator { private class BundleArtifactResult implements ContentAwareArtifactResult { BundleWiring wiring; public BundleArtifactResult(BundleWiring bundle) { this.wiring = bundle; } @Override public VisibilityType visibilityType() { return VisibilityType.STRICT; } @Override public String version() { return wiring.getBundle().getVersion().toString(); } @Override public ArtifactResultType type() { return ArtifactResultType.CEYLON; } @Override public String repositoryDisplayString() { return null; } @Override public String name() { return wiring.getBundle().getSymbolicName(); } @Override public ImportType importType() { return ImportType.UNDEFINED; } @Override public List<ArtifactResult> dependencies() throws RepositoryException { List<ArtifactResult> results = new ArrayList<>(); for (BundleWire dep : wiring.getRequiredWires(null)) { if (! "ceylon.dist.osgi".equals(dep.getProviderWiring().getBundle().getSymbolicName())) { results.add(new BundleArtifactResult(dep.getProviderWiring())); } } return results; } @Override public File artifact() throws RepositoryException { return null; } @Override public PathFilter filter(){ return null; } private String getPackageName(String name) { int lastSlash = name.lastIndexOf('/'); if(lastSlash == -1) return ""; return name.substring(0, lastSlash); } @Override public Collection<String> getPackages() { Set<String> packages = new HashSet<>(); for (String resource : wiring.listResources("/", "*", BundleWiring.LISTRESOURCES_RECURSE | BundleWiring.LISTRESOURCES_LOCAL)) { if (! resource.endsWith("/")) { packages.add(getPackageName(resource)); } } return packages; } @Override public Collection<String> getEntries() { Set<String> entries = new HashSet<>(); for (String resource : wiring.listResources("/", "*", BundleWiring.LISTRESOURCES_RECURSE | BundleWiring.LISTRESOURCES_LOCAL)) { if (! resource.endsWith("/")) { entries.add(resource); } } return entries; } @Override public byte[] getContents(String path) { URL url = wiring.getBundle().getResource(path); if (url != null) { InputStream is; try { is = url.openStream(); ByteArrayOutputStream os = new ByteArrayOutputStream(); try { byte[] buffer = new byte[1024]; int read = 0; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } } finally { try { is.close(); } catch (IOException e) { } try { os.close(); } catch (IOException e) { } } return os.toByteArray(); } catch (IOException e1) { e1.printStackTrace(); } } return new byte[0]; } @Override public List<String> getFileNames(String path) { path += "/"; return Arrays.asList(wiring.listResources(path, "*", BundleWiring.LISTRESOURCES_LOCAL).toArray(new String[]{})); } } @Override public void start(BundleContext context) throws Exception { Bundle bundle = context.getBundle(); BundleWiring wiring = bundle.adapt(BundleWiring.class); String symbolicName = bundle.getSymbolicName(); Version version = bundle.getVersion(); String versionString = new StringBuilder("") .append(version.getMajor()) .append('.') .append(version.getMinor()) .append('.') .append(version.getMicro()) .toString(); final ClassLoader bundleClassLoader = wiring.getClassLoader(); Metamodel.loadModule(symbolicName, versionString, new BundleArtifactResult(wiring), bundleClassLoader); } @Override public void stop(BundleContext context) throws Exception { } }
package com.facebook.react; import javax.annotation.Nullable; import java.util.List; import android.app.Application; import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.JavaScriptExecutorFactory; import com.facebook.react.common.LifecycleState; import com.facebook.react.devsupport.RedBoxHandler; import com.facebook.react.uimanager.UIImplementationProvider; /** * Simple class that holds an instance of {@link ReactInstanceManager}. This can be used in your * {@link Application class} (see {@link ReactApplication}), or as a static field. */ public abstract class ReactNativeHost { private final Application mApplication; private @Nullable ReactInstanceManager mReactInstanceManager; protected ReactNativeHost(Application application) { mApplication = application; } /** * Get the current {@link ReactInstanceManager} instance, or create one. */ public ReactInstanceManager getReactInstanceManager() { if (mReactInstanceManager == null) { mReactInstanceManager = createReactInstanceManager(); } return mReactInstanceManager; } /** * Get whether this holder contains a {@link ReactInstanceManager} instance, or not. I.e. if * {@link #getReactInstanceManager()} has been called at least once since this object was created * or {@link #clear()} was called. */ public boolean hasInstance() { return mReactInstanceManager != null; } /** * Destroy the current instance and release the internal reference to it, allowing it to be GCed. */ public void clear() { if (mReactInstanceManager != null) { mReactInstanceManager.destroy(); mReactInstanceManager = null; } } protected ReactInstanceManager createReactInstanceManager() { ReactInstanceManagerBuilder builder = ReactInstanceManager.builder() .setApplication(mApplication) .setJSMainModulePath(getJSMainModuleName()) .setUseDeveloperSupport(getUseDeveloperSupport()) .setRedBoxHandler(getRedBoxHandler()) .setJavaScriptExecutorFactory(getJavaScriptExecutorFactory()) .setUIImplementationProvider(getUIImplementationProvider()) .setInitialLifecycleState(LifecycleState.BEFORE_CREATE); for (ReactPackage reactPackage : getPackages()) { builder.addPackage(reactPackage); } String jsBundleFile = getJSBundleFile(); if (jsBundleFile != null) { builder.setJSBundleFile(jsBundleFile); } else { builder.setBundleAssetName(Assertions.assertNotNull(getBundleAssetName())); } return builder.build(); } /** * Get the {@link RedBoxHandler} to send RedBox-related callbacks to. */ protected @Nullable RedBoxHandler getRedBoxHandler() { return null; } /** * Get the {@link JavaScriptExecutorFactory}. Override this to use a custom * Executor. */ protected @Nullable JavaScriptExecutorFactory getJavaScriptExecutorFactory() { return null; } protected final Application getApplication() { return mApplication; } /** * Get the {@link UIImplementationProvider} to use. Override this method if you want to use a * custom UI implementation. * * Note: this is very advanced functionality, in 99% of cases you don't need to override this. */ protected UIImplementationProvider getUIImplementationProvider() { return new UIImplementationProvider(); } /** * Returns the name of the main module. Determines the URL used to fetch the JS bundle * from the packager server. It is only used when dev support is enabled. * This is the first file to be executed once the {@link ReactInstanceManager} is created. * e.g. "index.android" */ protected String getJSMainModuleName() { return "index.android"; } /** * Returns a custom path of the bundle file. This is used in cases the bundle should be loaded * from a custom path. By default it is loaded from Android assets, from a path specified * by {@link getBundleAssetName}. * e.g. "file://sdcard/myapp_cache/index.android.bundle" */ protected @Nullable String getJSBundleFile() { return null; } /** * Returns the name of the bundle in assets. If this is null, and no file path is specified for * the bundle, the app will only work with {@code getUseDeveloperSupport} enabled and will * always try to load the JS bundle from the packager server. * e.g. "index.android.bundle" */ protected @Nullable String getBundleAssetName() { return "index.android.bundle"; } /** * Returns whether dev mode should be enabled. This enables e.g. the dev menu. */ public abstract boolean getUseDeveloperSupport(); /** * Returns a list of {@link ReactPackage} used by the app. * You'll most likely want to return at least the {@code MainReactPackage}. * If your app uses additional views or modules besides the default ones, * you'll want to include more packages here. */ protected abstract List<ReactPackage> getPackages(); }
package ch.brickwork.bsuit.view; import ch.brickwork.bsuit.globals.IBoilersuitApplicationContext; import ch.brickwork.bsuit.interpreter.interpreters.ProcessingResult; import ch.brickwork.bsuit.util.FontUtils; import ch.brickwork.bsuit.util.ILog; import ch.brickwork.bsuit.util.ImageUtils; import javax.swing.*; import java.awt.*; public class OutputPanel extends JTabbedPane implements IProcessingResultDisplay, ILog { private final IBoilersuitApplicationContext context; private OutputConsole outputConsole; private TablePanel tablePanel; public OutputPanel(Font consoleFont, IBoilersuitApplicationContext context) { this.context = context; init(consoleFont); } private void init(Font consoleFont) { setFont(FontUtils.getFont(this, "ClearSans-Regular.ttf", 12f)); addTab("Console", new ImageIcon(ImageUtils.loadImage(this, "tab.png")), outputConsole = new OutputConsole(consoleFont)); addTab("Output", new ImageIcon(ImageUtils.loadImage(this, "tab.png")), tablePanel = new TablePanel(context)); setVisible(true); } @Override public void err(String s) { outputConsole.err(s); } @Override public void info(String s) { outputConsole.info(s); } @Override public void log(String s) { outputConsole.log(s); } @Override public void warn(String s) { outputConsole.warn(s); } @Override public void displayProcessingResult(ProcessingResult processingResult) { tablePanel.displayProcessingResult(processingResult); setSelectedComponent(tablePanel); } @Override public void displayTableOrView(String tableOrViewName, String variableName, String sortField, Boolean sortAsc) { tablePanel.displayTableOrView(tableOrViewName, variableName, sortField, sortAsc); setSelectedComponent(tablePanel); } @Override public void setRunStatus(RUN_STATUS runStatus) { // do nothing } }
package io.avaje.metrics.agent; import io.avaje.metrics.agent.asm.AnnotationVisitor; import io.avaje.metrics.agent.asm.ClassVisitor; import io.avaje.metrics.agent.asm.Label; import io.avaje.metrics.agent.asm.MethodVisitor; import io.avaje.metrics.agent.asm.Opcodes; import java.util.ArrayList; import java.util.List; /** * ClassAdapter used to add metrics collection. */ public class ClassAdapterMetric extends ClassVisitor implements Opcodes { private static final String SINGLETON = "/Singleton;"; private static final String SPRINGFRAMEWORK_STEREOTYPE = "Lorg/springframework/stereotype"; private static final String ANNOTATION_TIMED = "Lio/avaje/metrics/annotation/Timed;"; private static final String ANNOTATION_NOT_TIMED = "Lio/avaje/metrics/annotation/NotTimed;"; private static final String ANNOTATION_ALREADY_ENHANCED_MARKER = "Lio/avaje/metrics/spi/AlreadyEnhancedMarker;"; private final EnhanceContext enhanceContext; private boolean markerAnnotationAdded; private boolean detectSingleton; private boolean detectWebController; private boolean detectJaxrs; private boolean detectSpringComponent; private boolean detectExplicit; private boolean enhanceClassLevel; private boolean existingStaticInitialiser; protected String className; private String longName; private String shortName; /** * List of unique names to support parameter overloading. */ private final ArrayList<String> uniqueMethodNames = new ArrayList<>(); /** * The method adapters that detect if a method is enhanced and perform the enhancement. */ private final List<AddTimerMetricMethodAdapter> methodAdapters = new ArrayList<>(); /** * The metric full name that is a common prefix for each method. */ private String metricFullName; private String prefix; /** * The buckets defined commonly for all enhanced methods for this class. */ private int[] buckets; /** * Construct with visitor, context and classLoader. */ ClassAdapterMetric(ClassVisitor cv, EnhanceContext context) { super(ASM7, cv); this.enhanceContext = context; } EnhanceContext getEnhanceContext() { return enhanceContext; } boolean isLog(int level) { return enhanceContext.isLog(level); } private void log(int level, String msg) { if (isLog(level)) { enhanceContext.log(className, msg); } } private void log(int level, String msg, String extra, String extra2, String extra3) { if (isLog(level)) { enhanceContext.log(className, msg + extra + extra2 + extra3); } } private void log(int level, String msg, String extra) { if (isLog(level)) { enhanceContext.log(className, msg + extra); } } void log(String msg) { enhanceContext.log(className, msg); } /** * Set default buckets to use for methods enhanced for this class. */ private void setBuckets(Object value) { this.buckets = (int[]) value; } /** * Return true if there are default buckets defined at the class level. */ boolean hasBuckets() { return buckets != null && buckets.length > 0; } /** * Return the bucket ranges. */ int[] getBuckets() { return buckets; } /** * Return the class level metric prefix used to prefix timed metrics on methods. */ String getMetricPrefix() { if (prefix != null) { return prefix+"."+ shortName; } return enhanceContext.isNameIncludesPackage() ? longName : shortName; } String getShortName() { return shortName; } /** * Set the metric name via Timer annotation. */ private void setShortName(String shortName) { this.shortName = shortName; } private void setLongName(String fullName) { this.prefix = null; this.longName = fullName; this.shortName = fullName; } private void setPrefix(String prefix) { this.prefix = prefix; } private void setClassName(String className) { this.className = className; this.longName = className.replace('/', '.'); int lastDot = longName.lastIndexOf('.'); if (lastDot > -1) { shortName = longName.substring(lastDot + 1); } else { shortName = longName; } } @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { super.visit(version, access, name, signature, superName, interfaces); if ((access & Opcodes.ACC_INTERFACE) != 0) { throw new NoEnhancementRequiredException("Not enhancing interface"); } setClassName(name); } /** * Visit class level annotations. */ @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { AnnotationVisitor av = super.visitAnnotation(desc, visible); log(8, "... check annotation ", desc); if (desc.equals(ANNOTATION_ALREADY_ENHANCED_MARKER)) { throw new AlreadyEnhancedException("Already enhanced"); } if (desc.equals(ANNOTATION_NOT_TIMED)) { throw new NoEnhancementRequiredException("marked as NotTimed"); } if (desc.equals(ANNOTATION_TIMED)) { log(5, "found Timed annotation ", desc); detectExplicit = true; enhanceClassLevel = true; // read the name and bucket ranges from the class level Timer annotation return new ClassTimedAnnotationVisitor(av); } if (isWebEndpoint(desc)) { log(5, "found web endpoint annotation ", desc); detectWebController = true; enhanceClassLevel = true; } if (enhanceContext.isEnhanceSingleton() && desc.endsWith(SINGLETON)) { detectSingleton = true; enhanceClassLevel = true; } if (enhanceContext.isIncludeJaxRS() && isJaxRsEndpoint(desc)) { detectJaxrs = true; enhanceClassLevel = true; } // We are interested in Service, Controller, Component etc if (enhanceContext.isIncludeSpring() && desc.startsWith(SPRINGFRAMEWORK_STEREOTYPE)) { detectSpringComponent = true; enhanceClassLevel = true; } return av; } /** * Return true if this annotation marks a Rest Controller. */ private boolean isWebEndpoint(String desc) { return desc.equals("Lio/dinject/controller/Path;") || desc.equals("Lio/dinject/controller/Controller;"); } private boolean isJaxRsEndpoint(String desc) { return desc.equals("Ljavax/ws/rs/Path;") || desc.equals("Ljavax/ws/rs/Produces;") || desc.equals("Ljavax/ws/rs/Consumes;"); } private void addMarkerAnnotation() { if (!markerAnnotationAdded) { if (isLog(4)) { String flagExplicit = (detectExplicit ? "EXPLICIT " : ""); String flagWeb = (detectWebController ? "WebApi " : ""); String flagJaxrs = (detectJaxrs ? "JAXRS " : ""); String flagSpring = (detectSpringComponent ? "SPRING " : ""); String flagSingleton = (detectSingleton ? "SINGLETON" : ""); log(4, "enhancing - detection ", flagExplicit + flagWeb + flagJaxrs + flagSpring + flagSingleton); } AnnotationVisitor av = cv.visitAnnotation(ANNOTATION_ALREADY_ENHANCED_MARKER, true); if (av != null) { av.visitEnd(); } markerAnnotationAdded = true; } } /** * Helper to read and set the name and fullName attributes of the Timed annotation. */ private class ClassTimedAnnotationVisitor extends AnnotationVisitor { ClassTimedAnnotationVisitor(AnnotationVisitor av) { super(ASM7, av); } @Override public void visit(String name, Object value) { if ("name".equals(name) && !"".equals(value)) { setShortName(value.toString()); } else if ("fullName".equals(name) && !"".equals(value)) { setLongName(value.toString()); } else if ("buckets".equals(name)) { setBuckets(value); } else if ("prefix".equals(name)) { setPrefix(value.toString()); } } } /** * Visit the methods specifically looking for method level transactional annotations. */ @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { addMarkerAnnotation(); MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); if (name.equals("<init>")) { // not enhancing constructor log(5, "... not enhancing constructor:", name, " desc:", desc); return mv; } if (isCommonMethod(name)) { // not enhancing constructor log(5, "... not enhancing:", name, " desc:", desc); return mv; } if (name.equals("<clinit>")) { // static initializer, add call _$initMetrics() log(5, "... <clinit> exists - adding call to _$initMetrics()", ""); existingStaticInitialiser = true; return new StaticInitAdapter(mv, access, name, desc, className); } boolean publicMethod = isPublicMethod(access); int metricIndex = methodAdapters.size(); String uniqueMethodName = deriveUniqueMethodName(name); if (isLog(8)) { log("... method:" + name + " public:" + publicMethod + " index:" + metricIndex + " uniqueMethodName:" + uniqueMethodName); } boolean enhanceByDefault = enhanceClassLevel && publicMethod; if ((access & Opcodes.ACC_STATIC) != 0) { // by default not enhancing static method unless it is explicitly // annotated with a Timed annotation enhanceByDefault = enhanceContext.isIncludeStaticMethods(); if (isLog(5)) { log(5, "... static method:", name, " desc:", desc + " - enhanceByDefault" + enhanceByDefault); } } if (isPostConfiguredMethod(name)) { if (isLog(8)) { log("... method:" + name + " not enhanced by default (as postConfigured or init method)"); } enhanceByDefault = false; } // Not sure if we are enhancing this method yet ... AddTimerMetricMethodAdapter methodAdapter = createAdapter(enhanceByDefault, metricIndex, uniqueMethodName, mv, access, name, desc); methodAdapters.add(methodAdapter); return methodAdapter; } /** * Return true if a equals, hashCode or toString method - these are not enhanced. */ private boolean isCommonMethod(String name) { return name.equals("equals") || name.equals("hashCode") || name.equals("toString"); } /** * By default ignore these postConfigured/init type methods. */ private boolean isPostConfiguredMethod(String name) { return name.equals("init") || name.equals("postConfigured"); } private AddTimerMetricMethodAdapter createAdapter(boolean enhanceDefault, int metricIndex, String uniqueMethodName, MethodVisitor mv, int access, String name, String desc) { return new AddTimerMetricMethodAdapter(this, enhanceDefault, metricIndex, uniqueMethodName, mv, access, name, desc); } private boolean isPublicMethod(int access) { return ((access & Opcodes.ACC_PUBLIC) != 0); } /** * Create and return a unique method name in case of parameter overloading. */ private String deriveUniqueMethodName(String methodName) { int i = 1; String uniqueMethodName = methodName; while (uniqueMethodNames.contains(uniqueMethodName)) { uniqueMethodName = methodName + (i++); } uniqueMethodNames.add(uniqueMethodName); return uniqueMethodName; } @Override public void visitEnd() { if (noTimedMethods()) { log(8, "... no timed methods, not enhancing"); throw new NoEnhancementRequiredException(); } addStaticFieldDefinitions(); addStaticFieldInitialisers(); if (!existingStaticInitialiser) { log(5, "... add <clinit> to call _$initMetrics()"); addStaticInitialiser(); } super.visitEnd(); } /** * Return true if all the methods have no enhancement required. */ private boolean noTimedMethods() { for (AddTimerMetricMethodAdapter methodAdapter : methodAdapters) { if (methodAdapter.isEnhanced()){ return false; } } return true; } private void addStaticFieldDefinitions() { for (int i = 0; i < methodAdapters.size(); i++) { AddTimerMetricMethodAdapter methodAdapter = methodAdapters.get(i); methodAdapter.addFieldDefinition(cv, i); } } /** * Add the static _$initMetrics() method. */ private void addStaticFieldInitialisers() { MethodVisitor mv = cv.visitMethod(ACC_PRIVATE + ACC_STATIC, "_$initMetrics", "()V", null, null); mv.visitCode(); log(4, "... adding static _$initMetrics() method"); for (int i = 0; i < methodAdapters.size(); i++) { AddTimerMetricMethodAdapter methodAdapter = methodAdapters.get(i); methodAdapter.addFieldInitialisation(mv, i); } mv.visitInsn(RETURN); mv.visitMaxs(1, 0); mv.visitEnd(); } /** * Add a static initialization block when there was not one on the class. */ private void addStaticInitialiser() { MethodVisitor mv = cv.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null); mv.visitCode(); Label l0 = new Label(); mv.visitLabel(l0); mv.visitLineNumber(16, l0); mv.visitMethodInsn(INVOKESTATIC, className, "_$initMetrics", "()V", false); Label l1 = new Label(); mv.visitLabel(l1); mv.visitLineNumber(17, l1); mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } }
package ch.digitalfondue.synckv; import ch.digitalfondue.synckv.sync.MerkleTreeVariantRoot; import org.h2.mvstore.MVMap; import org.h2.mvstore.MVStore; import org.jgroups.JChannel; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.util.Iterator; import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; public class SyncKVTable { private final SecureRandom random; private final RpcFacade rpcFacade; private final JChannel channel; private final MVMap<byte[], byte[]> table; //nanoTime and random.nextLong private static final int METADATA_LENGTH = 2 * Long.BYTES; private final MerkleTreeVariantRoot syncTree; public SyncKVTable(String tableName, MVStore store, SecureRandom random, RpcFacade rpcFacade, JChannel channel, MerkleTreeVariantRoot syncTree) { this.random = random; this.rpcFacade = rpcFacade; this.channel = channel; this.table = store.openMap(tableName); this.syncTree = syncTree; } // the key are structured as: // + is = concatenation // key.bytes+nanoTime+seed public boolean put(String key, byte[] value) { return put(key, value, true); } public Set<String> keySet() { return table.keySet() .stream() .map(s -> new String(s, 0, s.length - METADATA_LENGTH, StandardCharsets.UTF_8)) //trim away the metadata .collect(Collectors.toCollection(TreeSet::new)); //keep the order and remove duplicate keys } synchronized boolean put(String key, byte[] value, boolean broadcast) { long time = System.nanoTime(); byte[] rawKey = key.getBytes(StandardCharsets.UTF_8); ByteBuffer bf = ByteBuffer.allocate(rawKey.length + METADATA_LENGTH); bf.put(rawKey); bf.putLong(time); bf.putLong(random.nextLong()); if (broadcast) { rpcFacade.putRequest(channel.getAddress(), table.getName(), key, value); } addRawKV(bf.array(), value); return true; } private synchronized void addRawKV(byte[] key, byte[] value) { table.put(key, value); syncTree.add(key); } public byte[] get(String key) { byte[][] res = get(key, true); return res != null ? res[1] : null; } //fetching a key, mean that we need to iterate as we may have multiple value for the same key //as the key are sorted, we only need to get the last one that have the same prefix and the same length (adjusted) byte[][] get(String key, boolean distributed) { byte[] rawKey = key.getBytes(StandardCharsets.UTF_8); int adjustedKeyLength = rawKey.length + METADATA_LENGTH; ByteBuffer keyBb = ByteBuffer.wrap(rawKey); Iterator<byte[]> it = table.keyIterator(rawKey); byte[] selectedKey = null; while (it.hasNext()) { byte[] candidateKey = it.next(); if (candidateKey.length == adjustedKeyLength && ByteBuffer.wrap(candidateKey, 0, rawKey.length).compareTo(keyBb) == 0) { selectedKey = candidateKey; } else { break; } } byte[] res = selectedKey != null ? table.get(selectedKey) : null; if (distributed && res == null) { //try to fetch the value in the cluster if it's not present locally byte[][] remote = rpcFacade.getValue(channel.getAddress(), table.getName(), key); //add value if it's missing if (remote != null && remote[0] != null) { System.err.println("ADDING VALUE FROM REMOTE ON GET"); addRawKV(remote[0], remote[1]); } return remote; } else { return new byte[][]{selectedKey, res}; } } }
package io.dropwizard.flyway.cli; import io.dropwizard.Configuration; import io.dropwizard.db.DatabaseConfiguration; import io.dropwizard.flyway.FlywayConfiguration; import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Subparser; import net.sourceforge.argparse4j.impl.Arguments; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.configuration.FluentConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static net.sourceforge.argparse4j.impl.Arguments.storeTrue; public class DbMigrateCommand<T extends Configuration> extends AbstractFlywayCommand<T> { private static final Logger LOG = LoggerFactory.getLogger(DbMigrateCommand.class); private static final String OUT_OF_ORDER = "outOfOrder"; private static final String VALIDATE_ON_MIGRATE = "validateOnMigrate"; private static final String CLEAN_ON_VALIDATION_ERROR = "cleanOnValidationError"; private static final String INIT_ON_MIGRATE = "initOnMigrate"; public DbMigrateCommand(final DatabaseConfiguration<T> databaseConfiguration, final FlywayConfiguration<T> flywayConfiguration, final Class<T> configurationClass) { super("migrate", "Migrates the database.", databaseConfiguration, flywayConfiguration, configurationClass); } @Override public void configure(Subparser subparser) { super.configure(subparser); subparser.addArgument("--" + OUT_OF_ORDER) .dest(OUT_OF_ORDER) .action(Arguments.storeConst()).setConst(Boolean.TRUE) .help("Allows migrations to be run \"out of order\". " + "If you already have versions 1 and 3 applied, and now a version 2 is found, it will be applied too instead of being ignored."); subparser.addArgument("--" + VALIDATE_ON_MIGRATE) .dest(VALIDATE_ON_MIGRATE) .action(Arguments.storeConst()).setConst(Boolean.TRUE) .help("Whether to automatically call validate or not when running migrate. " + "For each sql migration a CRC32 checksum is calculated when the sql script is executed. " + "The validate mechanism checks if the sql migration in the classpath still has the same checksum as the sql migration already executed in the database."); subparser.addArgument("--" + CLEAN_ON_VALIDATION_ERROR) .dest(CLEAN_ON_VALIDATION_ERROR) .action(Arguments.storeConst()).setConst(Boolean.TRUE) .help("Whether to automatically call clean or not when a validation error occurs. " + "This is exclusively intended as a convenience for development. " + "Even tough we strongly recommend not to change migration scripts once they have been checked into SCM and run, this provides a way of dealing with this case in a smooth manner. " + "The database will be wiped clean automatically, ensuring that the next migration will bring you back to the state checked into SCM. " + "Warning! Do not enable in production !"); subparser.addArgument("--" + INIT_ON_MIGRATE) .dest(INIT_ON_MIGRATE) .action(Arguments.storeConst()).setConst(Boolean.TRUE) .help("Whether to automatically call init when migrate is executed against a non-empty schema with no metadata table. " + "This schema will then be initialized with the initVersion before executing the migrations. " + "Only migrations above initVersion will then be applied. " + "This is useful for initial Flyway production deployments on projects with an existing DB. " + "Be careful when enabling this as it removes the safety net that ensures Flyway does not migrate the wrong database in case of a configuration mistake!"); } @Override public void run(final Namespace namespace, final Flyway flyway) throws Exception { final Boolean outOfOrder = namespace.getBoolean(OUT_OF_ORDER); final Boolean validateOnMigrate = namespace.getBoolean(VALIDATE_ON_MIGRATE); final Boolean cleanOnValidationError = namespace.getBoolean(CLEAN_ON_VALIDATION_ERROR); final Boolean baselineOnMigrate = namespace.getBoolean(INIT_ON_MIGRATE); FluentConfiguration config = Flyway.configure(flyway.getConfiguration().getClassLoader()).configuration(flyway.getConfiguration()); if (outOfOrder != null) { config.outOfOrder(outOfOrder); } if (validateOnMigrate != null) { config.validateOnMigrate(validateOnMigrate); } if (cleanOnValidationError != null) { config.cleanOnValidationError(cleanOnValidationError); } if (baselineOnMigrate != null) { config.baselineOnMigrate(baselineOnMigrate); } Flyway customFlyway = config.load(); final int successfulMigrations = customFlyway.migrate(); LOG.debug("{} successful migrations applied", successfulMigrations); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.*; import edu.wpi.first.wpilibj.DriverStationLCD.Line; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.Relay.*; /** * * @author Philip2 */ public class Shooter { int elevatorStatus = 0; Team3373 team; DriverStationLCD dsLCD; public Shooter(Team3373 t){ team = t; } public double start(){ double a = 0.1; return a; } public double increaseSpeed(double a){ //increases stage 2 by 1/10 of possible speed a += 0.1; if (a >= 1) {a = 1;} return a; } public double decreaseSpeed(double a){//decreases stage 2 by 1/10 of possible speed a -= 0.1; if (a <= 0){ a = 0;} return a; } public double increasePercentage(double a){//increases percentage of what stage 2 is multiplyied by to get 1 a += 0.05; if (a >= 1) {a = 1;} return a; } public double decreasePercentage(double a){//decreases percentage of what stage 2 is multiplyied by to get 1 a -= 0.05; if (a <= 0 ) {a = 0;} return a; } public double stop(){ double a = 0; return a; } public void elevator(double target){ if (team.pot1.getVoltage() >= 4.8 ) { team.flagRight = false; } else if (team.pot1.getVoltage() <= .2){ team.flagLeft = false; } else if (team.pot1.getVoltage() > .2){ team.flagLeft = true; } else if (team.pot1.getVoltage() < 4.8){ team.flagRight = true; } if (team.shootLB && team.flagLeft){ team.GrabSpike.set(Value.kReverse); } else if (team.shootRB && team.flagRight){ team.GrabSpike.set(Value.kForward); } switch (elevatorStatus){ case 0: //at required spot team.ShootSpike.set(Value.kOff); if (target > team.pot1.getVoltage() && (Math.abs(target - team.pot1.getVoltage()) <= .05)){ elevatorStatus = 1; } else if ((target < team.pot1.getVoltage()) && (Math.abs(target - team.pot1.getVoltage()) <= .05)){ elevatorStatus = 2; } else { elevatorStatus = 0; } break; case 1: //moving up team.ShootSpike.set(Value.kForward); if (Math.abs(target - team.pot1.getVoltage()) <= .05){ elevatorStatus = 0; } break; case 2: //moving down team.ShootSpike.set(Value.kReverse); if (Math.abs(target - team.pot1.getVoltage()) <= .05){ elevatorStatus = 0; } break; } /*if(team.shootA && !team.shootB){ team.GrabSpike.set(Value.kForward); } else if(!team.shootA && team.shootB){ team.GrabSpike.set(Value.kReverse); } else { team.GrabSpike.set(Value.kOff); } */ } }
package beans.user; import java.util.Locale; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import beans.scripts.PatientIllnessScript; import controller.NavigationController; import controller.SessionSettingController; import util.*; /** * Special settings for a VP session, e.g. different modes for feedback or scaffolding,... * Currently this needs to be provided by the parent VP system, otherwise default setting is used (e.g. expert feedback * always accessible) * @author ingahege * */ @ManagedBean(name = "sessSett", eager = true) @SessionScoped public class SessionSetting { public static final int EXPFEEDBACKMODE_END = 1; //show expert feedback only on last card public static final int EXPFEEDBACKMODE_NEVER = 2; //show no expert feedback at all public static final int LIST_MODE_NONE = 1; //no list is used public static final int LIST_MODE_USE = 0; //list is used private long id; /** * When shall the expert script be displayed... */ private int expFeedbackMode = 0; //0 or -1 is default /** * When shall the peer feedback be displayed... */ private int peerFeedbackMode = 0; //0 or -1 is default private String vpId; private long userId; /** * if the hint for the expert feedback has been displayed once, we set this to true and do not display it again. * Not stored in the database.... */ private boolean expHintDisplayed = false; /** * is choosing "no diagnosis" enabled (0) or not (1) */ private int ddxMode = 0; /** * Is a type-ahead list used or not? 0=default/List is used, 1=list is */ private int listMode = 0; /** * each position stands for a box (0=problems, 1=ddx, 2=tests, 3=therapies, 4=summary statement, 5 = patho), per default all * boxes are used. If boxes shall not be used/displayed, there needs to be a 0 at the position. * If boxes shall be displayed but in a passive mode, there needs to be a 2 at the position. * Is stores as a String in the database! */ //private int[] boxesUsed = {1,1,1,1,1,0}; private int boxUsedFdg = 1; //findings used (active=1, passive=2) private int boxUsedDDX = 1; //ddx used (active=1, passive=2) private int boxUsedTst = 1; //tests used (active=1, passive=2) private int boxUsedMng = 1; //management used (active=1, passive=2) private int boxUsedPat = 0; //pathophys used (active=1, passive=2) private int boxUsedSum = 1; //summary statement used (active=1, passive=2) /** * at which position is a box, default is problems (0) at pos[0] upper left corner etc * pos[1]=upper right corner, pos[2] = lower left corner, pos[3] = lower right corner */ private int[] boxesPositions = {0,1,2,3}; //default public SessionSetting(){} public SessionSetting(String vpId, long userId){ this.userId = userId; this.vpId = vpId; } public int getExpFeedbackMode() {return expFeedbackMode;} public void setExpFeedbackMode(int expFeedbackMode) {this.expFeedbackMode = expFeedbackMode;} public int getPeerFeedbackMode() {return peerFeedbackMode;} public void setPeerFeedbackMode(int peerFeedbackMode) {this.peerFeedbackMode = peerFeedbackMode;} public String getVpId() {return vpId;} public void setVpId(String vpId) {this.vpId = vpId;} public long getUserId() {return userId;} public void setUserId(long userId) {this.userId = userId;} public long getId() {return id;} public void setId(long id) {this.id = id;} private boolean isExpHintDisplayed() {return expHintDisplayed;} public void setExpHintDisplayed(boolean hintDisplayed) {this.expHintDisplayed = hintDisplayed;} public int getDdxMode() {return ddxMode;} public int getListMode() {return listMode;} public void setListMode(int listMode) {this.listMode = listMode;} public void setListMode(Locale loc) { //not very nice, should be configurable which languages use lists and which not. if(loc!=null && (loc.getLanguage().equalsIgnoreCase("pl") || loc.getLanguage().equalsIgnoreCase("sv"))) this.listMode = LIST_MODE_NONE; } /** * only allow "no diagnosis" option when the learner is at the point where he/she has to submit a daignosis. Otherwise * this could be misleading.... * @return */ public int getDdxModeForStage() { PatientIllnessScript patillscript = NavigationController.getInstance().getMyFacesContext().getPatillscript(); if(patillscript!=null && patillscript.getCurrentStage()==patillscript.getMaxSubmittedStage()) return ddxMode; else return PatientIllnessScript.FINAL_DDX_YES; } public void setDdxMode(int ddxMode) {this.ddxMode = ddxMode;} /** * return true if exp feedback shall be accessible, otherwise false. Depends on current stage in session and * feedback mode. * @param actStage * @param maxStage * @return */ public boolean displayExpFeedback(int actStage, int maxStage){ if(expFeedbackMode == EXPFEEDBACKMODE_NEVER) return false; //never show exp feedback if(expFeedbackMode<=0) return true; //default setting, feedback always accessible if(expFeedbackMode==EXPFEEDBACKMODE_END){ //only show at end: if(actStage>=maxStage){ return true; } return false; } return true; } /** * Decide whether a hint to the expert feedback button shall be displayed or not. Display if feedback is only available * at the end of a session if learner is on last stage/card. * @param actStage * @param maxStage * @return */ public boolean displayExpFeedbackHint(int actStage, int maxStage){ if(isExpHintDisplayed()) return false; //hint has already been displayed before.... if(expFeedbackMode == EXPFEEDBACKMODE_NEVER) return false; if(expFeedbackMode<=0) return false; if(expFeedbackMode==EXPFEEDBACKMODE_END && actStage==maxStage){ setExpHintDisplayed(true); return true; } return false; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o){ if(o instanceof SessionSetting){ SessionSetting sessSett = (SessionSetting) o; if(sessSett.getUserId()==this.userId && sessSett.getVpId().equals(this.vpId)) return true; if(sessSett.getId()==this.id) return true; return false; } return false; } /** * returns whether a box shall be displayed or not. Default is that it is displayed. * @param pos * @return */ /*public boolean displayBoxatPos(int pos){ try{ if (boxesUsed==null) return true; if (pos>boxesUsed.length) return true; if (boxesUsed[pos]==0) return false; return true; } catch (Exception e){ CRTLogger.out("Exception" + StringUtilities.stackTraceToString(e), CRTLogger.LEVEL_ERROR); return true; } }*/ //public int[] getBoxesUsed(){ return boxesUsed;} //public String getBoxesUsedStr(){ return StringUtilities.toString(boxesUsed,",");} /*public void setBoxesUsedStr(String boxesUsedStr){ if(boxesUsedStr==null || boxesUsedStr.equals("") || !boxesUsedStr.contains(",")) return; boxesUsed = StringUtilities.getIntArrFromString(boxesUsedStr, ","); }*/ /** * value was originally 0 or 1 (on/off), now we use a value to indicate the type of box * shall be displayed at which position. * value definitions see Relation class * @param i * @param value */ /*private void setBoxesUsed(int i, int value){ try{ if(value>=0) boxesUsed[i]=value; else boxesUsed[i]=1; } catch (Exception e){}; }*/ public int getBoxUsedFdg() { return boxUsedFdg;} public void setBoxUsedFdg(int boxUsedFdg) { this.boxUsedFdg = boxUsedFdg;} public int getBoxUsedDDX() {return boxUsedDDX;} public void setBoxUsedDDX(int boxUsedDDX) {this.boxUsedDDX = boxUsedDDX;} public int getBoxUsedTst() {return boxUsedTst;} public void setBoxUsedTst(int boxUsedTst) {this.boxUsedTst = boxUsedTst;} public int getBoxUsedMng() {return boxUsedMng;} public void setBoxUsedMng(int boxUsedMng) {this.boxUsedMng = boxUsedMng;} public int getBoxUsedPat() {return boxUsedPat;} public void setBoxUsedPat(int boxUsedPat) {this.boxUsedPat = boxUsedPat;} public int getBoxUsedSum() {return boxUsedSum;} public void setBoxUsedSum(int boxUsedSum) {this.boxUsedSum = boxUsedSum;} /*public int getProbBoxUsed(){ return boxesUsed[0];} public int getDdxBoxUsed(){ return boxesUsed[1];} public int getTestBoxUsed(){ return boxesUsed[2];} public int getMngBoxUsed(){ return boxesUsed[3];} public int getPathoBoxUsed(){ return boxesUsed[4];}*/ }
package dr.inference.operators; import dr.evomodel.continuous.LatentFactorModel; import dr.inference.distribution.DistributionLikelihood; import dr.inference.model.MatrixParameter; import dr.inference.model.Parameter; import dr.math.distributions.MultivariateNormalDistribution; import dr.math.distributions.NormalDistribution; import dr.math.matrixAlgebra.SymmetricMatrix; import java.util.ArrayList; import java.util.ListIterator; public class LoadingsGibbsOperator extends SimpleMCMCOperator implements GibbsOperator{ NormalDistribution prior; LatentFactorModel LFM; ArrayList<double[][]> precisionArray; ArrayList<double[]> meanMidArray; ArrayList<double[]> meanArray; MatrixParameter[] vectorProductAnswer; MatrixParameter[] priorMeanVector; double priorPrecision; double priorMeanPrecision; public LoadingsGibbsOperator(LatentFactorModel LFM, DistributionLikelihood prior, double weight){ setWeight(weight); this.prior=(NormalDistribution) prior.getDistribution(); this.LFM=LFM; precisionArray=new ArrayList<double[][]>(); double[][] temp; for (int i = 0; i < LFM.getFactorDimension() ; i++) { temp=new double[i+1][i+1]; precisionArray.add(temp); } meanArray=new ArrayList<double[]>(); meanMidArray=new ArrayList<double[]>(); double[] tempMean; for (int i = 0; i < LFM.getFactorDimension() ; i++) { tempMean=new double[i+1]; meanArray.add(tempMean); } for (int i = 0; i < LFM.getFactorDimension() ; i++) { tempMean=new double[i+1]; meanMidArray.add(tempMean); } vectorProductAnswer=new MatrixParameter[LFM.getLoadings().getRowDimension()]; for (int i = 0; i <vectorProductAnswer.length ; i++) { vectorProductAnswer[i]=new MatrixParameter(null); vectorProductAnswer[i].setDimensions(i+1, 1); } priorMeanVector=new MatrixParameter[LFM.getLoadings().getRowDimension()]; for (int i = 0; i <priorMeanVector.length ; i++) { priorMeanVector[i]=new MatrixParameter(null, i+1, 1, this.prior.getMean()/(this.prior.getSD()*this.prior.getSD())); } priorPrecision= 1/(this.prior.getSD()*this.prior.getSD()); priorMeanPrecision=this.prior.getMean()*priorPrecision; } private void getPrecisionOfTruncated(MatrixParameter full, int newRowDimension, double[][] answer){ // MatrixParameter answer=new MatrixParameter(null); // answer.setDimensions(this.getRowDimension(), Right.getRowDimension()); // System.out.println(answer.getRowDimension()); // System.out.println(answer.getColumnDimension()); int p = full.getColumnDimension(); for (int i = 0; i < newRowDimension; i++) { for (int j = 0; j < newRowDimension; j++) { double sum = 0; for (int k = 0; k < p; k++) sum += full.getParameterValue(i, k) * full.getParameterValue(j,k); answer[i][j]=sum*LFM.getColumnPrecision().getParameterValue(newRowDimension,newRowDimension); if(i==j){ answer[i][j]+=priorPrecision; } } } } private void getTruncatedMean(int newRowDimension, int dataColumn, double[][] variance, double[] midMean, double[] mean){ // MatrixParameter answer=new MatrixParameter(null); // answer.setDimensions(this.getRowDimension(), Right.getRowDimension()); // System.out.println(answer.getRowDimension()); // System.out.println(answer.getColumnDimension()); MatrixParameter data=LFM.getScaledData(); MatrixParameter Left=LFM.getFactors(); int p = Left.getColumnDimension(); for (int i = 0; i < newRowDimension; i++) { double sum = 0; for (int k = 0; k < p; k++) sum += Left.getParameterValue(i, k) * data.getParameterValue(dataColumn, k); sum=sum*LFM.getColumnPrecision().getParameterValue(i,i); sum+=priorMeanPrecision; midMean[i]=sum; } for (int i = 0; i < newRowDimension; i++) { double sum = 0; for (int k = 0; k < newRowDimension; k++) sum += variance[i][k] * midMean[k]; mean[i]=sum; } } private void getPrecision(int i, double[][] answer){ int size=LFM.getFactorDimension(); if(i<size){ getPrecisionOfTruncated(LFM.getFactors(), i + 1, answer); } else{ getPrecisionOfTruncated(LFM.getFactors(), size, answer); } } private void getMean(int i, double[][] variance, double[] midMean, double[] mean){ // Matrix factors=null; int size=LFM.getFactorDimension(); // double[] scaledDataColumn=LFM.getScaledData().getRowValues(i); // Vector dataColumn=null; // Vector priorVector=null; // Vector temp=null; // Matrix data=new Matrix(LFM.getScaledData().getParameterAsMatrix()); if(i<size){ getTruncatedMean(i + 1, i, variance, midMean, mean); // dataColumn=new Vector(data.toComponents()[i]); // try { // answer=precision.inverse().product(new Matrix(priorMeanVector[i].add(vectorProductAnswer[i]).getParameterAsMatrix())); } else{ getTruncatedMean(size, i, variance, midMean, mean); // dataColumn=new Vector(data.toComponents()[i]); // try { // answer=precision.inverse().product(new Matrix(priorMeanVector[size-1].add(vectorProductAnswer[size-1]).getParameterAsMatrix())); } } private void copy(int i, double[] random){ Parameter changing=LFM.getLoadings().getParameter(i); for (int j = 0; j <random.length ; j++) { changing.setParameterValueQuietly(j,random[j]); } } @Override public int getStepCount() { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getPerformanceSuggestion() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getOperatorName() { return "loadingsGibbsOperator"; //To change body of implemented methods use File | Settings | File Templates. } @Override public double doOperation() throws OperatorFailedException { ListIterator<double[][]> currentPrecision=precisionArray.listIterator(); ListIterator<double[]> currentMidMean=meanMidArray.listIterator(); ListIterator<double[]> currentMean=meanArray.listIterator(); double[] draws=null; double[][] precision=null; double[][] variance=null; double[] midMean=null; double[] mean=null; int size = LFM.getLoadings().getColumnDimension(); for (int i = 0; i < size; i++) { if(currentPrecision.hasNext()){ precision=currentPrecision.next();} if(currentMidMean.hasNext()) {midMean=currentMidMean.next(); } if(currentMean.hasNext()){ mean=currentMean.next(); } getPrecision(i, precision); variance=(new SymmetricMatrix(precision)).inverse().toComponents(); getMean(i, variance, mean, midMean); draws= MultivariateNormalDistribution.nextMultivariateNormalVariance(mean, variance); if(i<draws.length){ while(draws[i]<0){ draws= MultivariateNormalDistribution.nextMultivariateNormalVariance(mean, variance); } } copy(i, draws); } LFM.getLoadings().fireParameterChangedEvent(); return 0; //To change body of implemented methods use File | Settings | File Templates. } }
package beast.app.beauti; import java.awt.Color; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.EventObject; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.swing.Box; import javax.swing.DefaultCellEditor; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.event.CellEditorListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import beast.app.draw.ListInputEditor; import beast.app.draw.SmallButton; import beast.core.Input; import beast.core.MCMC; import beast.core.Plugin; import beast.core.Input.Validate; import beast.core.util.CompoundDistribution; import beast.evolution.alignment.Alignment; import beast.evolution.alignment.FilteredAlignment; import beast.evolution.branchratemodel.BranchRateModel; import beast.evolution.likelihood.TreeLikelihood; import beast.evolution.sitemodel.SiteModel; import beast.evolution.tree.Tree; // TODO: add useAmbiguities flag // TODO: add warning if useAmbiguities=false and nr of patterns=1 (happens when all data is ambiguous) public class AlignmentListInputEditor extends ListInputEditor { private static final long serialVersionUID = 1L; final static int NAME_COLUMN = 0; final static int FILE_COLUMN = 1; final static int TAXA_COLUMN = 2; final static int SITES_COLUMN = 3; final static int TYPE_COLUMN = 4; final static int SITEMODEL_COLUMN = 5; final static int CLOCKMODEL_COLUMN = 6; final static int TREE_COLUMN = 7; /** * alignments that form a partition. These can be FilteredAlignments * */ List<Alignment> alignments; int nPartitions; TreeLikelihood[] likelihoods; Object[][] tableData; JTable table; JTextField nameEditor; // public AlignmentListInputEditor() {} public AlignmentListInputEditor(BeautiDoc doc) { super(doc); } @Override public Class<?> type() { return List.class; } @Override public Class<?> baseType() { return Alignment.class; } @Override public Class<?>[] types() { Class<?>[] types = new Class[2]; types[0] = List.class; types[1] = Alignment.class; return types; } @SuppressWarnings("unchecked") public void init(Input<?> input, Plugin plugin, int itemNr, ExpandOption bExpandOption, boolean bAddButtons) { this.itemNr = itemNr; if (input.get() instanceof List) { alignments = (List<Alignment>) input.get(); } else { // we just have a single Alignment alignments = new ArrayList<Alignment>(); alignments.add((Alignment) input.get()); } nPartitions = alignments.size(); // super.init(input, plugin, bExpandOption, false); Box box = Box.createVerticalBox(); box.add(Box.createVerticalStrut(5)); box.add(createButtonBox()); box.add(Box.createVerticalStrut(5)); box.add(createListBox()); box.add(Box.createVerticalGlue()); Box buttonBox = Box.createHorizontalBox(); m_addButton = new SmallButton("+", true, SmallButton.ButtonType.square); m_addButton.setName("+"); m_addButton.setToolTipText("Add item to the list"); m_addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { addItem(); } }); buttonBox.add(Box.createHorizontalStrut(5)); buttonBox.add(m_addButton); buttonBox.add(Box.createHorizontalStrut(5)); JButton delButton = new SmallButton("-", true, SmallButton.ButtonType.square); delButton.setName("-"); delButton.setToolTipText("Delete selected items from the list"); delButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (doc.bHasLinkedAtLeastOnce) { JOptionPane.showMessageDialog(null, "Cannot delete partition while parameters are linked"); return; } delItem(); } }); buttonBox.add(delButton); buttonBox.add(Box.createHorizontalStrut(5)); JButton splitButton = new JButton("Split"); splitButton.setName("Split"); splitButton.setToolTipText("Split alignment into partitions, for example, codon positions"); splitButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { splitItem(); } }); buttonBox.add(splitButton); buttonBox.add(Box.createHorizontalGlue()); box.add(buttonBox); add(box); } protected Component createButtonBox() { Box box = Box.createHorizontalBox(); box.add(Box.createHorizontalGlue()); addLinkUnlinkPair(box, "Site Models"); addLinkUnlinkPair(box, "Clock Models"); addLinkUnlinkPair(box, "Trees"); box.add(Box.createHorizontalGlue()); return box; } private void addLinkUnlinkPair(Box box, String sLabel) { JButton linkSModelButton = new JButton("Link " + sLabel); linkSModelButton.setName("Link " + sLabel); linkSModelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JButton button = (JButton) e.getSource(); link(columnLabelToNr(button.getText())); table.repaint(); } }); box.add(linkSModelButton); linkSModelButton.setEnabled(!getDoc().bHasLinkedAtLeastOnce); JButton unlinkSModelButton = new JButton("Unlink " + sLabel); unlinkSModelButton.setName("Unlink " + sLabel); unlinkSModelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JButton button = (JButton) e.getSource(); unlink(columnLabelToNr(button.getText())); table.repaint(); } }); box.add(unlinkSModelButton); unlinkSModelButton.setEnabled(!getDoc().bHasLinkedAtLeastOnce); box.add(Box.createHorizontalGlue()); } private int columnLabelToNr(String sColumn) { int nColumn; if (sColumn.contains("Tree")) { nColumn = TREE_COLUMN; } else if (sColumn.contains("Clock")) { nColumn = CLOCKMODEL_COLUMN; } else { nColumn = SITEMODEL_COLUMN; } return nColumn; } private void link(int nColumn) { int[] nSelected = getTableRowSelection(); // do the actual linking for (int i = 1; i < nSelected.length; i++) { int iRow = nSelected[i]; Object old = tableData[iRow][nColumn]; tableData[iRow][nColumn] = tableData[nSelected[0]][nColumn]; try { updateModel(nColumn, iRow); } catch (Exception ex) { System.err.println(ex.getMessage()); // unlink if we could not link tableData[iRow][nColumn] = old; try { updateModel(nColumn, iRow); } catch (Exception ex2) { // ignore } } } } private void unlink(int nColumn) { int[] nSelected = getTableRowSelection(); for (int i = 1; i < nSelected.length; i++) { int iRow = nSelected[i]; tableData[iRow][nColumn] = getDoc().sPartitionNames.get(iRow).partition; try { updateModel(nColumn, iRow); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } } } int[] getTableRowSelection() { int[] nSelected = table.getSelectedRows(); if (nSelected.length == 0) { // select all nSelected = new int[nPartitions]; for (int i = 0; i < nPartitions; i++) { nSelected[i] = i; } } return nSelected; } /** set partition of type nColumn to partition model nr iRow **/ void updateModel(int nColumn, int iRow) throws Exception { System.err.println("updateModel: " + iRow + " " + nColumn + " " + table.getSelectedRow() + " " + table.getSelectedColumn()); for (int i = 0; i < nPartitions; i++) { System.err.println(i + " " + tableData[i][0] + " " + tableData[i][SITEMODEL_COLUMN] + " " + tableData[i][CLOCKMODEL_COLUMN] + " " + tableData[i][TREE_COLUMN]); } getDoc(); String sPartition = (String) tableData[iRow][nColumn]; // check if partition needs renaming String oldName = null; boolean isRenaming = false; try { switch (nColumn) { case SITEMODEL_COLUMN: if (!doc.pluginmap.containsKey("SiteModel.s:" + sPartition)) { String sID = likelihoods[iRow].m_pSiteModel.get().getID(); oldName = BeautiDoc.parsePartition(sID); doc.renamePartition(BeautiDoc.SITEMODEL_PARTITION, oldName, sPartition); isRenaming = true; } break; case CLOCKMODEL_COLUMN: { String sID = likelihoods[iRow].m_pBranchRateModel.get().getID(); String sClockModelName = sID.substring(0, sID.indexOf('.')) + ".c:" + sPartition; if (!doc.pluginmap.containsKey(sClockModelName)) { oldName = BeautiDoc.parsePartition(sID); doc.renamePartition(BeautiDoc.CLOCKMODEL_PARTITION, oldName, sPartition); isRenaming = true; } } break; case TREE_COLUMN: if (!doc.pluginmap.containsKey("Tree.t:" + sPartition)) { String sID = likelihoods[iRow].m_tree.get().getID(); oldName = BeautiDoc.parsePartition(sID); doc.renamePartition(BeautiDoc.TREEMODEL_PARTITION, oldName, sPartition); isRenaming = true; } break; } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Cannot rename item: " + e.getMessage()); tableData[iRow][nColumn] = oldName; return; } if (isRenaming) { doc.determinePartitions(); initTableData(); setUpComboBoxes(); table.repaint(); return; } int partitionID = BeautiDoc.ALIGNMENT_PARTITION; switch (nColumn) { case SITEMODEL_COLUMN: partitionID = BeautiDoc.SITEMODEL_PARTITION; break; case CLOCKMODEL_COLUMN: partitionID = BeautiDoc.CLOCKMODEL_PARTITION; break; case TREE_COLUMN: partitionID = BeautiDoc.TREEMODEL_PARTITION; break; } int nPartition = doc.getPartitionNr(sPartition, partitionID); TreeLikelihood treeLikelihood = null; if (nPartition >= 0) { // we ar linking treeLikelihood = likelihoods[nPartition]; } // (TreeLikelihood) doc.pluginmap.get("treeLikelihood." + // tableData[iRow][NAME_COLUMN]); boolean needsRePartition = false; PartitionContext oldContext = new PartitionContext(this.likelihoods[iRow]); switch (nColumn) { case SITEMODEL_COLUMN: { SiteModel.Base siteModel = null; if (treeLikelihood != null) { // getDoc().getPartitionNr(sPartition, // BeautiDoc.SITEMODEL_PARTITION) != // iRow) { siteModel = treeLikelihood.m_pSiteModel.get(); } else { siteModel = (SiteModel) doc.pluginmap.get("SiteModel.s:" + sPartition); if (siteModel != likelihoods[iRow].m_pSiteModel.get()) { PartitionContext context = getPartitionContext(iRow); siteModel = (SiteModel.Base) BeautiDoc.deepCopyPlugin(likelihoods[iRow].m_pSiteModel.get(), likelihoods[iRow], (MCMC) doc.mcmc.get(), context, doc); } } SiteModel.Base target = this.likelihoods[iRow].m_pSiteModel.get(); if (!target.m_pSubstModel.canSetValue(siteModel.m_pSubstModel.get(), target)) { throw new Exception("Cannot link site model: substitution models are incompatible"); } needsRePartition = (this.likelihoods[iRow].m_pSiteModel.get() != siteModel); this.likelihoods[iRow].m_pSiteModel.setValue(siteModel, this.likelihoods[iRow]); sPartition = likelihoods[iRow].m_pSiteModel.get().getID(); sPartition = BeautiDoc.parsePartition(sPartition); getDoc().setCurrentPartition(BeautiDoc.SITEMODEL_PARTITION, iRow, sPartition); } break; case CLOCKMODEL_COLUMN: { BranchRateModel clockModel = null; if (treeLikelihood != null) { // getDoc().getPartitionNr(sPartition, // BeautiDoc.CLOCKMODEL_PARTITION) // != iRow) { clockModel = treeLikelihood.m_pBranchRateModel.get(); } else { clockModel = getDoc().getClockModel(sPartition); if (clockModel != likelihoods[iRow].m_pBranchRateModel.get()) { PartitionContext context = getPartitionContext(iRow); clockModel = (BranchRateModel) BeautiDoc.deepCopyPlugin(likelihoods[iRow].m_pBranchRateModel.get(), likelihoods[iRow], (MCMC) doc.mcmc.get(), context, doc); } } // make sure that *if* the clock model has a tree as input, it is // the same as // for the likelihood Tree tree = null; for (Input<?> input : ((Plugin) clockModel).listInputs()) { if (input.getName().equals("tree")) { tree = (Tree) input.get(); } } if (tree != null && tree != this.likelihoods[iRow].m_tree.get()) { throw new Exception("Cannot link clock model with different trees"); } needsRePartition = (this.likelihoods[iRow].m_pBranchRateModel.get() != clockModel); this.likelihoods[iRow].m_pBranchRateModel.setValue(clockModel, this.likelihoods[iRow]); sPartition = likelihoods[iRow].m_pBranchRateModel.get().getID(); sPartition = BeautiDoc.parsePartition(sPartition); getDoc().setCurrentPartition(BeautiDoc.CLOCKMODEL_PARTITION, iRow, sPartition); } break; case TREE_COLUMN: { Tree tree = null; if (treeLikelihood != null) { // getDoc().getPartitionNr(sPartition, // BeautiDoc.TREEMODEL_PARTITION) != // iRow) { tree = treeLikelihood.m_tree.get(); } else { tree = (Tree) doc.pluginmap.get("Tree.t:" + sPartition); if (tree != likelihoods[iRow].m_tree.get()) { PartitionContext context = getPartitionContext(iRow); tree = (Tree) BeautiDoc.deepCopyPlugin(likelihoods[iRow].m_tree.get(), likelihoods[iRow], (MCMC) doc.mcmc.get(), context, doc); } } // sanity check: make sure taxon sets are compatible String[] taxa = tree.getTaxaNames(); List<String> taxa2 = this.likelihoods[iRow].m_data.get().getTaxaNames(); if (taxa.length != taxa2.size()) { throw new Exception("Cannot link trees: incompatible taxon sets"); } for (String taxon : taxa) { boolean found = false; for (String taxon2 : taxa2) { if (taxon.equals(taxon2)) { found = true; break; } } if (!found) { throw new Exception("Cannot link trees: taxon" + taxon + "is not in alignment"); } } needsRePartition = (this.likelihoods[iRow].m_tree.get() != tree); System.err.println("needsRePartition = " + needsRePartition); if (needsRePartition) { Tree oldTree = this.likelihoods[iRow].m_tree.get(); List<Tree> tModels = new ArrayList<Tree>(); for (TreeLikelihood likelihood : likelihoods) { if (likelihood.m_tree.get() == oldTree) { tModels.add(likelihood.m_tree.get()); } } if (tModels.size() == 1) { // remove old tree from model oldTree.m_bIsEstimated.setValue(false, this.likelihoods[iRow].m_tree.get()); for (Plugin plugin : oldTree.outputs.toArray(new Plugin[0])) { for (Input<?> input : plugin.listInputs()) { try { if (input.get() == oldTree && input.getRule() != Input.Validate.REQUIRED) { input.setValue(null, plugin); } else if (input.get() instanceof List) { List<?> list = (List<?>) input.get(); if (list.contains(oldTree) && input.getRule() != Validate.REQUIRED) { list.remove(oldTree); } } } catch (Exception e) { e.printStackTrace(); } } } } } likelihoods[iRow].m_tree.setValue(tree, likelihoods[iRow]); // TreeDistribution d = getDoc().getTreePrior(sPartition); // CompoundDistribution prior = (CompoundDistribution) // doc.pluginmap.get("prior"); // if (!getDoc().posteriorPredecessors.contains(d)) { // prior.pDistributions.setValue(d, prior); sPartition = likelihoods[iRow].m_tree.get().getID(); sPartition = BeautiDoc.parsePartition(sPartition); getDoc().setCurrentPartition(BeautiDoc.TREEMODEL_PARTITION, iRow, sPartition); } } tableData[iRow][nColumn] = sPartition; if (needsRePartition) { doc.setUpActivePlugins(); List<BeautiSubTemplate> templates = new ArrayList<BeautiSubTemplate>(); templates.add(doc.beautiConfig.partitionTemplate.get()); templates.addAll(doc.beautiConfig.subTemplates); doc.applyBeautiRules(templates, false, oldContext); doc.determinePartitions(); } if (treeLikelihood == null) { initTableData(); setUpComboBoxes(); } } private PartitionContext getPartitionContext(int iRow) { PartitionContext context = new PartitionContext( tableData[iRow][NAME_COLUMN].toString(), tableData[iRow][SITEMODEL_COLUMN].toString(), tableData[iRow][CLOCKMODEL_COLUMN].toString(), tableData[iRow][TREE_COLUMN].toString()); return context; } @Override protected void addInputLabel() { } void initTableData() { this.likelihoods = new TreeLikelihood[nPartitions]; if (tableData == null) { tableData = new Object[nPartitions][8]; } CompoundDistribution likelihoods = (CompoundDistribution) doc.pluginmap.get("likelihood"); for (int i = 0; i < nPartitions; i++) { Alignment data = alignments.get(i); // partition name tableData[i][NAME_COLUMN] = data; // alignment name if (data instanceof FilteredAlignment) { tableData[i][FILE_COLUMN] = ((FilteredAlignment) data).m_alignmentInput.get(); } else { tableData[i][FILE_COLUMN] = data; } // # taxa tableData[i][TAXA_COLUMN] = data.getNrTaxa(); // # sites tableData[i][SITES_COLUMN] = data.getSiteCount(); // Data type tableData[i][TYPE_COLUMN] = data.getDataType(); // site model TreeLikelihood likelihood = (TreeLikelihood) likelihoods.pDistributions.get().get(i); assert (likelihood != null); this.likelihoods[i] = likelihood; tableData[i][SITEMODEL_COLUMN] = getPartition(likelihood.m_pSiteModel); // clock model tableData[i][CLOCKMODEL_COLUMN] = getPartition(likelihood.m_pBranchRateModel); // tree tableData[i][TREE_COLUMN] = getPartition(likelihood.m_tree); } } private String getPartition(Input<?> input) { Plugin plugin = (Plugin) input.get(); String sID = plugin.getID(); String sPartition = BeautiDoc.parsePartition(sID); return sPartition; } protected Component createListBox() { String[] columnData = new String[] { "Name", "File", "Taxa", "Sites", "Data Type", "Site Model", "Clock Model", "Tree" }; initTableData(); // set up table. // special features: background shading of rows // custom editor allowing only Date column to be edited. table = new JTable(tableData, columnData) { private static final long serialVersionUID = 1L; // method that induces table row shading @Override public Component prepareRenderer(TableCellRenderer renderer, int Index_row, int Index_col) { Component comp = super.prepareRenderer(renderer, Index_row, Index_col); // even index, selected or not selected if (isCellSelected(Index_row, Index_col)) { comp.setBackground(Color.gray); } else if (Index_row % 2 == 0 && !isCellSelected(Index_row, Index_col)) { comp.setBackground(new Color(237, 243, 255)); } else { comp.setBackground(Color.white); } return comp; } }; table.setRowHeight(25); table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); table.setColumnSelectionAllowed(false); table.setRowSelectionAllowed(true); table.setName("alignmenttable"); setUpComboBoxes(); TableColumn col = table.getColumnModel().getColumn(NAME_COLUMN); nameEditor = new JTextField(); nameEditor.getDocument().addDocumentListener(new DocumentListener() { @Override public void removeUpdate(DocumentEvent e) { processPartitionName(); } @Override public void insertUpdate(DocumentEvent e) { processPartitionName(); } @Override public void changedUpdate(DocumentEvent e) { processPartitionName(); } }); col.setCellEditor(new DefaultCellEditor(nameEditor)); // // set up editor that makes sure only doubles are accepted as entry // // and only the Date column is editable. table.setDefaultEditor(Object.class, new TableCellEditor() { JTextField m_textField = new JTextField(); int m_iRow, m_iCol; @Override public boolean stopCellEditing() { System.err.println("stopCellEditing()"); table.removeEditor(); String sText = m_textField.getText(); try { Double.parseDouble(sText); } catch (Exception e) { return false; } tableData[m_iRow][m_iCol] = sText; return true; } @Override public boolean isCellEditable(EventObject anEvent) { System.err.println("isCellEditable()"); return table.getSelectedColumn() == 0; } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int iRow, int iCol) { return null; } @Override public boolean shouldSelectCell(EventObject anEvent) { return false; } @Override public void removeCellEditorListener(CellEditorListener l) { } @Override public Object getCellEditorValue() { return null; } @Override public void cancelCellEditing() { } @Override public void addCellEditorListener(CellEditorListener l) { } }); // show alignment viewer when double clicking a row table.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() > 1) { try { int iAlignmemt = table.rowAtPoint(e.getPoint()); Alignment alignment = alignments.get(iAlignmemt); int best = 0; BeautiAlignmentProvider provider = null; for (BeautiAlignmentProvider provider2 : doc.beautiConfig.alignmentProvider) { int match = provider2.matches(alignment); if (match > best) { best = match; provider = provider2; } } provider.editAlignment(alignment, doc); } catch (Exception e1) { e1.printStackTrace(); } } } }); JScrollPane scrollPane = new JScrollPane(table); return scrollPane; } // createListBox void setUpComboBoxes() { // set up comboboxes Set<String>[] partitionNames = new HashSet[3]; for (int i = 0; i < 3; i++) { partitionNames[i] = new HashSet<String>(); } for (int i = 0; i < nPartitions; i++) { partitionNames[0].add(likelihoods[i].m_pSiteModel.get().getID()); partitionNames[1].add(likelihoods[i].m_pBranchRateModel.get().getID()); partitionNames[2].add(likelihoods[i].m_tree.get().getID()); } String[][] sPartitionNames = new String[3][]; for (int i = 0; i < 3; i++) { sPartitionNames[i] = partitionNames[i].toArray(new String[0]); } for (int j = 0; j < 3; j++) { for (int i = 0; i < sPartitionNames[j].length; i++) { sPartitionNames[j][i] = BeautiDoc.parsePartition(sPartitionNames[j][i]); } } TableColumn col = table.getColumnModel().getColumn(SITEMODEL_COLUMN); JComboBox siteModelComboBox = new JComboBox(sPartitionNames[0]); siteModelComboBox.setEditable(true); siteModelComboBox.addActionListener(new ComboActionListener(SITEMODEL_COLUMN)); col.setCellEditor(new DefaultCellEditor(siteModelComboBox)); // If the cell should appear like a combobox in its // non-editing state, also set the combobox renderer col.setCellRenderer(new MyComboBoxRenderer(sPartitionNames[0])); col = table.getColumnModel().getColumn(CLOCKMODEL_COLUMN); JComboBox clockModelComboBox = new JComboBox(sPartitionNames[1]); clockModelComboBox.setEditable(true); clockModelComboBox.addActionListener(new ComboActionListener(CLOCKMODEL_COLUMN)); col.setCellEditor(new DefaultCellEditor(clockModelComboBox)); col.setCellRenderer(new MyComboBoxRenderer(sPartitionNames[1])); col = table.getColumnModel().getColumn(TREE_COLUMN); JComboBox treeComboBox = new JComboBox(sPartitionNames[2]); treeComboBox.setEditable(true); treeComboBox.addActionListener(new ComboActionListener(TREE_COLUMN)); col.setCellEditor(new DefaultCellEditor(treeComboBox)); col.setCellRenderer(new MyComboBoxRenderer(sPartitionNames[2])); col = table.getColumnModel().getColumn(TAXA_COLUMN); col.setPreferredWidth(30); col = table.getColumnModel().getColumn(SITES_COLUMN); col.setPreferredWidth(30); } void processPartitionName() { System.err.println("processPartitionName"); System.err.println(table.getSelectedColumn() + " " + table.getSelectedRow()); String oldName = tableData[table.getSelectedRow()][table.getSelectedColumn()].toString(); String newName = nameEditor.getText(); if (!oldName.equals(newName)) { try { int partitionID = -2; switch (table.getSelectedColumn()) { case NAME_COLUMN: partitionID = BeautiDoc.ALIGNMENT_PARTITION; break; case SITEMODEL_COLUMN: partitionID = BeautiDoc.SITEMODEL_PARTITION; break; case CLOCKMODEL_COLUMN: partitionID = BeautiDoc.CLOCKMODEL_PARTITION; break; case TREE_COLUMN: partitionID = BeautiDoc.TREEMODEL_PARTITION; break; default: throw new Exception("Cannot rename item in column"); } getDoc().renamePartition(partitionID, oldName, newName); table.setValueAt(newName, table.getSelectedRow(), table.getSelectedColumn()); setUpComboBoxes(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Renaming failed: " + e.getMessage()); } } // debugging code: for (int i = 0; i < nPartitions; i++) { System.err.println(i + " " + tableData[i][0]); } } class ComboActionListener implements ActionListener { int m_nColumn; public ComboActionListener(int nColumn) { m_nColumn = nColumn; } @Override public void actionPerformed(ActionEvent e) { // SwingUtilities.invokeLater(new Runnable() { // @Override // public void run() { System.err.println("actionPerformed "); System.err.println(table.getSelectedRow() + " " + table.getSelectedColumn()); if (table.getSelectedRow() >= 0 && table.getSelectedColumn() >= 0) { System.err.println(" " + table.getValueAt(table.getSelectedRow(), table.getSelectedColumn())); } for (int i = 0; i < nPartitions; i++) { try { updateModel(m_nColumn, i); } catch (Exception ex) { System.err.println(ex.getMessage()); } } } } public class MyComboBoxRenderer extends JComboBox implements TableCellRenderer { private static final long serialVersionUID = 1L; public MyComboBoxRenderer(String[] items) { super(items); setOpaque(true); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (isSelected) { // setForeground(table.getSelectionForeground()); super.setBackground(table.getSelectionBackground()); } else { setForeground(table.getForeground()); setBackground(table.getBackground()); } // Select the current value setSelectedItem(value); return this; } } @Override protected void addSingleItem(Plugin plugin) { initTableData(); repaint(); } @Override protected void addItem() { List<Plugin> plugins = pluginSelector(m_input, m_plugin, null); // Component c = this; if (plugins != null) { refreshPanel(); } } // addItem void delItem() { int[] nSelected = getTableRowSelection(); if (nSelected.length == 0) { JOptionPane.showMessageDialog(this, "Select partitions to delete, before hitting the delete button"); } // do the actual deleting for (int i = nSelected.length - 1; i >= 0; i int iRow = nSelected[i]; // before deleting, unlink site model, clock model and tree // check whether any of the models are linked BranchRateModel.Base clockModel = likelihoods[iRow].m_pBranchRateModel.get(); SiteModel.Base siteModel = likelihoods[iRow].m_pSiteModel.get(); Tree tree = likelihoods[iRow].m_tree.get(); List<TreeLikelihood> cModels = new ArrayList<TreeLikelihood>(); List<TreeLikelihood> sModels = new ArrayList<TreeLikelihood>(); List<TreeLikelihood> tModels = new ArrayList<TreeLikelihood>(); for (TreeLikelihood likelihood : likelihoods) { if (likelihood != likelihoods[iRow]) { if (likelihood.m_pBranchRateModel.get() == clockModel) { cModels.add(likelihood); } if (likelihood.m_pSiteModel.get() == siteModel) { sModels.add(likelihood); } if (likelihood.m_tree.get() == tree) { tModels.add(likelihood); } } } try { if (cModels.size() > 0) { // clock model is linked, so we need to unlink if (doc.getPartitionNr(clockModel) != iRow) { tableData[iRow][CLOCKMODEL_COLUMN] = getDoc().sPartitionNames.get(iRow).partition; } else { int iFreePartition = doc.getPartitionNr(cModels.get(0)); tableData[iRow][CLOCKMODEL_COLUMN] = getDoc().sPartitionNames.get(iFreePartition).partition; } updateModel(CLOCKMODEL_COLUMN, iRow); } if (sModels.size() > 0) { // site model is linked, so we need to unlink if (doc.getPartitionNr(siteModel) != iRow) { tableData[iRow][SITEMODEL_COLUMN] = getDoc().sPartitionNames.get(iRow).partition; } else { int iFreePartition = doc.getPartitionNr(sModels.get(0)); tableData[iRow][SITEMODEL_COLUMN] = getDoc().sPartitionNames.get(iFreePartition).partition; } updateModel(SITEMODEL_COLUMN, iRow); } if (tModels.size() > 0) { // tree is linked, so we need to unlink if (doc.getPartitionNr(tree) != iRow) { tableData[iRow][TREE_COLUMN] = getDoc().sPartitionNames.get(iRow).partition; } else { int iFreePartition = doc.getPartitionNr(tModels.get(0)); tableData[iRow][TREE_COLUMN] = getDoc().sPartitionNames.get(iFreePartition).partition; } updateModel(TREE_COLUMN, iRow); } getDoc().delAlignmentWithSubnet(alignments.get(iRow)); alignments.remove(iRow); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Deletion failed: " + e.getMessage()); e.printStackTrace(); } } refreshPanel(); } // delItem void splitItem() { int[] nSelected = getTableRowSelection(); if (nSelected.length == 0) { JOptionPane.showMessageDialog(this, "Select partitions to split, before hitting the split button"); return; } String[] options = { "{1,2} + 3", "{1,2} + 3 frame 2", "{1,2} + 3 frame 3", "1 + 2 + 3", "1 + 2 + 3 frame 2", "1 + 2 + 3 frame 3"}; String option = (String)JOptionPane.showInputDialog(null, "Split selected alignments into partitions", "Option", JOptionPane.WARNING_MESSAGE, null, options, "1 + 2 + 3"); if (option == null) { return; } String[] filters = null; String[] ids = null; if (option.equals(options[0])) { filters = new String[] { "1::3,2::3", "3::3" }; ids = new String[] { "_1,2", "_3" }; } else if (option.equals(options[1])) { filters = new String[] { "1::3,3::3", "2::3" }; ids = new String[] { "_1,2", "_3" }; } else if (option.equals(options[2])) { filters = new String[] { "2::3,3::3", "1::3" }; ids = new String[] { "_1,2", "_3" }; } else if (option.equals(options[3])) { filters = new String[] { "1::3", "2::3", "3::3" }; ids = new String[] { "_1", "_2", "_3" }; } else if (option.equals(options[4])) { filters = new String[] { "2::3", "3::3", "1::3" }; ids = new String[] { "_1", "_2", "_3" }; } else if (option.equals(options[5])) { filters = new String[] { "3::3", "1::3", "2::3" }; ids = new String[] { "_1", "_2", "_3" }; } else { return; } for (int i = nSelected.length - 1; i >= 0; i int iRow = nSelected[i]; Alignment alignment = alignments.remove(iRow); getDoc().delAlignmentWithSubnet(alignment); try { for (int j = 0; j < filters.length; j++) { FilteredAlignment f = new FilteredAlignment(); f.initByName("data", alignment, "filter", filters[j], "dataType", alignment.m_sDataType.get()); f.setID(alignment.getID() + ids[j]); getDoc().addAlignmentWithSubnet(f); } } catch (Exception e) { e.printStackTrace(); } } refreshPanel(); } // splitItem @Override public List<Plugin> pluginSelector(Input<?> input, Plugin plugin, List<String> sTabuList) { List<BeautiAlignmentProvider> providers = doc.beautiConfig.alignmentProvider; BeautiAlignmentProvider selectedProvider = null; if (providers.size() == 1) { selectedProvider = providers.get(0); } else { selectedProvider = (BeautiAlignmentProvider) JOptionPane.showInputDialog(this, "Select what to add", "Add partition", JOptionPane.QUESTION_MESSAGE, null, providers.toArray(), providers.get(0)); if (selectedProvider == null) { return null; } } List<Plugin> selectedPlugins = selectedProvider.getAlignments(doc); return selectedPlugins; } // pluginSelector } // class AlignmentListInputEditor
package cn.momia.mapi.api.v1.feed; import cn.momia.api.course.CourseServiceApi; import cn.momia.api.course.dto.CourseDto; import cn.momia.api.feed.FeedServiceApi; import cn.momia.api.feed.dto.FeedCommentDto; import cn.momia.api.feed.dto.FeedDto; import cn.momia.api.feed.dto.FeedStarDto; import cn.momia.api.user.UserServiceApi; import cn.momia.api.user.dto.UserDto; import cn.momia.common.api.dto.PagedList; import cn.momia.common.api.http.MomiaHttpResponse; import cn.momia.common.webapp.config.Configuration; import cn.momia.image.api.ImageFile; import cn.momia.mapi.api.v1.AbstractV1Api; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/v1/feed") public class FeedV1Api extends AbstractV1Api { @Autowired private CourseServiceApi courseServiceApi; @Autowired private FeedServiceApi feedServiceApi; @Autowired private UserServiceApi userServiceApi; @RequestMapping(value = "/follow", method = RequestMethod.POST) public MomiaHttpResponse follow(@RequestParam String utoken, @RequestParam(value = "fuid") long followedId) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (followedId <= 0) return MomiaHttpResponse.BAD_REQUEST; UserDto followedUser = userServiceApi.get(followedId); if (!followedUser.exists()) return MomiaHttpResponse.FAILED(""); UserDto user = userServiceApi.get(utoken); feedServiceApi.follow(user.getId(), followedId); return MomiaHttpResponse.SUCCESS; } @RequestMapping(method = RequestMethod.GET) public MomiaHttpResponse list(@RequestParam(required = false, defaultValue = "") String utoken, @RequestParam int start) { if (start < 0) return MomiaHttpResponse.BAD_REQUEST; long userId = 0; if (!StringUtils.isBlank(utoken)) { UserDto user = userServiceApi.get(utoken); userId = user.getId(); } PagedList<FeedDto> pagedFeeds = feedServiceApi.list(userId, start, Configuration.getInt("PageSize.Feed")); processFeeds(pagedFeeds.getList()); return MomiaHttpResponse.SUCCESS(pagedFeeds); } @RequestMapping(value = "/course", method = RequestMethod.GET) public MomiaHttpResponse course(@RequestParam(defaultValue = "") String utoken, @RequestParam(value = "coid") long courseId, @RequestParam final int start) { if (courseId <= 0 || start < 0) return MomiaHttpResponse.BAD_REQUEST; JSONObject courseFeedsJson = new JSONObject(); if (start == 0) { CourseDto course = courseServiceApi.get(courseId, CourseDto.Type.BASE); course.setCover(ImageFile.largeUrl(course.getCover())); courseFeedsJson.put("course", course); } long userId = StringUtils.isBlank(utoken) ? 0 : userServiceApi.get(utoken).getId(); PagedList<FeedDto> pagedFeeds = feedServiceApi.queryByCourse(userId, courseId, start, Configuration.getInt("PageSize.Feed")); processFeeds(pagedFeeds.getList()); courseFeedsJson.put("feeds", pagedFeeds); return MomiaHttpResponse.SUCCESS(courseFeedsJson); } @RequestMapping(value = "/course/list", method = RequestMethod.GET) public MomiaHttpResponse listCourses(@RequestParam String utoken, @RequestParam int start) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (start < 0) return MomiaHttpResponse.BAD_REQUEST; PagedList<? extends CourseDto> pagedCourses; UserDto user = userServiceApi.get(utoken); if (!feedServiceApi.isOfficialUser(user.getId())) { pagedCourses = courseServiceApi.queryFinishedByUser(user.getId(), start, Configuration.getInt("PageSize.Course")); } else { pagedCourses = courseServiceApi.listFinished(start, Configuration.getInt("PageSize.Course")); } for (CourseDto course : pagedCourses.getList()) { course.setCover(ImageFile.largeUrl(course.getCover())); } return MomiaHttpResponse.SUCCESS(pagedCourses); } @RequestMapping(value = "/tag", method = RequestMethod.GET) public MomiaHttpResponse listTags() { return MomiaHttpResponse.SUCCESS(feedServiceApi.listTags(Configuration.getInt("PageSize.FeedTag"))); } @RequestMapping(value = "/add", method = RequestMethod.POST) public MomiaHttpResponse add(@RequestParam String utoken, @RequestParam String feed) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (StringUtils.isBlank(feed)) return MomiaHttpResponse.BAD_REQUEST; UserDto user = userServiceApi.get(utoken); JSONObject feedJson = JSON.parseObject(feed); feedJson.put("userId", user.getId()); CourseDto course = courseServiceApi.get(feedJson.getLong("courseId"), CourseDto.Type.BASE); feedJson.put("subjectId", course.getSubjectId()); if (!courseServiceApi.joined(user.getId(), feedJson.getLong("courseId"))) return MomiaHttpResponse.FAILED("Feed"); feedServiceApi.add(feedJson); return MomiaHttpResponse.SUCCESS; } @RequestMapping(value = "/detail", method = RequestMethod.GET) public MomiaHttpResponse detail(@RequestParam(defaultValue = "") String utoken, @RequestParam long id) { if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; long userId = StringUtils.isBlank(utoken) ? 0 : userServiceApi.get(utoken).getId(); FeedDto feed = feedServiceApi.get(userId, id); processFeed(feed); PagedList<FeedStarDto> stars = feedServiceApi.listStars(id, 0, Configuration.getInt("PageSize.FeedDetailStar")); processStars(stars.getList()); PagedList<FeedCommentDto> comments = feedServiceApi.listComments(id, 0, Configuration.getInt("PageSize.FeedDetailComment")); processComments(comments.getList()); CourseDto course = courseServiceApi.get(feed.getCourseId(), CourseDto.Type.BASE); course.setCover(ImageFile.largeUrl(course.getCover())); JSONObject feedDetailJson = new JSONObject(); feedDetailJson.put("feed", feed); feedDetailJson.put("staredUsers", stars); feedDetailJson.put("comments", comments); feedDetailJson.put("course", course); return MomiaHttpResponse.SUCCESS(feedDetailJson); } private void processStars(List<FeedStarDto> stars) { for (FeedStarDto star : stars) { star.setAvatar(ImageFile.smallUrl(star.getAvatar())); } } private void processComments(List<FeedCommentDto> comments) { for (FeedCommentDto comment : comments) { comment.setAvatar(ImageFile.smallUrl(comment.getAvatar())); } } @RequestMapping(value = "/delete", method = RequestMethod.POST) public MomiaHttpResponse delete(@RequestParam String utoken, @RequestParam long id) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; UserDto user = userServiceApi.get(utoken); if (!feedServiceApi.delete(user.getId(), id)) return MomiaHttpResponse.FAILED("Feed"); return MomiaHttpResponse.SUCCESS; } @RequestMapping(value = "/comment", method = RequestMethod.GET) public MomiaHttpResponse listComments(@RequestParam long id, @RequestParam int start) { if (id <= 0 || start < 0) return MomiaHttpResponse.BAD_REQUEST; PagedList<FeedCommentDto> pagedComments = feedServiceApi.listComments(id, start, Configuration.getInt("PageSize.FeedComment")); processComments(pagedComments.getList()); return MomiaHttpResponse.SUCCESS(pagedComments); } @RequestMapping(value = "/comment/add", method = RequestMethod.POST) public MomiaHttpResponse addComment(@RequestParam String utoken, @RequestParam long id, @RequestParam String content) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (id <= 0 || StringUtils.isBlank(content)) return MomiaHttpResponse.BAD_REQUEST; UserDto user = userServiceApi.get(utoken); feedServiceApi.addComment(user.getId(), id, content); return MomiaHttpResponse.SUCCESS; } @RequestMapping(value = "/comment/delete", method = RequestMethod.POST) public MomiaHttpResponse deleteComment(@RequestParam String utoken, @RequestParam long id, @RequestParam(value = "cmid") long commentId) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (id <= 0 || commentId <= 0) return MomiaHttpResponse.BAD_REQUEST; UserDto user = userServiceApi.get(utoken); feedServiceApi.deleteComment(user.getId(), id, commentId); return MomiaHttpResponse.SUCCESS; } @RequestMapping(value = "/star", method = RequestMethod.POST) public MomiaHttpResponse star(@RequestParam String utoken, @RequestParam long id) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; UserDto user = userServiceApi.get(utoken); feedServiceApi.star(user.getId(), id); return MomiaHttpResponse.SUCCESS; } @RequestMapping(value = "/unstar", method = RequestMethod.POST) public MomiaHttpResponse unstar(@RequestParam String utoken, @RequestParam long id) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; UserDto user = userServiceApi.get(utoken); feedServiceApi.unstar(user.getId(), id); return MomiaHttpResponse.SUCCESS; } }
package io.github.aquerr.eaglefactions; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.format.TextColors; public abstract class PluginInfo { public static final String Id = "eaglefactions"; public static final String Name = "Eagle Factions"; public static final String Version = "0.9.8"; public static final String Description = "A factions plugin that will make managing your battle-server easier. :)"; public static final Text PluginPrefix = Text.of(TextColors.AQUA, "[EF]: "); public static final Text ErrorPrefix = Text.of(TextColors.DARK_RED, "[EF]: "); public static final String Author = "Aquerr"; }
package otld.otld.jvm; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.util.CheckClassAdapter; import otld.otld.Compiler; import otld.otld.intermediate.*; import java.util.*; /** * Compiler for compiling an intermediate Program to Java bytecode. * * This compiler targets Java version 1.7. Compiled programs can be run on any JRE that supports this language level, * which will most likely be JRE 7 or higher. * * Use {@code compileDebug()} instead of {@code compile()} to test ASM visitor calls. */ public class BytecodeCompiler extends Compiler { /** The compilation result. */ private byte[] result; /** The actual class writer. */ private ClassWriter writer; /** The visitor for writing a class. Will contain the class writer, possibly with adapters. */ private ClassVisitor visitor; /** Visitor for the current method. Can be {@code null}. */ private MethodVisitor methodVisitor; /** The storage location of variables. A negative value indicates that the variable is a field. */ private Map<Variable, Integer> localStorage; /** The local variable containing the class instance. */ private int objectLocation; /** The targets for the break operation. */ private Stack<Label> breakTargets; /** Variables with an initial value. */ private Set<Variable> initialVariables; /** The number of local variables used. */ private int maxLocal = 16; // Sane default /** The number of stack positions used. */ private int maxStack = 16; // Sane default /** * Creates a new compiler for Java bytecode. * @param program The program to compile. */ public BytecodeCompiler(final Program program) { super(program); this.result = new byte[0]; this.writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); this.visitor = this.writer; this.methodVisitor = null; this.localStorage = new HashMap<>(); this.objectLocation = 0; this.breakTargets = new Stack<>(); this.initialVariables = new HashSet<>(); } @Override public void compile() { this.visitProgram(this.program); this.result = this.writer.toByteArray(); this.compiled = true; } /** * Compiles the program while checking the ASM visitor calls made by the compiler. * This method is for debug purposes only and should not be used in production. */ public void compileDebug() { // Set debug visitor this.visitor = new CheckClassAdapter(this.writer); // Call compile as normal this.compile(); } @Override public byte[] asByteArray() { return this.result; } /** * Returns the location of the variable. * * A postitive number indicates the local storage slot the variable is in. * A negative number indicates that the variable is a field. * Zero is a special value and indicates the local class instance ({@code this}). * * @param variable The variable to get the location for. * @return The location of the variable. */ protected int getVariableLocation(final Variable variable) { // Defaults to -1, which indicates the variable is a field, as most variables are fields. return this.localStorage.getOrDefault(variable, -1); } /** * Sets the location of a variable. * * A postitive number indicates the local storage slot the variable is in. * A negative number indicates that the variable is a field. * Zero is a special value and indicates the local class instance ({@code this}). * * @param variable The variable to set the location for. * @param location The location of the variable. */ protected void setVariableLocation(final Variable variable, final int location) { this.localStorage.put(variable, location); } /** * Visitor method for when a variable value is needed on the stack. * Writes instructions that push the value of the variable to the top of the stack. * @param variable The variable to load. */ protected void visitLoadVariable(final Variable variable) { final int location = this.getVariableLocation(variable); if (location < 0) { // Put object reference on stack this.methodVisitor.visitVarInsn(Opcodes.ALOAD, this.objectLocation); // Put field value on stack this.methodVisitor.visitFieldInsn(Opcodes.GETFIELD, this.program.getId(), variable.getId(), ASM.getASMType(variable.getType()).getDescriptor()); } else { // Put value on stack switch (variable.getType()) { case BOOL: case INT: case CHAR: this.methodVisitor.visitVarInsn(Opcodes.ILOAD, location); break; default: this.unsupported(variable); } } } /** * Visitor method for when a value must be stored in a variable. * Writes instructions that push the value of the variable to the top of the stack. * @param variable The variable to write. */ protected void visitStoreVariable(final Variable variable) { final int location = this.getVariableLocation(variable); if (location < 0) { // Put object reference on stack this.methodVisitor.visitVarInsn(Opcodes.ALOAD, this.objectLocation); this.methodVisitor.visitInsn(Opcodes.SWAP); // Put field value on stack this.methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, this.program.getId(), variable.getId(), ASM.getASMType(variable.getType()).getDescriptor()); } else { // Store value in local variable switch (variable.getType()) { case BOOL: case INT: case CHAR: this.methodVisitor.visitVarInsn(Opcodes.ISTORE, location); break; default: this.unsupported(variable); } } } @Override protected void visitApplication(final Application application) { // Load argument values onto stack for (Variable arg : application.getArgs()) { this.visitLoadVariable(arg); } // Do operation and put result on stack this.visitOperator(application.getOperator()); // Store result this.visitStoreVariable(application.getVariable()); } @Override protected void visitAssignment(final Assignment assignment) { // Forward call to specialized visitor if (assignment instanceof ValueAssignment) { this.visitValueAssignment((ValueAssignment) assignment); } else if (assignment instanceof VariableAssignment) { this.visitVariableAssignment((VariableAssignment) assignment); } else { this.unsupported(assignment); } } @Override protected void visitBlock(final Block block) { // Forward call to specialized visitor if (block instanceof Conditional) { this.visitConditional((Conditional) block); } else if (block instanceof Loop) { this.visitLoop((Loop) block); } else { this.unsupported(block); } } @Override protected void visitBreak(Break brake) { // Check if there is a block to break out of if (this.breakTargets.empty()) { // If not, "break" out of the program with a void return this.methodVisitor.visitInsn(Opcodes.RETURN); } else { // Jump to the break target of the block this.methodVisitor.visitJumpInsn(Opcodes.GOTO, this.breakTargets.peek()); } } @Override protected void visitCall(Call call) { // Put object reference for field on stack this.methodVisitor.visitVarInsn(Opcodes.ALOAD, this.objectLocation); // Put argument values on stack. for (Variable arg : call.getArgs()) { this.visitLoadVariable(arg); } // Execute method and put result on stack this.methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, this.program.getId(), call.getFunction().getId(), ASM.getASMMethodType(call.getFunction().getType(), call.getFunction().getArgs()).getDescriptor(), false); // Store result in variable this.visitStoreVariable(call.getVariable()); } @Override protected void visitConditional(Conditional conditional) { // Create labels for jumps final Label labelFalse = new Label(); final Label labelEnd = new Label(); // Set break target this.breakTargets.push(labelEnd); // Put condition onto stack this.visitLoadVariable(conditional.getCondition()); // Jump if condition is false this.methodVisitor.visitJumpInsn(Opcodes.IFEQ, labelFalse); // Add 'true' body this.visitOperationSequence(conditional.getBodyTrue()); // Jump to end this.methodVisitor.visitJumpInsn(Opcodes.GOTO, labelEnd); // Place 'false' label this.methodVisitor.visitLabel(labelFalse); // Add 'false' body this.visitOperationSequence(conditional.getBodyFalse()); // Place 'end' label this.methodVisitor.visitLabel(labelEnd); // Unset break target this.breakTargets.pop(); } @Override protected void visitFunction(Function function) { // Set variable locations final Variable[] variables = function.getVariables(); for (int i = 0; i < variables.length; i++) { this.setVariableLocation(variables[i], i + 1); } // Create new method this.methodVisitor = this.visitor.visitMethod(Opcodes.ACC_PUBLIC, function.getId(), ASM.getASMMethodType(function.getType(), function.getArgs()).getDescriptor(), null, null); // Start method body this.methodVisitor.visitCode(); // Add method instructions this.visitOperationSequence(function.getBody()); // End method body this.methodVisitor.visitMaxs(this.maxStack, this.maxLocal); this.methodVisitor.visitEnd(); } @Override protected void visitInput(Input input) { // Create new scanner this.methodVisitor.visitTypeInsn(Opcodes.NEW, "java/util/Scanner"); this.methodVisitor.visitInsn(Opcodes.DUP); // Put reference to System.in on stack this.methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "in", "Ljava/io/InputStream;"); // Call constructor with argument this.methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/util/Scanner", "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType("Ljava/io/InputStream;")), false); // Print query this.methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); this.methodVisitor.visitLdcInsn(input.getQuery()); this.methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "print", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class)), false); // Consume scanner and put input value on stack switch (input.getDestination().getType()) { case BOOL: this.methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/Scanner", "nextBoolean", Type.getMethodDescriptor(Type.BOOLEAN_TYPE), false); break; case INT: this.methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/Scanner", "nextInt", Type.getMethodDescriptor(Type.INT_TYPE), false); break; case CHAR: // Put regex for a single char on the stack this.methodVisitor.visitLdcInsn("."); this.methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/Scanner", "next", Type.getMethodDescriptor(Type.getType(String.class)), false); // Consume string result and put the first char on the stack this.methodVisitor.visitIntInsn(Opcodes.SIPUSH, 0); this.methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/String", "charAt", Type.getMethodDescriptor(Type.CHAR_TYPE, Type.INT_TYPE), false); break; default: this.unsupported(input); } // Store input in variable this.visitStoreVariable(input.getDestination()); } @Override protected void visitLoop(Loop loop) { // Create labels for jumps final Label labelCond = new Label(); final Label labelEnd = new Label(); // Set break target this.breakTargets.push(labelEnd); // Place condition label this.methodVisitor.visitLabel(labelCond); // Execute condition body this.visitOperationSequence(loop.getConditionBody()); // Load condition onto stack this.visitLoadVariable(loop.getCondition()); // Jump to end if condition is false this.methodVisitor.visitJumpInsn(Opcodes.IFEQ, labelEnd); // Add loop instructions this.visitOperationSequence(loop.getBody()); // Jump back to condition this.methodVisitor.visitJumpInsn(Opcodes.GOTO, labelCond); // Place end label this.methodVisitor.visitLabel(labelEnd); // Unset break target this.breakTargets.pop(); } @Override protected void visitOperation(Operation operation) { // Forward call to specialized visitor if (operation instanceof Application) { this.visitApplication((Application) operation); } else if (operation instanceof Assignment) { this.visitAssignment((Assignment) operation); } else if (operation instanceof Break) { this.visitBreak((Break) operation); } else if (operation instanceof Block) { this.visitBlock((Block) operation); } else if (operation instanceof Call) { this.visitCall((Call) operation); } else if (operation instanceof Input) { this.visitInput((Input) operation); } else if (operation instanceof Output) { this.visitOutput((Output) operation); } else if (operation instanceof Return) { this.visitReturn((Return) operation); } else { this.unsupported(operation); } } @Override protected void visitOperationSequence(OperationSequence sequence) { // Visit all operations in the sequence. for (Operation operation : sequence) { this.visitOperation(operation); } } @Override protected void visitOperator(Operator operator) { // Write the correct opcode for the operator switch (operator) { case ADDITION: this.methodVisitor.visitInsn(Opcodes.IADD); break; case SUBTRACTION: this.methodVisitor.visitInsn(Opcodes.ISUB); break; case MULTIPLICATION: this.methodVisitor.visitInsn(Opcodes.IMUL); break; case DIVISION: this.methodVisitor.visitInsn(Opcodes.IDIV); break; case MODULUS: this.methodVisitor.visitInsn(Opcodes.IREM); break; case AND: case LAND: this.methodVisitor.visitInsn(Opcodes.IAND); break; case OR: case LOR: this.methodVisitor.visitInsn(Opcodes.IOR); break; case LXOR: this.methodVisitor.visitInsn(Opcodes.IXOR); break; case NOT: this.methodVisitor.visitIntInsn(Opcodes.SIPUSH, 1); this.methodVisitor.visitInsn(Opcodes.IADD); this.methodVisitor.visitIntInsn(Opcodes.SIPUSH, 2); this.methodVisitor.visitInsn(Opcodes.IREM); break; case COMPLTE: case COMPGTE: case COMPLT: case COMPGT: case EQUALS: case NEQUALS: // Create labels for jumps in comparison operators final Label labelTrue = new Label(); final Label labelEnd = new Label(); // Subtract values for comparison with 0 this.methodVisitor.visitInsn(Opcodes.ISUB); // Compare using appropriate operation switch (operator) { case COMPLTE: this.methodVisitor.visitJumpInsn(Opcodes.IFLE, labelTrue); break; case COMPGTE: this.methodVisitor.visitJumpInsn(Opcodes.IFGE, labelTrue); break; case COMPLT: this.methodVisitor.visitJumpInsn(Opcodes.IFLT, labelTrue); break; case COMPGT: this.methodVisitor.visitJumpInsn(Opcodes.IFGT, labelTrue); break; case EQUALS: this.methodVisitor.visitJumpInsn(Opcodes.IFEQ, labelTrue); break; case NEQUALS: this.methodVisitor.visitJumpInsn(Opcodes.IFNE, labelTrue); break; default: this.unsupported(operator); } // Put 0 on stack for false this.methodVisitor.visitInsn(Opcodes.ICONST_0); this.methodVisitor.visitJumpInsn(Opcodes.GOTO, labelEnd); // Put 1 on stack for true this.methodVisitor.visitLabel(labelTrue); this.methodVisitor.visitInsn(Opcodes.ICONST_1); // Add end label this.methodVisitor.visitLabel(labelEnd); break; default: this.unsupported(operator); } } @Override protected void visitOutput(Output output) { // Put references to System.out on stack this.methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); this.methodVisitor.visitInsn(Opcodes.DUP); // Put string constant on stack this.methodVisitor.visitLdcInsn(output.getDescription()); // Call print this.methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "print", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Object.class)), false); // Put value on stack this.visitLoadVariable(output.getSource()); // Call println this.methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", Type.getMethodDescriptor(Type.VOID_TYPE, ASM.getASMType(output.getSource().getType())), false); } @Override protected void visitProgram(Program program) { // Create new class this.visitor.visit(Opcodes.V1_7, Opcodes.ACC_PUBLIC, program.getId(), null, "java/lang/Object", null); // Declare variables as fields for (Variable variable : program.getVariables()) { this.visitVariable(variable); } // Declare functions as methods for (Function function : program.getFunctions()) { this.visitFunction(function); } // Build constructor this.visitProgramConstructor(program); // Build main method this.visitProgramMain(program); } protected void visitProgramConstructor(final Program program) { // Add class constructor this.methodVisitor = this.visitor.visitMethod(Opcodes.ACC_PUBLIC, "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), null, null); // Set body of constructor this.methodVisitor.visitCode(); // Call superclass constructor this.methodVisitor.visitVarInsn(Opcodes.ALOAD, this.objectLocation); this.methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); // Set initial values for variables for (Variable variable : this.initialVariables) { this.visitValueAssignment(variable.createValueAssignment(variable.getInitialValue())); } // Void return this.methodVisitor.visitInsn(Opcodes.RETURN); this.methodVisitor.visitMaxs(this.maxStack, this.maxLocal); this.methodVisitor.visitEnd(); } protected void visitProgramMain(final Program program) { // Store current object location final int oldObjectLocation = this.objectLocation; // Set object location for main method. this.objectLocation = 1; // Add main method this.methodVisitor = this.visitor.visitMethod(Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC, "main", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String[].class)), null, null); // Begin main method code this.methodVisitor.visitCode(); // Create new instance this.methodVisitor.visitTypeInsn(Opcodes.NEW, program.getId()); this.methodVisitor.visitInsn(Opcodes.DUP); this.methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, program.getId(), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); // Store instance in local storage this.methodVisitor.visitVarInsn(Opcodes.ASTORE, this.objectLocation); // Add method instructions this.visitOperationSequence(program.getBody()); // Add void return this.methodVisitor.visitInsn(Opcodes.RETURN); // End main method code this.methodVisitor.visitMaxs(this.maxStack, this.maxLocal); this.methodVisitor.visitEnd(); // Restore object location this.objectLocation = oldObjectLocation; } @Override protected void visitReturn(Return returm) { // Load value onto stack this.visitLoadVariable(returm.getSource()); // Return value with correct operation for each type switch (returm.getSource().getType()) { case BOOL: case INT: case CHAR: this.methodVisitor.visitInsn(Opcodes.IRETURN); break; default: this.unsupported(returm); } } @Override protected void visitValueAssignment(ValueAssignment assignment) { // Put value on stack for different types switch (assignment.getDestination().getType()) { case BOOL: this.visitIntConst(((boolean) assignment.getValue()) ? 1 : 0); // True = 1, False = 0 break; case INT: this.visitIntConst((int) assignment.getValue()); break; case CHAR: this.visitIntConst((int) (char) assignment.getValue()); // Integer value of character break; default: this.unsupported(assignment); } // Store value to variable this.visitStoreVariable(assignment.getDestination()); } @Override protected void visitVariable(Variable variable) { // Add field for the variable this.visitor.visitField(Opcodes.ACC_PUBLIC, variable.getId(), ASM.getASMType(variable.getType()).getDescriptor(), null, null); // Queue initial value if (variable.getInitialValue() != null) { this.initialVariables.add(variable); } } @Override protected void visitVariableAssignment(VariableAssignment assignment) { // Load value of source variable this.visitLoadVariable(assignment.getSource()); // Store value to destination variable this.visitStoreVariable(assignment.getDestination()); } /** * Visitor for an integer constant. * Writes code which puts the constant to the stack. * @param value The value to put on the stack. */ protected void visitIntConst(int value) { int mult = value / Byte.MAX_VALUE; int rest = value % Byte.MAX_VALUE; // Put rest on stack. this.methodVisitor.visitIntInsn(Opcodes.BIPUSH, rest); // Put multiples of maximum value on stack until desired value is reached. while (mult > 0) { // Put maximum on stack this.methodVisitor.visitIntInsn(Opcodes.BIPUSH, Byte.MAX_VALUE); // Multiply desired number of times (if mult is too large, take maximum value) this.methodVisitor.visitIntInsn(Opcodes.BIPUSH, Math.min(mult, Byte.MAX_VALUE)); this.methodVisitor.visitInsn(Opcodes.IMUL); // Add multiplied value to rest this.methodVisitor.visitInsn(Opcodes.IADD); // Decrease mult with maximum value to get remaining mults, gets below zero (ends loop) when finished mult -= Byte.MAX_VALUE; } } }
package edu.colorado.csdms.wmt.client.ui; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.DockLayoutPanel; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.HasVerticalAlignment; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.SplitLayoutPanel; import com.google.gwt.user.client.ui.TabLayoutPanel; import edu.colorado.csdms.wmt.client.control.DataManager; import edu.colorado.csdms.wmt.client.ui.handler.AuthenticationHandler; import edu.colorado.csdms.wmt.client.ui.widgets.ComponentInfoDialogBox; /** * Defines the initial layout of views (a perspective, in Eclipse parlance) * for a WMT instance in a browser window. The Perspective holds four views, * named North, West, Center and South. The top-level organizing panel for the * GUI is a DockLayoutPanel. Includes getters and setters for the UI elements * that are arrayed on the Perspective. * * @author Mark Piper (mark.piper@colorado.edu) */ public class Perspective extends DockLayoutPanel { private DataManager data; // Fractional sizes of views. private final static Double VIEW_EAST_FRACTION = 0.50; // Browser window dimensions (in px) used for setting up UI views. private Integer browserWindowWidth; // Width (in px) of splitter grabby bar. private final static Integer SPLITTER_SIZE = 3; // Height (in px) of tab bars. private final static Double TAB_BAR_HEIGHT = 2.0; // Primary UI panels. private ViewNorth viewNorth; private ViewWest viewWest; private ViewEast viewEast; // Secondary UI panels/widgets. private ScrollPanel scrollModel; private ScrollPanel scrollParameters; private ActionButtonPanel actionButtonPanel; private HTML loginHtml; private ModelTree modelTree; private ParameterTable parameterTable; private ComponentInfoDialogBox componentInfoBox; /** * Draws the panels and their children that compose the basic WMT GUI. */ public Perspective(DataManager data) { super(Unit.PX); this.data = data; this.data.setPerspective(this); this.addStyleName("wmt-DockLayoutPanel"); if (data.isDevelopmentMode()) { this.addStyleDependentName("devmode"); } // Determine initial view sizes based on browser window dimensions. browserWindowWidth = Window.getClientWidth(); Integer viewEastInitialWidth = (int) Math.round(VIEW_EAST_FRACTION * browserWindowWidth); Integer headerHeight = 70; // TODO diagnose from largest header elt // The Perspective has two children, a header in the north panel // and a SplitLayoutPanel below. viewNorth = new ViewNorth(); this.addNorth(viewNorth, headerHeight); SplitLayoutPanel splitter = new SplitLayoutPanel(SPLITTER_SIZE); splitter.addStyleName("wmt-SplitLayoutPanel"); this.add(splitter); // The SplitLayoutPanel defines panels which translate to the West // and East views of WMT. viewEast = new ViewEast(); splitter.addEast(viewEast, viewEastInitialWidth); viewWest = new ViewWest(); splitter.add(viewWest); // must be last // The ComponentInfoDialogBox floats above the Perspective. this.setComponentInfoBox(new ComponentInfoDialogBox()); } /** * An inner class to define the header (North view) of the WMT GUI. */ private class ViewNorth extends Grid { /** * Makes the Header (North) view of the WMT GUI. */ public ViewNorth() { super(1, 3); this.setWidth("100%"); actionButtonPanel = new ActionButtonPanel(data); this.setWidget(0, 0, actionButtonPanel); this.getCellFormatter().setStyleName(0, 0, "wmt-ViewNorth0"); loginHtml = new HTML( "<i class='fa fa-sign-in'></i> <a href=\"javascript:;\">Login</a>"); loginHtml.setTitle("Login to WMT to save and run models."); this.setWidget(0, 1, loginHtml); this.getCellFormatter().setHorizontalAlignment(0, 1, HasHorizontalAlignment.ALIGN_RIGHT); this.getCellFormatter().setStyleName(0, 1, "wmt-ViewNorth1"); Image logo = new Image("images/CSDMS_Logo_1.jpg"); logo.setTitle("Go to the CSDMS website."); logo.setAltText("CSDMS logo"); this.setWidget(0, 2, logo); this.getCellFormatter() .setAlignment(0, 2, HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_MIDDLE); this.getCellFormatter().setStyleName(0, 2, "wmt-ViewNorth2"); // Clicking the login link prompts for credentials. loginHtml.addClickHandler(new AuthenticationHandler(data)); // Clicking the CSDMS logo opens the CSDMS website in a new browser tab. logo.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { Window.open("http://csdms.colorado.edu", "_blank", null); } }); } } // end ViewNorth /** * An inner class to define the Center panel of the WMT GUI. */ private class ViewWest extends TabLayoutPanel { /** * Makes the Center view of the WMT GUI. It displays the model. */ public ViewWest() { super(TAB_BAR_HEIGHT, Unit.EM); setModelPanel(new ScrollPanel()); String tabTitle = data.tabPrefix("model") + "Model"; this.add(scrollModel, tabTitle, true); } } // end ViewCenter /** * An inner class to define the East panel of the WMT GUI. */ private class ViewEast extends TabLayoutPanel { /** * Makes the East view of the WMT GUI. It displays the parameters of the * currently selected model. */ public ViewEast() { super(TAB_BAR_HEIGHT, Unit.EM); setParametersPanel(new ScrollPanel()); String tabTitle = data.tabPrefix("parameter") + "Parameters"; this.add(scrollParameters, tabTitle, true); } } // end ViewEast public ScrollPanel getModelPanel() { return scrollModel; } public void setModelPanel(ScrollPanel scrollModel) { this.scrollModel = scrollModel; } /** * A convenience method for setting the tab title of the Model panel. If the * model isn't saved, prepend an asterisk to its name. */ public void setModelPanelTitle() { String tabTitle = data.tabPrefix("model") + "Model"; if (data.getModel().getName() != null) { String marker = data.modelIsSaved() ? "" : "*"; tabTitle += " (" + marker + data.getModel().getName() + ")"; } else { data.getModel().setName("Model " + data.saveAttempts.toString()); } viewWest.setTabHTML(0, tabTitle); } public HTML getLoginHtml() { return loginHtml; } public void setLoginHtml(HTML loginHtml) { this.loginHtml = loginHtml; } public ComponentInfoDialogBox getComponentInfoBox() { return componentInfoBox; } public void setComponentInfoBox(ComponentInfoDialogBox componentInfoBox) { this.componentInfoBox = componentInfoBox; } /** * Returns a reference to the {@link ModelTree} used in a WMT session. */ public ModelTree getModelTree() { return modelTree; } /** * Stores a reference to the {@link ModelTree} used in a WMT session. * * @param modelTree the ModelTree instance */ public void setModelTree(ModelTree modelTree) { this.modelTree = modelTree; } public ScrollPanel getParametersPanel() { return scrollParameters; } public void setParametersPanel(ScrollPanel scrollParameters) { this.scrollParameters = scrollParameters; } /** * A convenience method for setting the title of the Parameters panel. * * @param componentId the id of the component whose parameters are displayed */ public void setParameterPanelTitle(String componentId) { String tabTitle = data.tabPrefix("parameter") + "Parameters"; if (componentId != null) { String componentName = data.getModelComponent(componentId).getName(); tabTitle += " (" + componentName + ")"; } viewEast.setTabHTML(0, tabTitle); } /** * Returns a reference to the {@link ParameterTable} used in the * "Parameters" tab of a WMT session. */ public ParameterTable getParameterTable() { return parameterTable; } /** * Stores a reference to the {@link ParameterTable} used in the "Parameters" * tab of a WMT session. * * @param parameterTable the parameterTable to set */ public void setParameterTable(ParameterTable parameterTable) { this.parameterTable = parameterTable; } public TabLayoutPanel getViewEast() { return viewEast; } public TabLayoutPanel getViewWest() { return viewWest; } public ActionButtonPanel getActionButtonPanel() { return actionButtonPanel; } public void setActionButtonPanel(ActionButtonPanel actionButtonPanel) { this.actionButtonPanel = actionButtonPanel; } /** * Sets up the default starting ModelTree in the "Model" tab, showing only * the open port for the driver of the model. */ public void initializeModel() { modelTree = new ModelTree(data); scrollModel.add(modelTree); } /** * Creates an empty ParameterTable to display in the "Parameters" tab. */ public void initializeParameterTable() { parameterTable = new ParameterTable(data); scrollParameters.add(parameterTable); } /** * Resets WMT to an approximation of its startup state. */ public void reset() { data.resetModelComponents(); parameterTable.clearTable(); modelTree.initializeTree(); modelTree.getDriverComponentCell().getComponentMenu().updateComponents(); setModelPanelTitle(); } }
package io.github.biezhi.wechat.api; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import io.github.biezhi.wechat.WeChatBot; import io.github.biezhi.wechat.api.client.BotClient; import io.github.biezhi.wechat.api.constant.Constant; import io.github.biezhi.wechat.api.constant.StateCode; import io.github.biezhi.wechat.api.enums.AccountType; import io.github.biezhi.wechat.api.enums.ApiURL; import io.github.biezhi.wechat.api.enums.RetCode; import io.github.biezhi.wechat.api.model.*; import io.github.biezhi.wechat.api.request.BaseRequest; import io.github.biezhi.wechat.api.request.FileRequest; import io.github.biezhi.wechat.api.request.JsonRequest; import io.github.biezhi.wechat.api.request.StringRequest; import io.github.biezhi.wechat.api.response.*; import io.github.biezhi.wechat.exception.WeChatException; import io.github.biezhi.wechat.utils.*; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import okhttp3.MediaType; import okhttp3.RequestBody; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.InputStream; import java.net.SocketTimeoutException; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static io.github.biezhi.wechat.api.constant.Constant.*; /** * API * * @author biezhi * @date 2018/1/21 */ @Slf4j public class WeChatApiImpl implements WeChatApi { private static final Pattern UUID_PATTERN = Pattern.compile("window.QRLogin.code = (\\d+); window.QRLogin.uuid = \"(\\S+?)\";"); private static final Pattern CHECK_LOGIN_PATTERN = Pattern.compile("window.code=(\\d+)"); private static final Pattern PROCESS_LOGIN_PATTERN = Pattern.compile("window.redirect_uri=\"(\\S+)\";"); private static final Pattern SYNC_CHECK_PATTERN = Pattern.compile("window.synccheck=\\{retcode:\"(\\d+)\",selector:\"(\\d+)\"}"); private String uuid; private boolean logging; private int memberCount; private WeChatBot bot; private BotClient client; @Getter private Map<String, Account> accountMap = new HashMap<>(); @Getter private List<Account> specialUsersList = Collections.EMPTY_LIST; @Getter private List<Account> publicUsersList = Collections.EMPTY_LIST; @Getter private List<Account> contactList = Collections.EMPTY_LIST; @Getter private List<Account> groupList = Collections.EMPTY_LIST; /** * UserName */ private Set<String> groupUserNames = new HashSet<>(); public WeChatApiImpl(WeChatBot bot) { this.bot = bot; this.client = bot.client(); } private void autoLogin() { String file = bot.config().assetsDir() + "/login.json"; try { HotReload hotReload = WeChatUtils.fromJson(new FileReader(file), HotReload.class); hotReload.reLogin(bot); } catch (FileNotFoundException e) { this.login(false); } } @Override public void login(boolean autoLogin) { if (bot.isRunning() || logging) { log.warn(""); return; } if (autoLogin) { this.autoLogin(); } else { this.logging = true; while (logging) { this.uuid = pushLogin(); if (null == this.uuid) { while (null == this.getUUID()) { DateUtils.sleep(10); } log.info(""); this.getQrImage(this.uuid, bot.config().showTerminal()); log.info(""); } Boolean isLoggedIn = false; while (null == isLoggedIn || !isLoggedIn) { String status = this.checkLogin(this.uuid); if (StateCode.SUCCESS.equals(status)) { isLoggedIn = true; } else if ("201".equals(status)) { if (null != isLoggedIn) { log.info(""); isLoggedIn = null; } } else if ("408".equals(status)) { break; } DateUtils.sleep(300); } if (null != isLoggedIn && isLoggedIn) { break; } if (logging) { log.info(""); } } } this.webInit(); this.statusNotify(); this.loadContact(0); log.info(" {} {} ", this.memberCount, this.accountMap.size()); System.out.println(); log.info(" {} | {} | {} {} ", this.groupUserNames.size(), this.contactList.size(), this.specialUsersList.size(), this.publicUsersList.size()); this.loadGroupList(); log.info("[{}] .", bot.session().getNickName()); this.startRevive(); this.logging = false; } /** * UUID * * @return uuid */ private String getUUID() { log.info("UUID"); ApiResponse response = this.client.send(new StringRequest("https://login.weixin.qq.com/jslogin") .add("appid", "wx782c26e4c19acffb").add("fun", "new")); Matcher matcher = UUID_PATTERN.matcher(response.getRawBody()); if (matcher.find() && StateCode.SUCCESS.equals(matcher.group(1))) { this.uuid = matcher.group(2); } return this.uuid; } /** * * * @param uuid uuid * @param terminalShow */ private void getQrImage(String uuid, boolean terminalShow) { String uid = null != uuid ? uuid : this.uuid; String imgDir = bot.config().assetsDir(); FileResponse fileResponse = this.client.download( new FileRequest(String.format("%s/qrcode/%s", Constant.BASE_URL, uid))); InputStream inputStream = fileResponse.getInputStream(); File qrCode = WeChatUtils.saveFile(inputStream, imgDir, "qrcode.png"); DateUtils.sleep(500); QRCodeUtils.showQrCode(qrCode, terminalShow); } /** * * * @param uuid uuid * @return */ private String checkLogin(String uuid) { String uid = null != uuid ? uuid : this.uuid; String url = String.format("%s/cgi-bin/mmwebwx-bin/login", Constant.BASE_URL); Long time = System.currentTimeMillis(); ApiResponse response = this.client.send(new StringRequest(url) .add("loginicon", true).add("uuid", uid) .add("tip", "1").add("_", time) .add("r", (int) (-time / 1000) / 1579) .timeout(30)); Matcher matcher = CHECK_LOGIN_PATTERN.matcher(response.getRawBody()); if (matcher.find()) { if (StateCode.SUCCESS.equals(matcher.group(1))) { if (!this.processLoginSession(response.getRawBody())) { return StateCode.FAIL; } return StateCode.SUCCESS; } return matcher.group(1); } return StateCode.FAIL; } /** * session * * @param loginContent text * @return */ private boolean processLoginSession(String loginContent) { LoginSession loginSession = bot.session(); Matcher matcher = PROCESS_LOGIN_PATTERN.matcher(loginContent); if (matcher.find()) { loginSession.setUrl(matcher.group(1)); } ApiResponse response = this.client.send(new StringRequest(loginSession.getUrl()).noRedirect()); loginSession.setUrl(loginSession.getUrl().substring(0, loginSession.getUrl().lastIndexOf("/"))); String body = response.getRawBody(); List<String> fileUrl = new ArrayList<>(); List<String> syncUrl = new ArrayList<>(); for (int i = 0; i < FILE_URL.size(); i++) { fileUrl.add(String.format("https://%s/cgi-bin/mmwebwx-bin", FILE_URL.get(i))); syncUrl.add(String.format("https://%s/cgi-bin/mmwebwx-bin", WEB_PUSH_URL.get(i))); } boolean flag = false; for (int i = 0; i < FILE_URL.size(); i++) { String indexUrl = INDEX_URL.get(i); if (loginSession.getUrl().contains(indexUrl)) { loginSession.setFileUrl(fileUrl.get(i)); loginSession.setSyncUrl(syncUrl.get(i)); flag = true; break; } } if (!flag) { loginSession.setFileUrl(loginSession.getUrl()); loginSession.setSyncUrl(loginSession.getUrl()); } loginSession.setDeviceId("e" + String.valueOf(System.currentTimeMillis())); BaseRequest baseRequest = new BaseRequest(); loginSession.setBaseRequest(baseRequest); loginSession.setSKey(WeChatUtils.match("<skey>(\\S+)</skey>", body)); loginSession.setWxSid(WeChatUtils.match("<wxsid>(\\S+)</wxsid>", body)); loginSession.setWxUin(WeChatUtils.match("<wxuin>(\\S+)</wxuin>", body)); loginSession.setPassTicket(WeChatUtils.match("<pass_ticket>(\\S+)</pass_ticket>", body)); baseRequest.setSkey(loginSession.getSKey()); baseRequest.setSid(loginSession.getWxSid()); baseRequest.setUin(loginSession.getWxUin()); baseRequest.setDeviceID(loginSession.getDeviceId()); return true; } /** * * * @return uuid */ private String pushLogin() { String uin = this.client.cookie("wxUin"); if (StringUtils.isEmpty(uin)) { return null; } String url = String.format("%s/cgi-bin/mmwebwx-bin/webwxpushloginurl?uin=%s", Constant.BASE_URL, uin); JsonResponse jsonResponse = this.client.send(new JsonRequest(url)); return jsonResponse.getString("uuid"); } private void statusNotify() { log.info(""); String url = String.format("%s/webwxstatusnotify?lang=zh_CN&pass_ticket=%s", bot.session().getUrl(), bot.session().getPassTicket()); this.client.send(new JsonRequest(url).post().jsonBody() .add("BaseRequest", bot.session().getBaseRequest()) .add("Code", 3) .add("FromUserName", bot.session().getUserName()) .add("ToUserName", bot.session().getUserName()) .add("ClientMsgId", System.currentTimeMillis() / 1000)); } /** * web */ private void webInit() { log.info("..."); int r = (int) (-System.currentTimeMillis() / 1000) / 1579; String url = String.format("%s/webwxinit?r=%d&pass_ticket=%s", bot.session().getUrl(), r, bot.session().getPassTicket()); JsonResponse response = this.client.send(new JsonRequest(url).post().jsonBody() .add("BaseRequest", bot.session().getBaseRequest())); WebInitResponse webInitResponse = response.parse(WebInitResponse.class); List<Account> contactList = webInitResponse.getContactList(); this.syncRecentContact(contactList); Account account = webInitResponse.getAccount(); SyncKey syncKey = webInitResponse.getSyncKey(); bot.session().setInviteStartCount(webInitResponse.getInviteStartCount()); bot.session().setAccount(account); bot.session().setUserName(account.getUserName()); bot.session().setNickName(account.getNickName()); bot.session().setSyncKey(syncKey); } private void startRevive() { bot.setRunning(true); Thread thread = new Thread(new ChatLoop(bot)); thread.setName("wechat-listener"); thread.setDaemon(true); thread.start(); } /** * * * @return SyncCheckRet */ @Override public SyncCheckRet syncCheck() { String url = String.format("%s/synccheck", bot.session().getSyncOrUrl()); try { ApiResponse response = this.client.send(new StringRequest(url) .add("r", System.currentTimeMillis()) .add("skey", bot.session().getSKey()) .add("sid", bot.session().getWxSid()) .add("uin", bot.session().getWxUin()) .add("deviceid", bot.session().getDeviceId()) .add("synckey", bot.session().getSyncKeyStr()) .add("_", System.currentTimeMillis()) .timeout(30) ); Matcher matcher = SYNC_CHECK_PATTERN.matcher(response.getRawBody()); if (matcher.find()) { if (!"0".equals(matcher.group(1))) { log.debug("Unexpected sync check result: {}", response.getRawBody()); return new SyncCheckRet(RetCode.parse(Integer.valueOf(matcher.group(1))), 0); } return new SyncCheckRet(RetCode.parse(Integer.valueOf(matcher.group(1))), Integer.valueOf(matcher.group(2))); } return new SyncCheckRet(RetCode.UNKNOWN, 0); } catch (Exception e) { if (e instanceof SocketTimeoutException) { log.warn(""); return syncCheck(); } log.error("", e); return new SyncCheckRet(RetCode.UNKNOWN, 0); } } /** * * * @return WebSyncResponse */ @Override public WebSyncResponse webSync() { String url = String.format("%s/webwxsync?sid=%s&sKey=%s&passTicket=%s", bot.session().getUrl(), bot.session().getWxSid(), bot.session().getSKey(), bot.session().getPassTicket()); JsonResponse response = this.client.send(new JsonRequest(url).post().jsonBody() .add("BaseRequest", bot.session().getBaseRequest()) .add("SyncKey", bot.session().getSyncKey()) .add("rr", ~(System.currentTimeMillis() / 1000))); WebSyncResponse webSyncResponse = response.parse(WebSyncResponse.class); if (!webSyncResponse.success()) { log.warn(""); return webSyncResponse; } bot.session().setSyncKey(webSyncResponse.getSyncKey()); return webSyncResponse; } @Override public void logout() { if (bot.isRunning()) { String url = String.format("%s/webwxlogout", bot.session().getUrl()); this.client.send(new StringRequest(url) .add("redirect", 1) .add("type", 1) .add("sKey", bot.session().getSKey())); bot.setRunning(false); } this.logging = false; this.client.cookies().clear(); String file = bot.config().assetsDir() + "/login.json"; new File(file).delete(); } /** * * * @param seq 00 */ @Override public void loadContact(int seq) { log.info(""); while (true) { String url = String.format("%s/webwxgetcontact?r=%s&seq=%s&skey=%s", bot.session().getUrl(), System.currentTimeMillis(), seq, bot.session().getSKey()); JsonResponse response = this.client.send(new JsonRequest(url).jsonBody()); JsonObject jsonObject = response.toJsonObject(); seq = jsonObject.get("Seq").getAsInt(); this.memberCount += jsonObject.get("MemberCount").getAsInt(); List<Account> memberList = WeChatUtils.fromJson(WeChatUtils.toJson(jsonObject.getAsJsonArray("MemberList")), new TypeToken<List<Account>>() {}); for (Account account : memberList) { if (null == account.getUserName()) { accountMap.put(account.getUserName(), account); } } // seq000 if (seq == 0) { break; } } this.contactList = new ArrayList<>(this.getAccountByType(AccountType.TYPE_FRIEND)); this.publicUsersList = new ArrayList<>(this.getAccountByType(AccountType.TYPE_MP)); this.specialUsersList = new ArrayList<>(this.getAccountByType(AccountType.TYPE_SPECIAL)); Set<Account> groupAccounts = this.getAccountByType(AccountType.TYPE_GROUP); for (Account groupAccount : groupAccounts) { groupUserNames.add(groupAccount.getUserName()); } } public void loadGroupList() { log.info(""); List<Map<String, String>> list = new ArrayList<>(groupUserNames.size()); for (String groupUserName : groupUserNames) { Map<String, String> map = new HashMap<>(2); map.put("UserName", groupUserName); map.put("EncryChatRoomId", ""); list.add(map); } String url = String.format("%s/webwxbatchgetcontact?type=ex&r=%s&pass_ticket=%s", bot.session().getUrl(), System.currentTimeMillis() / 1000, bot.session().getPassTicket()); JsonResponse jsonResponse = this.client.send(new JsonRequest(url).post().jsonBody() .add("BaseRequest", bot.session().getBaseRequest()) .add("Count", groupUserNames.size()) .add("List", list) ); this.groupList = WeChatUtils.fromJson(WeChatUtils.toJson(jsonResponse.toJsonObject().getAsJsonArray("ContactList")), new TypeToken<List<Account>>() {}); } /** * UserNameAccount * * @param id UserName * @return */ @Override public Account getAccountById(String id) { return accountMap.get(id); } /** * * * @param name * @return */ @Override public Account getAccountByName(String name) { for (Account account : accountMap.values()) { if (name.equals(account.getRemarkName())) { return account; } if (name.equals(account.getNickName())) { return account; } } return null; } @Override public void verify(Recommend recommend) { String url = String.format("%s/webwxverifyuser?r=%s&lang=zh_CN&pass_ticket=%s", bot.session().getUrl(), System.currentTimeMillis() / 1000, bot.session().getPassTicket()); List<Map<String, Object>> verifyUserList = new ArrayList<>(); Map<String, Object> verifyUser = new HashMap<>(2); verifyUser.put("Value", recommend.getUserName()); verifyUser.put("VerifyUserTicket", recommend.getTicket()); verifyUserList.add(verifyUser); ApiResponse response = client.send(new StringRequest(url).post().jsonBody() .add("BaseRequest", bot.session().getBaseRequest()) .add("Opcode", 3) .add("VerifyUserListSize", 1) .add("VerifyUserList", verifyUserList) .add("VerifyContent", "") .add("SceneListCount", 1) .add("SceneList", Arrays.asList(33)) .add("skey", bot.session().getSyncKeyStr()) ); System.out.println(response.getRawBody()); } private String getUserRemarkName(String id) { String name = id.contains("@@") ? "" : ""; if (id.equals(this.bot.session().getUserName())) { return this.bot.session().getNickName(); } Account account = accountMap.get(id); if (null == account) { return name; } String nickName = StringUtils.isNotEmpty(account.getRemarkName()) ? account.getRemarkName() : account.getNickName(); return StringUtils.isNotEmpty(nickName) ? nickName : name; } private List<Account> getNameById(String id) { String url = String.format("%s/webwxbatchgetcontact?type=ex&r=%s&pass_ticket=%s", bot.session().getUrl(), System.currentTimeMillis() / 1000, bot.session().getPassTicket()); List<Map<String, String>> list = new ArrayList<>(); Map<String, String> map = new HashMap<>(); map.put("UserName", id); map.put("EncryChatRoomId", id); list.add(map); JsonResponse response = this.client.send(new JsonRequest(url).post().jsonBody() .add("BaseRequest", bot.session().getBaseRequest()) .add("Count", bot.session().getBaseRequest()) .add("List", list)); return WeChatUtils.fromJson(WeChatUtils.toJson(response.toJsonObject().getAsJsonObject("")), new TypeToken<List<Account>>() {}); } /** * * * @param accountType * @return */ public Set<Account> getAccountByType(AccountType accountType) { Set<Account> accountSet = new HashSet<>(); for (Account account : accountMap.values()) { if (account.getAccountType().equals(accountType)) { accountSet.add(account); } } return accountSet; } /** * * <p> * * * @param contactList */ public void syncRecentContact(List<Account> contactList) { if (null != contactList && contactList.size() > 0) { for (Account account : contactList) { accountMap.put(account.getUserName(), account); } } } /** * * * @param messages */ @Override public List<WeChatMessage> handleMsg(List<Message> messages) { if (null != messages && messages.size() > 0) { List<WeChatMessage> weChatMessages = new ArrayList<>(messages.size()); log.info(""); for (Message message : messages) { weChatMessages.add(this.processMsg(message)); } return weChatMessages; } return null; } private WeChatMessage processMsg(Message message) { Integer type = message.getType(); String name = this.getUserRemarkName(message.getFromUserName()); String msgId = message.getId(); String content = message.getContent(); if (message.isGroup()) { if (message.getFromUserName().contains(GROUP_IDENTIFY) && !groupUserNames.contains(message.getFromUserName())) { this.groupUserNames.add(message.getFromUserName()); } if (message.getToUserName().contains(GROUP_IDENTIFY) && !groupUserNames.contains(message.getToUserName())) { this.groupUserNames.add(message.getToUserName()); } if (content.contains(GROUP_BR)) { content = content.substring(content.indexOf(GROUP_BR) + 6); } } content = WeChatUtils.formatMsg(content); WeChatMessage.WeChatMessageBuilder weChatMessageBuilder = WeChatMessage.builder() .raw(message) .fromUserName(message.getFromUserName()) .toUserName(message.getToUserName()) .msgType(message.msgType()) .text(content); Account fromAccount = this.getAccountById(message.getFromUserName()); if (null == fromAccount) { log.warn(": {}", message.msgType()); log.warn(": {}", WeChatUtils.toPrettyJson(message)); } else { weChatMessageBuilder.fromNickName(fromAccount.getNickName()).fromRemarkName(fromAccount.getRemarkName()); if (log.isDebugEnabled()) { log.debug("JSON: {}", WeChatUtils.toJson(message)); } } switch (message.msgType()) { case TEXT: return weChatMessageBuilder.build(); case IMAGE: String imgPath = this.downloadImg(msgId); return weChatMessageBuilder.imagePath(imgPath).build(); case VOICE: String voicePath = this.downloadVoice(msgId); return weChatMessageBuilder.voicePath(voicePath).build(); case ADD_FRIEND: return weChatMessageBuilder.text(message.getRecommend().getContent()).build(); case PERSON_CARD: return weChatMessageBuilder.recommend(message.getRecommend()).build(); case VIDEO: String videoPath = this.downloadVideo(msgId); return weChatMessageBuilder.videoPath(videoPath).build(); case EMOTICONS: String imgUrl = this.searchContent("cdnurl", content); return weChatMessageBuilder.imagePath(imgUrl).build(); case SHARE: String shareUrl = this.searchContent("url", content); return weChatMessageBuilder.text(shareUrl).build(); case CONTACT_INIT: break; case SYSTEM: break; case REVOKE_MSG: log.info("{} : {}", name, content); return weChatMessageBuilder.build(); default: log.info(": {}, , : {}", type, WeChatUtils.toJson(message)); break; } return weChatMessageBuilder.build(); } private String searchContent(String key, String content) { String r = WeChatUtils.match(key + "\\s?=\\s?\"([^\"<]+)\"", content); if (StringUtils.isNotEmpty(r)) { return r; } r = WeChatUtils.match(String.format("<%s>([^<]+)</%s>", key, key), content); if (StringUtils.isNotEmpty(r)) { return r; } r = WeChatUtils.match(String.format("<%s><\\!\\[CDATA\\[(.*?)\\]\\]></%s>", key, key), content); if (StringUtils.isNotEmpty(r)) { return r; } return ""; } /** * * * @param msgId id * @return */ private String downloadImg(String msgId) { return this.downloadFile( new DownLoad(ApiURL.IMAGE, bot.session().getUrl(), msgId, bot.session().getSKey()) .msgId(msgId).saveByDay() ); } /** * * * @param msgId iconid * @return Icon */ private String downloadIconImg(String msgId) { return this.downloadFile( new DownLoad(ApiURL.ICON, bot.session().getUrl(), msgId, bot.session().getSKey()) .msgId(msgId) ); } /** * * * @param userName * @return */ private String downloadHeadImg(String userName) { return this.downloadFile( new DownLoad(ApiURL.HEAD_IMG, bot.session().getUrl(), userName, bot.session().getSKey()) .msgId(userName) ); } /** * * * @param msgId id * @return */ private String downloadVideo(String msgId) { return this.downloadFile( new DownLoad(ApiURL.VIDEO, bot.session().getUrl(), msgId, bot.session().getSKey()) .msgId(msgId).saveByDay() ); } /** * * * @param msgId id * @return */ private String downloadVoice(String msgId) { return this.downloadFile( new DownLoad(ApiURL.VOICE, bot.session().getUrl(), msgId, bot.session().getSKey()) .msgId(msgId).saveByDay() ); } private String downloadFile(DownLoad downLoad) { String url = String.format(downLoad.getApiURL().getUrl(), downLoad.getParams()); FileResponse response = this.client.download(new FileRequest(url)); InputStream inputStream = response.getInputStream(); String id = downLoad.getFileName(); String dir = downLoad.getDir(bot); return WeChatUtils.saveFileByDay(inputStream, dir, id, downLoad.isSaveByDay()).getPath(); } /** * * * @param toUser * @param filePath * @return MediaResponse */ @Override public MediaResponse uploadMedia(String toUser, String filePath) { File file = new File(filePath); if (!file.exists()) { throw new WeChatException("[" + filePath + "]"); } log.info(": {}", filePath); long size = file.length(); String mimeType = WeChatUtils.getMimeType(filePath); String mediatype = "doc"; if (mediatype.contains("image")) { mediatype = "pic"; } if (mediatype.contains("audio")) { mediatype = "audio"; } if (mediatype.contains("video")) { mediatype = "video"; } String url = String.format("%s/webwxuploadmedia?f=json", bot.session().getFileUrl()); String mediaId = System.currentTimeMillis() / 1000 + StringUtils.random(6); Map<String, Object> uploadMediaRequest = new HashMap<>(10); uploadMediaRequest.put("UploadType", 2); uploadMediaRequest.put("BaseRequest", bot.session().getBaseRequest()); uploadMediaRequest.put("ClientMediaId", mediaId); uploadMediaRequest.put("TotalLen", size); uploadMediaRequest.put("StartPos", 0); uploadMediaRequest.put("DataLen", size); uploadMediaRequest.put("MediaType", 4); uploadMediaRequest.put("FromUserName", bot.session().getUserName()); uploadMediaRequest.put("ToUserName", toUser); uploadMediaRequest.put("FileMd5", MD5Checksum.getMD5Checksum(file.getPath())); String dataTicket = this.client.cookie("webwx_data_ticket"); if (StringUtils.isEmpty(dataTicket)) { throw new WeChatException("Cookie"); } ApiResponse response = this.client.send(new StringRequest(url).post().multipart() .fileName(file.getName()) .add("id", "WU_FILE_0") .add("name", filePath) .add("type", mimeType) .add("lastModifieDate", new SimpleDateFormat("yyyy MM dd HH:mm:ss").format(new Date())) .add("size", String.valueOf(size)) .add("mediatype", mediatype) .add("uploadmediarequest", WeChatUtils.toJson(uploadMediaRequest)) .add("webwx_data_ticket", dataTicket) .add("pass_ticket", bot.session().getPassTicket()) .add("filename", RequestBody.create(MediaType.parse(mimeType), file))); MediaResponse mediaResponse = response.parse(MediaResponse.class); if (!mediaResponse.success()) { log.warn(": {}", mediaResponse.getMsg()); } log.info(": {}", filePath); return mediaResponse; } /** * * * @param toUserName * @param filePath */ @Override public void sendImg(String toUserName, String filePath) { String mediaId = this.uploadMedia(toUserName, filePath).getMediaId(); if (StringUtils.isEmpty(mediaId)) { log.warn("Media"); return; } String url = String.format("%s/webwxsendmsgimg?fun=async&f=json&pass_ticket=%s", bot.session().getUrl(), bot.session().getPassTicket()); String msgId = System.currentTimeMillis() / 1000 + StringUtils.random(6); Map<String, Object> msg = new HashMap<>(); msg.put("Type", 3); msg.put("MediaId", mediaId); msg.put("FromUserName", bot.session().getUserName()); msg.put("ToUserName", toUserName); msg.put("LocalID", msgId); msg.put("ClientMsgId", msgId); this.client.send(new JsonRequest(url).post().jsonBody() .add("BaseRequest", bot.session().getBaseRequest()) .add("Msg", msg) ); } @Override public void sendImgByName(String name, String filePath) { Account account = this.getAccountByName(name); if (null == account) { log.warn(": {}", name); return; } this.sendFile(account.getUserName(), filePath); } /** * * * @param msg * @param toUserName */ @Override public void sendText(String toUserName, String msg) { String url = String.format("%s/webwxsendmsg?pass_ticket=%s", bot.session().getUrl(), bot.session().getPassTicket()); String msgId = System.currentTimeMillis() / 1000 + StringUtils.random(6); this.client.send(new JsonRequest(url).post().jsonBody() .add("BaseRequest", bot.session().getBaseRequest()) .add("Msg", new SendMessage(1, msg, bot.session().getUserName(), toUserName, msgId, msgId)) ); } @Override public void sendTextByName(String name, String msg) { Account account = this.getAccountByName(name); if (null == account) { log.warn(": {}", name); return; } this.sendText(account.getUserName(), msg); } @Override public void sendFile(String toUser, String filePath) { String title = new File(filePath).getName(); MediaResponse mediaResponse = this.uploadMedia(toUser, filePath); if (null == mediaResponse) { log.warn(""); return; } String url = String.format("%s/webwxsendappmsg?fun=async&f=json&pass_ticket=%s", bot.session().getUrl(), bot.session().getPassTicket()); String fileSuffix = title.substring(title.lastIndexOf(".") + 1, title.length()); String msgId = System.currentTimeMillis() + ""; String content = String.format("<appmsg appid='wxeb7ec651dd0aefa9' sdkver=''>" + "<title>%s</title><des></des><action></action><type>6</type><content></content><url></url><lowurl></lowurl>" + "<appattach><totallen>%s</totallen><attachid>%s</attachid><fileext>%s</fileext></appattach><extinfo></extinfo></appmsg>", title, mediaResponse.getStartPos(), mediaResponse.getMediaId(), fileSuffix); Map<String, String> msgMap = new HashMap<>(6); msgMap.put("Type", "6"); msgMap.put("Content", content); msgMap.put("FromUserName", bot.session().getUserName()); msgMap.put("ToUserName", toUser); msgMap.put("LocalID", msgId); msgMap.put("ClientMsgId", msgId); client.send(new JsonRequest(url).post().jsonBody() .add("BaseRequest", bot.session().getBaseRequest()) .add("Msg", msgMap) .add("Scene", 0) ); } @Override public void sendFileByName(String name, String filePath) { Account account = this.getAccountByName(name); if (null == account) { log.warn(": {}", name); return; } this.sendFileByName(account.getUserName(), filePath); } }
package cc.mallet.fst; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Random; import java.util.logging.Logger; import cc.mallet.optimize.LimitedMemoryBFGS; import cc.mallet.optimize.Optimizer; import cc.mallet.types.ExpGain; import cc.mallet.types.FeatureInducer; import cc.mallet.types.FeatureSelection; import cc.mallet.types.FeatureVector; import cc.mallet.types.GradientGain; import cc.mallet.types.InfoGain; import cc.mallet.types.Instance; import cc.mallet.types.InstanceList; import cc.mallet.types.Label; import cc.mallet.types.LabelAlphabet; import cc.mallet.types.LabelSequence; import cc.mallet.types.LabelVector; import cc.mallet.types.RankedFeatureVector; import cc.mallet.types.Sequence; import cc.mallet.util.MalletLogger; /** Unlike ClassifierTrainer, TransducerTrainer is not "stateless" between calls to train. * A TransducerTrainer is constructed paired with a specific Transducer, and can only train that Transducer. * * CRF stores and has methods for FeatureSelection and weight freezing. * CRFTrainer stores and has methods for determining the contents/dimensions/sparsity/FeatureInduction * of the CRF's weights as determined by training data. * * */ /** In the future this class may go away in favor of some default version of CRFTrainerByValueGradients... */ public class CRFTrainerByLabelLikelihood extends TransducerTrainer implements TransducerTrainer.ByOptimization { private static Logger logger = MalletLogger.getLogger(CRFTrainerByLabelLikelihood.class.getName()); static final double DEFAULT_GAUSSIAN_PRIOR_VARIANCE = 1.0; static final double DEFAULT_HYPERBOLIC_PRIOR_SLOPE = 0.2; static final double DEFAULT_HYPERBOLIC_PRIOR_SHARPNESS = 10.0; CRF crf; //OptimizableCRF ocrf; CRFOptimizableByLabelLikelihood ocrf; Optimizer opt; int iterationCount = 0; boolean converged; boolean usingHyperbolicPrior = false; double gaussianPriorVariance = DEFAULT_GAUSSIAN_PRIOR_VARIANCE; double hyperbolicPriorSlope = DEFAULT_HYPERBOLIC_PRIOR_SLOPE; double hyperbolicPriorSharpness = DEFAULT_HYPERBOLIC_PRIOR_SHARPNESS; boolean useSparseWeights = true; boolean useNoWeights = false; // TODO remove this; it is just for debugging private transient boolean useSomeUnsupportedTrick = true; // Various values from CRF acting as indicators of when we need to ... private int cachedValueWeightsStamp = -1; // ... re-calculate expectations and values to getValue() because weights' values changed private int cachedGradientWeightsStamp = -1; // ... re-calculate to getValueGradient() because weights' values changed private int cachedWeightsStructureStamp = -1; // ... re-allocate crf.weights, expectations & constraints because new states, transitions // Use mcrf.trainingSet to see when we need to re-allocate crf.weights, expectations & constraints because we are using a different TrainingList than last time // xxx temporary hack. This is quite useful to have, though!! -cas public boolean printGradient = false; public CRFTrainerByLabelLikelihood (CRF crf) { this.crf = crf; } public Transducer getTransducer() { return crf; } public CRF getCRF () { return crf; } public Optimizer getOptimizer() { return opt; } public boolean isConverged() { return converged; } public boolean isFinishedTraining() { return converged; } public int getIteration () { return iterationCount; } public CRFOptimizableByLabelLikelihood getOptimizableCRF (InstanceList trainingSet) { if (cachedWeightsStructureStamp != crf.weightsStructureChangeStamp) { if (!useNoWeights) { if (useSparseWeights) crf.setWeightsDimensionAsIn (trainingSet, useSomeUnsupportedTrick); else crf.setWeightsDimensionDensely (); } //reallocateSufficientStatistics(); // Not necessary here because it is done in the constructor for OptimizableCRF ocrf = null; cachedWeightsStructureStamp = crf.weightsStructureChangeStamp; } if (ocrf == null || ocrf.trainingSet != trainingSet) { //ocrf = new OptimizableCRF (crf, trainingSet); ocrf = new CRFOptimizableByLabelLikelihood(crf, trainingSet); opt = null; } return ocrf; } public Optimizer getOptimizer (InstanceList trainingSet) { getOptimizableCRF(trainingSet); // this will set this.mcrf if necessary if (opt == null || ocrf != opt.getOptimizable()) opt = new LimitedMemoryBFGS(ocrf); // Alternative: opt = new ConjugateGradient (0.001); return opt; } // Java question: // If I make a non-static inner class CRF.Trainer, // can that class by subclassed in another .java file, // and can that subclass still have access to all the CRF's // instance variables? // ANSWER: Yes and yes, but you have to use special syntax in the subclass ctor (see mallet-dev archive) -cas public boolean trainIncremental (InstanceList training) { return train (training, Integer.MAX_VALUE); } public boolean train (InstanceList trainingSet, int numIterations) { if (numIterations <= 0) return false; assert (trainingSet.size() > 0); getOptimizableCRF(trainingSet); // This will set this.mcrf if necessary getOptimizer(trainingSet); // This will set this.opt if necessary boolean converged = false; logger.info ("CRF about to train with "+numIterations+" iterations"); for (int i = 0; i < numIterations; i++) { try { converged = opt.optimize (1); iterationCount++; logger.info ("CRF finished one iteration of maximizer, i="+i); runEvaluators(); } catch (IllegalArgumentException e) { e.printStackTrace(); logger.info ("Catching exception; saying converged."); converged = true; } if (converged) { logger.info ("CRF training has converged, i="+i); break; } } return converged; } /** * Train a CRF on various-sized subsets of the data. This method is typically used to accelerate training by * quickly getting to reasonable parameters on only a subset of the parameters first, then on progressively more data. * @param training The training Instances. * @param numIterationsPerProportion Maximum number of Maximizer iterations per training proportion. * @param trainingProportions If non-null, train on increasingly * larger portions of the data, e.g. new double[] {0.2, 0.5, 1.0}. This can sometimes speedup convergence. * Be sure to end in 1.0 if you want to train on all the data in the end. * @return True if training has converged. */ public boolean train (InstanceList training, int numIterationsPerProportion, double[] trainingProportions) { int trainingIteration = 0; assert (trainingProportions.length > 0); boolean converged = false; for (int i = 0; i < trainingProportions.length; i++) { assert (trainingProportions[i] <= 1.0); logger.info ("Training on "+trainingProportions[i]+"% of the data this round."); if (trainingProportions[i] == 1.0) converged = this.train (training, numIterationsPerProportion); else converged = this.train (training.split (new Random(1), new double[] {trainingProportions[i], 1-trainingProportions[i]})[0], numIterationsPerProportion); trainingIteration += numIterationsPerProportion; } return converged; } public boolean trainWithFeatureInduction (InstanceList trainingData, InstanceList validationData, InstanceList testingData, TransducerEvaluator eval, int numIterations, int numIterationsBetweenFeatureInductions, int numFeatureInductions, int numFeaturesPerFeatureInduction, double trueLabelProbThreshold, boolean clusteredFeatureInduction, double[] trainingProportions) { return trainWithFeatureInduction (trainingData, validationData, testingData, eval, numIterations, numIterationsBetweenFeatureInductions, numFeatureInductions, numFeaturesPerFeatureInduction, trueLabelProbThreshold, clusteredFeatureInduction, trainingProportions, "exp"); } /** * Train a CRF using feature induction to generate conjunctions of * features. Feature induction is run periodically during * training. The features are added to improve performance on the * mislabeled instances, with the specific scoring criterion given * by the {@link FeatureInducer} specified by <code>gainName</code> * * @param training The training Instances. * @param validation The validation Instances. * @param testing The testing instances. * @param eval For evaluation during training. * @param numIterations Maximum number of Maximizer iterations. * @param numIterationsBetweenFeatureInductions Number of maximizer * iterations between each call to the Feature Inducer. * @param numFeatureInductions Maximum number of rounds of feature * induction. * @param numFeaturesPerFeatureInduction Maximum number of features * to induce at each round of induction. * @param trueLabelProbThreshold If the model's probability of the * true Label of an Instance is less than this value, it is added as * an error instance to the {@link FeatureInducer}. * @param clusteredFeatureInduction If true, a separate {@link * FeatureInducer} is constructed for each label pair. This can * avoid inducing a disproportionate number of features for a single * label. * @param trainingProportions If non-null, train on increasingly * larger portions of the data (e.g. [0.2, 0.5, 1.0]. This can * sometimes speedup convergence. * @param gainName The type of {@link FeatureInducer} to use. One of * "exp", "grad", or "info" for {@link ExpGain}, {@link * GradientGain}, or {@link InfoGain}. * @return True if training has converged. */ public boolean trainWithFeatureInduction (InstanceList trainingData, InstanceList validationData, InstanceList testingData, TransducerEvaluator eval, int numIterations, int numIterationsBetweenFeatureInductions, int numFeatureInductions, int numFeaturesPerFeatureInduction, double trueLabelProbThreshold, boolean clusteredFeatureInduction, double[] trainingProportions, String gainName) { int trainingIteration = 0; int numLabels = crf.outputAlphabet.size(); crf.globalFeatureSelection = trainingData.getFeatureSelection(); if (crf.globalFeatureSelection == null) { // Mask out all features; some will be added later by FeatureInducer.induceFeaturesFor(.) crf.globalFeatureSelection = new FeatureSelection (trainingData.getDataAlphabet()); trainingData.setFeatureSelection (crf.globalFeatureSelection); } // TODO Careful! If validationData and testingData get removed as arguments to this method // then the next two lines of work will have to be done somewhere. if (validationData != null) validationData.setFeatureSelection (crf.globalFeatureSelection); if (testingData != null) testingData.setFeatureSelection (crf.globalFeatureSelection); for (int featureInductionIteration = 0; featureInductionIteration < numFeatureInductions; featureInductionIteration++) { // Print out some feature information logger.info ("Feature induction iteration "+featureInductionIteration); // Train the CRF InstanceList theTrainingData = trainingData; if (trainingProportions != null && featureInductionIteration < trainingProportions.length) { logger.info ("Training on "+trainingProportions[featureInductionIteration]+"% of the data this round."); InstanceList[] sampledTrainingData = trainingData.split (new Random(1), new double[] {trainingProportions[featureInductionIteration], 1-trainingProportions[featureInductionIteration]}); theTrainingData = sampledTrainingData[0]; theTrainingData.setFeatureSelection (crf.globalFeatureSelection); // xxx necessary? logger.info (" which is "+theTrainingData.size()+" instances"); } boolean converged = false; if (featureInductionIteration != 0) // Don't train until we have added some features converged = this.train (theTrainingData, numIterationsBetweenFeatureInductions); trainingIteration += numIterationsBetweenFeatureInductions; logger.info ("Starting feature induction with "+crf.inputAlphabet.size()+" features."); // Create the list of error tokens, for both unclustered and clustered feature induction InstanceList errorInstances = new InstanceList (trainingData.getDataAlphabet(), trainingData.getTargetAlphabet()); // This errorInstances.featureSelection will get examined by FeatureInducer, // so it can know how to add "new" singleton features errorInstances.setFeatureSelection (crf.globalFeatureSelection); ArrayList errorLabelVectors = new ArrayList(); InstanceList clusteredErrorInstances[][] = new InstanceList[numLabels][numLabels]; ArrayList clusteredErrorLabelVectors[][] = new ArrayList[numLabels][numLabels]; for (int i = 0; i < numLabels; i++) for (int j = 0; j < numLabels; j++) { clusteredErrorInstances[i][j] = new InstanceList (trainingData.getDataAlphabet(), trainingData.getTargetAlphabet()); clusteredErrorInstances[i][j].setFeatureSelection (crf.globalFeatureSelection); clusteredErrorLabelVectors[i][j] = new ArrayList(); } for (int i = 0; i < theTrainingData.size(); i++) { logger.info ("instance="+i); Instance instance = theTrainingData.get(i); Sequence input = (Sequence) instance.getData(); Sequence trueOutput = (Sequence) instance.getTarget(); assert (input.size() == trueOutput.size()); SumLattice lattice = crf.sumLatticeFactory.newSumLattice (crf, input, (Sequence)null, (Transducer.Incrementor)null, (LabelAlphabet)theTrainingData.getTargetAlphabet()); int prevLabelIndex = 0; // This will put extra error instances in this cluster for (int j = 0; j < trueOutput.size(); j++) { Label label = (Label) ((LabelSequence)trueOutput).getLabelAtPosition(j); assert (label != null); //System.out.println ("Instance="+i+" position="+j+" fv="+lattice.getLabelingAtPosition(j).toString(true)); LabelVector latticeLabeling = lattice.getLabelingAtPosition(j); double trueLabelProb = latticeLabeling.value(label.getIndex()); int labelIndex = latticeLabeling.getBestIndex(); //System.out.println ("position="+j+" trueLabelProb="+trueLabelProb); if (trueLabelProb < trueLabelProbThreshold) { logger.info ("Adding error: instance="+i+" position="+j+" prtrue="+trueLabelProb+ (label == latticeLabeling.getBestLabel() ? " " : " *")+ " truelabel="+label+ " predlabel="+latticeLabeling.getBestLabel()+ " fv="+((FeatureVector)input.get(j)).toString(true)); errorInstances.add (input.get(j), label, null, null); errorLabelVectors.add (latticeLabeling); clusteredErrorInstances[prevLabelIndex][labelIndex].add (input.get(j), label, null, null); clusteredErrorLabelVectors[prevLabelIndex][labelIndex].add (latticeLabeling); } prevLabelIndex = labelIndex; } } logger.info ("Error instance list size = "+errorInstances.size()); if (clusteredFeatureInduction) { FeatureInducer[][] klfi = new FeatureInducer[numLabels][numLabels]; for (int i = 0; i < numLabels; i++) { for (int j = 0; j < numLabels; j++) { // Note that we may see some "impossible" transitions here (like O->I in a OIB model) // because we are using lattice gammas to get the predicted label, not Viterbi. // I don't believe this does any harm, and may do some good. logger.info ("Doing feature induction for "+ crf.outputAlphabet.lookupObject(i)+" -> "+crf.outputAlphabet.lookupObject(j)+ " with "+clusteredErrorInstances[i][j].size()+" instances"); if (clusteredErrorInstances[i][j].size() < 20) { logger.info ("..skipping because only "+clusteredErrorInstances[i][j].size()+" instances."); continue; } int s = clusteredErrorLabelVectors[i][j].size(); LabelVector[] lvs = new LabelVector[s]; for (int k = 0; k < s; k++) lvs[k] = (LabelVector) clusteredErrorLabelVectors[i][j].get(k); RankedFeatureVector.Factory gainFactory = null; if (gainName.equals ("exp")) gainFactory = new ExpGain.Factory (lvs, gaussianPriorVariance); else if (gainName.equals("grad")) gainFactory = new GradientGain.Factory (lvs); else if (gainName.equals("info")) gainFactory = new InfoGain.Factory (); klfi[i][j] = new FeatureInducer (gainFactory, clusteredErrorInstances[i][j], numFeaturesPerFeatureInduction, 2*numFeaturesPerFeatureInduction, 2*numFeaturesPerFeatureInduction); crf.featureInducers.add(klfi[i][j]); } } for (int i = 0; i < numLabels; i++) { for (int j = 0; j < numLabels; j++) { logger.info ("Adding new induced features for "+ crf.outputAlphabet.lookupObject(i)+" -> "+crf.outputAlphabet.lookupObject(j)); if (klfi[i][j] == null) { logger.info ("...skipping because no features induced."); continue; } // Note that this adds features globally, but not on a per-transition basis klfi[i][j].induceFeaturesFor (trainingData, false, false); if (testingData != null) klfi[i][j].induceFeaturesFor (testingData, false, false); } } klfi = null; } else { int s = errorLabelVectors.size(); LabelVector[] lvs = new LabelVector[s]; for (int i = 0; i < s; i++) lvs[i] = (LabelVector) errorLabelVectors.get(i); RankedFeatureVector.Factory gainFactory = null; if (gainName.equals ("exp")) gainFactory = new ExpGain.Factory (lvs, gaussianPriorVariance); else if (gainName.equals("grad")) gainFactory = new GradientGain.Factory (lvs); else if (gainName.equals("info")) gainFactory = new InfoGain.Factory (); FeatureInducer klfi = new FeatureInducer (gainFactory, errorInstances, numFeaturesPerFeatureInduction, 2*numFeaturesPerFeatureInduction, 2*numFeaturesPerFeatureInduction); crf.featureInducers.add(klfi); // Note that this adds features globally, but not on a per-transition basis klfi.induceFeaturesFor (trainingData, false, false); if (testingData != null) klfi.induceFeaturesFor (testingData, false, false); logger.info ("CRF4 FeatureSelection now includes "+crf.globalFeatureSelection.cardinality()+" features"); klfi = null; } // This is done in CRF4.train() anyway //this.setWeightsDimensionAsIn (trainingData); ////this.growWeightsDimensionToInputAlphabet (); } return this.train (trainingData, numIterations - trainingIteration); } public void setUseHyperbolicPrior (boolean f) { usingHyperbolicPrior = f; } public void setHyperbolicPriorSlope (double p) { hyperbolicPriorSlope = p; } public void setHyperbolicPriorSharpness (double p) { hyperbolicPriorSharpness = p; } public double getUseHyperbolicPriorSlope () { return hyperbolicPriorSlope; } public double getUseHyperbolicPriorSharpness () { return hyperbolicPriorSharpness; } public void setGaussianPriorVariance (double p) { gaussianPriorVariance = p; } public double getGaussianPriorVariance () { return gaussianPriorVariance; } //public int getDefaultFeatureIndex () { return defaultFeatureIndex;} public void setUseSparseWeights (boolean b) { useSparseWeights = b; } public boolean getUseSparseWeights () { return useSparseWeights; } /** Sets whether to use the 'some unsupported trick.' This trick is, if training a CRF * where some training has been done and sparse weights are used, to add a few weights * for feaures that do not occur in the tainig data. * <p> * This generally leads to better accuracy at only a small memory cost. * * @param b Whether to use the trick */ public void setUseSomeUnsupportedTrick (boolean b) { useSomeUnsupportedTrick = b; } // Serialization for CRFTrainerByLikelihood private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 1; static final int NULL_INTEGER = -1; /* Need to check for null pointers. */ private void writeObject (ObjectOutputStream out) throws IOException { int i, size; out.writeInt (CURRENT_SERIAL_VERSION); //out.writeInt(defaultFeatureIndex); out.writeBoolean(usingHyperbolicPrior); out.writeDouble(gaussianPriorVariance); out.writeDouble(hyperbolicPriorSlope); out.writeDouble(hyperbolicPriorSharpness); out.writeInt(cachedGradientWeightsStamp); out.writeInt(cachedValueWeightsStamp); out.writeInt(cachedWeightsStructureStamp); out.writeBoolean(printGradient); out.writeBoolean (useSparseWeights); throw new IllegalStateException("Implementation not yet complete."); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int size, i; int version = in.readInt (); //defaultFeatureIndex = in.readInt(); usingHyperbolicPrior = in.readBoolean(); gaussianPriorVariance = in.readDouble(); hyperbolicPriorSlope = in.readDouble(); hyperbolicPriorSharpness = in.readDouble(); printGradient = in.readBoolean(); useSparseWeights = in.readBoolean(); throw new IllegalStateException("Implementation not yet complete."); } }
package edu.dynamic.dynamiz.controller; import edu.dynamic.dynamiz.parser.OptionType; import edu.dynamic.dynamiz.structure.MyDate; import edu.dynamic.dynamiz.structure.ToDoItem; /** * Defines the command to search for item with the given keyword in their description, * filtered by the specified options, in the given storage. * * Constructor * CommandSearch(int id) //Deprecated. Creates a new instance of this command to search by ID. * CommandSearch(String keyword, int priority, Date start, Date end) //Creates an instance of this command object. * * Public Methods * Options extractOptions(Options options) //Extracts the options in this list that are applicable to this command. * void execute() //Executes this command. * ToDoItem[] getAffectItems() //Gets the list of items with the keyword in their description. * String getCommandName() //Gets the string representation of this command's type. * * @author zixian */ public class CommandSearch extends Command { //The string representation of this command's type. private static final String COMMAND_TYPE = "search"; //Main data members private String searchKey; private int priority, id; private MyDate start, end; private ToDoItem[] searchList = null; private OptionType[] optList; private boolean isIdSearch = false; /** * Creates an instance of this search command. * @param keyword The keyword to search by, or null if search by keyword is not required. * @param priority The priority level of the item(s) to search, or -1 if not required. * @param start The start date of the item(s) to search, or null if not required. * @param end The end date of the item(s)to search, or null if not required. */ public CommandSearch(String searchKey, int priority, MyDate start, MyDate end, OptionType[] optList){ this.searchKey = searchKey; this.priority = priority; this.start = start; this.end = end; this.optList = optList; } @Override /** * Executes this command. */ public void execute() { if(isIdSearch){ searchList = storage.searchItems(id); } else{ searchList = storage.searchItems(searchKey, priority, start, end, optList); } } @Override /** * Gets the string representation of this command's type. * @return The string representation of this command's type. */ public String getCommandName() { return COMMAND_TYPE; } @Override /** * Gets the list of items obtained by this command. * Must be called only after calling the execute() method. * @return An array of ToDoItem objects resulting from this command's execution or * null if the list is empty. */ public ToDoItem[] getAffectedItems() { return searchList; } }
package com.areen.jlib.gui; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.List; import javax.swing.AbstractListModel; import javax.swing.ComboBoxModel; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.Timer; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.JTextComponent; import javax.swing.text.PlainDocument; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; public class FilteredComboBox extends JComboBox { // Setting variables private boolean addingToTopEnabled = true; // Variables private static final Logger LOGGER = Logger.getLogger(FilteredComboBox.class); private FilteredComboBoxTestModel model; private final JTextComponent textComponent = (JTextComponent) getEditor().getEditorComponent(); private boolean modelFilling = false; private boolean updatePopup; private boolean layingOut = false; private AutoCompleteDocument autoCompleteDocument; private String previousPattern = null; // Constructors public FilteredComboBox() { model = new FilteredComboBoxTestModel(); setEditable(true); LOGGER.debug("setPattern() called from constructor"); setPattern(null); updatePopup = false; autoCompleteDocument = new AutoCompleteDocument(); autoCompleteDocument.setAddingEnabled(addingToTopEnabled); textComponent.setDocument(autoCompleteDocument); setModel(model); setSelectedItem(null); new Timer(20, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (updatePopup && isDisplayable()) { setPopupVisible(false); if (model.getSize() > 0) { setPopupVisible(true); } updatePopup = false; } } }).start(); } public FilteredComboBox(String[] argComboItems) { model = new FilteredComboBoxTestModel(argComboItems); setEditable(true); LOGGER.debug("setPattern() called from constructor"); setPattern(null); updatePopup = false; autoCompleteDocument = new AutoCompleteDocument(); autoCompleteDocument.setAddingEnabled(addingToTopEnabled); textComponent.setDocument(autoCompleteDocument); setModel(model); setSelectedItem(null); new Timer(20, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (updatePopup && isDisplayable()) { setPopupVisible(false); if (model.getSize() > 0) { setPopupVisible(true); } updatePopup = false; } } }).start(); } // Superclass/interface methods /** * {@inheritDoc } */ @Override public void doLayout() { try { layingOut = true; super.doLayout(); } finally { layingOut = false; } // finally } // doLayout() method /** * {@inheritDoc } * * @return Dimension object containing a much better dimension than the one from the JComboBox. */ @Override public Dimension getSize() { Dimension dim = super.getSize(); if (!layingOut) { dim.width = Math.max(dim.width, getPreferredSize().width); } return dim; } // getSize() method /** * An internal class that deals with FilteredComboBox entries as a Document. */ private class AutoCompleteDocument extends PlainDocument { boolean arrowKeyPressed = false; private boolean addingEnabled = false; public AutoCompleteDocument() { textComponent.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_ENTER) { LOGGER.debug("[key listener] enter key pressed"); //there is no such element in the model for now String text = textComponent.getText(); if (!model.data.contains(text)) { LOGGER.debug("addToTop() called from keyPressed()"); if (addingEnabled) { addToTop(text); } } } else if (key == KeyEvent.VK_UP || key == KeyEvent.VK_DOWN) { arrowKeyPressed = true; LOGGER.debug("arrow key pressed"); } } }); } void updateModel() throws BadLocationException { String textToMatch = getText(0, getLength()); LOGGER.debug("setPattern() called from updateModel()"); setPattern(textToMatch); } @Override public void remove(int offs, int len) throws BadLocationException { if (modelFilling) { LOGGER.debug("[remove] model is being filled now"); return; } super.remove(offs, len); if (arrowKeyPressed) { arrowKeyPressed = false; LOGGER.debug("[remove] arrow key was pressed, updateModel() was NOT called"); } else { LOGGER.debug("[remove] calling updateModel()"); updateModel(); } clearSelection(); } @Override public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { if (modelFilling) { LOGGER.debug("[insert] model is being filled now"); return; } // insert the string into the document super.insertString(offs, str, a); // if (enterKeyPressed) { // logger.debug("[insertString] enter key was pressed"); // enterKeyPressed = false; // return; String text = getText(0, getLength()); if (arrowKeyPressed) { LOGGER.debug("[insert] arrow key was pressed, updateModel() was NOT called"); model.setSelectedItem(text); LOGGER.debug(String.format("[insert] model.setSelectedItem(%s)", text)); arrowKeyPressed = false; } else if (!text.equals(getSelectedItem())) { LOGGER.debug("[insert] calling updateModel()"); updateModel(); } clearSelection(); } public boolean isAddingEnabled() { return addingEnabled; } public void setAddingEnabled(boolean argAddingEnabled) { addingEnabled = argAddingEnabled; } } // AutoCompleteDocument class (inner) public void setText(String text) { if (model.data.contains(text)) { setSelectedItem(text); } else { addToTop(text); setSelectedIndex(0); } } public String getText() { return getEditor().getItem().toString(); } private void setPattern(String pattern) { if (pattern != null && pattern.trim().isEmpty()) { pattern = null; } if (previousPattern == null && pattern == null || pattern != null && pattern.equals(previousPattern)) { LOGGER.debug("[setPatter] pattern is the same as previous: " + previousPattern); return; } previousPattern = pattern; modelFilling = true; // logger.debug("setPattern(): start"); model.setPattern(pattern); if (LOGGER.isDebugEnabled()) { StringBuilder b = new StringBuilder(100); b.append("pattern filter '").append(pattern == null ? "null" : pattern).append("' set:\n"); for (int i = 0; i < model.getSize(); i++) { b.append(", ").append('[').append(model.getElementAt(i)).append(']'); } int ind = b.indexOf(", "); if (ind != -1) { b.delete(ind, ind + 2); } // b.append('\n'); LOGGER.debug(b); } // logger.debug("setPattern(): end"); modelFilling = false; if (pattern != null) { updatePopup = true; } } // setPattern() method private void clearSelection() { int i = getText().length(); textComponent.setSelectionStart(i); textComponent.setSelectionEnd(i); } // @Override // public void setSelectedItem(Object anObject) { // super.setSelectedItem(anObject); // clearSelection(); public synchronized void addToTop(String aString) { model.addToTop(aString); } public boolean isAddingToTopEnabled() { return addingToTopEnabled; } /** * Use this method to disable adding of items to the top of the FilteredComboBox. * * @param addingToTopEnabled */ public void setAddingToTopEnabled(boolean argAddingToTopEnabled) { addingToTopEnabled = argAddingToTopEnabled; autoCompleteDocument.setAddingEnabled(addingToTopEnabled); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { // Logger root = Logger.getRootLogger(); // root.addAppender(new ConsoleAppender(new PatternLayout("%d{ISO8601} [%5p] %m at %l%n"))); Logger root = Logger.getRootLogger(); root.addAppender(new ConsoleAppender(new PatternLayout("%d{ISO8601} %m at %L%n"))); // BasicConfigurator.configure(); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new GridLayout(3, 1)); final JLabel label = new JLabel("label "); frame.add(label); final FilteredComboBox combo = new FilteredComboBox(); // combo.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() { // @Override // public void keyReleased(KeyEvent e) { // if (e.getKeyCode() == KeyEvent.VK_ENTER) { // String text = combo.getEditor().getItem().toString(); // if(text.isEmpty()) // return; // combo.addToTop(text); frame.add(combo); JComboBox combo2 = new JComboBox(new String[]{"Item 1", "Item 2", "Item 3", "Item 4"}); combo2.setEditable(true); frame.add(combo2); frame.pack(); frame.setSize(500, frame.getHeight()); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } // main() method // Nested classes /** * A basic model for the FilteredComboBox . */ private class FilteredComboBoxTestModel extends AbstractListModel implements ComboBoxModel { // String pattern; String selected; final String delimiter = ";;;"; final int limit = 20; /** * This nested class holds all strings that are filtered by the FilteredComboBox */ class Data { private List<String> list = new ArrayList<String>(limit); private List<String> lowercase = new ArrayList<String>(limit); private List<String> filtered; void add(String s) { list.add(s); lowercase.add(s.toLowerCase()); } void addToTop(String s) { list.add(0, s); lowercase.add(0, s.toLowerCase()); } void remove(int index) { list.remove(index); lowercase.remove(index); } List<String> getList() { return list; } List<String> getFiltered() { if (filtered == null) { filtered = list; } return filtered; } int size() { return list.size(); } void setPattern(String pattern) { if (pattern == null || pattern.isEmpty()) { filtered = list; FilteredComboBox.this.setSelectedItem(model.getElementAt(0)); LOGGER.debug(String.format("[setPattern] combo.setSelectedItem(null)")); } else { filtered = new ArrayList<String>(limit); pattern = pattern.toLowerCase(); for (int i = 0; i < lowercase.size(); i++) { //case insensitive search if (lowercase.get(i).contains(pattern)) { filtered.add(list.get(i)); } } FilteredComboBox.this.setSelectedItem(pattern); LOGGER.debug(String.format("[setPattern] combo.setSelectedItem(%s)", pattern)); } LOGGER.debug(String.format("pattern:'%s', filtered: %s", pattern, filtered)); } boolean contains(String s) { if (s == null || s.trim().isEmpty()) { return true; } s = s.toLowerCase(); for (String item : lowercase) { if (item.equals(s)) { return true; } } return false; } } // Data class (nested) FilteredComboBoxTestModel.Data data = new FilteredComboBoxTestModel.Data(); public FilteredComboBoxTestModel() { readData(); } public FilteredComboBoxTestModel(String[] argValues) { for (String el : argValues) { data.add(el); } } void readData() { String[] countries = { "Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Argentina", "Armenia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Benin", "Bhutan", "Bolivia", "Bosnia & Herzegovina", "Botswana", "Brazil", "Bulgaria", "Burkina Faso", "Burma", "Burundi", "Cambodia", "Cameroon", "Canada", "China", "Colombia", "Comoros", "Congo", "Croatia", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Georgia", "Germany", "Ghana", "Great Britain", "Greece", "Somalia", "Spain", "Sri Lanka", "Sudan", "Suriname", "Swaziland", "Sweden", "Switzerland", "Syria", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "Yemen", "Zaire", "Zambia", "Zimbabwe"}; for (String country : countries) { data.add(country); } } boolean isThreadStarted = false; void writeData() { StringBuilder b = new StringBuilder(limit * 60); for (String url : data.getList()) { b.append(delimiter).append(url); } b.delete(0, delimiter.length()); //waiting thread is already being run if (isThreadStarted) { return; } //we do saving in different thread //for optimization reasons (saving may take much time) new Thread(new Runnable() { @Override public void run() { //we do sleep because saving operation //may occur more than one per waiting period try { Thread.sleep(2000); } catch (InterruptedException ex) { LOGGER.debug(ex); } //we need this synchronization to //synchronize with FilteredComboBox.addElement method //(race condition may occur) synchronized (FilteredComboBox.this) { //HERE MUST BE SAVING OPERATION //(SAVING INTO FILE OR SOMETHING) //don't forget replace readData() method //to read saved data when creating bean isThreadStarted = false; } } }).start(); isThreadStarted = true; } public void setPattern(String pattern) { int size1 = getSize(); data.setPattern(pattern); int size2 = getSize(); if (size1 < size2) { fireIntervalAdded(this, size1, size2 - 1); fireContentsChanged(this, 0, size1 - 1); } else if (size1 > size2) { fireIntervalRemoved(this, size2, size1 - 1); fireContentsChanged(this, 0, size2 - 1); } } public void addToTop(String aString) { if (aString == null || data.contains(aString)) { return; } if (data.size() == 0) { data.add(aString); } else { data.addToTop(aString); } while (data.size() > limit) { int index = data.size() - 1; data.remove(index); } setPattern(null); model.setSelectedItem(aString); LOGGER.debug(String.format("[addToTop] model.setSelectedItem(%s)", aString)); //saving into options if (data.size() > 0) { writeData(); } } @Override public Object getSelectedItem() { return selected; } @Override public void setSelectedItem(Object anObject) { if ((selected != null && !selected.equals(anObject)) || selected == null && anObject != null) { selected = (String) anObject; fireContentsChanged(this, -1, -1); } } @Override public int getSize() { return data.getFiltered().size(); } @Override public Object getElementAt(int index) { return data.getFiltered().get(index); } } } // FilteredComboBox class
package com.sometrik.framework; import com.sometrik.framework.NativeCommand.Selector; import android.graphics.Bitmap; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.PopupMenu; public class FWActionSheet extends PopupMenu implements NativeCommandHandler { private int id; private boolean hasEntries = false; public FWActionSheet(final FrameWork frame, View anchor, final int id) { super(frame, anchor); this.id = id; this.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(PopupMenu arg0) { frame.intChangedEvent(id, 0, 0); } }); this.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { frame.intChangedEvent(id, item.getItemId(), 0); return true; } }); // Add dummy entry, or the menu will not have any width getMenu().add("No menu entries"); show(); } @Override public void onScreenOrientationChange(boolean isLandscape) { } @Override public void addChild(View view) { } @Override public void addOption(int optionId, String text) { if (!hasEntries) { getMenu().clear(); hasEntries = true; } getMenu().add(Menu.NONE, optionId, Menu.NONE, text); } @Override public void addColumn(String text, int columnType) { } @Override public void addData(String text, int row, int column, int sheet) { } @Override public void setValue(String v) { } @Override public void setBitmap(Bitmap bitmap) { } @Override public void addImageUrl(String url, int width, int height) { } @Override public void setValue(int v) { } @Override public void reshape(int value, int size) { } @Override public void reshape(int size) { } @Override public void setViewVisibility(boolean visible) { } @Override public void setStyle(Selector selector, String key, String value) { } @Override public void setError(boolean hasError, String errorText) { } @Override public void clear() { } @Override public void flush() { } @Override public void deinitialize() { dismiss(); } @Override public int getElementId() { return id; } }
package edu.first.team2903.robot.commands; import edu.first.team2903.robot.OI; import java.util.Random; public class TeleopMode extends CommandBase { public TeleopMode() { requires(drivetrain); requires(shooter); } protected void initialize() { shooter.frisbeePusher.setAngle(5); shooter.diskDrop.setAngle(0); } protected void execute() { //boolean state = true; //commented out in an attempt to stop the acceleration bug //Can't figure out how to turn setPusher to true to activate the //frisbee into the shooter area. Set to button 5 in OI.java //OI.triggerButton.whenPressed(new ToggleShooter()); if (OI.rightStick.getZ() < 0) { shooter.setSpeed(-OI.rightStick.getZ() * 2); } else { shooter.setSpeed(0); } //smart shooter if (OI.rightStick.getRawButton(1)) { try { shooter.shoot(); } catch (InterruptedException ex) { System.out.println("EXCEPTION OCCURED?!"); System.out.println("Today's Execption Occured Lotto Winner: "+new Random().nextInt()); } } drivetrain.drive(OI.leftStick.getY(), OI.rightStick.getY()); } protected boolean isFinished() { //Will end when teleop is done return false; } protected void end() { } protected void interrupted() { } }
package com.bainedog.patent.crawler; import java.io.IOException; import java.io.InputStream; import org.apache.http.Header; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.GetObjectMetadataRequest; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectRequest; public class Handler { private static String n(String header) { return header.replaceAll("-", "").toLowerCase(); } private static final Logger logger = LoggerFactory.getLogger(Handler.class); public String myHandler(CacheRequest request, Context context) throws IOException { logger.info("hello"); String uri = request.url; HeadMetadata hm = new HeadMetadata(); AmazonS3 s3 = new AmazonS3Client(); try (CloseableHttpClient http = HttpClients.createDefault()) { logger.info("begin HEAD of {}", uri); HttpUriRequest head = new HttpHead(uri); CloseableHttpResponse response = http.execute(head); for (Header h : response.getAllHeaders()) { logger.info("{} -> {}", h.getName(), h.getValue()); String n = n(h.getName()); if ("etag".equals(n)) { hm.setEtag(h.getValue()); } else if ("contentlength".equals(n)) { hm.setContentLength(Long.parseLong(h.getValue())); } else if ("contentmd5".equals(n)) { hm.setMd5(h.getValue()); } } EntityUtils.consume(response.getEntity()); response.close(); logger.info("finished HEAD of {}", uri); String bucketName = "patent-cache-us-east-1-prod"; String key = uri.replaceAll("http: ""); GetObjectMetadataRequest r = new GetObjectMetadataRequest( bucketName, key); logger.info("begin s3 HEAD of s3://{}/{}", bucketName, key); try { ObjectMetadata s3meta = s3.getObjectMetadata(r); S3Metadata s3Metadata = new S3Metadata(); s3Metadata.setContentLength(s3meta.getContentLength()); s3Metadata.setMd5(s3meta.getContentMD5()); s3Metadata.setEtag(s3meta.getETag()); s3Metadata.setSourceEtag(s3meta .getUserMetaDataOf("source-etag")); } catch (com.amazonaws.services.s3.model.AmazonS3Exception e) { logger.error("exception calling s3", e); } logger.info("finished s3 HEAD of s3://{}/{}", bucketName, key); logger.info("begin s3 PUT of {}", uri); HttpUriRequest get = new HttpGet(uri); CloseableHttpResponse getResponse = http.execute(head); InputStream inputStream = getResponse.getEntity().getContent(); ObjectMetadata om = new ObjectMetadata(); om.setContentLength(hm.getContentLength()); PutObjectRequest por = new PutObjectRequest(bucketName, key, inputStream, om); s3.putObject(por); logger.info("finished s3 PUT of {}", uri); } return "SUCCESS"; } }
package com.bloatit.web.actions; import com.bloatit.framework.Demand; import com.bloatit.framework.Description; import com.bloatit.web.server.Action; import com.bloatit.web.server.Session; import com.bloatit.web.utils.QueryParam; import com.bloatit.web.utils.TestQueryAnnotation.DemandLoader; import java.math.BigDecimal; import java.util.Date; import java.util.HashMap; import java.util.Map; public class OfferAction extends Action { /** * The idea on which the author wants to create a new offer */ @QueryParam(name = "idea", loader = DemandLoader.class, error = "Invalid idea") private Demand targetIdea = null; /** * The desired price for the offer */ @QueryParam(name = "offer_price") private BigDecimal price; /** * The expiration date for the offer */ @QueryParam(name = "offer_expiry_date") private Date expiryDate; /** * The title of the offer */ @QueryParam(name = "offer_title") private String title; /** * The short description of the offer */ @QueryParam(name = "offer_description") private String description; public OfferAction(Session session) { super(session, new HashMap<String, String>()); } public OfferAction(Session session, Map<String, String> parameters) { super(session, parameters); } /** * @return the code used to generate the form input field for the price */ public String getPriceCode() { return "offer_price"; } /** * @return the code used to generate the form input field for the expiration date */ public String getExpiryDateCode() { return "offer_expiry_date"; } /** * @return the code used to generate the form input field for the offer title */ public String getTitleCode() { return "offer_title"; } /** * @return the code used to generate the form input field for description of the offer */ public String getDescriptionCode() { return "offer_description"; } @Override public String getCode() { return "offer"; } @Override protected void process() { // Handle errors here // targetIdea.addOffer(price, , expiryDate); } }