lang
stringclasses
1 value
license
stringclasses
13 values
stderr
stringlengths
0
350
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
7
45.1k
new_contents
stringlengths
0
1.87M
new_file
stringlengths
6
292
old_contents
stringlengths
0
1.87M
message
stringlengths
6
9.26k
old_file
stringlengths
6
292
subject
stringlengths
0
4.45k
Java
bsd-3-clause
b52efa843dc1c94e76340ff151763e21aecc553d
0
gengo/gengo-java
package com.gengo.client; /** * @author [email protected] * */ public final class GengoConstants { static String BASE_URL_STANDARD = "https://api.staging.gengo.com/v2/"; static String BASE_URL_SANDBOX = "http://api.sandbox.gengo.com/v2/"; }
src/main/java/com/gengo/client/GengoConstants.java
/** * */ package com.gengo.client; /** * @author [email protected] * */ public final class GengoConstants { protected static String BASE_URL_STANDARD = "https://api.gengo.com/v2/"; protected static String BASE_URL_SANDBOX = "http://api.sandbox.gengo.com/v2/"; }
Modified accessor appropriately.
src/main/java/com/gengo/client/GengoConstants.java
Modified accessor appropriately.
Java
bsd-3-clause
51086f01de0792117e3d0df7cf551c21934912ff
0
NCIP/cadsr-cdecurate,NCIP/cadsr-cdecurate,NCIP/cadsr-cdecurate,NCIP/cadsr-cdecurate,NCIP/cadsr-cdecurate,NCIP/cadsr-cdecurate
// Copyright (c) 2005 ScenPro, Inc. // $Header: /CVSNT/cdecurate/src/gov/nih/nci/cadsr/cdecurate/tool/CurationServlet.java,v 1.81 2007/04/30 14:29:11 // lhebel Exp $ // $Name: not supported by cvs2svn $ package gov.nih.nci.cadsr.cdecurate.tool; // import files import gov.nih.nci.cadsr.cdecurate.database.SQLHelper; import gov.nih.nci.cadsr.cdecurate.ui.AltNamesDefsServlet; import gov.nih.nci.cadsr.cdecurate.ui.DesDEServlet; import gov.nih.nci.cadsr.cdecurate.util.DataManager; import gov.nih.nci.cadsr.persist.exception.DBException; import gov.nih.nci.cadsr.persist.user.User_Accounts_Mgr; import gov.nih.nci.cadsr.sentinel.util.DSRAlert; import gov.nih.nci.cadsr.sentinel.util.DSRAlertImpl; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Hashtable; import java.util.Vector; import javax.naming.Context; import javax.naming.InitialContext; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.sql.DataSource; import org.apache.log4j.Logger; /** * The CurationServlet is the main servlet for communicating between the client and the server. * <P> * * @author Joe Zhou, Sumana Hegde, Tom Phillips, Jesse McKean * @version 3.0 * */ /* * The CaCORE Software License, Version 3.0 Copyright 2002-2005 ScenPro, Inc. (ScenPro) Copyright Notice. The software * subject to this notice and license includes both human readable source code form and machine readable, binary, object * code form (the CaCORE Software). The CaCORE Software was developed in conjunction with the National Cancer * Institute (NCI) by NCI employees and employees of SCENPRO. To the extent government employees are authors, any * rights in such works shall be subject to Title 17 of the United States Code, section 105. This CaCORE Software * License (the License) is between NCI and You. You (or Your) shall mean a person or an entity, and all other * entities that control, are controlled by, or are under common control with the entity. Control for purposes of this * definition means (i) the direct or indirect power to cause the direction or management of such entity, whether by * contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) * beneficial ownership of such entity. This License is granted provided that You agree to the conditions described * below. NCI grants You a non-exclusive, worldwide, perpetual, fully-paid-up, no-charge, irrevocable, transferable and * royalty-free right and license in its rights in the CaCORE Software to (i) use, install, access, operate, execute, * copy, modify, translate, market, publicly display, publicly perform, and prepare derivative works of the CaCORE * Software; (ii) distribute and have distributed to and by third parties the CaCORE Software and any modifications and * derivative works thereof; and (iii) sublicense the foregoing rights set out in (i) and (ii) to third parties, * including the right to license such rights to further third parties. For sake of clarity, and not by way of * limitation, NCI shall have no right of accounting or right of payment from You or Your sublicensees for the rights * granted under this License. This License is granted at no charge to You. 1. Your redistributions of the source code * for the Software must retain the above copyright notice, this list of conditions and the disclaimer and limitation of * liability of Article 6, below. Your redistributions in object code form must reproduce the above copyright notice, * this list of conditions and the disclaimer of Article 6 in the documentation and/or other materials provided with the * distribution, if any. 2. Your end-user documentation included with the redistribution, if any, must include the * following acknowledgment: This product includes software developed by SCENPRO and the National Cancer Institute. If * You do not include such end-user documentation, You shall include this acknowledgment in the Software itself, * wherever such third-party acknowledgments normally appear. 3. You may not use the names "The National Cancer * Institute", "NCI" ScenPro, Inc. and "SCENPRO" to endorse or promote products derived from this Software. This * License does not authorize You to use any trademarks, service marks, trade names, logos or product names of either * NCI or SCENPRO, except as required to comply with the terms of this License. 4. For sake of clarity, and not by way * of limitation, You may incorporate this Software into Your proprietary programs and into any third party proprietary * programs. However, if You incorporate the Software into third party proprietary programs, You agree that You are * solely responsible for obtaining any permission from such third parties required to incorporate the Software into * such third party proprietary programs and for informing Your sublicensees, including without limitation Your * end-users, of their obligation to secure any required permissions from such third parties before incorporating the * Software into such third party proprietary software programs. In the event that You fail to obtain such permissions, * You agree to indemnify NCI for any claims against NCI by such third parties, except to the extent prohibited by law, * resulting from Your failure to obtain such permissions. 5. For sake of clarity, and not by way of limitation, You may * add Your own copyright statement to Your modifications and to the derivative works, and You may provide additional or * different license terms and conditions in Your sublicenses of modifications of the Software, or any derivative works * of the Software as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the * conditions stated in this License. 6. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, * (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, SCENPRO, OR THEIR AFFILIATES BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @author shegde * */ public class CurationServlet { protected SetACService m_setAC = new SetACService(this); public HttpServletRequest m_classReq = null; public HttpServletResponse m_classRes = null; protected ServletContext m_servletContext; public Connection m_conn=null; public static final Logger logger = Logger.getLogger(CurationServlet.class.getName()); /** declare the global variable sessionData */ public Session_Data sessionData; /** * @param req HttpServletRequest object * @param res HttpServletResponse object * @param sc ServletContext object * */ public CurationServlet(HttpServletRequest req, HttpServletResponse res, ServletContext sc) { m_classReq = req; m_classRes = res; m_servletContext = sc; } /** * */ public CurationServlet() { } /** * @param req HttpServletRequest object * @param res HttpServletResponse object * @param sc ServletContext object * */ public void init(HttpServletRequest req, HttpServletResponse res, ServletContext sc) { m_classReq = req; m_classRes = res; m_servletContext = sc; } /** * makes the login message with all the information * * @param req * @param sMethod * string a function name this is called from * @param endMsg * string a message to append to * @param bDate * Date begin date to calculate teh duration * @param eDate * date end date to calculate teh duration * @return String message */ public String getLogMessage(HttpServletRequest req, String sMethod, String endMsg, java.util.Date bDate, java.util.Date eDate) { String sMsg = ""; try { HttpSession session = req.getSession(); // call this in utility service class UtilService util = new UtilService(); sMsg = util.makeLogMessage(session, sMethod, endMsg, bDate, eDate); } catch (Exception e) { logger.warn("Unable to get the log message - " + sMsg); } return sMsg; } /** * display user friendly error message * * @param eMsg * String message * @return String user friendly message */ private String getDBConnectMessage(String eMsg) { String retMsg = ""; if (eMsg.contains("invalid username/password")) retMsg = "caDSR connection error, please verify the user name and password."; else if (eMsg.contains("maximum number of processes")) retMsg = "Reached connection limits, please try again later. If this persists contact the NIH Help Desk."; else if (eMsg.contains("Network Adapter") || eMsg.contains("Got minus one")) retMsg = "Network connection error, please contact the NIH Help Desk."; else if (eMsg.contains("Session Terminated")) retMsg = "Session has been terminated. Possible reasons could be a session timeout or an internal processing error. Please try again or contact the NIH Help Desk."; else retMsg = "Encountered an unexpected and unknown connection error, please contact the NIH Help Desk."; return retMsg; } /** * Start in the /conf/template.cdecurate-oracle-ds.xml file. Notice the <jndi-name>. * This name is used by JBoss to create and identify the connection pool. * We copied this name to the /conf/template.web.xml file in the <param-value> element. * The <param-name> for this initialization value appears in the code * NCICurationServlet.initOracleConnect() method. * The data source pool name is then saved in a class variable _dataSourceName. * * The variable is used by the CurationServlet.getConnFromDS() method which * is used by the CurationServlet.connectDB() method. * @return */ public Connection getConnFromDS() { // Use tool database pool. Context envContext = null; DataSource ds = null; String user_; String pswd_; try { envContext = new InitialContext(); ds = (DataSource) envContext.lookup(NCICurationServlet._dataSourceName); user_ = NCICurationServlet._userName; pswd_ = NCICurationServlet._password; } catch (Exception e) { String stErr = "Error creating database pool[" + e.getMessage() + "]."; e.printStackTrace(); System.out.println(stErr); logger.fatal(stErr, e); return null; } // Test connnection Connection con = null; try { con = ds.getConnection(user_, pswd_); } catch (Exception e) { System.err.println("Could not open database connection."); e.printStackTrace(); logger.fatal(e.toString(), e); return null; } return con; } /** * @param ub_ * @return Connection */ public Connection connectDB() { Connection SBRDb_conn = null; try { try { SBRDb_conn = this.getConnFromDS(); } catch (Exception e) { logger.fatal("Servlet error: no pool connection.", e); } } catch (Exception e) { logger.fatal("Servlet connectDB : " + e.toString(), e); } return SBRDb_conn; } /** * Performs the login * @param req * @param res * @param session */ private void login(HttpServletRequest req, HttpServletResponse res,HttpSession session)throws Exception { String username = req.getParameter("Username").toUpperCase(); String password = req.getParameter("Password"); CaDsrUserCredentials uc = new CaDsrUserCredentials(); UserBean userbean = new UserBean(); User_Accounts_Mgr userAccountMgr = new User_Accounts_Mgr(); try { userbean.setUsername(username); userbean.setPassword(password); uc.validateCredentials(NCICurationServlet._userName, NCICurationServlet._password, username, password); userbean.setUserFullName(userAccountMgr.getUserFullName(username, m_conn)); userbean.setPassword(""); userbean.setDBAppContext("/cdecurate"); DataManager.setAttribute(session, "Userbean", userbean); DataManager.setAttribute(session, "Username", userbean.getUsername()); sessionData.UsrBean = userbean; GetACService getAC = new GetACService(m_classReq, m_classRes, this); getAC.getWriteContextList(); } catch(DBException e){ logger.error("Unable to get User FullName" + e); } catch (Exception ex) { userbean=null; logger.error("Failed credential validation, code is " + uc.getCheckCode()); logger.error("Redirecting the user to Login Page"); ForwardErrorJSP(req, res, "Incorrect Username or Password. Please re-enter."); } } /** * Authenticates the user login credentials with the jboss authentication * data source. * @param user * @return */ /* private boolean authenticate(UserBean user) { // Use tool database pool. Context envContext = null; DataSource ds = null; boolean validUser =false; try { envContext = new InitialContext(); ds = (DataSource) envContext.lookup(NCICurationServlet._authenticateDSName); } catch (Exception e) { String stErr = "Error creating database pool[" + e.getMessage() + "]."; logger.fatal(stErr, e); return false; } // Test connnection Connection con = null; try { con = ds.getConnection(user.getUsername(), user.getPassword()); if(con!=null) { validUser = true; } } catch (SQLException e) { logger.fatal(e.toString(), e); return false; }finally{ SQLHelper.closeConnection(con); } return validUser; } */ public void get_m_conn() { HttpSession session = m_classReq.getSession(true); // get the session data object from the session sessionData = (Session_Data) session.getAttribute(Session_Data.CURATION_SESSION_ATTR); if (sessionData == null) sessionData = new Session_Data(); //get the connection if (m_conn == null) { m_conn = connectDB(); setConn(m_conn); } } protected UserBean checkLoggedIn() throws Exception { UserBean ub = checkUserBean(m_classReq, m_classRes); if (ub == null) { HttpSession session = m_classReq.getSession(true); String errMsg = getDBConnectMessage("Session Terminated"); DataManager.setAttribute(session, "ErrorMessage", errMsg); // get the menu action from request String mnReq = (String) m_classReq.getParameter("serMenuAct"); if (mnReq == null) mnReq = ""; DataManager.setAttribute(session, "serMenuAct", mnReq); // forward the error page ForwardErrorJSP(m_classReq, m_classRes, errMsg); } return ub; } /** * The service method services all requests to this servlet. * */ public void service() { UserBean ub = null; HttpSession session; session = m_classReq.getSession(true); try { // get the session data object from the session sessionData = (Session_Data) session.getAttribute(Session_Data.CURATION_SESSION_ATTR); if (sessionData == null) sessionData = new Session_Data(); else m_conn = connectDB(); String reqType = m_classReq.getParameter("reqType"); m_classReq.setAttribute("LatestReqType", reqType); if (reqType != null) { while (true) { // check the validity of the user login if (reqType.equals("login")) { //DataManager.clearSessionAttributes(session); // sessionData = new Session_Data(); login(m_classReq,m_classRes,session); String prevReq = m_classReq.getParameter("previousReqType"); if (prevReq == null) prevReq = "/SearchResultsPage.jsp"; ForwardJSP(m_classReq, m_classRes, prevReq); break; } if ("heartbeat".equals(reqType)) { doLogout(m_classReq, m_classRes); break; } // do the requests ub = checkUserBean(m_classReq, m_classRes); if (ub != null) { if (reqType.equals("newCCFromMenu")) // fromForm { doCreateCCActions(m_classReq, m_classRes); } if (reqType.equals("newPV")) // fromForm { doCreatePVActions(m_classReq, m_classRes); } else if (reqType.equals("pvEdits")) // fromForm { doEditPVActions(m_classReq, m_classRes); } else if (reqType.equals(VMForm.ELM_FORM_REQ_DETAIL) || reqType.equals(VMForm.ELM_FORM_REQ_USED) || reqType.equals(VMForm.ELM_FORM_REQ_VAL)) // fromForm { doEditVMActions(m_classReq, m_classRes); } else if (reqType.equals("createPV") || reqType.equals("editPV")) { doOpenCreatePVPage(m_classReq, m_classRes, reqType, ""); } else if (reqType.equals("errorPageForward")) { doJspErrorAction(m_classReq, m_classRes); // on click on the edit/create from menu } else if (reqType.equals("logout")) { doLogout(m_classReq, m_classRes); } else if (reqType.equals("searchEVS")) { doSearchEVS(m_classReq, m_classRes); } // else if (reqType.equals("searchQualifiers")) // { // doQualifierSearchActions(m_classReq, m_classRes); // } // get more records of Doc Text else if (reqType.equals("getRefDocument")) { this.doRefDocSearchActions(m_classReq, m_classRes); } // get more records of alternate names else if (reqType.equals("getAltNames")) { this.doAltNameSearchActions(m_classReq, m_classRes); } // get more records of permissible values else if (reqType.equals("getPermValue")) { this.doPermValueSearchActions(m_classReq, m_classRes); } // get more records of protocol crf else if (reqType.equals("getProtoCRF")) { this.doProtoCRFSearchActions(m_classReq, m_classRes); } // get detailed records of concept class else if (reqType.equals("getConClassForAC")) { this.doConClassSearchActions(m_classReq, m_classRes); } // get cd details for vm else if (reqType.equals("showCDDetail")) { this.doConDomainSearchActions(m_classReq, m_classRes); } else if (reqType.equals("treeSearch")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("treeRefresh")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("treeExpand")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("treeCollapse")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("getSubConcepts")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("getSuperConcepts")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("designateDE")) { new DesDEServlet(this, ub).doAction(m_classReq, m_classRes, "Edit"); } else if (reqType.equals(AltNamesDefsServlet._reqType)) { new AltNamesDefsServlet(this, ub).doAction(m_classReq, m_classRes); } else if (reqType.equals("RefDocumentUpload")) { this.doRefDocumentUpload(m_classReq, m_classRes, "Request"); } else if (reqType.equals("nonEVSSearch")) { this.doNonEVSPageAction(m_classReq, m_classRes); } else if (reqType.equals("ACcontact")) { this.doContactEditActions(m_classReq, m_classRes); } break; } if (!reqType.equals("login")) { String errMsg = getDBConnectMessage("Session Terminated"); // "Please login again. Your session has // been terminated. Possible reasons // could be a session timeout or an // internal processing error."; DataManager.setAttribute(session, "ErrorMessage", errMsg); // get the menu action from request String mnReq = (String) m_classReq.getParameter("serMenuAct"); if (mnReq == null) mnReq = ""; DataManager.setAttribute(session, "serMenuAct", mnReq); // forward the error page ForwardErrorJSP(m_classReq, m_classRes, errMsg); break; } break; } } else { this.logger.fatal("Service: no DB Connection"); ErrorLogin(m_classReq, m_classRes); } SQLHelper.closeConnection(m_conn); } catch (Exception e) { logger.fatal("Service error : " + e.toString(), e); session = m_classReq.getSession(); String msg = e.toString(); try { if (msg != null) ForwardErrorJSP(m_classReq, m_classRes, msg); else ForwardErrorJSP(m_classReq, m_classRes, "A page error has occurred. Please login again."); } catch (Exception ee) { logger.fatal("Service forward error : " + ee.toString(), ee); } }finally{ SQLHelper.closeConnection(m_conn); } } // end of service /** * The service method services all requests to this servlet. * */ public void serviceOLD() { UserBean ub = null; HttpSession session; session = m_classReq.getSession(true); try { // get the session data object from the session sessionData = (Session_Data) session.getAttribute(Session_Data.CURATION_SESSION_ATTR); if (sessionData == null) sessionData = new Session_Data(); else m_conn = connectDB(); String reqType = m_classReq.getParameter("reqType"); m_classReq.setAttribute("LatestReqType", reqType); if (reqType != null) { while (true) { // check the validity of the user login if (reqType.equals("login")) { DataManager.clearSessionAttributes(session); sessionData = new Session_Data(); login(m_classReq,m_classRes,session); break; } if ("heartbeat".equals(reqType)) { doLogout(m_classReq, m_classRes); break; } // do the requests ub = checkUserBean(m_classReq, m_classRes); if (ub != null) { /* if (reqType.equals("homePage")) { doHomePage(m_classReq, m_classRes); } else if (DERequestTypes.valueOf(reqType) != null) { DE_Servlet deServ = new DE_Servlet(m_classReq, m_classRes); // doOpenCreateNewPages(m_classReq, m_classRes, "de"); deServ.AC_Service(DERequestTypes.valueOf(reqType)); } else if (reqType.equals("newDECFromMenu")) { // doOpenCreateNewPages(m_classReq, m_classRes, "dec"); } else if (reqType.equals("newVDFromMenu")) { // doOpenCreateNewPages(m_classReq, m_classRes, "vd"); } else if (reqType.equals("newDECfromForm")) // when DEC form is submitted { doCreateDECActions(m_classReq, m_classRes); } else if (reqType.equals("newVDfromForm")) // when Edit VD form is submitted { doCreateVDActions(m_classReq, m_classRes); } else if (reqType.equals("editDEC")) // when Edit DEC form is submitted { doEditDECActions(m_classReq, m_classRes); } else if (reqType.equals("editVD")) { doEditVDActions(m_classReq, m_classRes); } else*/ if (reqType.equals("newPV")) // fromForm { doCreatePVActions(m_classReq, m_classRes); } else if (reqType.equals("pvEdits")) // fromForm { doEditPVActions(m_classReq, m_classRes); } else if (reqType.equals(VMForm.ELM_FORM_REQ_DETAIL) || reqType.equals(VMForm.ELM_FORM_REQ_USED) || reqType.equals(VMForm.ELM_FORM_REQ_VAL)) // fromForm { doEditVMActions(m_classReq, m_classRes); } else if (reqType.equals("createPV") || reqType.equals("editPV")) { doOpenCreatePVPage(m_classReq, m_classRes, reqType, ""); } /* else if (reqType.equals("createNewDEC")) { doOpenCreateDECPage(m_classReq, m_classRes); } else if (reqType.equals("createNewVD")) { doOpenCreateVDPage(m_classReq, m_classRes); } else if (reqType.equals("validateDECFromForm")) { doInsertDEC(m_classReq, m_classRes); } else if (reqType.equals("validateVDFromForm")) { doInsertVD(m_classReq, m_classRes); } */ /* else if (reqType.equals("searchACs")) { doGetACSearchActions(m_classReq, m_classRes); // m_classReq for search parameters page } else if (reqType.equals("showResult")) { doSearchResultsAction(m_classReq, m_classRes, ub); // m_classReq from search results page } else if (reqType.equals("showBEDisplayResult")) { doDisplayWindowBEAction(m_classReq, m_classRes); // m_classReq from search results page showBEDisplayResult } else if (reqType.equals("showDECDetail")) { doDECDetailDisplay(m_classReq, m_classRes); // m_classReq from DECDetailsWindow page } else if (reqType.equals("doSortCDE")) { doSortACActions(m_classReq, m_classRes); // on sort by heading for search } else if (reqType.equals("doSortBlocks")) { doSortBlockActions(m_classReq, m_classRes, "Blocks"); // on sort by heading for search } else if (reqType.equals("doSortQualifiers")) { doSortBlockActions(m_classReq, m_classRes, "Qualifiers"); // on sort by heading for search } else if (reqType.equals("getSearchFilter")) { doOpenSearchPage(m_classReq, m_classRes); // on click on the search from menu } else if (reqType.equals("actionFromMenu")) { doMenuAction(m_classReq, m_classRes); // on click on the edit/create from menu } */ else if (reqType.equals("errorPageForward")) { doJspErrorAction(m_classReq, m_classRes); // on click on the edit/create from menu } else if (reqType.equals("logout")) { doLogout(m_classReq, m_classRes); } else if (reqType.equals("searchEVS")) { doSearchEVS(m_classReq, m_classRes); } /* else if (reqType.equals("searchBlocks")) { doBlockSearchActions(m_classReq, m_classRes); } else if (reqType.equals("searchQualifiers")) { doQualifierSearchActions(m_classReq, m_classRes); } */ // get more records of Doc Text else if (reqType.equals("getRefDocument")) { this.doRefDocSearchActions(m_classReq, m_classRes); } // get more records of alternate names else if (reqType.equals("getAltNames")) { this.doAltNameSearchActions(m_classReq, m_classRes); } // get more records of permissible values else if (reqType.equals("getPermValue")) { this.doPermValueSearchActions(m_classReq, m_classRes); } // get more records of protocol crf else if (reqType.equals("getProtoCRF")) { this.doProtoCRFSearchActions(m_classReq, m_classRes); } // get detailed records of concept class else if (reqType.equals("getConClassForAC")) { this.doConClassSearchActions(m_classReq, m_classRes); } // get cd details for vm else if (reqType.equals("showCDDetail")) { this.doConDomainSearchActions(m_classReq, m_classRes); } else if (reqType.equals("treeSearch")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("treeRefresh")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("treeExpand")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("treeCollapse")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("getSubConcepts")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("getSuperConcepts")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("designateDE")) { new DesDEServlet(this, ub).doAction(m_classReq, m_classRes, "Edit"); } else if (reqType.equals(AltNamesDefsServlet._reqType)) { new AltNamesDefsServlet(this, ub).doAction(m_classReq, m_classRes); } else if (reqType.equals("RefDocumentUpload")) { this.doRefDocumentUpload(m_classReq, m_classRes, "Request"); } else if (reqType.equals("nonEVSSearch")) { this.doNonEVSPageAction(m_classReq, m_classRes); } else if (reqType.equals("ACcontact")) { this.doContactEditActions(m_classReq, m_classRes); } break; } if (!reqType.equals("login")) { String errMsg = getDBConnectMessage("Session Terminated"); // "Please login again. Your session has // been terminated. Possible reasons // could be a session timeout or an // internal processing error."; DataManager.setAttribute(session, "ErrorMessage", errMsg); // get the menu action from request String mnReq = (String) m_classReq.getParameter("serMenuAct"); if (mnReq == null) mnReq = ""; DataManager.setAttribute(session, "serMenuAct", mnReq); // forward the error page ForwardErrorJSP(m_classReq, m_classRes, errMsg); break; } break; } } else { this.logger.fatal("Service: no DB Connection"); ErrorLogin(m_classReq, m_classRes); } SQLHelper.closeConnection(m_conn); } catch (Exception e) { logger.fatal("Service error : " + e.toString(), e); session = m_classReq.getSession(); String msg = e.toString(); try { if (msg != null) ForwardErrorJSP(m_classReq, m_classRes, msg); else ForwardErrorJSP(m_classReq, m_classRes, "A page error has occurred. Please login again."); } catch (Exception ee) { logger.fatal("Service forward error : " + ee.toString(), ee); } }finally{ SQLHelper.closeConnection(m_conn); } } // end of service /** * The checkUserBean method gets the session then checks whether a Userbean exits. Called from 'service' method. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @return userBeanExists * * @throws Exception */ private UserBean checkUserBean(HttpServletRequest req, @SuppressWarnings("unused") HttpServletResponse res) throws Exception { HttpSession session; session = req.getSession(true); UserBean userbean = (UserBean) session.getAttribute("Userbean"); if (userbean == null) { logger.fatal("User bean is null"); // ForwardErrorJSP(req, res, "Please login again. Your session has been terminated. Possible reasons could // be a session timeout or an internal processing error."); } else { EVS_UserBean eUser = (EVS_UserBean) this.sessionData.EvsUsrBean; // (EVS_UserBean)session.getAttribute(EVSSearch.EVS_USER_BEAN_ARG); // //("EvsUserBean"); if (eUser == null) eUser = new EVS_UserBean(); } return userbean; } // //////////////////////////////////////////////////////////////////////////////////// /** * The doLogin method forwards to CDEHomePage.jsp. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ /* private void doLogin(HttpServletRequest req, HttpServletResponse res) throws Exception { ForwardJSP(req, res, "/CDEHomePage.jsp"); } */ /** * Gets the Help URL from Tool options table. * @param req * @param res */ public String getHelpURL(Connection con) { GetACService getAC = new GetACService(); Vector vList = new Vector(); vList = getAC.getToolOptionData(con,"CURATION", "HELP.HOME", ""); String aURL = null; if (vList != null && vList.size() > 0) { TOOL_OPTION_Bean tob = (TOOL_OPTION_Bean) vList.elementAt(0); if (tob != null) aURL = tob.getVALUE(); } return aURL; } /** * @param req * @param res * @throws Exception */ private void doCreateCCActions(HttpServletRequest req, HttpServletResponse res) throws Exception { ForwardJSP(req, res, "/CreateConceptClass.jsp"); } /** * The doCreatePVActions method handles the submission of a CreatePV form Called from DON'T KNOW Calls * 'doValidatePV' if the action is Validate or submit. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ @SuppressWarnings("unchecked") private void doCreatePVActions(HttpServletRequest req, HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); String sAction = (String) req.getParameter("pageAction"); String sMenuAction = (String) req.getParameter("MenuAction"); if (sMenuAction != null) DataManager.setAttribute(session, Session_Data.SESSION_MENU_ACTION, sMenuAction); String sButtonPressed = (String) session.getAttribute("LastMenuButtonPressed"); // String sOriginAction = (String) session.getAttribute("originAction"); // clear searched data from teh session attributes /* * if (sAction.equals("submit")) doSubmitPV(req, res); else if (sAction.equals("validate")) doValidatePV(req, * res); else */if (sAction.equals("createNewVM")) this.doOpenCreateVMPage(req, res, "vm"); // store vm attributes in pv bean else if (sAction.equals("appendSearchVM")) { PV_Bean pvBean = (PV_Bean) session.getAttribute("m_PV"); if (pvBean == null) pvBean = new PV_Bean(); SetACService setAC = new SetACService(this); setAC.setPVValueFromPage(req, res, pvBean); String selVM = pvBean.getPV_SHORT_MEANING(); Vector vRSel = (Vector) session.getAttribute("vACSearch"); if (vRSel == null) vRSel = new Vector(); for (int i = 0; i < (vRSel.size()); i++) { VM_Bean vmBean = (VM_Bean) vRSel.elementAt(i); // store the vm attributes in pv attribute /*if (vmBean.getVM_SHORT_MEANING().equals(selVM))*/ if (vmBean.getVM_LONG_NAME().equals(selVM)) { // pvBean.setPV_MEANING_DESCRIPTION(vmBean.getVM_DESCRIPTION()); pvBean.setPV_MEANING_DESCRIPTION(vmBean.getVM_PREFERRED_DEFINITION()); // pvBean.setVM_CONCEPT(vmBean.getVM_CONCEPT()); pvBean.setPV_VM(vmBean); break; } } DataManager.setAttribute(session, "m_PV", pvBean); ForwardJSP(req, res, "/CreatePVPage.jsp"); } else if (sAction.equals("clearBoxes")) { PV_Bean pvOpen = (PV_Bean) session.getAttribute("pageOpenBean"); PV_Bean pvBean = (PV_Bean) session.getAttribute("m_PV"); if (pvOpen != null) pvBean = pvBean.copyBean(pvOpen); DataManager.setAttribute(session, "m_PV", pvBean); ForwardJSP(req, res, "/CreatePVPage.jsp"); } else if (sAction.equals("backToVD")) { // set the checked property to false Vector<PV_Bean> vOldVDPVList = (Vector) session.getAttribute("oldVDPVList"); if (vOldVDPVList != null) { for (int i = 0; i < vOldVDPVList.size(); i++) { PV_Bean oldPV = (PV_Bean) vOldVDPVList.elementAt(i); // System.out.println(oldPV.getPV_BEGIN_DATE() + " back vd old " + oldPV.getPV_END_DATE()); oldPV.setPV_CHECKED(false); vOldVDPVList.setElementAt(oldPV, i); } DataManager.setAttribute(session, "VDPVList", vOldVDPVList); } if (sMenuAction.equals("editVD") || sMenuAction.equals("editDE") || sButtonPressed.equals("Search")) ForwardJSP(req, res, "/EditVDPage.jsp"); // back to Edit VD Screen else ForwardJSP(req, res, "/CreateVDPage.jsp"); } } /** * @param req * @param res * @throws Exception */ protected void doOpenEditVM(HttpServletRequest req, HttpServletResponse res, VM_Bean vm, PV_Bean pv) throws Exception { ValueDomainServlet vdServ = (ValueDomainServlet) this.getACServlet("ValueDomain"); PVServlet pvSer = new PVServlet(req, res, vdServ); String pageFor = pvSer.openVMPageEdit(vm,pv); if (pageFor != null && !pageFor.equals("")) { if (pageFor.charAt(0) != '/') pageFor = "/" + pageFor; ForwardJSP(req, res, pageFor); } } /** * The doEditPVActions method handles the submission of a CreatePV form Calls 'doValidatePV' if the action is * Validate or submit. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doEditPVActions(HttpServletRequest req, HttpServletResponse res) throws Exception { ValueDomainServlet vdServ = (ValueDomainServlet) this.getACServlet("ValueDomain"); PVServlet pvSer = new PVServlet(req, res, vdServ); String pageFor = pvSer.doEditPVActions(); if (pageFor != null && !pageFor.equals("")) { if (pageFor.charAt(0) != '/') pageFor = "/" + pageFor; ForwardJSP(req, res, pageFor); } } /** * The doEditVMActions method handles the submission of a CreatePV form Calls 'doValidateVM' if the action is * Validate or submit. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doEditVMActions(HttpServletRequest req, HttpServletResponse res) throws Exception { VMServlet vmSer = new VMServlet(req, res, this); String pageFor = vmSer.run(); // doEditVMActions(); if (pageFor != null && !pageFor.equals("")) { if (pageFor.charAt(0) != '/') pageFor = "/" + pageFor; ForwardJSP(req, res, pageFor); } } /** * adds and removes alternate names and reference documents from the vectors * * @param req * @param pageAct * @throws java.lang.Exception */ private void doMarkAddRemoveDesignation(HttpServletRequest req, String pageAct) throws Exception { // call methods for different actions if (pageAct.equals("addAlt")) // do add alt name action this.doMarkAddAltNames(req); else if (pageAct.equals("addRefDoc")) // do add ref doc action this.doMarkAddRefDocs(req); else if (pageAct.equals("removeAlt")) // remove alt names this.doMarkRemoveAltNames(req); else if (pageAct.equals("removeRefDoc")) // remove refernece documents this.doMarkRemoveRefDocs(req); } /** * adds alternate names to the vectors * * @param req * @throws java.lang.Exception */ @SuppressWarnings("unchecked") private void doMarkAddAltNames(HttpServletRequest req) throws Exception { HttpSession session = req.getSession(); // InsACService insAC = new InsACService(m_classReq, m_classRes, this); // String stgContMsg = ""; // get the sessin vectors Vector<ALT_NAME_Bean> vAltNames = (Vector) session.getAttribute("AllAltNameList"); Vector vContext = (Vector) session.getAttribute("vWriteContextDE"); if (vContext == null) vContext = new Vector(); // add alternate names String selName = (String) req.getParameter("txtAltName"); if (selName == null) selName = ""; selName = selName.trim(); if (selName.equals("")) { storeStatusMsg("Please enter a text for the alternate name"); return; } // get the request vectors Vector<String> vACId = (Vector) session.getAttribute("vACId"); if (vACId == null) vACId = new Vector<String>(); Vector<String> vACName = (Vector) session.getAttribute("vACName"); if (vACName == null) vACName = new Vector<String>(); String sContID = (String) req.getParameter("selContext"); String sContext = (String) req.getParameter("contextName"); if (sContID != null) req.setAttribute("desContext", sContID); String sLang = (String) req.getParameter("dispLanguage"); if (sLang != null) req.setAttribute("desLang", sLang); String selType = (String) req.getParameter("selAltType"); // handle the context and ac name for new AC (DE, DEC and VD) if (vACId.size() < 1) vACId.addElement("new"); if (vACName.size() < 1) vACName.addElement("new"); if (sContID == null || sContID.equals("")) sContID = "new"; // continue with acitons for (int i = 0; i < vACId.size(); i++) { // get ac names String acID = (String) vACId.elementAt(i); if (acID == null) acID = ""; String acName = ""; if (vACName.size() > i) acName = (String) vACName.elementAt(i); // get page attributes // check if another record with same type, name, ac and context exists already boolean isExist = false; for (int k = 0; k < vAltNames.size(); k++) { ALT_NAME_Bean altBean = (ALT_NAME_Bean) vAltNames.elementAt(k); // check if it was existed in the list already if (altBean.getALT_TYPE_NAME().equals(selType) && altBean.getALTERNATE_NAME().equals(selName) && altBean.getCONTE_IDSEQ().equals(sContID) && altBean.getAC_IDSEQ().equals(acID)) { // change the submit action if deleted if (altBean.getALT_SUBMIT_ACTION().equals("DEL")) { // mark it as ins if new one or upd if old one String altID = altBean.getALT_NAME_IDSEQ(); if (altID == null || altID.equals("") || altID.equals("new")) altBean.setALT_SUBMIT_ACTION("INS"); else altBean.setALT_SUBMIT_ACTION("UPD"); vAltNames.setElementAt(altBean, k); } isExist = true; } } // add new one if not existed in teh bean already if (isExist == false) { // fill in the bean and vector ALT_NAME_Bean AltNameBean = new ALT_NAME_Bean(); AltNameBean.setALT_NAME_IDSEQ("new"); AltNameBean.setCONTE_IDSEQ(sContID); AltNameBean.setCONTEXT_NAME(sContext); AltNameBean.setALTERNATE_NAME(selName); AltNameBean.setALT_TYPE_NAME(selType); AltNameBean.setAC_LONG_NAME(acName); AltNameBean.setAC_IDSEQ(acID); AltNameBean.setAC_LANGUAGE(sLang); AltNameBean.setALT_SUBMIT_ACTION("INS"); vAltNames.addElement(AltNameBean); // add the bean to a vector } } DataManager.setAttribute(session, "AllAltNameList", vAltNames); } /** * removes alternate names from the vectors * * @param req * @throws java.lang.Exception */ @SuppressWarnings("unchecked") private void doMarkRemoveAltNames(HttpServletRequest req) throws Exception { HttpSession session = req.getSession(); // InsACService insAC = new InsACService(m_classReq, m_classRes, this); String stgContMsg = ""; // get the sessin vectors Vector<ALT_NAME_Bean> vAltNames = (Vector) session.getAttribute("AllAltNameList"); Vector<String> vContext = (Vector) session.getAttribute("vWriteContextDE"); if (vContext == null) vContext = new Vector<String>(); String sContID = (String) req.getParameter("selContext"); if (sContID != null) req.setAttribute("desContext", sContID); int j = -1; // to keep track of number of items on the page Vector<String> vAltAttrs = new Vector<String>(); for (int i = 0; i < vAltNames.size(); i++) { ALT_NAME_Bean aBean = (ALT_NAME_Bean) vAltNames.elementAt(i); if (!aBean.getALT_SUBMIT_ACTION().equals("DEL")) { String altName = aBean.getALTERNATE_NAME(); String altType = aBean.getALT_TYPE_NAME(); String altCont = aBean.getCONTEXT_NAME(); // go to next record if same type, name and context does exist String curAltAttr = altType + " " + altName + " " + altCont; // increase teh count only if it didn't exist in the disp vecot list if (!vAltAttrs.contains(curAltAttr)) { vAltAttrs.addElement(curAltAttr); j += 1; } String ckItem = (String) req.getParameter("ACK" + j); // get the right selected item to mark as deleted if (ckItem != null) { if (vContext.contains(altCont) || altCont.equals("") || altCont.equalsIgnoreCase("new")) { aBean.setALT_SUBMIT_ACTION("DEL"); vAltNames.setElementAt(aBean, i); // check if another record with same type, name and context but diff ac exists to remove for (int k = 0; k < vAltNames.size(); k++) { ALT_NAME_Bean altBean = (ALT_NAME_Bean) vAltNames.elementAt(k); if (!altBean.getALT_SUBMIT_ACTION().equals("DEL") && altBean.getALTERNATE_NAME().equals(altName)) { if (altBean.getALT_TYPE_NAME().equals(altType) && altBean.getCONTEXT_NAME().equals(altCont)) { altBean.setALT_SUBMIT_ACTION("DEL"); // mark them also deleted vAltNames.setElementAt(altBean, k); } } } } else stgContMsg += "\\n\\t" + altName + " in " + altCont + " Context "; break; } } } if (stgContMsg != null && !stgContMsg.equals("")) storeStatusMsg("Unable to remove the following Alternate Names, because the user does not have write permission to remove " + stgContMsg); DataManager.setAttribute(session, "AllAltNameList", vAltNames); } // end remove alt names /** * adds reference documents to the vectors * * @param req * @throws java.lang.Exception */ @SuppressWarnings("unchecked") private void doMarkAddRefDocs(HttpServletRequest req) throws Exception { HttpSession session = req.getSession(); // InsACService insAC = new InsACService(m_classReq, m_classRes, this); String selName = (String) req.getParameter("txtRefName"); if (selName == null) selName = ""; selName = selName.trim(); if (selName.equals("")) { storeStatusMsg("Please enter a text for the alternate name"); return; } // continue with adding // String stgContMsg = ""; Vector<REF_DOC_Bean> vRefDocs = (Vector) session.getAttribute("AllRefDocList"); Vector<String> vACId = (Vector) session.getAttribute("vACId"); if (vACId == null) vACId = new Vector<String>(); Vector<String> vACName = (Vector) session.getAttribute("vACName"); if (vACName == null) vACName = new Vector<String>(); Vector vContext = (Vector) session.getAttribute("vWriteContextDE"); if (vContext == null) vContext = new Vector(); // get request attributes String sContID = (String) req.getParameter("selContext"); String sContext = (String) req.getParameter("contextName"); if (sContID != null) req.setAttribute("desContext", sContID); String sLang = (String) req.getParameter("dispLanguage"); if (sLang != null) req.setAttribute("desLang", sLang); String selType = (String) req.getParameter("selRefType"); String selText = (String) req.getParameter("txtRefText"); String selUrl = (String) req.getParameter("txtRefURL"); // handle the context and ac name for new AC (DE, DEC and VD) if (vACId.size() < 1) vACId.addElement("new"); if (vACName.size() < 1) vACName.addElement("new"); if (sContID == null || sContID.equals("")) sContID = "new"; // do add ref doc action for (int i = 0; i < vACId.size(); i++) { // get ac names String acID = (String) vACId.elementAt(i); if (acID == null) acID = ""; String acName = ""; if (vACName.size() > i) acName = (String) vACName.elementAt(i); // check if another record with same type, name, ac and context exists already boolean isExist = false; for (int k = 0; k < vRefDocs.size(); k++) { REF_DOC_Bean refBean = (REF_DOC_Bean) vRefDocs.elementAt(k); // check if it was existed in the list already if (refBean.getDOC_TYPE_NAME().equals(selType) && refBean.getDOCUMENT_NAME().equals(selName) && refBean.getCONTE_IDSEQ().equals(sContID) && refBean.getAC_IDSEQ().equals(acID)) { // change the submit action if deleted if (refBean.getREF_SUBMIT_ACTION().equals("DEL")) { // mark it as ins if new one or upd if old one String refID = refBean.getREF_DOC_IDSEQ(); if (refID == null || refID.equals("") || refID.equals("new")) refBean.setREF_SUBMIT_ACTION("INS"); else refBean.setREF_SUBMIT_ACTION("UPD"); vRefDocs.setElementAt(refBean, k); } isExist = true; } } // add new one if not existed in teh bean already if (isExist == false) { // fill in the bean and vector REF_DOC_Bean RefDocBean = new REF_DOC_Bean(); RefDocBean.setAC_IDSEQ(acID); RefDocBean.setAC_LONG_NAME(acName); RefDocBean.setREF_DOC_IDSEQ("new"); RefDocBean.setDOCUMENT_NAME(selName); RefDocBean.setDOC_TYPE_NAME(selType); RefDocBean.setDOCUMENT_TEXT(selText); RefDocBean.setDOCUMENT_URL(selUrl); RefDocBean.setCONTE_IDSEQ(sContID); RefDocBean.setCONTEXT_NAME(sContext); RefDocBean.setAC_LANGUAGE(sLang); RefDocBean.setREF_SUBMIT_ACTION("INS"); vRefDocs.addElement(RefDocBean); // add the bean to a vector } } DataManager.setAttribute(session, "AllRefDocList", vRefDocs); } // end add ref docs /** * removes reference documents from the vectors * * @param req * @throws java.lang.Exception */ @SuppressWarnings("unchecked") private void doMarkRemoveRefDocs(HttpServletRequest req) throws Exception { HttpSession session = req.getSession(); //InsACService insAC = new InsACService(m_classReq, m_classRes, this); String stgContMsg = ""; Vector<REF_DOC_Bean> vRefDocs = (Vector) session.getAttribute("AllRefDocList"); Vector vContext = (Vector) session.getAttribute("vWriteContextDE"); if (vContext == null) vContext = new Vector(); String sContID = (String) req.getParameter("selContext"); if (sContID != null) req.setAttribute("desContext", sContID); int j = -1; // to keep track of number of items on the page Vector<String> vRefAttrs = new Vector<String>(); for (int i = 0; i < vRefDocs.size(); i++) { REF_DOC_Bean rBean = (REF_DOC_Bean) vRefDocs.elementAt(i); // String refID = rBean.getREF_DOC_IDSEQ(); if (!rBean.getREF_SUBMIT_ACTION().equals("DEL")) { String refName = rBean.getDOCUMENT_NAME(); String refType = rBean.getDOC_TYPE_NAME(); String refCont = rBean.getCONTEXT_NAME(); // go to next record if same type, name and context does exist String curRefAttr = refType + " " + refName + " " + refCont; // increase teh count only if it didn't exist in the disp vecot list if (!vRefAttrs.contains(curRefAttr)) { vRefAttrs.addElement(curRefAttr); j += 1; // increase the count } String ckItem = (String) req.getParameter("RCK" + j); // get the right selected item to mark as deleted if (ckItem != null) { if (vContext.contains(refCont) || refCont.equals("") || refCont.equalsIgnoreCase("new")) { rBean.setREF_SUBMIT_ACTION("DEL"); vRefDocs.setElementAt(rBean, i); // check if another record with same type, name and context but diff ac exists to remove for (int k = 0; k < vRefDocs.size(); k++) { REF_DOC_Bean refBean = (REF_DOC_Bean) vRefDocs.elementAt(k); if (!refBean.getREF_SUBMIT_ACTION().equals("DEL") && refBean.getDOCUMENT_NAME().equals(refName)) { if (refBean.getDOC_TYPE_NAME().equals(refType) && refBean.getCONTEXT_NAME().equals(refCont)) { refBean.setREF_SUBMIT_ACTION("DEL"); // mark them also deleted vRefDocs.setElementAt(refBean, k); } } } } else stgContMsg += "\\n\\t" + refName + " in " + refCont + " Context "; break; } } } if (stgContMsg != null && !stgContMsg.equals("")) storeStatusMsg("Unable to remove the following Reference Documents, because the user does not have write permission to remove " + stgContMsg); DataManager.setAttribute(session, "AllRefDocList", vRefDocs); } // end remove ref doc /** * stores altname and reference documetns created while maintaining ac in the ac bean * * @param req * HttpServletRequest request object * @param res * HttpServletResponse response object * @param sAC * maintained ac * @param sType * type whether alt name or ref doc * @param sACAct * is ac edit or create */ public void doMarkACBeanForAltRef(HttpServletRequest req, HttpServletResponse res, String sAC, String sType, String sACAct) { HttpSession session = (HttpSession) req.getSession(); if (sACAct.equals("openAR") || sACAct.equals("submitAR")) { Vector vRefDoc = new Vector(), vAltName = new Vector(); // get the alt names and ref docs from teh bean if (sAC.equals("DataElement")) { DE_Bean de = (DE_Bean) session.getAttribute("m_DE"); vAltName = (Vector) de.getAC_ALT_NAMES(); vRefDoc = (Vector) de.getAC_REF_DOCS(); } if (sAC.equals("DataElementConcept")) { DEC_Bean dec = (DEC_Bean) session.getAttribute("m_DEC"); vAltName = dec.getAC_ALT_NAMES(); vRefDoc = dec.getAC_REF_DOCS(); } if (sAC.equals("ValueDomain")) { VD_Bean vd = (VD_Bean) session.getAttribute("m_VD"); vAltName = vd.getAC_ALT_NAMES(); vRefDoc = vd.getAC_REF_DOCS(); } // store the alt name and ref doc in the session if (vAltName == null) vAltName = new Vector(); Vector<ALT_NAME_Bean> vAllAltName = new Vector<ALT_NAME_Bean>(); for (int i = 0; i < vAltName.size(); i++) { ALT_NAME_Bean thisAlt = new ALT_NAME_Bean(); thisAlt = thisAlt.copyAltNames((ALT_NAME_Bean) vAltName.elementAt(i)); vAllAltName.addElement(thisAlt); } DataManager.setAttribute(session, "AllAltNameList", vAllAltName); if (vRefDoc == null) vRefDoc = new Vector(); Vector<REF_DOC_Bean> vAllRefDoc = new Vector<REF_DOC_Bean>(); for (int i = 0; i < vRefDoc.size(); i++) { REF_DOC_Bean thisDoc = new REF_DOC_Bean(); thisDoc = thisDoc.copyRefDocs((REF_DOC_Bean) vRefDoc.elementAt(i)); vAllRefDoc.addElement(thisDoc); } DataManager.setAttribute(session, "AllRefDocList", vAllRefDoc); } else { sType = sType.replace("Store ", ""); // remove word store from the string to use later Vector vAllRefDoc = (Vector) session.getAttribute("AllRefDocList"); Vector vAllAltName = (Vector) session.getAttribute("AllAltNameList"); if (sAC.equals("DataElement")) { // System.out.println("checking de bean"); // stroe it in the bean DE_Bean de = (DE_Bean) session.getAttribute("m_DE"); m_setAC.setDEValueFromPage(req, res, de); // capture all other page or request attributes if (sType.equals("Alternate Names")) de.setAC_ALT_NAMES((Vector) vAllAltName); else if (sType.equals("Reference Documents")) de.setAC_REF_DOCS((Vector) vAllRefDoc); // update session and forward DataManager.setAttribute(session, "m_DE", de); if (sACAct.equals("createAC")) ForwardJSP(req, res, "/CreateDEPage.jsp"); else if (sACAct.equals("editAC")) ForwardJSP(req, res, "/EditDEPage.jsp"); } else if (sAC.equals("DataElementConcept")) { // stroe it in the bean DEC_Bean dec = (DEC_Bean) session.getAttribute("m_DEC"); m_setAC.setDECValueFromPage(req, res, dec); // capture all other page or request attributes if (sType.equals("Alternate Names")) dec.setAC_ALT_NAMES(vAllAltName); else if (sType.equals("Reference Documents")) dec.setAC_REF_DOCS(vAllRefDoc); // update session and forward DataManager.setAttribute(session, "m_DEC", dec); if (sACAct.equals("createAC")) ForwardJSP(req, res, "/CreateDECPage.jsp"); else if (sACAct.equals("editAC")) ForwardJSP(req, res, "/EditDECPage.jsp"); } else if (sAC.equals("ValueDomain")) { // stroe it in the bean VD_Bean vd = (VD_Bean) session.getAttribute("m_VD"); m_setAC.setVDValueFromPage(req, res, vd); // capture all other page or request attributes if (sType.equals("Alternate Names")) vd.setAC_ALT_NAMES(vAllAltName); else if (sType.equals("Reference Documents")) vd.setAC_REF_DOCS(vAllRefDoc); // update session and forward DataManager.setAttribute(session, "m_VD", vd); if (sACAct.equals("createAC")) ForwardJSP(req, res, "/CreateVDPage.jsp"); else if (sACAct.equals("editAC")) ForwardJSP(req, res, "/EditVDPage.jsp"); } } } /** * The doChangeContext method resets the bean then forwards to Create page Called from 'doCreateDEActions', * 'doCreateDECActions', 'doCreateVDActions' methods. Calls 'getAC.getACList' if the action is Validate or submit. * Stores empty bean and forwards the create page of the selected component. Stores selected context as default * session. If the create DEC and VD origin is DE, only store the new context in the bean. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @param sACType * String ac type * * @throws Exception */ /* public void doChangeContext(HttpServletRequest req, HttpServletResponse res, String sACType) throws Exception { UtilService util = new UtilService(); HttpSession session = req.getSession(); String sContextID = (String) req.getParameter("selContext"); String sNewContext = util.getNameByID((Vector) session.getAttribute("vContext"), (Vector) session .getAttribute("vContext_ID"), sContextID); String sOriginAction = (String) session.getAttribute("originAction"); if (sOriginAction == null) sOriginAction = ""; boolean bNewContext = true; // boolean bDE = sACType.equals("de"); if (sNewContext != null) { GetACService getAC = new GetACService(req, res, this); getAC.getACList(req, res, sNewContext, bNewContext, sACType); } if (sACType.equals("de")) { DataManager.setAttribute(session, "sDefaultContext", sNewContext); DataManager.setAttribute(session, "m_DE", new DE_Bean()); ForwardJSP(req, res, "/CreateDEPage.jsp"); } else if (sACType.equals("dec")) { DEC_Bean m_DEC = new DEC_Bean(); if (sOriginAction.equals("CreateNewDEC")) m_DEC.setDEC_CONTEXT_NAME(sNewContext); else DataManager.setAttribute(session, "sDefaultContext", sNewContext); DataManager.setAttribute(session, "m_DEC", m_DEC); ForwardJSP(req, res, "/CreateDECPage.jsp"); } else if (sACType.equals("vd")) { VD_Bean m_VD = new VD_Bean(); if (sOriginAction.equals("CreateNewVD")) m_VD.setVD_CONTEXT_NAME(sNewContext); else DataManager.setAttribute(session, "sDefaultContext", sNewContext); DataManager.setAttribute(session, "m_VD", m_VD); ForwardJSP(req, res, "/CreateVDPage.jsp"); } } */ /** * gets the row number from the hiddenSelRow Loops through the selected row and gets the evs bean for that row from * the vector of evs search results. adds it to vList vector and return the vector back * * @param req * HttpServletRequest * @return Vector of EVS Beans * @throws java.lang.Exception */ public EVS_Bean getEVSSelRow(HttpServletRequest req) throws Exception { HttpSession session = req.getSession(); // InsACService insAC = new InsACService(req, m_classRes, this); // get the result vector from the session EVS_Bean eBean = new EVS_Bean(); Vector vRSel = (Vector) session.getAttribute("vACSearch"); if (vRSel == null) vRSel = new Vector(); // get the array from teh hidden list String selRows[] = req.getParameterValues("hiddenSelRow"); if (selRows == null) storeStatusMsg("Unable to select Concept, please try again"); else { // loop through the array of strings for (int i = 0; i < selRows.length; i++) { String thisRow = selRows[i]; Integer IRow = new Integer(thisRow); int iRow = IRow.intValue(); if (iRow < 0 || iRow > vRSel.size()) storeStatusMsg("Row size is either too big or too small."); else { eBean = (EVS_Bean) vRSel.elementAt(iRow); if (eBean == null || eBean.getLONG_NAME() == null) { storeStatusMsg("Unable to obtain concept from the " + iRow + " row of the search results.\\n" + "Please try again."); continue; } } } } return eBean; } /** * gets the row number from the hiddenSelRow Loops through the selected row and gets the evs bean for that row from * the vector of evs search results. adds it to vList vector and return the vector back * * @param req * HttpServletRequest * @param vList * Existing Vector of EVS Beans * @return Vector of EVS Beans * @throws java.lang.Exception */ private Vector<EVS_Bean> getEVSSelRowVector(HttpServletRequest req, Vector<EVS_Bean> vList) throws Exception { HttpSession session = req.getSession(); // get the result vector from the session Vector vRSel = (Vector) session.getAttribute("vACSearch"); if (vRSel == null) vRSel = new Vector(); // get the array from teh hidden list String selRows[] = req.getParameterValues("hiddenSelRow"); if (selRows == null) storeStatusMsg("Unable to select Concept, please try again"); else { // loop through the array of strings for (int i = 0; i < selRows.length; i++) { String thisRow = selRows[i]; int iRow = Integer.parseInt(thisRow); // Integer IRow = new Integer(thisRow); // int iRow = IRow.intValue(); if (iRow < 0 || iRow > vRSel.size()) { storeStatusMsg(iRow + " Row size is either too big or too small."); logger.fatal(iRow + " CurationServelt - getEVSSelRowVector: Row size is either too big or too small."); } else { EVS_Bean eBean = (EVS_Bean) vRSel.elementAt(iRow); // send it back if unable to obtion the concept if (eBean == null || eBean.getLONG_NAME() == null) { storeStatusMsg("Unable to obtain concept from the " + thisRow + " row of the search results.\\n" + "Please try again."); logger.fatal(thisRow + " CurationServelt - getEVSSelRowVector: Unable to obtain concept from the results."); continue; } vList.addElement(eBean); } } //add duplicate checks logic here EVSSearch serEVS = new EVSSearch(m_classReq, m_classRes, this); if (vList != null && vList.size() > 0) vList = serEVS.getNCIPrefConcepts(vList); } return vList; } /** * fills in the non evs parent attributes and sends back to create non evs parent page to view details * * @param req * HttpServletRequest object * @param res * HttpServletResponse object * @throws java.lang.Exception */ private void doNonEVSPageAction(HttpServletRequest req, HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); String sPageAct = (String) req.getParameter("actSelect"); if (sPageAct.equals("viewParent")) { VD_Bean vd = (VD_Bean) session.getAttribute("m_VD"); Vector<EVS_Bean> vParentCon = vd.getReferenceConceptList(); // (Vector)session.getAttribute("VDParentConcept"); if (vParentCon != null) { String selName = (String) req.getParameter("txtRefName"); for (int i = 0; i < vParentCon.size(); i++) { EVS_Bean eBean = (EVS_Bean) vParentCon.elementAt(i); String thisName = eBean.getLONG_NAME(); String sDB = eBean.getEVS_DATABASE(); // get the selected name from the vector if (selName != null && thisName != null && sDB != null && selName.equals(thisName) && sDB.equals("Non_EVS")) { req.setAttribute("SelectedVDParent", eBean); break; } } } this.ForwardJSP(req, res, "/NonEVSSearchPage.jsp"); } else { // send back to block search for parent ForwardJSP(req, res, "/OpenSearchWindowBlocks.jsp"); } } /** * to store the selected value meanings from EVS into pv bean to submit later. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @param sPVAction * string pv action * */ public void doSelectVMConcept(HttpServletRequest req, HttpServletResponse res, String sPVAction) { try { //InsACService insAC = new InsACService(req, res, this); HttpSession session = req.getSession(); DataManager.setAttribute(session, "PVAction", sPVAction); VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); // new VD_Bean(); // get the existing pvs from the session Vector<PV_Bean> vVDPVList = m_VD.getVD_PV_List(); // (Vector)session.getAttribute("VDPVList"); if (vVDPVList == null) vVDPVList = new Vector<PV_Bean>(); // get the VMs selected from EVS from the page. Vector<EVS_Bean> vEVSList = this.getEVSSelRowVector(req, new Vector<EVS_Bean>()); if (vEVSList != null && vEVSList.size() > 0) { // get the parent concept which is same for all the selected values String sSelectedParentName = (String) session.getAttribute("SelectedParentName"); String sSelectedParentCC = (String) session.getAttribute("SelectedParentCC"); String sSelectedParentDB = (String) session.getAttribute("SelectedParentDB"); String sSelectedParentMetaSource = (String) session.getAttribute("SelectedParentMetaSource"); // get the parent concept EVS_Bean parConcept = new EVS_Bean(); if (sSelectedParentName != null && !sSelectedParentName.equals("")) { parConcept.setLONG_NAME(sSelectedParentName); parConcept.setCONCEPT_IDENTIFIER(sSelectedParentCC); parConcept.setEVS_DATABASE(sSelectedParentDB); parConcept.setEVS_CONCEPT_SOURCE(sSelectedParentMetaSource); } String notUpdateVDPVs = ""; // String updatedVDPVs = ""; for (int i = 0; i < vEVSList.size(); i++) { EVS_Bean eBean = (EVS_Bean) vEVSList.elementAt(i); EVS_UserBean eUser = (EVS_UserBean) this.sessionData.EvsUsrBean; // if (eUser == null) eUser = new EVS_UserBean(); // get the nci vocab if it meta or other vocab only if not referenced if (sSelectedParentName == null || sSelectedParentName.equals("")) { // get teh right vocab name String eDB = eBean.getVocabAttr(eUser, eBean.getEVS_ORIGIN(), EVSSearch.VOCAB_NAME, EVSSearch.VOCAB_DBORIGIN); // "vocabName", "vocabDBOrigin"); if (eDB.equals(EVSSearch.META_VALUE)) // "MetaValue")) eDB = eBean.getEVS_ORIGIN(); eBean.setEVS_DATABASE(eDB); // eBean.getEVS_ORIGIN()); // get the thesaurus term EVSSearch evs = new EVSSearch(req, res, this); eBean = evs.getThesaurusConcept(eBean); } // get cadsr data ConceptAction conact = new ConceptAction(); ConceptForm data = new ConceptForm(); //data.setDBConnection(this.connectDB(req, res)); data.setDBConnection(m_conn); data.setCurationServlet(this); eBean = conact.getCaDSRConcept(eBean, eUser, data); //this.freeConnection(data.getDBConnection()); String errMsg = data.getStatusMsg(); if (!errMsg.equals("")) storeStatusMsg(errMsg + "\\n"); String sValue = eBean.getLONG_NAME(); String sMean = eBean.getLONG_NAME(); System.out.println(sValue + " selectVMConcept " + sMean); // add the level to the value if parent exists to update the value if (sSelectedParentName != null && !sSelectedParentName.equals("")) { Integer iLevel = new Integer(eBean.getLEVEL()); sValue = sValue + " [" + iLevel.toString() + "]"; } boolean isExist = false; boolean isUpdated = false; // int updRow = -1; for (int j = 0; j < vVDPVList.size(); j++) // check if the concept already exists. { PV_Bean pvBean = new PV_Bean(); pvBean = (PV_Bean) vVDPVList.elementAt(j); VM_Bean vdVM = pvBean.getPV_VM(); String vdValue = pvBean.getPV_VALUE(); String vdMean = ""; if (vdVM != null) vdMean = vdVM.getVM_LONG_NAME();//vdVM.getVM_SHORT_MEANING(); // pvBean.getPV_SHORT_MEANING(); // check if value meaning was already existed if (vdMean != null && vdMean.equalsIgnoreCase(sMean)) { String pvSubmit = pvBean.getVP_SUBMIT_ACTION(); // put back the deleted pv if it has same value-vm pair if (pvSubmit != null && pvSubmit.equals("DEL") && vdValue.equalsIgnoreCase(sValue)) { // set to update if idseq is non evs and is from cadsr if (pvBean.getPV_PV_IDSEQ() != null && !pvBean.getPV_PV_IDSEQ().equals("EVS_" + sValue)) pvBean.setVP_SUBMIT_ACTION("UPD"); else pvBean.setVP_SUBMIT_ACTION("INS"); // evs term // mark as deleted isUpdated = true; // updRow = j; //need this to update the vector this.storePVinVDPVList(vVDPVList, pvBean, eBean, parConcept, sValue, sMean, j, true); } else if (pvSubmit != null && !pvSubmit.equals("DEL") && vdValue.equalsIgnoreCase(sValue)) // was not deleted { String sValMean = "\\tValue: " + sValue + " and Meaning: " + sMean + "\\n"; notUpdateVDPVs += sValMean; isExist = true; } } } // add to the bean if not exists if (isExist == false && !isUpdated) { this.storePVinVDPVList(vVDPVList, new PV_Bean(), eBean, parConcept, sValue, sMean, -1, false); } } // System.out.println(updatedVDPVs + " selMinVD " + vVDPVList.size()); // DataManager.setAttribute(session, "VDPVList", vVDPVList); m_VD.setVD_PV_List(vVDPVList); DataManager.setAttribute(session, "m_VD", m_VD); // alert if value meaning alredy exists but updated with concept info /* * if (updatedVDPVs != null && !updatedVDPVs.equals("")) { String stMsg = "The following Value and * Meaning is updated with the Concept Relationship. \\n"; InsACService insAC = new InsACService(req, * res, this); insAC.storeStatusMsg(stMsg + updatedVDPVs); } */// alert if value meaning alredy exists for pv on the page if (notUpdateVDPVs != null && !notUpdateVDPVs.equals("")) { String stMsg = "The following Value and Meaning already exists in the Value Domain.\\n"; storeStatusMsg(stMsg + notUpdateVDPVs); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); logger.fatal("ERROR - ", e); } } /** * stores the selected pvs from concepts search in vdpv list * @param vVPList Vector<PV_Bean> object * @param pBean PV_Bean permissible value object * @param eBean EVS_Bean concept object * @param parBean EVS_Bean parent concept * @param sValue String value * @param sMean String value meaning * @param updRow int single row * @param isUpdated boolean value of updated or not * @return Vector<PV_Bean> object */ private Vector<PV_Bean> storePVinVDPVList(Vector<PV_Bean> vVPList, PV_Bean pBean, EVS_Bean eBean, EVS_Bean parBean, String sValue, String sMean, int updRow, boolean isUpdated) { try { if (!isUpdated) // do not update these if { // store concept name as value and vm in the pv bean // pBean = new PV_Bean(); pBean.setPV_PV_IDSEQ("EVS_" + sValue); // store id as EVS pBean.setPV_VALUE(sValue); pBean.setPV_SHORT_MEANING(sMean); pBean.setVP_SUBMIT_ACTION("INS"); } // allow to update the definition if different description for evs selected items pBean.setPV_MEANING_DESCRIPTION(eBean.getPREFERRED_DEFINITION()); // these are for vd-pvs SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); if (pBean.getVP_SUBMIT_ACTION().equals("INS")) pBean.setPV_BEGIN_DATE(formatter.format(new java.util.Date())); // add evs bean to pv bean VM_Bean vm = new VM_Bean(); // vm.setVM_SHORT_MEANING(pBean.getPV_SHORT_MEANING()); vm.setVM_LONG_NAME(pBean.getPV_SHORT_MEANING()); // vm.setVM_DESCRIPTION(pBean.getPV_MEANING_DESCRIPTION()); vm.setVM_PREFERRED_DEFINITION(pBean.getPV_MEANING_DESCRIPTION()); vm.setVM_CONDR_IDSEQ(eBean.getCONDR_IDSEQ()); Vector<EVS_Bean> vmCon = new Vector<EVS_Bean>(); vmCon.addElement(eBean); vm.setVM_CONCEPT_LIST(vmCon); vm.setVM_SUBMIT_ACTION(VMForm.CADSR_ACTION_INS); pBean.setPV_VM(vm); System.out.println(eBean.getCONCEPT_IDENTIFIER() + " vm concepts " + vmCon.size()); // pBean.setVM_CONCEPT(eBean); pBean.setPARENT_CONCEPT(parBean); if (isUpdated) vVPList.setElementAt(pBean, updRow); // udpate the vector else vVPList.addElement(pBean); // store bean in vector } catch (Exception e) { logger.fatal("Error - store value and meaning in vdpv list: Value - " + sValue + " and Meaning - " + sMean, e); } return vVPList; } /** * called after setDEC or setVD to reset EVS session attributes * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ /* public void resetEVSBeans(HttpServletRequest req, @SuppressWarnings("unused") HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); EVS_Bean m_OC = new EVS_Bean(); DataManager.setAttribute(session, "m_OC", m_OC); EVS_Bean m_PC = new EVS_Bean(); DataManager.setAttribute(session, "m_PC", m_PC); EVS_Bean m_Rep = new EVS_Bean(); DataManager.setAttribute(session, "m_Rep", m_Rep); EVS_Bean m_OCQ = new EVS_Bean(); DataManager.setAttribute(session, "m_OCQ", m_OCQ); EVS_Bean m_PCQ = new EVS_Bean(); DataManager.setAttribute(session, "m_PCQ", m_PCQ); EVS_Bean m_REPQ = new EVS_Bean(); DataManager.setAttribute(session, "m_REPQ", m_REPQ); DataManager.setAttribute(session, "selPropRow", ""); DataManager.setAttribute(session, "selPropQRow", ""); DataManager.setAttribute(session, "selObjQRow", ""); DataManager.setAttribute(session, "selObjRow", ""); DataManager.setAttribute(session, "selRepQRow", ""); DataManager.setAttribute(session, "selRepRow", ""); } */ /** * gets the point or whole version number from old version for block versioning. * * @param version * Version of the selected from the page either point or whole * @param lastVersion * old Version number of the selected bean. * * @return newVersion version number that need to updated to. * @throws Exception */ protected String getNewVersionNumber(String version, String lastVersion) throws Exception { int index = -1; String pointStr = "."; String strWhBegNumber = ""; int iWhBegNumber = 0; index = lastVersion.indexOf(pointStr); String strPtBegNumber = lastVersion.substring(0, index); String afterDecimalNumber = lastVersion.substring((index + 1), (index + 2)); if (index == 1) strWhBegNumber = ""; else if (index == 2) { strWhBegNumber = lastVersion.substring(0, index - 1); Integer WhBegNumber = new Integer(strWhBegNumber); iWhBegNumber = WhBegNumber.intValue(); } String strWhEndNumber = ".0"; String beforeDecimalNumber = lastVersion.substring((index - 1), (index)); String sNewVersion = ""; Integer IadNumber = new Integer(0); Integer IbdNumber = new Integer(0); String strIncADNumber = ""; String strIncBDNumber = ""; if (version == null) version = ""; else if (version.equals("Point")) { // Point new version int incrementADNumber = 0; int incrementBDNumber = 0; Integer adNumber = new Integer(afterDecimalNumber); Integer bdNumber = new Integer(strPtBegNumber); int iADNumber = adNumber.intValue(); // after decimal int iBDNumber = bdNumber.intValue(); // before decimal if (iADNumber != 9) { incrementADNumber = iADNumber + 1; IadNumber = new Integer(incrementADNumber); strIncADNumber = IadNumber.toString(); sNewVersion = strPtBegNumber + "." + strIncADNumber; // + strPtEndNumber; } else // adNumber == 9 { incrementADNumber = 0; incrementBDNumber = iBDNumber + 1; IbdNumber = new Integer(incrementBDNumber); strIncBDNumber = IbdNumber.toString(); IadNumber = new Integer(incrementADNumber); strIncADNumber = IadNumber.toString(); sNewVersion = strIncBDNumber + "." + strIncADNumber; // + strPtEndNumber; } // DEBeanSR.setDE_VERSION(sNewVersion); } else if (version.equals("Whole")) { // Whole new version Integer bdNumber = new Integer(beforeDecimalNumber); int iBDNumber = bdNumber.intValue(); int incrementBDNumber = iBDNumber + 1; if (iBDNumber != 9) { IbdNumber = new Integer(incrementBDNumber); strIncBDNumber = IbdNumber.toString(); sNewVersion = strWhBegNumber + strIncBDNumber + strWhEndNumber; } else // before decimal number == 9 { int incrementWhBegNumber = iWhBegNumber + 1; Integer IWhBegNumber = new Integer(incrementWhBegNumber); String strIncWhBegNumber = IWhBegNumber.toString(); IbdNumber = new Integer(0); strIncBDNumber = IbdNumber.toString(); sNewVersion = strIncWhBegNumber + strIncBDNumber + strWhEndNumber; } // DEBeanSR.setDE_VERSION(sNewVersion); } return sNewVersion; } /** * The doSuggestionDE method forwards to EVSSearch jsp * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ protected void doSuggestionDE(HttpServletRequest req, HttpServletResponse res) throws Exception { ForwardJSP(req, res, "/EVSSearch.jsp"); } /** * The doOpenCreatePVPage method gets the session, gets some values from the createVD page and stores in bean m_VD, * sets some session attributes, then forwards to CreatePV page * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @param sPVAction * string pv action * @param vdPage * string opened vd page * * @throws Exception */ protected void doOpenCreatePVPage(HttpServletRequest req, HttpServletResponse res, String sPVAction, String vdPage) throws Exception { HttpSession session = req.getSession(); DataManager.setAttribute(session, "PVAction", sPVAction); VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); // new VD_Bean(); m_setAC.setVDValueFromPage(req, res, m_VD); // store VD bean DataManager.setAttribute(session, "VDPageAction", "validate"); DataManager.setAttribute(session, "m_VD", m_VD); // call the method to add/remove pvs. m_setAC.addRemovePageVDPVs(req, res); if (sPVAction.equals("removePV")) { if (vdPage.equals("editVD")) ForwardJSP(req, res, "/EditVDPage.jsp"); else ForwardJSP(req, res, "/CreateVDPage.jsp"); } else { // store the old pv in another session PV_Bean pvBean = (PV_Bean) session.getAttribute("m_PV"); if (pvBean == null) pvBean = new PV_Bean(); // copy the pv session attributes to store that can be used for clear button PV_Bean pageBean = new PV_Bean(); pageBean = pageBean.copyBean(pvBean); DataManager.setAttribute(session, "pageOpenBean", pageBean); ForwardJSP(req, res, "/CreatePVPage.jsp"); } } /** * The doJspErrorAction method is called when there is an error on a jsp page. User is forwarded to * SearchResultsPage * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ public void doJspErrorAction(HttpServletRequest req, HttpServletResponse res) throws Exception { // doOpenSearchPage(req, res); Later*** } /** * The doSearchPV method gets the session, gets some values from the createVD page and stores in bean m_VD, sets * some session attributes, then forwards to CreatePV page * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ /* public void doSearchPV(HttpServletRequest req, HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); // new VD_Bean(); EVS_Bean m_OC = new EVS_Bean(); EVS_Bean m_PC = new EVS_Bean(); EVS_Bean m_REP = new EVS_Bean(); EVS_Bean m_OCQ = new EVS_Bean(); EVS_Bean m_PCQ = new EVS_Bean(); EVS_Bean m_REPQ = new EVS_Bean(); m_setAC.setVDValueFromPage(req, res, m_VD); // store VD bean DataManager.setAttribute(session, "VDPageAction", "searchValues"); DataManager.setAttribute(session, "m_VD", m_VD); DataManager.setAttribute(session, "m_OC", m_OC); DataManager.setAttribute(session, "m_PC", m_PC); DataManager.setAttribute(session, "m_REP", m_REP); DataManager.setAttribute(session, "m_OCQ", m_OCQ); DataManager.setAttribute(session, "m_PCQ", m_PCQ); DataManager.setAttribute(session, "m_REPQ", m_REPQ); DataManager.setAttribute(session, "PValue", ""); ForwardJSP(req, res, "/SearchResultsPage.jsp"); } */ /** * The doOpenCreateVMPage method gets the session, gets some values from the createVD page and stores in bean m_VD, * sets some session attributes, then forwards to CreateVM page * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @param origin * * @throws Exception */ protected void doOpenCreateVMPage(HttpServletRequest req, HttpServletResponse res, @SuppressWarnings("unused") String origin) throws Exception { HttpSession session = req.getSession(); String sOrigin = (String) session.getAttribute("originAction"); PV_Bean m_PV = new PV_Bean(); SetACService setAC = new SetACService(this); setAC.setPVValueFromPage(req, res, m_PV); DataManager.setAttribute(session, "m_PV", m_PV); // reset vm bean VM_Bean VMBean = new VM_Bean(); // get cd value from the VD bean and make it default for VM VD_Bean VDBean = (VD_Bean) session.getAttribute("m_VD"); VMBean.setVM_CD_NAME(VDBean.getVD_CD_NAME()); VMBean.setVM_CD_IDSEQ(VDBean.getVD_CD_IDSEQ()); // store the bean in the session DataManager.setAttribute(session, "m_VM", VMBean); DataManager.setAttribute(session, "creSearchAC", "EVSValueMeaning"); if (sOrigin.equals("CreateInSearch")) ForwardJSP(req, res, "/CreateVMSearchPage.jsp"); else ForwardJSP(req, res, "/CreateVMPage.jsp"); } /** * method to call all evs actions * * @param reqType * String evs search action * @param req * HttpServletRequest * @param res * HttpServletResponse */ protected void doEVSSearchActions(String reqType, HttpServletRequest req, HttpServletResponse res) { try { // System.out.println("evs search " + reqType); EVSSearch evs = new EVSSearch(req, res, this); if (reqType.equals("getSuperConcepts")) evs.doGetSuperConcepts(); else if (reqType.equals("getSubConcepts")) evs.doGetSubConcepts(); else if (reqType.equals("treeSearch")) evs.doTreeSearchRequest("", "", "", ""); else if (reqType.equals("treeRefresh")) evs.doTreeRefreshRequest(); else if (reqType.equals("treeExpand")) evs.doTreeExpandRequest(); else if (reqType.equals("treeCollapse")) evs.doTreeCollapseRequest(); else if (reqType.equals("OpenTreeToConcept")) evs.openTreeToConcept(reqType); else if (reqType.equals("OpenTreeToParentConcept")) evs.openTreeToConcept(reqType); // else if (reqType.equals("OpenTreeToParentConcept")) // evs.openTreeToParentConcept(reqType); else if (reqType.equals("term") || reqType.equals("tree")) { String dtsVocab = req.getParameter("listContextFilterVocab"); evs.doCollapseAllNodes(dtsVocab); evs.doTreeSearch(reqType, "Blocks"); } else if (reqType.equals("defaultBlock")) { String dtsVocab = req.getParameter("listContextFilterVocab"); evs.doCollapseAllNodes(dtsVocab); } else if (reqType.equals("showConceptInTree")) evs.showConceptInTree(reqType); } catch (Exception ex) { // System.out.println("doEVSSearchActions : " + ex.toString()); logger.fatal("doEVSSearchActions : " + ex.toString(), ex); // this.ForwardErrorJSP(req, res, ex.getMessage()); } } /** * resorts the display attributes from the component attributes after add/remove attributes of selected attribute * vector. * * @param vCompAttr * list of attributes of the selected component * @param vSelectAttr * list of selected attributes of according to the action * * @return return the sorted selected attributes list * * @throws Exception */ public Vector<String> resortDisplayAttributes(Vector<String> vCompAttr, Vector<String> vSelectAttr) throws Exception { // resort the display attributes Vector<String> vReSort = new Vector<String>(); if (vCompAttr != null) { for (int j = 0; j < vCompAttr.size(); j++) { String thisAttr = (String) vCompAttr.elementAt(j); // add this attr to a vector if it is a selected attr if (vSelectAttr.contains(thisAttr)) vReSort.addElement(thisAttr); } } return vReSort; } /** * To search results by clicking on the column heading. Called from 'service' method where reqType is 'searchEVS' * forwards page 'EVSSearchPage.jsp'. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doSearchEVS(HttpServletRequest req, HttpServletResponse res) throws Exception { //HttpSession session = req.getSession(); //Vector vResults = new Vector(); try { GetACSearch getACSearch = new GetACSearch(req, res, this); getACSearch.doSearchEVS(req, res); } catch (Exception e) { // System.err.println("EVS Search : " + e); this.logger.fatal("ERROR - EVS Search : " + e.toString(), e); } ForwardJSP(req, res, "/EVSSearchPage.jsp"); // ForwardJSP(req, res, "/OpenSearchWindow.jsp"); } /** * To search a component or to display more attributes after the serach. Called from 'service' method where reqType * is 'searchACs' calls 'getACSearch.getACKeywordResult' method when the action is a new search. calls * 'getACSearch.getACShowResult' method when the action is a display attributes. forwards JSP * 'SearchResultsPage.jsp' if the action is not searchForCreate. if action is searchForCreate forwards * OpenSearchWindow.jsp * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ /* public void doQualifierSearchActions(HttpServletRequest req, HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); String actType = (String) req.getParameter("actSelect"); String menuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); GetACSearch getACSearch = new GetACSearch(req, res, this); if ((menuAction != null) && (actType != null)) { if (actType.equals("Search")) { if (menuAction.equals("searchForCreate")) { getACSearch.getACSearchForCreate(req, res, false); ForwardJSP(req, res, "/OpenSearchWindowQualifiers.jsp"); } else { getACSearch.getACKeywordResult(req, res); ForwardJSP(req, res, "/SearchResultsPage2.jsp"); } } else if (actType.equals("Attribute")) { getACSearch.getACShowResult(req, res, "Attribute"); if (menuAction.equals("searchForCreate")) ForwardJSP(req, res, "/OpenSearchWindowQualifiers.jsp"); else ForwardJSP(req, res, "/SearchResultsPage2.jsp"); } } else ForwardJSP(req, res, "/ErrorPage.jsp"); } */ /** * Sets a session attribute for a Building Block search. Called from 'service' method where reqType is 'newSearchBB' * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ /* public void doNewSearchBB(HttpServletRequest req, HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); DEC_Bean m_DEC = (DEC_Bean) session.getAttribute("m_DEC"); if (m_DEC == null) m_DEC = new DEC_Bean(); // EVS_Bean m_OC = new EVS_Bean(); // EVS_Bean m_PC = new EVS_Bean(); // EVS_Bean m_OCQ = new EVS_Bean(); // EVS_Bean m_PCQ = new EVS_Bean(); // GetACService getAC = new GetACService(req, res, this); m_setAC.setDECValueFromPage(req, res, m_DEC); DataManager.setAttribute(session, "m_DEC", m_DEC); String searchComp = (String) req.getParameter("searchComp"); if (searchComp.equals("ObjectClass")) DataManager.setAttribute(session, "creSearchAC", "ObjectClass"); else if (searchComp.equals("Property")) DataManager.setAttribute(session, "creSearchAC", "Property"); else if (searchComp.equals("ObjectQualifier")) DataManager.setAttribute(session, "creSearchAC", "ObjectQualifier"); else if (searchComp.equals("PropertyQualifier")) DataManager.setAttribute(session, "creSearchAC", "PropertyQualifier"); ForwardJSP(req, res, "/CreateDECPage.jsp"); } */ /** * to get reference documents for the selected ac and doc type called when the reference docuemnts window opened * first time and calls 'getAC.getReferenceDocuments' forwards page back to reference documents * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doRefDocSearchActions(HttpServletRequest req, HttpServletResponse res) throws Exception { GetACSearch getAC = new GetACSearch(req, res, this); String acID = req.getParameter("acID"); String itemType = req.getParameter("itemType"); @SuppressWarnings("unused") Vector vRef = getAC.doRefDocSearch(acID, itemType, "open"); ForwardJSP(req, res, "/ReferenceDocumentWindow.jsp"); } /** * to get alternate names for the selected ac and doc type called when the alternate names window opened first time * and calls 'getAC.getAlternateNames' forwards page back to alternate name window jsp * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doAltNameSearchActions(HttpServletRequest req, HttpServletResponse res) throws Exception { GetACSearch getAC = new GetACSearch(req, res, this); String acID = req.getParameter("acID"); String CD_ID = req.getParameter("CD_ID"); if (CD_ID == null) CD_ID = ""; String itemType = req.getParameter("itemType"); if (itemType != null && itemType.equals("ALL")) itemType = ""; @SuppressWarnings("unused") Vector vAlt = getAC.doAltNameSearch(acID, itemType, CD_ID, "other", "open"); ForwardJSP(req, res, "/AlternateNameWindow.jsp"); } /** * to get Permissible Values for the selected ac called when the permissible value window opened first time and * calls 'getAC.doPVACSearch' forwards page back to Permissible Value window jsp * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doPermValueSearchActions(HttpServletRequest req, HttpServletResponse res) throws Exception { // GetACSearch getAC = new GetACSearch(req, res, this); String acID = req.getParameter("acID"); String acName = req.getParameter("itemType"); // ac name for pv if (acName != null && acName.equals("ALL")) acName = "-"; String sConteIdseq = (String) req.getParameter("sConteIdseq"); if (sConteIdseq == null) sConteIdseq = ""; ValueDomainServlet vdServ = (ValueDomainServlet) this.getACServlet("ValueDomain"); PVServlet pvser = new PVServlet(req, res, vdServ); pvser.searchVersionPV(null, 0, acID, acName); ForwardJSP(req, res, "/PermissibleValueWindow.jsp"); } /** * display all the concepts for the selected ac from search results page * * @param req * HttpServletRequest * @param res * HttpServletResponse * @throws Exception */ private void doConClassSearchActions(HttpServletRequest req, HttpServletResponse res) throws Exception { GetACSearch getAC = new GetACSearch(req, res, this); String acID = req.getParameter("acID"); // dec id String ac2ID = req.getParameter("ac2ID"); // vd id //String acType = req.getParameter("acType"); // actype to search String acName = req.getParameter("acName"); // ac name for pv // call the api to return concept attributes according to ac type and ac idseq Vector<EVS_Bean> conList = new Vector<EVS_Bean>(); conList = getAC.do_ConceptSearch("", "", "", "", "", acID, ac2ID, conList); req.setAttribute("ConceptClassList", conList); req.setAttribute("ACName", acName); // store them in request parameter to display and forward the page ForwardJSP(req, res, "/ConceptClassDetailWindow.jsp"); } /** * display conceptual for the selected vm from the search results. * * @param req * HttpServletRequest * @param res * HttpServletResponse * @throws Exception */ private void doConDomainSearchActions(HttpServletRequest req, HttpServletResponse res) throws Exception { GetACSearch getAC = new GetACSearch(req, res, this); String sVM = req.getParameter("acName"); // ac name for pv // call the api to return concept attributes according to ac type and ac idseq Vector cdList = new Vector(); cdList = getAC.doCDSearch("", "", "", "", "", "", "", "", "", "", "", "", "", "", 0, "", "", sVM, cdList); // get // the // list // of // Conceptual // Domains req.setAttribute("ConDomainList", cdList); req.setAttribute("VMName", sVM); // store them in request parameter to display and forward the page ForwardJSP(req, res, "/ConDomainDetailWindow.jsp"); } /** * contact action from create and edit ac pages to either remove the selected contact or store the modified contact * back in the ac bean * * @param req * HttpServletRequest * @param sAct * String AC contact update action from create and edit pages * @return Hashtable of contact name and contact bean object */ @SuppressWarnings("unchecked") protected Hashtable<String, AC_CONTACT_Bean> doContactACUpdates(HttpServletRequest req, String sAct) { HttpSession session = req.getSession(); Hashtable<String, AC_CONTACT_Bean> hConts = (Hashtable) session.getAttribute("AllContacts"); if (hConts == null) hConts = new Hashtable<String, AC_CONTACT_Bean>(); try { String sCont = ""; AC_CONTACT_Bean accBean = new AC_CONTACT_Bean(); if (sAct.equals("removeContact")) { sCont = (String) req.getParameter("selContact"); if (sCont != null && !sCont.equals("") && hConts.containsKey(sCont)) accBean = accBean.copyContacts((AC_CONTACT_Bean) hConts.get(sCont)); accBean.setACC_SUBMIT_ACTION("DEL"); } else { sCont = (String) session.getAttribute("selContactKey"); accBean = accBean.copyContacts((AC_CONTACT_Bean) session.getAttribute("selACContact")); if (accBean == null) accBean = new AC_CONTACT_Bean(); // new contact if (sCont == null || sCont.equals("")) { Hashtable hOrg = (Hashtable) session.getAttribute("Organizations"); Hashtable hPer = (Hashtable) session.getAttribute("Persons"); sCont = accBean.getPERSON_IDSEQ(); if (sCont != null && !sCont.equals("") && hPer.containsKey(sCont)) sCont = (String) hPer.get(sCont); else { sCont = accBean.getORG_IDSEQ(); if (sCont != null && !sCont.equals("") && hOrg.containsKey(sCont)) sCont = (String) hOrg.get(sCont); } accBean.setACC_SUBMIT_ACTION("INS"); } else accBean.setACC_SUBMIT_ACTION("UPD"); } // put it back in teh hash table if (sCont != null && !sCont.equals("")) hConts.put(sCont, accBean); } catch (Exception e) { logger.fatal("Error - doContactACUpdates : " + e.toString(), e); } DataManager.setAttribute(session, "selContactKey", ""); // remove the attributes DataManager.setAttribute(session, "selACContact", null); // session.removeAttribute("selContactKey"); //remove the attributes // session.removeAttribute("selACContact"); return hConts; } /** * Contact edit action including open, view, edit comm, edit addr and change organization etc * * @param req * HttpServletRequest * @param res * HttpServletResponse * @throws Exception */ @SuppressWarnings("unchecked") private void doContactEditActions(HttpServletRequest req, HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); // get all the contacts from the session attribute set in create/edit page of the ac Hashtable hConts = (Hashtable) session.getAttribute("AllContacts"); if (hConts == null) hConts = new Hashtable(); // get the page action String sPgAct = (String) req.getParameter("pageAction"); if (sPgAct != null && !sPgAct.equals("")) { try { // get request and session attributes String sContAct = (String) req.getParameter("contAction"); if (sContAct == null || sContAct.equals("")) sContAct = "new"; AC_CONTACT_Bean accBean = (AC_CONTACT_Bean) session.getAttribute("selACContact"); if (accBean == null) accBean = new AC_CONTACT_Bean(); // if page action contact action is edit pull out contact bean from the all contacts for selected contxt if (sPgAct.equals("openPage")) // && sContAct.equals("view")) { if (sContAct.equals("view")) // edit contact { String selCont = (String) req.getParameter("selContact"); if (selCont != null && hConts.containsKey(selCont)) { accBean = accBean.copyContacts((AC_CONTACT_Bean) hConts.get(selCont)); DataManager.setAttribute(session, "selContactKey", selCont); } // System.out.println(sContAct + " contat sele " + selCont + " contains " + // hConts.containsKey(selCont)); } else // new contact { accBean = new AC_CONTACT_Bean(); DataManager.setAttribute(session, "selContactKey", ""); } } else // if (!sPgAct.equals("openPage")) //if not opening the page store the changed data in teh bean { String conOrder = (String) req.getParameter("rank"); if (conOrder != null && !conOrder.equals("")) accBean.setRANK_ORDER(conOrder); String conPer = (String) req.getParameter("selPer"); if (conPer == null) conPer = ""; accBean.setPERSON_IDSEQ(conPer); String conOrg = (String) req.getParameter("selOrg"); if (conOrg == null) conOrg = ""; accBean.setORG_IDSEQ(conOrg); String conRole = (String) req.getParameter("selRole"); if (conRole != null && !conRole.equals("")) accBean.setCONTACT_ROLE(conRole); } // change the radio button action if (sPgAct.equals("changeType")) { String sType = (String) req.getParameter("rType"); if (sType != null && !sType.equals("")) req.setAttribute("TypeSelected", sType); } // get the comm and addr info for the selected contact else if (sPgAct.equals("changeContact")) { String perID = accBean.getPERSON_IDSEQ(); String orgID = accBean.getORG_IDSEQ(); if ((perID != null && !perID.equals("")) || (orgID != null && !orgID.equals(""))) { GetACSearch getAC = new GetACSearch(req, res, this); Vector<AC_COMM_Bean> vComm = getAC.getContactComm("", orgID, perID); if (vComm == null) vComm = new Vector<AC_COMM_Bean>(); accBean.setACC_COMM_List(vComm); Vector<AC_ADDR_Bean> vAddr = getAC.getContactAddr("", orgID, perID); if (vAddr == null) vAddr = new Vector<AC_ADDR_Bean>(); accBean.setACC_ADDR_List(vAddr); } } // adding comm attributes to com bean else if (sPgAct.indexOf("Comm") > -1) accBean = this.doContCommAction(req, accBean, sPgAct); // adding comm attributes to com bean else if (sPgAct.indexOf("Addr") > -1) accBean = this.doContAddrAction(req, accBean, sPgAct); // store contact changes with all contacts as new or update else if (sPgAct.equals("updContact")) { sContAct = "doContactUpd"; String sMsg = "Contact Information updated successfully, \\n" + "but will not be associated to the Administered Component (AC) \\n" + "or written to the database until the AC has been successfully submitted."; DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, sMsg); } // store the acc bean in teh request (sends back empty if new action) DataManager.setAttribute(session, "selACContact", accBean); req.setAttribute("ContAction", sContAct); } catch (Exception e) { logger.fatal("Error - doContactEditActions : " + e.toString(), e); } } ForwardJSP(req, res, "/EditACContact.jsp"); } /** * Contact communication change actions * * @param req * HttpServletRequest * @param ACBean * AC_CONTACT_Bean * @param sAct * String communication action * @return AC_CONTACT_Bean */ private AC_CONTACT_Bean doContCommAction(HttpServletRequest req, AC_CONTACT_Bean ACBean, String sAct) { try { Vector<AC_COMM_Bean> vComm = ACBean.getACC_COMM_List(); if (vComm == null) vComm = new Vector<AC_COMM_Bean>(); AC_COMM_Bean commB = new AC_COMM_Bean(); int selInd = -1; for (int j = 0; j < vComm.size(); j++) // loop through existing lists { String rSel = (String) req.getParameter("com" + j); // check if this id is selected if (rSel != null) { commB = commB.copyComms((AC_COMM_Bean) vComm.elementAt(j)); selInd = j; break; } } // System.out.println(selInd + " commAct " + sAct); // if editComm action set comm bean in teh request and return back if (sAct.equals("editComm") && selInd > -1) { req.setAttribute("CommForEdit", commB); req.setAttribute("CommCheckForEdit", "com" + selInd); return ACBean; } // handle remove or add selection actions if (commB == null) commB = new AC_COMM_Bean(); if (sAct.equals("removeComm")) // remove the item and exit commB.setCOMM_SUBMIT_ACTION("DEL"); else if (sAct.equals("addComm")) // udpate or adding new { // get the attributes from the page String cType = (String) req.getParameter("selCommType"); if (cType == null) cType = ""; String cOrd = (String) req.getParameter("comOrder"); if (cOrd == null) cOrd = ""; String cCyber = (String) req.getParameter("comCyber"); if (cCyber == null) cCyber = ""; String sCommName = cType + "_" + cOrd + "_" + cCyber; // check these attributes already exist in the list boolean wasDeleted = false; for (int k = 0; k < vComm.size(); k++) { AC_COMM_Bean exComm = (AC_COMM_Bean) vComm.elementAt(k); String ct = exComm.getCTL_NAME(); if (ct == null) ct = ""; String cc = exComm.getCYBER_ADDR(); if (cc == null) cc = ""; String co = exComm.getRANK_ORDER(); // leave this for now till confirmed if (co == null) co = ""; String exCommName = cType + "_" + cOrd + "_" + cCyber; if (sCommName.equals(exCommName)) { // allow to create duplicates but undelete if it was deleted String exSubmit = commB.getCOMM_SUBMIT_ACTION(); if (exSubmit != null && exSubmit.equals("DEL")) { wasDeleted = true; commB = commB.copyComms((AC_COMM_Bean) vComm.elementAt(k)); if (commB.getAC_COMM_IDSEQ() == null || commB.getAC_COMM_IDSEQ().equals(exCommName)) commB.setCOMM_SUBMIT_ACTION("INS"); else commB.setCOMM_SUBMIT_ACTION("UPD"); selInd = k; // reset the index } break; } } // update or add new attributes if was not deleted if (!wasDeleted) { commB.setCTL_NAME(cType); commB.setRANK_ORDER(cOrd); commB.setCYBER_ADDR(cCyber); if (selInd > -1) commB.setCOMM_SUBMIT_ACTION("UPD"); else commB.setCOMM_SUBMIT_ACTION("INS"); } } // set the vector if (selInd > -1) vComm.setElementAt(commB, selInd); else vComm.addElement(commB); ACBean.setACC_COMM_List(vComm); // set the bean } catch (Exception e) { logger.fatal("Error - doContCommAction : " + e.toString(), e); } return ACBean; } /** * Contact address change action * * @param req * HttpServletRequest * @param ACBean * AC_CONTACT_Bean * @param sAct * String address edit action * @return AC_CONTACT_Bean */ private AC_CONTACT_Bean doContAddrAction(HttpServletRequest req, AC_CONTACT_Bean ACBean, String sAct) { try { Vector<AC_ADDR_Bean> vAddr = ACBean.getACC_ADDR_List(); if (vAddr == null) vAddr = new Vector<AC_ADDR_Bean>(); AC_ADDR_Bean addrB = new AC_ADDR_Bean(); int selInd = -1; for (int j = 0; j < vAddr.size(); j++) // loop through existing lists { String rSel = (String) req.getParameter("addr" + j); // check if this id is selected if (rSel != null) { addrB = addrB.copyAddress((AC_ADDR_Bean) vAddr.elementAt(j)); selInd = j; break; } } // System.out.println(selInd + " addrAct " + sAct); // if editAddr action set addr bean in teh request and return back if (sAct.equals("editAddr") && selInd > -1) { req.setAttribute("AddrForEdit", addrB); req.setAttribute("AddrCheckForEdit", "addr" + selInd); return ACBean; } // handle remove or add selection actions if (addrB == null) addrB = new AC_ADDR_Bean(); if (sAct.equals("removeAddr")) // remove the item and exit addrB.setADDR_SUBMIT_ACTION("DEL"); else if (sAct.equals("addAddr")) // udpate or adding new { // get the attributes from the page String aType = (String) req.getParameter("selAddrType"); if (aType == null) aType = ""; String aOrd = (String) req.getParameter("txtPrimOrder"); if (aOrd == null) aOrd = ""; String aAddr1 = (String) req.getParameter("txtAddr1"); if (aAddr1 == null) aAddr1 = ""; String aAddr2 = (String) req.getParameter("txtAddr2"); if (aAddr2 == null) aAddr2 = ""; String aCity = (String) req.getParameter("txtCity"); if (aCity == null) aCity = ""; String aState = (String) req.getParameter("txtState"); if (aState == null) aState = ""; String aCntry = (String) req.getParameter("txtCntry"); if (aCntry == null) aCntry = ""; String aPost = (String) req.getParameter("txtPost"); if (aPost == null) aPost = ""; String selAddrName = aType + "_" + aOrd + "_" + aAddr1 + "_" + aAddr2 + "_" + aCity + "_" + aState + "_" + aCntry + "_" + aPost; // check these attributes already exist in the list boolean wasDeleted = false; for (int k = 0; k < vAddr.size(); k++) { AC_ADDR_Bean exAddr = (AC_ADDR_Bean) vAddr.elementAt(k); String at = exAddr.getATL_NAME(); if (at == null) at = ""; String ao = exAddr.getRANK_ORDER(); if (ao == null) ao = ""; String aA1 = exAddr.getADDR_LINE1(); if (aA1 == null) aA1 = ""; String aA2 = exAddr.getADDR_LINE2(); if (aA2 == null) aA2 = ""; String aCy = exAddr.getCITY(); if (aCy == null) aCy = ""; String aS = exAddr.getSTATE_PROV(); if (aS == null) aS = ""; String aCny = exAddr.getCOUNTRY(); if (aCny == null) aCny = ""; String aP = exAddr.getPOSTAL_CODE(); if (aP == null) aP = ""; String exAddrName = at + "_" + ao + "_" + aA1 + "_" + aA2 + "_" + aCy + "_" + aS + "_" + aCny + "_" + aP; // compare the two to check if exists if (selAddrName.equals(exAddrName)) { // allow to create duplicates but undelete if it was deleted String exSubmit = addrB.getADDR_SUBMIT_ACTION(); if (exSubmit != null && exSubmit.equals("DEL")) { wasDeleted = true; addrB = addrB.copyAddress((AC_ADDR_Bean) vAddr.elementAt(k)); if (addrB.getAC_ADDR_IDSEQ() == null || addrB.getAC_ADDR_IDSEQ().equals(exAddrName)) addrB.setADDR_SUBMIT_ACTION("INS"); else addrB.setADDR_SUBMIT_ACTION("UPD"); selInd = k; // reset the index } break; } } // update or add new attributes if was not deleted if (!wasDeleted) { addrB.setATL_NAME(aType); addrB.setRANK_ORDER(aOrd); addrB.setADDR_LINE1(aAddr1); addrB.setADDR_LINE2(aAddr2); addrB.setCITY(aCity); addrB.setSTATE_PROV(aState); addrB.setCOUNTRY(aCntry); addrB.setPOSTAL_CODE(aPost); if (selInd > -1) addrB.setADDR_SUBMIT_ACTION("UPD"); else addrB.setADDR_SUBMIT_ACTION("INS"); } } // set the vector if (selInd > -1) vAddr.setElementAt(addrB, selInd); else vAddr.addElement(addrB); ACBean.setACC_ADDR_List(vAddr); // set the bean } catch (Exception e) { logger.fatal("Error - doContAddrAction : " + e.toString(), e); } return ACBean; } /** * to get Protocol CRF for the selected ac called when the ProtoCRF window opened first time and calls * 'getAC.doProtoCRFSearch' forwards page back to ProtoCRFwindow jsp * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doProtoCRFSearchActions(HttpServletRequest req, HttpServletResponse res) throws Exception { GetACSearch getAC = new GetACSearch(req, res, this); String acID = req.getParameter("acID"); String acName = req.getParameter("itemType"); // ac name for proto crf if (acName != null && acName.equals("ALL")) acName = "-"; @SuppressWarnings("unused") Integer pvCount = getAC.doProtoCRFSearch(acID, acName); ForwardJSP(req, res, "/ProtoCRFWindow.jsp"); } /** * Monitor the user selected items with a Sentinel Alert. * * @param req * The session request. * @param res * The session response. */ protected void doMonitor(HttpServletRequest req, HttpServletResponse res) { // Init main variables. HttpSession session = req.getSession(); String msg = null; Vector<String> vCheckList = new Vector<String>(); while (true) { // Be sure something was selected by the user. Vector vSRows = (Vector) session.getAttribute("vSelRows"); if (vSRows == null || vSRows.size() == 0) { msg = "No items were selected from the Search Results."; break; } // Get session information. UserBean Userbean = new UserBean(); Userbean = (UserBean) session.getAttribute("Userbean"); if (Userbean == null) { msg = "User session information is missing."; break; } CallableStatement stmt = null; try { // Get the selected items and associate each with the appropriate CSI String user = Userbean.getUsername(); user = user.toUpperCase(); // Add the selected items to the CSI String csi_idseq = null; int ndx = 0; stmt = m_conn.prepareCall("begin SBREXT_CDE_CURATOR_PKG.ADD_TO_SENTINEL_CS(?,?,?); end;"); stmt.registerOutParameter(3, java.sql.Types.VARCHAR); stmt.setString(2, user); try { vCheckList = new Vector<String>(); for (ndx = 0; ndx < vSRows.size(); ++ndx) { String temp; String ckName = ("CK" + ndx); temp = req.getParameter(ckName); if (temp != null) { AC_Bean bean = (AC_Bean) vSRows.elementAt(ndx); temp = bean.getIDSEQ(); stmt.setString(1, temp); stmt.execute(); temp = stmt.getString(3); vCheckList.addElement(ckName); if (temp != null) csi_idseq = temp; } } DataManager.setAttribute(session, "CheckList", vCheckList); // add the check list in the session. } catch (ClassCastException e) { // This happens when the selected element does not extend the AC_Bean abstract class. csi_idseq = ""; } if (csi_idseq == null) { msg = "None of the selected items can be added to your Reserved CSI."; } else if (csi_idseq.length() == 0) { msg = "The selected items are not supported for the Monitor feature."; } else { // Have the Sentinel watch the CSI. DSRAlert sentinel = DSRAlertImpl.factory(m_conn); ndx = sentinel.createAlert(user, csi_idseq); switch (ndx) { case DSRAlert.RC_FAILED: msg = "An error occurred attempting to create the Alert Definition."; break; case DSRAlert.RC_INCOMPATIBLE: msg = "The Sentinel API server does not support this request."; break; case DSRAlert.RC_UNAUTHORIZED: msg = "You are not authorized to create a Sentinel Alert."; break; default: String itemTxt = (vSRows.size() == 1) ? "item is" : "items are"; msg = "The selected " + itemTxt + " now monitored by the Alert Definition \"" + sentinel.getAlertName() + "\""; msg = msg.replaceAll("[\"]", "\\\\\""); break; } } } catch (Exception e) { msg = "An unexpected exception occurred, please notify the Help Desk. Details have been written to the log."; logger.fatal("cdecurate: doMonitor(): " + e.toString(), e); } finally{ SQLHelper.closeCallableStatement(stmt); } break; } // Send the message back to the user. GetACSearch getACSearch = new GetACSearch(req, res, this); getACSearch.getACShowResult2(req, res, "Monitor"); DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, msg); ForwardJSP(req, res, "/SearchResultsPage.jsp"); } /** * Unmonitor the user selected items with a Sentinel Alert. * * @param req * The session request. * @param res * The session response. */ protected void doUnmonitor(HttpServletRequest req, HttpServletResponse res) { // Init main variables. HttpSession session = req.getSession(); String msg = null; Vector<String> vCheckList = new Vector<String>(); while (true) { // Be sure something was selected by the user. Vector vSRows = (Vector) session.getAttribute("vSelRows"); if (vSRows == null || vSRows.size() == 0) { msg = "No items were selected from the Search Results."; break; } // Get session information. UserBean Userbean = new UserBean(); Userbean = (UserBean) session.getAttribute("Userbean"); if (Userbean == null) { msg = "User session information is missing."; break; } // Get list of selected AC's. Vector<String> list = new Vector<String>(); for (int ndx = 0; ndx < vSRows.size(); ++ndx) { try { String temp; String ckName = ("CK" + ndx); temp = req.getParameter(ckName); if (temp != null) { AC_Bean bean = (AC_Bean) vSRows.elementAt(ndx); temp = bean.getIDSEQ(); list.add(temp); vCheckList.addElement(ckName); } } catch (ClassCastException e) { } } DataManager.setAttribute(session, "CheckList", vCheckList); // add the check list in the session. if (list.size() == 0) { msg = "None of the selected AC's were previously Monitored."; break; } // Update the database - remove the CSI association to the AC's. String user = Userbean.getUsername(); user = user.toUpperCase(); CallableStatement stmt=null; for (int ndx = 0; ndx < list.size(); ++ndx) { try { String temp = list.elementAt(ndx); stmt = m_conn.prepareCall("begin SBREXT_CDE_CURATOR_PKG.REMOVE_FROM_SENTINEL_CS('" + temp + "','" + user + "'); END;"); stmt.execute(); SQLHelper.closeCallableStatement(stmt); msg = "The selected item is no longer monitored by the Alert Definition"; } catch (Exception e) { msg = "An unexpected exception occurred, please notify the Help Desk. Details have been written to the log."; logger.fatal("cdecurate: doUnmonitor(): " + e.toString(), e); }finally{ SQLHelper.closeCallableStatement(stmt); } } break; } // Send the message back to the user. GetACSearch getACSearch = new GetACSearch(req, res, this); getACSearch.getACShowResult2(req, res, "Monitor"); DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, msg); ForwardJSP(req, res, "/SearchResultsPage.jsp"); } /** * The doRefreshPVSearchPage method forwards crfValue search page with refreshed list updates the quest value bean * with searched/created pv data, * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @param m_PV * PV_Bean searched/created pv data * @param Origin * String origin of the action * * @throws Exception */ public void doRefreshPVSearchPage(HttpServletRequest req, HttpServletResponse res, PV_Bean m_PV, String Origin) throws Exception { HttpSession session = req.getSession(); if (Origin.equals("CreateNew")) { DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, "Value created and inserted successfully."); Vector<String> vNewPV = new Vector<String>(); vNewPV.addElement(m_PV.getPV_PV_IDSEQ()); vNewPV.addElement(m_PV.getPV_VALUE()); vNewPV.addElement(m_PV.getPV_SHORT_MEANING()); req.setAttribute("newPVData", vNewPV); } // get the selected pv data from the request else { // using designation hidden fields to get the selected value & meanings String sPVID = (String) req.getParameter("desName"); if (sPVID != null) m_PV.setPV_PV_IDSEQ(sPVID); String sPValue = (String) req.getParameter("desContext"); if (sPValue != null) m_PV.setPV_VALUE(sPValue); String sPVMean = (String) req.getParameter("desContextID"); if (sPVMean != null) m_PV.setPV_SHORT_MEANING(sPVMean); } // forwards the page to regular pv search if not questions String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); if (Origin.equals("CreateNew") && !sMenuAction.equals("Questions")) ForwardJSP(req, res, "/OpenSearchWindow.jsp"); else { // get the selected crf value and update its attribute with the selected/created pvvalue String selCRFValue = (String) session.getAttribute("selCRFValueID"); if (selCRFValue != null) { // get the crf value vector to update Vector vQuestValue = (Vector) session.getAttribute("vQuestValue"); if (vQuestValue != null) { for (int i = 0; i < (vQuestValue.size()); i++) { Quest_Value_Bean QuestValueBean = new Quest_Value_Bean(); QuestValueBean = (Quest_Value_Bean) vQuestValue.elementAt(i); // update the quest bean with the new value meaning if (QuestValueBean.getQUESTION_VALUE_IDSEQ().equalsIgnoreCase(selCRFValue)) { QuestValueBean.setPERM_VALUE_IDSEQ(m_PV.getPV_PV_IDSEQ()); QuestValueBean.setPERMISSIBLE_VALUE(m_PV.getPV_VALUE()); QuestValueBean.setVALUE_MEANING(m_PV.getPV_SHORT_MEANING()); break; } } DataManager.setAttribute(session, "vQuestValue", vQuestValue); } } ForwardJSP(req, res, "/CRFValueSearchWindow.jsp"); } } /** * gets the selected row from the search result to forward the data. Called from 'doSearchResultsAction' method * where actType is 'edit' calls 'getACSearch.getSelRowToEdit' method to get the row bean. if user doesn't have * permission to write to the selected context goes back to search page. otherwise forwards to create/edit pages for * the selected component. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ protected void doSearchSelectionAction(HttpServletRequest req, HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); String sSearchAC = (String) session.getAttribute("searchAC"); // get the selected component CurationServlet acServlet = getACServlet(sSearchAC); // gets the bean for the row selected GetACSearch getACSearch = new GetACSearch(req, res, acServlet); if (getACSearch.getSelRowToEdit(req, res, "") == false) ForwardJSP(req, res, "/SearchResultsPage.jsp"); else { // String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); // get the selected // menu action // String sButtonPressed = (String) session.getAttribute("LastMenuButtonPressed"); // String sOriginAction = (String) session.getAttribute("sOriginAction"); // call method to handle DE actions. if (sSearchAC.equals("DataElement")) this.doSerSelectActDE(req, res); else if (sSearchAC.equals("DataElementConcept")) this.doSerSelectActDEC(req, res); else if (sSearchAC.equals("ValueDomain")) this.doSerSelectActVD(req, res); else if (sSearchAC.equals("ValueMeaning")) this.doSerSelectActVM(req, res); else if (sSearchAC.equals("Questions")) { // DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, ""); // get status indicatior from the quest bean Quest_Bean QuestBean = (Quest_Bean) session.getAttribute("m_Quest"); String sStatus = QuestBean.getSTATUS_INDICATOR(); // forward the page to createDE if new or existing or to edit page if edit if (sStatus.equals("Edit")) ForwardJSP(req, res, "/EditDEPage.jsp"); else ForwardJSP(req, res, "/CreateDEPage.jsp"); } else { DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, "Unable to open the Create or Edit page.\n" + "Please try again."); ForwardJSP(req, res, "/SearchResultsPage.jsp"); } } } /** * gets the selected row from the search result to forward the data. Called from 'doSearchResultsAction' method * where actType is 'edit' calls 'getACSearch.getSelRowToEdit' method to get the row bean. if user doesn't have * permission to write to the selected context goes back to search page. otherwise forwards to create/edit pages for * the selected component. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ protected void doSearchSelectionBEAction() throws Exception { HttpSession session = m_classReq.getSession(); // gets the bean for the row selected GetACSearch getACSearch = new GetACSearch(m_classReq, m_classRes, this); if (getACSearch.getSelRowToEdit(m_classReq, m_classRes, "BlockEdit") == false) ForwardJSP(m_classReq, m_classRes, "/SearchResultsPage.jsp"); else { // String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); // get the selected // menu action String sSearchAC = (String) session.getAttribute("searchAC"); // get the selected component // String sButtonPressed = (String) session.getAttribute("LastMenuButtonPressed"); if (sSearchAC.equals("DataElement")) { // open the edit page DE_Bean DEBean = (DE_Bean) session.getAttribute("m_DE"); DEBean.setDE_DEC_IDSEQ(""); DEBean.setDE_DEC_NAME(""); DEBean.setDE_VD_IDSEQ(""); DEBean.setDE_VD_NAME(""); DataManager.setAttribute(session, "m_DE", DEBean); // users need cs-csi to view DataManager.setAttribute(session, "originAction", "BlockEditDE"); DataManager.setAttribute(session, "DEEditAction", ""); ForwardJSP(m_classReq, m_classRes, "/EditDEPage.jsp"); } else if (sSearchAC.equals("DataElementConcept")) { DataManager.setAttribute(session, "originAction", "BlockEditDEC"); this.clearBuildingBlockSessionAttributes(m_classReq, m_classRes); ForwardJSP(m_classReq, m_classRes, "/EditDECPage.jsp"); } else if (sSearchAC.equals("ValueDomain")) { DataManager.setAttribute(session, "vRepTerm", null); DataManager.setAttribute(session, "newRepTerm", ""); DataManager.setAttribute(session, "originAction", "BlockEditVD"); ForwardJSP(m_classReq, m_classRes, "/EditVDPage.jsp"); } else { DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, "Unable to open the Create or Edit page.\\n" + "Please try again."); ForwardJSP(m_classReq, m_classRes, "/SearchResultsPage.jsp"); } } } /** * get the definition property from the setting * * @return the DEDefinition value */ public String getPropertyDefinition() { return NCICurationServlet.m_settings.getProperty("DEDefinition"); } /** * does the search selection action for the Data element search forward the page according to the action * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doSerSelectActDE(HttpServletRequest req, HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); // get the selected menu // action String sButtonPressed = (String) session.getAttribute("LastMenuButtonPressed"); // make sure the menu action is for DE, set it otherwise if (sMenuAction.equalsIgnoreCase("NewDECTemplate") || (sMenuAction.equalsIgnoreCase("NewVDTemplate"))) sMenuAction = "NewDETemplate"; else if (sMenuAction.equalsIgnoreCase("NewDECVersion") || (sMenuAction.equalsIgnoreCase("NewVDVersion"))) sMenuAction = "NewDEVersion"; else if (sMenuAction.equalsIgnoreCase("editDEC") || (sMenuAction.equalsIgnoreCase("editVD"))) sMenuAction = "editDE"; // set the menuaction session attribute DataManager.setAttribute(session, Session_Data.SESSION_MENU_ACTION, sMenuAction); // forward to create DE page if template or version if ((sMenuAction.equals("NewDETemplate")) || (sMenuAction.equals("NewDEVersion"))) { // DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, ""); DataManager.setAttribute(session, "sCDEAction", "validate"); ForwardJSP(req, res, "/CreateDEPage.jsp"); DataManager.setAttribute(session, "originAction", "NewDE"); } // forward to edit DE page if editing else if (sMenuAction.equals("editDE") || sMenuAction.equals("nothing")) { DataManager.setAttribute(session, "originAction", "EditDE"); ForwardJSP(req, res, "/EditDEPage.jsp"); } else if (sButtonPressed.equals("Search")) { DataManager.setAttribute(session, "originAction", "EditDE"); ForwardJSP(req, res, "/EditDEPage.jsp"); } else { DataManager.setAttribute(session, "originAction", "EditDE"); DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, "Unable to open the Create or Edit page.\\n" + "Please try again."); ForwardJSP(req, res, "/SearchResultsPage.jsp"); } } /** * does the search selection action for the Data element concept search forward the page according to the action * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doSerSelectActDEC(HttpServletRequest req, HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); // get the selected menu // action String sButtonPressed = (String) session.getAttribute("LastMenuButtonPressed"); // make sure the menu action is for DEC, set it otherwise if (sMenuAction.equalsIgnoreCase("NewDETemplate") || (sMenuAction.equalsIgnoreCase("NewVDTemplate"))) sMenuAction = "NewDECTemplate"; else if (sMenuAction.equalsIgnoreCase("NewDEVersion") || (sMenuAction.equalsIgnoreCase("NewVDVersion"))) sMenuAction = "NewDECVersion"; else if (sMenuAction.equalsIgnoreCase("editDE") || (sMenuAction.equalsIgnoreCase("editVD"))) sMenuAction = "editDEC"; // set the menuaction session attribute DataManager.setAttribute(session, Session_Data.SESSION_MENU_ACTION, sMenuAction); // forward to create DEC page if template or version if ((sMenuAction.equals("NewDECTemplate")) || (sMenuAction.equals("NewDECVersion"))) { DataManager.setAttribute(session, "DECPageAction", "validate"); ForwardJSP(req, res, "/CreateDECPage.jsp"); // DataManager.setAttribute(session, "originAction", "NewDEC"); } // forward to edit DEC page if editing else if (sMenuAction.equals("editDEC") || sMenuAction.equals("nothing")) { DataManager.setAttribute(session, "originAction", "EditDEC"); ForwardJSP(req, res, "/EditDECPage.jsp"); } else if (sButtonPressed.equals("Search")) { DataManager.setAttribute(session, "originAction", "EditDEC"); ForwardJSP(req, res, "/EditDECPage.jsp"); } else { DataManager.setAttribute(session, "originAction", "EditDEC"); DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, "Unable to open the Create or Edit page.\\n" + "Please try again."); ForwardJSP(req, res, "/SearchResultsPage.jsp"); } } /** * does the search selection action for the Value Domain search forward the page according to the action * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doSerSelectActVD(HttpServletRequest req, HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); // get the selected menu // action String sButtonPressed = (String) session.getAttribute("LastMenuButtonPressed"); // make sure the menu action is for DE, set it otherwise if (sMenuAction.equalsIgnoreCase("NewDETemplate") || (sMenuAction.equalsIgnoreCase("NewDECTemplate"))) sMenuAction = "NewVDTemplate"; else if (sMenuAction.equalsIgnoreCase("NewDEVersion") || (sMenuAction.equalsIgnoreCase("NewDECVersion"))) sMenuAction = "NewVDVersion"; else if (sMenuAction.equalsIgnoreCase("editDE") || (sMenuAction.equalsIgnoreCase("editDEC"))) sMenuAction = "editVD"; // set the menuaction session attribute DataManager.setAttribute(session, Session_Data.SESSION_MENU_ACTION, sMenuAction); // forward to create VD page if template or version if ((sMenuAction.equals("NewVDTemplate")) || (sMenuAction.equals("NewVDVersion"))) { DataManager.setAttribute(session, "VDPageAction", "validate"); ForwardJSP(req, res, "/CreateVDPage.jsp"); DataManager.setAttribute(session, "originAction", "NewVD"); } // forward to edit VD page if editing else if (sMenuAction.equals("editVD") || sMenuAction.equals("nothing")) { DataManager.setAttribute(session, "originAction", "EditVD"); ForwardJSP(req, res, "/EditVDPage.jsp"); } else if (sButtonPressed.equals("Search")) { DataManager.setAttribute(session, "originAction", "EditVD"); ForwardJSP(req, res, "/EditVDPage.jsp"); } else { DataManager.setAttribute(session, "originAction", "EditVD"); DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, "Unable to open the Create or Edit page.\\n" + "Please try again."); ForwardJSP(req, res, "/SearchResultsPage.jsp"); } } /** * does the search selection action for the Value Meaning search forward the page according to the action * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doSerSelectActVM(HttpServletRequest req, HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); // get the selected menu // action String sButtonPressed = (String) session.getAttribute("LastMenuButtonPressed"); // make sure the menu action is for DE, set it otherwise if (sMenuAction.equalsIgnoreCase("NewDETemplate") || (sMenuAction.equalsIgnoreCase("NewDECTemplate"))) sMenuAction = "NewVMTemplate"; else if (sMenuAction.equalsIgnoreCase("NewDEVersion") || (sMenuAction.equalsIgnoreCase("NewDECVersion"))) sMenuAction = "NewVMVersion"; else if (sMenuAction.equalsIgnoreCase("editDE") || (sMenuAction.equalsIgnoreCase("editDEC"))) sMenuAction = "editVM"; // set the menuaction session attribute DataManager.setAttribute(session, Session_Data.SESSION_MENU_ACTION, sMenuAction); // forward to create VM page if template or version if ((sMenuAction.equals("NewVMTemplate")) || (sMenuAction.equals("NewVMVersion"))) { DataManager.setAttribute(session, "VMPageAction", "validate"); ForwardJSP(req, res, "/CreateVMPage.jsp"); DataManager.setAttribute(session, "originAction", "NewVM"); } // forward to edit VM page if editing else if (sMenuAction.equals("editVM") || sMenuAction.equals("nothing")) { DataManager.setAttribute(session, "originAction", "EditVM"); ForwardJSP(req, res, "/ValueMeaningDetail.jsp"); } else if (sButtonPressed.equals("Search")) { DataManager.setAttribute(session, "originAction", "EditVM"); ForwardJSP(req, res, "/ValueMeaningDetail.jsp"); } else { DataManager.setAttribute(session, "originAction", "EditVM"); DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, "Unable to open the Create or Edit page.\\n" + "Please try again."); ForwardJSP(req, res, "/SearchResultsPage.jsp"); } } /** * stores status message in the session * @param sMsg string message to append to. */ @SuppressWarnings("unchecked") public void storeStatusMsg(String sMsg) { try { HttpSession session = m_classReq.getSession(); UtilService util = new UtilService(); Vector<String> vStatMsg = (Vector)session.getAttribute("vStatMsg"); String statusMsg = (String)session.getAttribute(Session_Data.SESSION_STATUS_MESSAGE); if (statusMsg == null) statusMsg = ""; //parse single double quotes and new line char if any String alrtMsg = sMsg; if (!alrtMsg.equalsIgnoreCase("\\n")) alrtMsg = util.parsedStringAlertNewLine(alrtMsg); alrtMsg = util.parsedStringDoubleQuote(alrtMsg); alrtMsg = util.parsedStringSingleQuote(alrtMsg); if (vStatMsg == null) vStatMsg = new Vector<String>(); //add message to both to string status message and vector stats message if not too big if (vStatMsg.size() < 35) { if (sMsg.equalsIgnoreCase("\\n")) statusMsg = statusMsg + alrtMsg; else statusMsg = statusMsg + alrtMsg + "\\n"; DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, statusMsg); } //remove tab and newline from the msg for vector if (!sMsg.equalsIgnoreCase("\\n") && !sMsg.equalsIgnoreCase("\n")) sMsg = util.parsedStringMsgVectorTabs(sMsg, vStatMsg); if (!sMsg.equals("")) vStatMsg.addElement(sMsg); DataManager.setAttribute(session, "vStatMsg", vStatMsg); //add this message to the logger logger.info("Log Status Message " + sMsg); } catch(Exception e) { logger.fatal("ERROR in CurationServlet-storeStatusMsg for exception : " + e.toString(), e); // m_classReq.setAttribute("retcode", "Message Exception"); } } /** * To clear session attributes when a main Menu button/item is selected. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @throws Exception */ protected void clearSessionAttributes(HttpServletRequest req, @SuppressWarnings("unused") HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); DataManager.setAttribute(session, "vSearchIDStack", null); DataManager.setAttribute(session, "SearchID", null); DataManager.setAttribute(session, "vSearchNameStack", null); DataManager.setAttribute(session, "SearchName", null); DataManager.setAttribute(session, "sSearchACStack", null); DataManager.setAttribute(session, "vACSearchStack", null); DataManager.setAttribute(session, "vSearchASLStack", null); DataManager.setAttribute(session, "vACSearch", null); DataManager.setAttribute(session, "vSelRowsStack", null); DataManager.setAttribute(session, "vResultStack", null); DataManager.setAttribute(session, "vCompAttrStack", null); DataManager.setAttribute(session, "backFromGetAssociated", ""); DataManager.setAttribute(session, "GetAssocSearchAC", ""); DataManager.setAttribute(session, "results", null); DataManager.setAttribute(session, "vSelRows", null); DataManager.setAttribute(session, "selCS", ""); DataManager.setAttribute(session, "serSelectedCD", ""); // parent concept for the VD // DataManager.setAttribute(session, "VDParentConcept", new Vector()); DataManager.setAttribute(session, "vParentList", null); DataManager.setAttribute(session, "vParentNames", null); DataManager.setAttribute(session, "vParentCodes", null); DataManager.setAttribute(session, "vParentDB", null); DataManager.setAttribute(session, "vParentMetaSource", null); DataManager.setAttribute(session, "SelectedParentName", ""); DataManager.setAttribute(session, "SelectedParentCC", ""); DataManager.setAttribute(session, "SelectedParentDB", ""); DataManager.setAttribute(session, "ParentMetaSource", null); // pv list for the vd // DataManager.setAttribute(session, "VDPVList", new Vector()); // DataManager.setAttribute(session, "PVIDList", new Vector()); DataManager.setAttribute(session, "m_OC", null); DataManager.setAttribute(session, "selObjRow", null); DataManager.setAttribute(session, "m_PC", null); DataManager.setAttribute(session, "selPropRow", null); DataManager.setAttribute(session, "vObjectClass", null); DataManager.setAttribute(session, "vProperty", null); DataManager.setAttribute(session, "m_DEC", null); DataManager.setAttribute(session, "m_REP", null); DataManager.setAttribute(session, "selRepRow", null); DataManager.setAttribute(session, "m_OCQ", null); DataManager.setAttribute(session, "selObjQRow", null); DataManager.setAttribute(session, "m_PCQ", null); DataManager.setAttribute(session, "selPropQRow", null); DataManager.setAttribute(session, "m_REPQ", null); DataManager.setAttribute(session, "selRepQRow", null); DataManager.setAttribute(session, "creKeyword", ""); DataManager.setAttribute(session, "serKeyword", ""); DataManager.setAttribute(session, "EVSresults", null); DataManager.setAttribute(session, "VDEditAction", null); DataManager.setAttribute(session, "DEEditAction", null); DataManager.setAttribute(session, "DECEditAction", null); DataManager.setAttribute(session, "ParentConceptCode", null); DataManager.setAttribute(session, "VMForm.SESSION_RET_PAGE", null); // DataManager.setAttribute(session, "OpenTreeToConcept", ""); } /** * To clear session attributes when a main Menu button/item is selected. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @throws Exception */ public void clearBuildingBlockSessionAttributes(HttpServletRequest req, @SuppressWarnings("unused") HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); DataManager.setAttribute(session, "m_OC", null); DataManager.setAttribute(session, "selObjRow", null); DataManager.setAttribute(session, "m_PC", null); DataManager.setAttribute(session, "selPropRow", null); DataManager.setAttribute(session, "vObjResults", null); DataManager.setAttribute(session, "vPropResults", null); DataManager.setAttribute(session, "vRepResults", null); DataManager.setAttribute(session, "m_REP", null); DataManager.setAttribute(session, "selRepRow", null); DataManager.setAttribute(session, "vObjQResults", null); DataManager.setAttribute(session, "m_OCQ", null); DataManager.setAttribute(session, "selObjQRow", null); DataManager.setAttribute(session, "vPropQResults", null); DataManager.setAttribute(session, "m_PCQ", null); DataManager.setAttribute(session, "selPropQRow", null); DataManager.setAttribute(session, "vRepQResults", null); DataManager.setAttribute(session, "m_REPQ", null); DataManager.setAttribute(session, "selRepQRow", null); DataManager.setAttribute(session, "vObjectClass", null); DataManager.setAttribute(session, "newObjectClass", ""); DataManager.setAttribute(session, "RemoveOCBlock", ""); DataManager.setAttribute(session, "vProperty", null); DataManager.setAttribute(session, "newProperty", ""); DataManager.setAttribute(session, "RemovePropBlock", ""); DataManager.setAttribute(session, "vRepTerm", null); DataManager.setAttribute(session, "newRepTerm", ""); DataManager.setAttribute(session, "ConceptLevel", "0"); DataManager.setAttribute(session, "creMetaCodeSearch", null); DataManager.setAttribute(session, "creKeyword", ""); DataManager.setAttribute(session, "serKeyword", ""); DataManager.setAttribute(session, "EVSresults", null); DataManager.setAttribute(session, "ParentMetaSource", null); DataManager.setAttribute(session, "ParentConceptCode", null); } /** * To clear session attributes when a main Menu button/item is selected. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @throws Exception */ protected void clearCreateSessionAttributes(HttpServletRequest req, @SuppressWarnings("unused") HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); // parent concept for the VD // DataManager.setAttribute(session, "VDParentConcept", new Vector()); DataManager.setAttribute(session, "SelectedParentName", ""); DataManager.setAttribute(session, "SelectedParentCC", ""); DataManager.setAttribute(session, "SelectedParentDB", ""); // pv list for the vd // DataManager.setAttribute(session, "VDPVList", new Vector()); DataManager.setAttribute(session, "PVIDList", new Vector()); DataManager.setAttribute(session, "creKeyword", ""); DataManager.setAttribute(session, "serKeyword", ""); DataManager.setAttribute(session, "EVSresults", null); DataManager.setAttribute(session, "OpenTreeToConcept", ""); DataManager.setAttribute(session, "labelKeyword", ""); // clear altname refdoc attributes after creating, editing, or back DataManager.setAttribute(session, "AllAltNameList", new Vector()); DataManager.setAttribute(session, "AllRefDocList", new Vector()); DataManager.setAttribute(session, "vACId", new Vector()); DataManager.setAttribute(session, "vACName", new Vector()); DataManager.setAttribute(session, "TabFocus", "VD"); // clear vm attribute DataManager.setAttribute(session, VMForm.SESSION_SELECT_VM, new VM_Bean()); } /** * This method forwards to an Error page. Called from 'service' method where reqType is 'actionFromMenu' forwards * page 'ErrorLoginPage.jsp'. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * */ public void ErrorLogin(HttpServletRequest req, HttpServletResponse res) { // capture the stack in logger try { throw new Exception("Error Login used in various methods"); } catch (Exception e) { logger.fatal("Error Caught : ", e); } // forward to error jsp try { ForwardErrorJSP(req, res, "Session Terminated. Please log in again."); } catch (Exception e) { // System.err.println("ERROR - ErrorLogin: " + e); this.logger.fatal("ERROR - ErrorLogin: " + e.toString(), e); } } /** * The destroy method closes a connection pool to db. */ public void destroy() { SQLHelper.closeConnection(m_conn); } /** * doLogout method closes the connection and forwards to Login page Called from Logout button on Titlebar.jsp * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doLogout(HttpServletRequest req, HttpServletResponse res) throws Exception { try { HttpSession session = req.getSession(); session.invalidate(); ForwardErrorJSP(req, res, "Logged out."); } catch (Exception e) { logger.fatal("ERROR - ErrorLogin: " + e.toString(), e); } } /** * The ForwardJSP method forwards to a jsp page. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @param sJSPPage * The JSP page to which to forward. */ public void ForwardJSP(HttpServletRequest req, HttpServletResponse res, String sJSPPage) { try { // forward to the jsp (or htm) HttpSession session = req.getSession(); String sMsg = (String) session.getAttribute(Session_Data.SESSION_STATUS_MESSAGE); if (sMsg != null && !sMsg.equals("")) { sMsg += "\\n\\nPlease use Ctrl+C to copy the message to a text file"; DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, sMsg); } // store the session data object in the session at the end of the request DataManager.setAttribute(session, Session_Data.CURATION_SESSION_ATTR, this.sessionData); String fullPage = "/jsp" + sJSPPage; // ServletContext sc = this.getServletContext(); RequestDispatcher rd = this.m_servletContext.getRequestDispatcher(fullPage); rd.forward(req, res); return; } catch (Exception e) { // e.printStackTrace(); this.logger.fatal("Servlet-ForwardJSP : " + e.toString(), e); } } /** * The ForwardErrorJSP method forwards to a jsp page. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @param errMsg * String error message * @throws Exception */ public void ForwardErrorJSP(HttpServletRequest req, HttpServletResponse res, String errMsg) throws Exception { try { HttpSession session; session = req.getSession(true); String fullPage = "/"; String reqMsg = (String) req.getAttribute("ReqErrorMessage"); if (reqMsg != null && !reqMsg.equals("")) errMsg = reqMsg; DataManager.setAttribute(session, "ErrorMessage", errMsg); if (!(errMsg).equals("Logged out.")) fullPage = "/jsp/ErrorPage.jsp"; //ServletContext sc = this.getServletContext(); RequestDispatcher rd = m_servletContext.getRequestDispatcher(fullPage); rd.forward(req, res); } catch (Exception e) { logger.fatal("Servlet-ForwardErrorJSP : " + e.toString(), e); } } /** * This is the primary method for handling requests from the Reference Document Attachments page. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @param sOrigin * The String controling weather this is a open action or other request type action */ protected void doRefDocumentUpload(HttpServletRequest req, HttpServletResponse res, String sOrigin) { String sAction; String msg = null; // HttpSession session = req.getSession(); RefDocAttachment refDocAt = new RefDocAttachment(req, res, this); msg = req.getContentType(); // upload file into the database as blob if (msg.startsWith("multipart/form-data")) { // file upload refDocAt.doFileUpload(); } else { // get action type if ((String) req.getParameter("newRefDocPageAction") != null) { sAction = (String) req.getParameter("newRefDocPageAction"); } else { sAction = "nothing"; } // Open the upload ref doc page if (sOrigin.equals("Open")) { refDocAt.doOpen(); } // Request from page to preform actions else if (sOrigin.equals("Request")) { // return to search results from upload page if (sAction.equals("backToSearch")) { refDocAt.doBack(); } // Delete ref doc attachment else if (sAction.equals("DeleteAttachment")) { refDocAt.doDeleteAttachment(); } // Catch any undefined action from page else { try { logger.fatal("Reference Document Attachments Upload: Unknown Request Type."); ForwardErrorJSP(req, res, "Unexpected Request. Session Terminated. Please login again."); } catch (Exception e) { logger.fatal("ERROR - ErrorLogin: " + e.toString(), e); } } } // catch unknown Ref type else { try { ForwardErrorJSP(req, res, "Unexpected Request. Session Terminated. Please login again."); logger.fatal("Reference Document Attachments Upload: Unknown Origin Type."); } catch (Exception e) { logger.fatal("ERROR - ErrorLogin: " + e.toString(), e); } } } } /** * @return the m_conn */ public Connection getConn() { return this.m_conn; } /** * @param m_conn the m_conn to set */ public void setConn(Connection conn) { this.m_conn = conn; } public void execute(ACRequestTypes reqType) throws Exception { System.out.println("curation servlet"); } public AC_Bean getACNames(EVS_Bean newBean, String nameAct, AC_Bean pageAC) { logger.debug("get name " + nameAct); return pageAC; } public AC_Bean getACNames(String nameAct, String origin, AC_Bean bean) { logger.debug("get name " + nameAct); return bean; } public AC_Bean getSystemName(AC_Bean ac, Vector<EVS_Bean> vParent) { logger.debug("get name "); return ac; } public CurationServlet getACServlet(String ac) { CurationServlet servObj = this; try { ACRequestTypes acrt = ACRequestTypes.valueOf(ac); if (acrt != null) { String className = acrt.getClassName(); servObj = (CurationServlet) Class.forName(className).newInstance(); servObj.init(m_classReq, m_classRes, this.m_servletContext); servObj.setConn(this.m_conn); servObj.sessionData = this.sessionData; } } catch (Exception e) { logger.error("Which AC " + e.toString()); } return servObj; } } // end of class
src/gov/nih/nci/cadsr/cdecurate/tool/CurationServlet.java
// Copyright (c) 2005 ScenPro, Inc. // $Header: /CVSNT/cdecurate/src/gov/nih/nci/cadsr/cdecurate/tool/CurationServlet.java,v 1.81 2007/04/30 14:29:11 // lhebel Exp $ // $Name: not supported by cvs2svn $ package gov.nih.nci.cadsr.cdecurate.tool; // import files import gov.nih.nci.cadsr.cdecurate.database.SQLHelper; import gov.nih.nci.cadsr.cdecurate.ui.AltNamesDefsServlet; import gov.nih.nci.cadsr.cdecurate.ui.DesDEServlet; import gov.nih.nci.cadsr.cdecurate.util.DataManager; import gov.nih.nci.cadsr.persist.exception.DBException; import gov.nih.nci.cadsr.persist.user.User_Accounts_Mgr; import gov.nih.nci.cadsr.sentinel.util.DSRAlert; import gov.nih.nci.cadsr.sentinel.util.DSRAlertImpl; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Hashtable; import java.util.Vector; import javax.naming.Context; import javax.naming.InitialContext; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.sql.DataSource; import org.apache.log4j.Logger; /** * The CurationServlet is the main servlet for communicating between the client and the server. * <P> * * @author Joe Zhou, Sumana Hegde, Tom Phillips, Jesse McKean * @version 3.0 * */ /* * The CaCORE Software License, Version 3.0 Copyright 2002-2005 ScenPro, Inc. (ScenPro) Copyright Notice. The software * subject to this notice and license includes both human readable source code form and machine readable, binary, object * code form (the CaCORE Software). The CaCORE Software was developed in conjunction with the National Cancer * Institute (NCI) by NCI employees and employees of SCENPRO. To the extent government employees are authors, any * rights in such works shall be subject to Title 17 of the United States Code, section 105. This CaCORE Software * License (the License) is between NCI and You. You (or Your) shall mean a person or an entity, and all other * entities that control, are controlled by, or are under common control with the entity. Control for purposes of this * definition means (i) the direct or indirect power to cause the direction or management of such entity, whether by * contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) * beneficial ownership of such entity. This License is granted provided that You agree to the conditions described * below. NCI grants You a non-exclusive, worldwide, perpetual, fully-paid-up, no-charge, irrevocable, transferable and * royalty-free right and license in its rights in the CaCORE Software to (i) use, install, access, operate, execute, * copy, modify, translate, market, publicly display, publicly perform, and prepare derivative works of the CaCORE * Software; (ii) distribute and have distributed to and by third parties the CaCORE Software and any modifications and * derivative works thereof; and (iii) sublicense the foregoing rights set out in (i) and (ii) to third parties, * including the right to license such rights to further third parties. For sake of clarity, and not by way of * limitation, NCI shall have no right of accounting or right of payment from You or Your sublicensees for the rights * granted under this License. This License is granted at no charge to You. 1. Your redistributions of the source code * for the Software must retain the above copyright notice, this list of conditions and the disclaimer and limitation of * liability of Article 6, below. Your redistributions in object code form must reproduce the above copyright notice, * this list of conditions and the disclaimer of Article 6 in the documentation and/or other materials provided with the * distribution, if any. 2. Your end-user documentation included with the redistribution, if any, must include the * following acknowledgment: This product includes software developed by SCENPRO and the National Cancer Institute. If * You do not include such end-user documentation, You shall include this acknowledgment in the Software itself, * wherever such third-party acknowledgments normally appear. 3. You may not use the names "The National Cancer * Institute", "NCI" ScenPro, Inc. and "SCENPRO" to endorse or promote products derived from this Software. This * License does not authorize You to use any trademarks, service marks, trade names, logos or product names of either * NCI or SCENPRO, except as required to comply with the terms of this License. 4. For sake of clarity, and not by way * of limitation, You may incorporate this Software into Your proprietary programs and into any third party proprietary * programs. However, if You incorporate the Software into third party proprietary programs, You agree that You are * solely responsible for obtaining any permission from such third parties required to incorporate the Software into * such third party proprietary programs and for informing Your sublicensees, including without limitation Your * end-users, of their obligation to secure any required permissions from such third parties before incorporating the * Software into such third party proprietary software programs. In the event that You fail to obtain such permissions, * You agree to indemnify NCI for any claims against NCI by such third parties, except to the extent prohibited by law, * resulting from Your failure to obtain such permissions. 5. For sake of clarity, and not by way of limitation, You may * add Your own copyright statement to Your modifications and to the derivative works, and You may provide additional or * different license terms and conditions in Your sublicenses of modifications of the Software, or any derivative works * of the Software as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the * conditions stated in this License. 6. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, * (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, SCENPRO, OR THEIR AFFILIATES BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @author shegde * */ public class CurationServlet { protected SetACService m_setAC = new SetACService(this); public HttpServletRequest m_classReq = null; public HttpServletResponse m_classRes = null; protected ServletContext m_servletContext; public Connection m_conn=null; public static final Logger logger = Logger.getLogger(CurationServlet.class.getName()); /** declare the global variable sessionData */ public Session_Data sessionData; /** * @param req HttpServletRequest object * @param res HttpServletResponse object * @param sc ServletContext object * */ public CurationServlet(HttpServletRequest req, HttpServletResponse res, ServletContext sc) { m_classReq = req; m_classRes = res; m_servletContext = sc; } /** * */ public CurationServlet() { } /** * @param req HttpServletRequest object * @param res HttpServletResponse object * @param sc ServletContext object * */ public void init(HttpServletRequest req, HttpServletResponse res, ServletContext sc) { m_classReq = req; m_classRes = res; m_servletContext = sc; } /** * makes the login message with all the information * * @param req * @param sMethod * string a function name this is called from * @param endMsg * string a message to append to * @param bDate * Date begin date to calculate teh duration * @param eDate * date end date to calculate teh duration * @return String message */ public String getLogMessage(HttpServletRequest req, String sMethod, String endMsg, java.util.Date bDate, java.util.Date eDate) { String sMsg = ""; try { HttpSession session = req.getSession(); // call this in utility service class UtilService util = new UtilService(); sMsg = util.makeLogMessage(session, sMethod, endMsg, bDate, eDate); } catch (Exception e) { logger.warn("Unable to get the log message - " + sMsg); } return sMsg; } /** * display user friendly error message * * @param eMsg * String message * @return String user friendly message */ private String getDBConnectMessage(String eMsg) { String retMsg = ""; if (eMsg.contains("invalid username/password")) retMsg = "caDSR connection error, please verify the user name and password."; else if (eMsg.contains("maximum number of processes")) retMsg = "Reached connection limits, please try again later. If this persists contact the NIH Help Desk."; else if (eMsg.contains("Network Adapter") || eMsg.contains("Got minus one")) retMsg = "Network connection error, please contact the NIH Help Desk."; else if (eMsg.contains("Session Terminated")) retMsg = "Session has been terminated. Possible reasons could be a session timeout or an internal processing error. Please try again or contact the NIH Help Desk."; else retMsg = "Encountered an unexpected and unknown connection error, please contact the NIH Help Desk."; return retMsg; } /** * Start in the /conf/template.cdecurate-oracle-ds.xml file. Notice the <jndi-name>. * This name is used by JBoss to create and identify the connection pool. * We copied this name to the /conf/template.web.xml file in the <param-value> element. * The <param-name> for this initialization value appears in the code * NCICurationServlet.initOracleConnect() method. * The data source pool name is then saved in a class variable _dataSourceName. * * The variable is used by the CurationServlet.getConnFromDS() method which * is used by the CurationServlet.connectDB() method. * @return */ public Connection getConnFromDS() { // Use tool database pool. Context envContext = null; DataSource ds = null; String user_; String pswd_; try { envContext = new InitialContext(); ds = (DataSource) envContext.lookup(NCICurationServlet._dataSourceName); user_ = NCICurationServlet._userName; pswd_ = NCICurationServlet._password; } catch (Exception e) { String stErr = "Error creating database pool[" + e.getMessage() + "]."; e.printStackTrace(); System.out.println(stErr); logger.fatal(stErr, e); return null; } // Test connnection Connection con = null; try { con = ds.getConnection(user_, pswd_); } catch (Exception e) { System.err.println("Could not open database connection."); e.printStackTrace(); logger.fatal(e.toString(), e); return null; } return con; } /** * @param ub_ * @return Connection */ public Connection connectDB() { Connection SBRDb_conn = null; try { try { SBRDb_conn = this.getConnFromDS(); } catch (Exception e) { logger.fatal("Servlet error: no pool connection.", e); } } catch (Exception e) { logger.fatal("Servlet connectDB : " + e.toString(), e); } return SBRDb_conn; } /** * Performs the login * @param req * @param res * @param session */ private void login(HttpServletRequest req, HttpServletResponse res,HttpSession session)throws Exception { String username = req.getParameter("Username").toUpperCase(); String password = req.getParameter("Password"); CaDsrUserCredentials uc = new CaDsrUserCredentials(); UserBean userbean = new UserBean(); User_Accounts_Mgr userAccountMgr = new User_Accounts_Mgr(); try { userbean.setUsername(username); userbean.setPassword(password); uc.validateCredentials(NCICurationServlet._userName, NCICurationServlet._password, username, password); userbean.setUserFullName(userAccountMgr.getUserFullName(username, m_conn)); userbean.setPassword(""); userbean.setDBAppContext("/cdecurate"); DataManager.setAttribute(session, "Userbean", userbean); DataManager.setAttribute(session, "Username", userbean.getUsername()); sessionData.UsrBean = userbean; GetACService getAC = new GetACService(m_classReq, m_classRes, this); getAC.getWriteContextList(); } catch(DBException e){ logger.error("Unable to get User FullName" + e); } catch (Exception ex) { userbean=null; logger.error("Failed credential validation, code is " + uc.getCheckCode()); logger.error("Redirecting the user to Login Page"); ForwardErrorJSP(req, res, "Incorrect Username or Password. Please re-enter."); } } /** * Authenticates the user login credentials with the jboss authentication * data source. * @param user * @return */ /* private boolean authenticate(UserBean user) { // Use tool database pool. Context envContext = null; DataSource ds = null; boolean validUser =false; try { envContext = new InitialContext(); ds = (DataSource) envContext.lookup(NCICurationServlet._authenticateDSName); } catch (Exception e) { String stErr = "Error creating database pool[" + e.getMessage() + "]."; logger.fatal(stErr, e); return false; } // Test connnection Connection con = null; try { con = ds.getConnection(user.getUsername(), user.getPassword()); if(con!=null) { validUser = true; } } catch (SQLException e) { logger.fatal(e.toString(), e); return false; }finally{ SQLHelper.closeConnection(con); } return validUser; } */ public void get_m_conn() { HttpSession session = m_classReq.getSession(true); // get the session data object from the session sessionData = (Session_Data) session.getAttribute(Session_Data.CURATION_SESSION_ATTR); if (sessionData == null) sessionData = new Session_Data(); //get the connection if (m_conn == null) { m_conn = connectDB(); setConn(m_conn); } } protected UserBean checkLoggedIn() throws Exception { UserBean ub = checkUserBean(m_classReq, m_classRes); if (ub == null) { HttpSession session = m_classReq.getSession(true); String errMsg = getDBConnectMessage("Session Terminated"); DataManager.setAttribute(session, "ErrorMessage", errMsg); // get the menu action from request String mnReq = (String) m_classReq.getParameter("serMenuAct"); if (mnReq == null) mnReq = ""; DataManager.setAttribute(session, "serMenuAct", mnReq); // forward the error page ForwardErrorJSP(m_classReq, m_classRes, errMsg); } return ub; } /** * The service method services all requests to this servlet. * */ public void service() { UserBean ub = null; HttpSession session; session = m_classReq.getSession(true); try { // get the session data object from the session sessionData = (Session_Data) session.getAttribute(Session_Data.CURATION_SESSION_ATTR); if (sessionData == null) sessionData = new Session_Data(); else m_conn = connectDB(); String reqType = m_classReq.getParameter("reqType"); m_classReq.setAttribute("LatestReqType", reqType); if (reqType != null) { while (true) { // check the validity of the user login if (reqType.equals("login")) { //DataManager.clearSessionAttributes(session); // sessionData = new Session_Data(); login(m_classReq,m_classRes,session); String prevReq = m_classReq.getParameter("previousReqType"); if (prevReq == null) prevReq = "/SearchResultsPage.jsp"; ForwardJSP(m_classReq, m_classRes, prevReq); break; } if ("heartbeat".equals(reqType)) { doLogout(m_classReq, m_classRes); break; } // do the requests ub = checkUserBean(m_classReq, m_classRes); if (ub != null) { if (reqType.equals("newPV")) // fromForm { doCreatePVActions(m_classReq, m_classRes); } else if (reqType.equals("pvEdits")) // fromForm { doEditPVActions(m_classReq, m_classRes); } else if (reqType.equals(VMForm.ELM_FORM_REQ_DETAIL) || reqType.equals(VMForm.ELM_FORM_REQ_USED) || reqType.equals(VMForm.ELM_FORM_REQ_VAL)) // fromForm { doEditVMActions(m_classReq, m_classRes); } else if (reqType.equals("createPV") || reqType.equals("editPV")) { doOpenCreatePVPage(m_classReq, m_classRes, reqType, ""); } else if (reqType.equals("errorPageForward")) { doJspErrorAction(m_classReq, m_classRes); // on click on the edit/create from menu } else if (reqType.equals("logout")) { doLogout(m_classReq, m_classRes); } else if (reqType.equals("searchEVS")) { doSearchEVS(m_classReq, m_classRes); } // else if (reqType.equals("searchQualifiers")) // { // doQualifierSearchActions(m_classReq, m_classRes); // } // get more records of Doc Text else if (reqType.equals("getRefDocument")) { this.doRefDocSearchActions(m_classReq, m_classRes); } // get more records of alternate names else if (reqType.equals("getAltNames")) { this.doAltNameSearchActions(m_classReq, m_classRes); } // get more records of permissible values else if (reqType.equals("getPermValue")) { this.doPermValueSearchActions(m_classReq, m_classRes); } // get more records of protocol crf else if (reqType.equals("getProtoCRF")) { this.doProtoCRFSearchActions(m_classReq, m_classRes); } // get detailed records of concept class else if (reqType.equals("getConClassForAC")) { this.doConClassSearchActions(m_classReq, m_classRes); } // get cd details for vm else if (reqType.equals("showCDDetail")) { this.doConDomainSearchActions(m_classReq, m_classRes); } else if (reqType.equals("treeSearch")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("treeRefresh")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("treeExpand")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("treeCollapse")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("getSubConcepts")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("getSuperConcepts")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("designateDE")) { new DesDEServlet(this, ub).doAction(m_classReq, m_classRes, "Edit"); } else if (reqType.equals(AltNamesDefsServlet._reqType)) { new AltNamesDefsServlet(this, ub).doAction(m_classReq, m_classRes); } else if (reqType.equals("RefDocumentUpload")) { this.doRefDocumentUpload(m_classReq, m_classRes, "Request"); } else if (reqType.equals("nonEVSSearch")) { this.doNonEVSPageAction(m_classReq, m_classRes); } else if (reqType.equals("ACcontact")) { this.doContactEditActions(m_classReq, m_classRes); } break; } if (!reqType.equals("login")) { String errMsg = getDBConnectMessage("Session Terminated"); // "Please login again. Your session has // been terminated. Possible reasons // could be a session timeout or an // internal processing error."; DataManager.setAttribute(session, "ErrorMessage", errMsg); // get the menu action from request String mnReq = (String) m_classReq.getParameter("serMenuAct"); if (mnReq == null) mnReq = ""; DataManager.setAttribute(session, "serMenuAct", mnReq); // forward the error page ForwardErrorJSP(m_classReq, m_classRes, errMsg); break; } break; } } else { this.logger.fatal("Service: no DB Connection"); ErrorLogin(m_classReq, m_classRes); } SQLHelper.closeConnection(m_conn); } catch (Exception e) { logger.fatal("Service error : " + e.toString(), e); session = m_classReq.getSession(); String msg = e.toString(); try { if (msg != null) ForwardErrorJSP(m_classReq, m_classRes, msg); else ForwardErrorJSP(m_classReq, m_classRes, "A page error has occurred. Please login again."); } catch (Exception ee) { logger.fatal("Service forward error : " + ee.toString(), ee); } }finally{ SQLHelper.closeConnection(m_conn); } } // end of service /** * The service method services all requests to this servlet. * */ public void serviceOLD() { UserBean ub = null; HttpSession session; session = m_classReq.getSession(true); try { // get the session data object from the session sessionData = (Session_Data) session.getAttribute(Session_Data.CURATION_SESSION_ATTR); if (sessionData == null) sessionData = new Session_Data(); else m_conn = connectDB(); String reqType = m_classReq.getParameter("reqType"); m_classReq.setAttribute("LatestReqType", reqType); if (reqType != null) { while (true) { // check the validity of the user login if (reqType.equals("login")) { DataManager.clearSessionAttributes(session); sessionData = new Session_Data(); login(m_classReq,m_classRes,session); break; } if ("heartbeat".equals(reqType)) { doLogout(m_classReq, m_classRes); break; } // do the requests ub = checkUserBean(m_classReq, m_classRes); if (ub != null) { /* if (reqType.equals("homePage")) { doHomePage(m_classReq, m_classRes); } else if (DERequestTypes.valueOf(reqType) != null) { DE_Servlet deServ = new DE_Servlet(m_classReq, m_classRes); // doOpenCreateNewPages(m_classReq, m_classRes, "de"); deServ.AC_Service(DERequestTypes.valueOf(reqType)); } else if (reqType.equals("newDECFromMenu")) { // doOpenCreateNewPages(m_classReq, m_classRes, "dec"); } else if (reqType.equals("newVDFromMenu")) { // doOpenCreateNewPages(m_classReq, m_classRes, "vd"); } else if (reqType.equals("newDECfromForm")) // when DEC form is submitted { doCreateDECActions(m_classReq, m_classRes); } else if (reqType.equals("newVDfromForm")) // when Edit VD form is submitted { doCreateVDActions(m_classReq, m_classRes); } else if (reqType.equals("editDEC")) // when Edit DEC form is submitted { doEditDECActions(m_classReq, m_classRes); } else if (reqType.equals("editVD")) { doEditVDActions(m_classReq, m_classRes); } else*/ if (reqType.equals("newPV")) // fromForm { doCreatePVActions(m_classReq, m_classRes); } else if (reqType.equals("pvEdits")) // fromForm { doEditPVActions(m_classReq, m_classRes); } else if (reqType.equals(VMForm.ELM_FORM_REQ_DETAIL) || reqType.equals(VMForm.ELM_FORM_REQ_USED) || reqType.equals(VMForm.ELM_FORM_REQ_VAL)) // fromForm { doEditVMActions(m_classReq, m_classRes); } else if (reqType.equals("createPV") || reqType.equals("editPV")) { doOpenCreatePVPage(m_classReq, m_classRes, reqType, ""); } /* else if (reqType.equals("createNewDEC")) { doOpenCreateDECPage(m_classReq, m_classRes); } else if (reqType.equals("createNewVD")) { doOpenCreateVDPage(m_classReq, m_classRes); } else if (reqType.equals("validateDECFromForm")) { doInsertDEC(m_classReq, m_classRes); } else if (reqType.equals("validateVDFromForm")) { doInsertVD(m_classReq, m_classRes); } */ /* else if (reqType.equals("searchACs")) { doGetACSearchActions(m_classReq, m_classRes); // m_classReq for search parameters page } else if (reqType.equals("showResult")) { doSearchResultsAction(m_classReq, m_classRes, ub); // m_classReq from search results page } else if (reqType.equals("showBEDisplayResult")) { doDisplayWindowBEAction(m_classReq, m_classRes); // m_classReq from search results page showBEDisplayResult } else if (reqType.equals("showDECDetail")) { doDECDetailDisplay(m_classReq, m_classRes); // m_classReq from DECDetailsWindow page } else if (reqType.equals("doSortCDE")) { doSortACActions(m_classReq, m_classRes); // on sort by heading for search } else if (reqType.equals("doSortBlocks")) { doSortBlockActions(m_classReq, m_classRes, "Blocks"); // on sort by heading for search } else if (reqType.equals("doSortQualifiers")) { doSortBlockActions(m_classReq, m_classRes, "Qualifiers"); // on sort by heading for search } else if (reqType.equals("getSearchFilter")) { doOpenSearchPage(m_classReq, m_classRes); // on click on the search from menu } else if (reqType.equals("actionFromMenu")) { doMenuAction(m_classReq, m_classRes); // on click on the edit/create from menu } */ else if (reqType.equals("errorPageForward")) { doJspErrorAction(m_classReq, m_classRes); // on click on the edit/create from menu } else if (reqType.equals("logout")) { doLogout(m_classReq, m_classRes); } else if (reqType.equals("searchEVS")) { doSearchEVS(m_classReq, m_classRes); } /* else if (reqType.equals("searchBlocks")) { doBlockSearchActions(m_classReq, m_classRes); } else if (reqType.equals("searchQualifiers")) { doQualifierSearchActions(m_classReq, m_classRes); } */ // get more records of Doc Text else if (reqType.equals("getRefDocument")) { this.doRefDocSearchActions(m_classReq, m_classRes); } // get more records of alternate names else if (reqType.equals("getAltNames")) { this.doAltNameSearchActions(m_classReq, m_classRes); } // get more records of permissible values else if (reqType.equals("getPermValue")) { this.doPermValueSearchActions(m_classReq, m_classRes); } // get more records of protocol crf else if (reqType.equals("getProtoCRF")) { this.doProtoCRFSearchActions(m_classReq, m_classRes); } // get detailed records of concept class else if (reqType.equals("getConClassForAC")) { this.doConClassSearchActions(m_classReq, m_classRes); } // get cd details for vm else if (reqType.equals("showCDDetail")) { this.doConDomainSearchActions(m_classReq, m_classRes); } else if (reqType.equals("treeSearch")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("treeRefresh")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("treeExpand")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("treeCollapse")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("getSubConcepts")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("getSuperConcepts")) { this.doEVSSearchActions(reqType, m_classReq, m_classRes); } else if (reqType.equals("designateDE")) { new DesDEServlet(this, ub).doAction(m_classReq, m_classRes, "Edit"); } else if (reqType.equals(AltNamesDefsServlet._reqType)) { new AltNamesDefsServlet(this, ub).doAction(m_classReq, m_classRes); } else if (reqType.equals("RefDocumentUpload")) { this.doRefDocumentUpload(m_classReq, m_classRes, "Request"); } else if (reqType.equals("nonEVSSearch")) { this.doNonEVSPageAction(m_classReq, m_classRes); } else if (reqType.equals("ACcontact")) { this.doContactEditActions(m_classReq, m_classRes); } break; } if (!reqType.equals("login")) { String errMsg = getDBConnectMessage("Session Terminated"); // "Please login again. Your session has // been terminated. Possible reasons // could be a session timeout or an // internal processing error."; DataManager.setAttribute(session, "ErrorMessage", errMsg); // get the menu action from request String mnReq = (String) m_classReq.getParameter("serMenuAct"); if (mnReq == null) mnReq = ""; DataManager.setAttribute(session, "serMenuAct", mnReq); // forward the error page ForwardErrorJSP(m_classReq, m_classRes, errMsg); break; } break; } } else { this.logger.fatal("Service: no DB Connection"); ErrorLogin(m_classReq, m_classRes); } SQLHelper.closeConnection(m_conn); } catch (Exception e) { logger.fatal("Service error : " + e.toString(), e); session = m_classReq.getSession(); String msg = e.toString(); try { if (msg != null) ForwardErrorJSP(m_classReq, m_classRes, msg); else ForwardErrorJSP(m_classReq, m_classRes, "A page error has occurred. Please login again."); } catch (Exception ee) { logger.fatal("Service forward error : " + ee.toString(), ee); } }finally{ SQLHelper.closeConnection(m_conn); } } // end of service /** * The checkUserBean method gets the session then checks whether a Userbean exits. Called from 'service' method. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @return userBeanExists * * @throws Exception */ private UserBean checkUserBean(HttpServletRequest req, @SuppressWarnings("unused") HttpServletResponse res) throws Exception { HttpSession session; session = req.getSession(true); UserBean userbean = (UserBean) session.getAttribute("Userbean"); if (userbean == null) { logger.fatal("User bean is null"); // ForwardErrorJSP(req, res, "Please login again. Your session has been terminated. Possible reasons could // be a session timeout or an internal processing error."); } else { EVS_UserBean eUser = (EVS_UserBean) this.sessionData.EvsUsrBean; // (EVS_UserBean)session.getAttribute(EVSSearch.EVS_USER_BEAN_ARG); // //("EvsUserBean"); if (eUser == null) eUser = new EVS_UserBean(); } return userbean; } // //////////////////////////////////////////////////////////////////////////////////// /** * The doLogin method forwards to CDEHomePage.jsp. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ /* private void doLogin(HttpServletRequest req, HttpServletResponse res) throws Exception { ForwardJSP(req, res, "/CDEHomePage.jsp"); } */ /** * Gets the Help URL from Tool options table. * @param req * @param res */ public String getHelpURL(Connection con) { GetACService getAC = new GetACService(); Vector vList = new Vector(); vList = getAC.getToolOptionData(con,"CURATION", "HELP.HOME", ""); String aURL = null; if (vList != null && vList.size() > 0) { TOOL_OPTION_Bean tob = (TOOL_OPTION_Bean) vList.elementAt(0); if (tob != null) aURL = tob.getVALUE(); } return aURL; } /** * The doCreatePVActions method handles the submission of a CreatePV form Called from DON'T KNOW Calls * 'doValidatePV' if the action is Validate or submit. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ @SuppressWarnings("unchecked") private void doCreatePVActions(HttpServletRequest req, HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); String sAction = (String) req.getParameter("pageAction"); String sMenuAction = (String) req.getParameter("MenuAction"); if (sMenuAction != null) DataManager.setAttribute(session, Session_Data.SESSION_MENU_ACTION, sMenuAction); String sButtonPressed = (String) session.getAttribute("LastMenuButtonPressed"); // String sOriginAction = (String) session.getAttribute("originAction"); // clear searched data from teh session attributes /* * if (sAction.equals("submit")) doSubmitPV(req, res); else if (sAction.equals("validate")) doValidatePV(req, * res); else */if (sAction.equals("createNewVM")) this.doOpenCreateVMPage(req, res, "vm"); // store vm attributes in pv bean else if (sAction.equals("appendSearchVM")) { PV_Bean pvBean = (PV_Bean) session.getAttribute("m_PV"); if (pvBean == null) pvBean = new PV_Bean(); SetACService setAC = new SetACService(this); setAC.setPVValueFromPage(req, res, pvBean); String selVM = pvBean.getPV_SHORT_MEANING(); Vector vRSel = (Vector) session.getAttribute("vACSearch"); if (vRSel == null) vRSel = new Vector(); for (int i = 0; i < (vRSel.size()); i++) { VM_Bean vmBean = (VM_Bean) vRSel.elementAt(i); // store the vm attributes in pv attribute /*if (vmBean.getVM_SHORT_MEANING().equals(selVM))*/ if (vmBean.getVM_LONG_NAME().equals(selVM)) { // pvBean.setPV_MEANING_DESCRIPTION(vmBean.getVM_DESCRIPTION()); pvBean.setPV_MEANING_DESCRIPTION(vmBean.getVM_PREFERRED_DEFINITION()); // pvBean.setVM_CONCEPT(vmBean.getVM_CONCEPT()); pvBean.setPV_VM(vmBean); break; } } DataManager.setAttribute(session, "m_PV", pvBean); ForwardJSP(req, res, "/CreatePVPage.jsp"); } else if (sAction.equals("clearBoxes")) { PV_Bean pvOpen = (PV_Bean) session.getAttribute("pageOpenBean"); PV_Bean pvBean = (PV_Bean) session.getAttribute("m_PV"); if (pvOpen != null) pvBean = pvBean.copyBean(pvOpen); DataManager.setAttribute(session, "m_PV", pvBean); ForwardJSP(req, res, "/CreatePVPage.jsp"); } else if (sAction.equals("backToVD")) { // set the checked property to false Vector<PV_Bean> vOldVDPVList = (Vector) session.getAttribute("oldVDPVList"); if (vOldVDPVList != null) { for (int i = 0; i < vOldVDPVList.size(); i++) { PV_Bean oldPV = (PV_Bean) vOldVDPVList.elementAt(i); // System.out.println(oldPV.getPV_BEGIN_DATE() + " back vd old " + oldPV.getPV_END_DATE()); oldPV.setPV_CHECKED(false); vOldVDPVList.setElementAt(oldPV, i); } DataManager.setAttribute(session, "VDPVList", vOldVDPVList); } if (sMenuAction.equals("editVD") || sMenuAction.equals("editDE") || sButtonPressed.equals("Search")) ForwardJSP(req, res, "/EditVDPage.jsp"); // back to Edit VD Screen else ForwardJSP(req, res, "/CreateVDPage.jsp"); } } /** * @param req * @param res * @throws Exception */ protected void doOpenEditVM(HttpServletRequest req, HttpServletResponse res, VM_Bean vm, PV_Bean pv) throws Exception { ValueDomainServlet vdServ = (ValueDomainServlet) this.getACServlet("ValueDomain"); PVServlet pvSer = new PVServlet(req, res, vdServ); String pageFor = pvSer.openVMPageEdit(vm,pv); if (pageFor != null && !pageFor.equals("")) { if (pageFor.charAt(0) != '/') pageFor = "/" + pageFor; ForwardJSP(req, res, pageFor); } } /** * The doEditPVActions method handles the submission of a CreatePV form Calls 'doValidatePV' if the action is * Validate or submit. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doEditPVActions(HttpServletRequest req, HttpServletResponse res) throws Exception { ValueDomainServlet vdServ = (ValueDomainServlet) this.getACServlet("ValueDomain"); PVServlet pvSer = new PVServlet(req, res, vdServ); String pageFor = pvSer.doEditPVActions(); if (pageFor != null && !pageFor.equals("")) { if (pageFor.charAt(0) != '/') pageFor = "/" + pageFor; ForwardJSP(req, res, pageFor); } } /** * The doEditVMActions method handles the submission of a CreatePV form Calls 'doValidateVM' if the action is * Validate or submit. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doEditVMActions(HttpServletRequest req, HttpServletResponse res) throws Exception { VMServlet vmSer = new VMServlet(req, res, this); String pageFor = vmSer.run(); // doEditVMActions(); if (pageFor != null && !pageFor.equals("")) { if (pageFor.charAt(0) != '/') pageFor = "/" + pageFor; ForwardJSP(req, res, pageFor); } } /** * adds and removes alternate names and reference documents from the vectors * * @param req * @param pageAct * @throws java.lang.Exception */ private void doMarkAddRemoveDesignation(HttpServletRequest req, String pageAct) throws Exception { // call methods for different actions if (pageAct.equals("addAlt")) // do add alt name action this.doMarkAddAltNames(req); else if (pageAct.equals("addRefDoc")) // do add ref doc action this.doMarkAddRefDocs(req); else if (pageAct.equals("removeAlt")) // remove alt names this.doMarkRemoveAltNames(req); else if (pageAct.equals("removeRefDoc")) // remove refernece documents this.doMarkRemoveRefDocs(req); } /** * adds alternate names to the vectors * * @param req * @throws java.lang.Exception */ @SuppressWarnings("unchecked") private void doMarkAddAltNames(HttpServletRequest req) throws Exception { HttpSession session = req.getSession(); // InsACService insAC = new InsACService(m_classReq, m_classRes, this); // String stgContMsg = ""; // get the sessin vectors Vector<ALT_NAME_Bean> vAltNames = (Vector) session.getAttribute("AllAltNameList"); Vector vContext = (Vector) session.getAttribute("vWriteContextDE"); if (vContext == null) vContext = new Vector(); // add alternate names String selName = (String) req.getParameter("txtAltName"); if (selName == null) selName = ""; selName = selName.trim(); if (selName.equals("")) { storeStatusMsg("Please enter a text for the alternate name"); return; } // get the request vectors Vector<String> vACId = (Vector) session.getAttribute("vACId"); if (vACId == null) vACId = new Vector<String>(); Vector<String> vACName = (Vector) session.getAttribute("vACName"); if (vACName == null) vACName = new Vector<String>(); String sContID = (String) req.getParameter("selContext"); String sContext = (String) req.getParameter("contextName"); if (sContID != null) req.setAttribute("desContext", sContID); String sLang = (String) req.getParameter("dispLanguage"); if (sLang != null) req.setAttribute("desLang", sLang); String selType = (String) req.getParameter("selAltType"); // handle the context and ac name for new AC (DE, DEC and VD) if (vACId.size() < 1) vACId.addElement("new"); if (vACName.size() < 1) vACName.addElement("new"); if (sContID == null || sContID.equals("")) sContID = "new"; // continue with acitons for (int i = 0; i < vACId.size(); i++) { // get ac names String acID = (String) vACId.elementAt(i); if (acID == null) acID = ""; String acName = ""; if (vACName.size() > i) acName = (String) vACName.elementAt(i); // get page attributes // check if another record with same type, name, ac and context exists already boolean isExist = false; for (int k = 0; k < vAltNames.size(); k++) { ALT_NAME_Bean altBean = (ALT_NAME_Bean) vAltNames.elementAt(k); // check if it was existed in the list already if (altBean.getALT_TYPE_NAME().equals(selType) && altBean.getALTERNATE_NAME().equals(selName) && altBean.getCONTE_IDSEQ().equals(sContID) && altBean.getAC_IDSEQ().equals(acID)) { // change the submit action if deleted if (altBean.getALT_SUBMIT_ACTION().equals("DEL")) { // mark it as ins if new one or upd if old one String altID = altBean.getALT_NAME_IDSEQ(); if (altID == null || altID.equals("") || altID.equals("new")) altBean.setALT_SUBMIT_ACTION("INS"); else altBean.setALT_SUBMIT_ACTION("UPD"); vAltNames.setElementAt(altBean, k); } isExist = true; } } // add new one if not existed in teh bean already if (isExist == false) { // fill in the bean and vector ALT_NAME_Bean AltNameBean = new ALT_NAME_Bean(); AltNameBean.setALT_NAME_IDSEQ("new"); AltNameBean.setCONTE_IDSEQ(sContID); AltNameBean.setCONTEXT_NAME(sContext); AltNameBean.setALTERNATE_NAME(selName); AltNameBean.setALT_TYPE_NAME(selType); AltNameBean.setAC_LONG_NAME(acName); AltNameBean.setAC_IDSEQ(acID); AltNameBean.setAC_LANGUAGE(sLang); AltNameBean.setALT_SUBMIT_ACTION("INS"); vAltNames.addElement(AltNameBean); // add the bean to a vector } } DataManager.setAttribute(session, "AllAltNameList", vAltNames); } /** * removes alternate names from the vectors * * @param req * @throws java.lang.Exception */ @SuppressWarnings("unchecked") private void doMarkRemoveAltNames(HttpServletRequest req) throws Exception { HttpSession session = req.getSession(); // InsACService insAC = new InsACService(m_classReq, m_classRes, this); String stgContMsg = ""; // get the sessin vectors Vector<ALT_NAME_Bean> vAltNames = (Vector) session.getAttribute("AllAltNameList"); Vector<String> vContext = (Vector) session.getAttribute("vWriteContextDE"); if (vContext == null) vContext = new Vector<String>(); String sContID = (String) req.getParameter("selContext"); if (sContID != null) req.setAttribute("desContext", sContID); int j = -1; // to keep track of number of items on the page Vector<String> vAltAttrs = new Vector<String>(); for (int i = 0; i < vAltNames.size(); i++) { ALT_NAME_Bean aBean = (ALT_NAME_Bean) vAltNames.elementAt(i); if (!aBean.getALT_SUBMIT_ACTION().equals("DEL")) { String altName = aBean.getALTERNATE_NAME(); String altType = aBean.getALT_TYPE_NAME(); String altCont = aBean.getCONTEXT_NAME(); // go to next record if same type, name and context does exist String curAltAttr = altType + " " + altName + " " + altCont; // increase teh count only if it didn't exist in the disp vecot list if (!vAltAttrs.contains(curAltAttr)) { vAltAttrs.addElement(curAltAttr); j += 1; } String ckItem = (String) req.getParameter("ACK" + j); // get the right selected item to mark as deleted if (ckItem != null) { if (vContext.contains(altCont) || altCont.equals("") || altCont.equalsIgnoreCase("new")) { aBean.setALT_SUBMIT_ACTION("DEL"); vAltNames.setElementAt(aBean, i); // check if another record with same type, name and context but diff ac exists to remove for (int k = 0; k < vAltNames.size(); k++) { ALT_NAME_Bean altBean = (ALT_NAME_Bean) vAltNames.elementAt(k); if (!altBean.getALT_SUBMIT_ACTION().equals("DEL") && altBean.getALTERNATE_NAME().equals(altName)) { if (altBean.getALT_TYPE_NAME().equals(altType) && altBean.getCONTEXT_NAME().equals(altCont)) { altBean.setALT_SUBMIT_ACTION("DEL"); // mark them also deleted vAltNames.setElementAt(altBean, k); } } } } else stgContMsg += "\\n\\t" + altName + " in " + altCont + " Context "; break; } } } if (stgContMsg != null && !stgContMsg.equals("")) storeStatusMsg("Unable to remove the following Alternate Names, because the user does not have write permission to remove " + stgContMsg); DataManager.setAttribute(session, "AllAltNameList", vAltNames); } // end remove alt names /** * adds reference documents to the vectors * * @param req * @throws java.lang.Exception */ @SuppressWarnings("unchecked") private void doMarkAddRefDocs(HttpServletRequest req) throws Exception { HttpSession session = req.getSession(); // InsACService insAC = new InsACService(m_classReq, m_classRes, this); String selName = (String) req.getParameter("txtRefName"); if (selName == null) selName = ""; selName = selName.trim(); if (selName.equals("")) { storeStatusMsg("Please enter a text for the alternate name"); return; } // continue with adding // String stgContMsg = ""; Vector<REF_DOC_Bean> vRefDocs = (Vector) session.getAttribute("AllRefDocList"); Vector<String> vACId = (Vector) session.getAttribute("vACId"); if (vACId == null) vACId = new Vector<String>(); Vector<String> vACName = (Vector) session.getAttribute("vACName"); if (vACName == null) vACName = new Vector<String>(); Vector vContext = (Vector) session.getAttribute("vWriteContextDE"); if (vContext == null) vContext = new Vector(); // get request attributes String sContID = (String) req.getParameter("selContext"); String sContext = (String) req.getParameter("contextName"); if (sContID != null) req.setAttribute("desContext", sContID); String sLang = (String) req.getParameter("dispLanguage"); if (sLang != null) req.setAttribute("desLang", sLang); String selType = (String) req.getParameter("selRefType"); String selText = (String) req.getParameter("txtRefText"); String selUrl = (String) req.getParameter("txtRefURL"); // handle the context and ac name for new AC (DE, DEC and VD) if (vACId.size() < 1) vACId.addElement("new"); if (vACName.size() < 1) vACName.addElement("new"); if (sContID == null || sContID.equals("")) sContID = "new"; // do add ref doc action for (int i = 0; i < vACId.size(); i++) { // get ac names String acID = (String) vACId.elementAt(i); if (acID == null) acID = ""; String acName = ""; if (vACName.size() > i) acName = (String) vACName.elementAt(i); // check if another record with same type, name, ac and context exists already boolean isExist = false; for (int k = 0; k < vRefDocs.size(); k++) { REF_DOC_Bean refBean = (REF_DOC_Bean) vRefDocs.elementAt(k); // check if it was existed in the list already if (refBean.getDOC_TYPE_NAME().equals(selType) && refBean.getDOCUMENT_NAME().equals(selName) && refBean.getCONTE_IDSEQ().equals(sContID) && refBean.getAC_IDSEQ().equals(acID)) { // change the submit action if deleted if (refBean.getREF_SUBMIT_ACTION().equals("DEL")) { // mark it as ins if new one or upd if old one String refID = refBean.getREF_DOC_IDSEQ(); if (refID == null || refID.equals("") || refID.equals("new")) refBean.setREF_SUBMIT_ACTION("INS"); else refBean.setREF_SUBMIT_ACTION("UPD"); vRefDocs.setElementAt(refBean, k); } isExist = true; } } // add new one if not existed in teh bean already if (isExist == false) { // fill in the bean and vector REF_DOC_Bean RefDocBean = new REF_DOC_Bean(); RefDocBean.setAC_IDSEQ(acID); RefDocBean.setAC_LONG_NAME(acName); RefDocBean.setREF_DOC_IDSEQ("new"); RefDocBean.setDOCUMENT_NAME(selName); RefDocBean.setDOC_TYPE_NAME(selType); RefDocBean.setDOCUMENT_TEXT(selText); RefDocBean.setDOCUMENT_URL(selUrl); RefDocBean.setCONTE_IDSEQ(sContID); RefDocBean.setCONTEXT_NAME(sContext); RefDocBean.setAC_LANGUAGE(sLang); RefDocBean.setREF_SUBMIT_ACTION("INS"); vRefDocs.addElement(RefDocBean); // add the bean to a vector } } DataManager.setAttribute(session, "AllRefDocList", vRefDocs); } // end add ref docs /** * removes reference documents from the vectors * * @param req * @throws java.lang.Exception */ @SuppressWarnings("unchecked") private void doMarkRemoveRefDocs(HttpServletRequest req) throws Exception { HttpSession session = req.getSession(); //InsACService insAC = new InsACService(m_classReq, m_classRes, this); String stgContMsg = ""; Vector<REF_DOC_Bean> vRefDocs = (Vector) session.getAttribute("AllRefDocList"); Vector vContext = (Vector) session.getAttribute("vWriteContextDE"); if (vContext == null) vContext = new Vector(); String sContID = (String) req.getParameter("selContext"); if (sContID != null) req.setAttribute("desContext", sContID); int j = -1; // to keep track of number of items on the page Vector<String> vRefAttrs = new Vector<String>(); for (int i = 0; i < vRefDocs.size(); i++) { REF_DOC_Bean rBean = (REF_DOC_Bean) vRefDocs.elementAt(i); // String refID = rBean.getREF_DOC_IDSEQ(); if (!rBean.getREF_SUBMIT_ACTION().equals("DEL")) { String refName = rBean.getDOCUMENT_NAME(); String refType = rBean.getDOC_TYPE_NAME(); String refCont = rBean.getCONTEXT_NAME(); // go to next record if same type, name and context does exist String curRefAttr = refType + " " + refName + " " + refCont; // increase teh count only if it didn't exist in the disp vecot list if (!vRefAttrs.contains(curRefAttr)) { vRefAttrs.addElement(curRefAttr); j += 1; // increase the count } String ckItem = (String) req.getParameter("RCK" + j); // get the right selected item to mark as deleted if (ckItem != null) { if (vContext.contains(refCont) || refCont.equals("") || refCont.equalsIgnoreCase("new")) { rBean.setREF_SUBMIT_ACTION("DEL"); vRefDocs.setElementAt(rBean, i); // check if another record with same type, name and context but diff ac exists to remove for (int k = 0; k < vRefDocs.size(); k++) { REF_DOC_Bean refBean = (REF_DOC_Bean) vRefDocs.elementAt(k); if (!refBean.getREF_SUBMIT_ACTION().equals("DEL") && refBean.getDOCUMENT_NAME().equals(refName)) { if (refBean.getDOC_TYPE_NAME().equals(refType) && refBean.getCONTEXT_NAME().equals(refCont)) { refBean.setREF_SUBMIT_ACTION("DEL"); // mark them also deleted vRefDocs.setElementAt(refBean, k); } } } } else stgContMsg += "\\n\\t" + refName + " in " + refCont + " Context "; break; } } } if (stgContMsg != null && !stgContMsg.equals("")) storeStatusMsg("Unable to remove the following Reference Documents, because the user does not have write permission to remove " + stgContMsg); DataManager.setAttribute(session, "AllRefDocList", vRefDocs); } // end remove ref doc /** * stores altname and reference documetns created while maintaining ac in the ac bean * * @param req * HttpServletRequest request object * @param res * HttpServletResponse response object * @param sAC * maintained ac * @param sType * type whether alt name or ref doc * @param sACAct * is ac edit or create */ public void doMarkACBeanForAltRef(HttpServletRequest req, HttpServletResponse res, String sAC, String sType, String sACAct) { HttpSession session = (HttpSession) req.getSession(); if (sACAct.equals("openAR") || sACAct.equals("submitAR")) { Vector vRefDoc = new Vector(), vAltName = new Vector(); // get the alt names and ref docs from teh bean if (sAC.equals("DataElement")) { DE_Bean de = (DE_Bean) session.getAttribute("m_DE"); vAltName = (Vector) de.getAC_ALT_NAMES(); vRefDoc = (Vector) de.getAC_REF_DOCS(); } if (sAC.equals("DataElementConcept")) { DEC_Bean dec = (DEC_Bean) session.getAttribute("m_DEC"); vAltName = dec.getAC_ALT_NAMES(); vRefDoc = dec.getAC_REF_DOCS(); } if (sAC.equals("ValueDomain")) { VD_Bean vd = (VD_Bean) session.getAttribute("m_VD"); vAltName = vd.getAC_ALT_NAMES(); vRefDoc = vd.getAC_REF_DOCS(); } // store the alt name and ref doc in the session if (vAltName == null) vAltName = new Vector(); Vector<ALT_NAME_Bean> vAllAltName = new Vector<ALT_NAME_Bean>(); for (int i = 0; i < vAltName.size(); i++) { ALT_NAME_Bean thisAlt = new ALT_NAME_Bean(); thisAlt = thisAlt.copyAltNames((ALT_NAME_Bean) vAltName.elementAt(i)); vAllAltName.addElement(thisAlt); } DataManager.setAttribute(session, "AllAltNameList", vAllAltName); if (vRefDoc == null) vRefDoc = new Vector(); Vector<REF_DOC_Bean> vAllRefDoc = new Vector<REF_DOC_Bean>(); for (int i = 0; i < vRefDoc.size(); i++) { REF_DOC_Bean thisDoc = new REF_DOC_Bean(); thisDoc = thisDoc.copyRefDocs((REF_DOC_Bean) vRefDoc.elementAt(i)); vAllRefDoc.addElement(thisDoc); } DataManager.setAttribute(session, "AllRefDocList", vAllRefDoc); } else { sType = sType.replace("Store ", ""); // remove word store from the string to use later Vector vAllRefDoc = (Vector) session.getAttribute("AllRefDocList"); Vector vAllAltName = (Vector) session.getAttribute("AllAltNameList"); if (sAC.equals("DataElement")) { // System.out.println("checking de bean"); // stroe it in the bean DE_Bean de = (DE_Bean) session.getAttribute("m_DE"); m_setAC.setDEValueFromPage(req, res, de); // capture all other page or request attributes if (sType.equals("Alternate Names")) de.setAC_ALT_NAMES((Vector) vAllAltName); else if (sType.equals("Reference Documents")) de.setAC_REF_DOCS((Vector) vAllRefDoc); // update session and forward DataManager.setAttribute(session, "m_DE", de); if (sACAct.equals("createAC")) ForwardJSP(req, res, "/CreateDEPage.jsp"); else if (sACAct.equals("editAC")) ForwardJSP(req, res, "/EditDEPage.jsp"); } else if (sAC.equals("DataElementConcept")) { // stroe it in the bean DEC_Bean dec = (DEC_Bean) session.getAttribute("m_DEC"); m_setAC.setDECValueFromPage(req, res, dec); // capture all other page or request attributes if (sType.equals("Alternate Names")) dec.setAC_ALT_NAMES(vAllAltName); else if (sType.equals("Reference Documents")) dec.setAC_REF_DOCS(vAllRefDoc); // update session and forward DataManager.setAttribute(session, "m_DEC", dec); if (sACAct.equals("createAC")) ForwardJSP(req, res, "/CreateDECPage.jsp"); else if (sACAct.equals("editAC")) ForwardJSP(req, res, "/EditDECPage.jsp"); } else if (sAC.equals("ValueDomain")) { // stroe it in the bean VD_Bean vd = (VD_Bean) session.getAttribute("m_VD"); m_setAC.setVDValueFromPage(req, res, vd); // capture all other page or request attributes if (sType.equals("Alternate Names")) vd.setAC_ALT_NAMES(vAllAltName); else if (sType.equals("Reference Documents")) vd.setAC_REF_DOCS(vAllRefDoc); // update session and forward DataManager.setAttribute(session, "m_VD", vd); if (sACAct.equals("createAC")) ForwardJSP(req, res, "/CreateVDPage.jsp"); else if (sACAct.equals("editAC")) ForwardJSP(req, res, "/EditVDPage.jsp"); } } } /** * The doChangeContext method resets the bean then forwards to Create page Called from 'doCreateDEActions', * 'doCreateDECActions', 'doCreateVDActions' methods. Calls 'getAC.getACList' if the action is Validate or submit. * Stores empty bean and forwards the create page of the selected component. Stores selected context as default * session. If the create DEC and VD origin is DE, only store the new context in the bean. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @param sACType * String ac type * * @throws Exception */ /* public void doChangeContext(HttpServletRequest req, HttpServletResponse res, String sACType) throws Exception { UtilService util = new UtilService(); HttpSession session = req.getSession(); String sContextID = (String) req.getParameter("selContext"); String sNewContext = util.getNameByID((Vector) session.getAttribute("vContext"), (Vector) session .getAttribute("vContext_ID"), sContextID); String sOriginAction = (String) session.getAttribute("originAction"); if (sOriginAction == null) sOriginAction = ""; boolean bNewContext = true; // boolean bDE = sACType.equals("de"); if (sNewContext != null) { GetACService getAC = new GetACService(req, res, this); getAC.getACList(req, res, sNewContext, bNewContext, sACType); } if (sACType.equals("de")) { DataManager.setAttribute(session, "sDefaultContext", sNewContext); DataManager.setAttribute(session, "m_DE", new DE_Bean()); ForwardJSP(req, res, "/CreateDEPage.jsp"); } else if (sACType.equals("dec")) { DEC_Bean m_DEC = new DEC_Bean(); if (sOriginAction.equals("CreateNewDEC")) m_DEC.setDEC_CONTEXT_NAME(sNewContext); else DataManager.setAttribute(session, "sDefaultContext", sNewContext); DataManager.setAttribute(session, "m_DEC", m_DEC); ForwardJSP(req, res, "/CreateDECPage.jsp"); } else if (sACType.equals("vd")) { VD_Bean m_VD = new VD_Bean(); if (sOriginAction.equals("CreateNewVD")) m_VD.setVD_CONTEXT_NAME(sNewContext); else DataManager.setAttribute(session, "sDefaultContext", sNewContext); DataManager.setAttribute(session, "m_VD", m_VD); ForwardJSP(req, res, "/CreateVDPage.jsp"); } } */ /** * gets the row number from the hiddenSelRow Loops through the selected row and gets the evs bean for that row from * the vector of evs search results. adds it to vList vector and return the vector back * * @param req * HttpServletRequest * @return Vector of EVS Beans * @throws java.lang.Exception */ public EVS_Bean getEVSSelRow(HttpServletRequest req) throws Exception { HttpSession session = req.getSession(); // InsACService insAC = new InsACService(req, m_classRes, this); // get the result vector from the session EVS_Bean eBean = new EVS_Bean(); Vector vRSel = (Vector) session.getAttribute("vACSearch"); if (vRSel == null) vRSel = new Vector(); // get the array from teh hidden list String selRows[] = req.getParameterValues("hiddenSelRow"); if (selRows == null) storeStatusMsg("Unable to select Concept, please try again"); else { // loop through the array of strings for (int i = 0; i < selRows.length; i++) { String thisRow = selRows[i]; Integer IRow = new Integer(thisRow); int iRow = IRow.intValue(); if (iRow < 0 || iRow > vRSel.size()) storeStatusMsg("Row size is either too big or too small."); else { eBean = (EVS_Bean) vRSel.elementAt(iRow); if (eBean == null || eBean.getLONG_NAME() == null) { storeStatusMsg("Unable to obtain concept from the " + iRow + " row of the search results.\\n" + "Please try again."); continue; } } } } return eBean; } /** * gets the row number from the hiddenSelRow Loops through the selected row and gets the evs bean for that row from * the vector of evs search results. adds it to vList vector and return the vector back * * @param req * HttpServletRequest * @param vList * Existing Vector of EVS Beans * @return Vector of EVS Beans * @throws java.lang.Exception */ private Vector<EVS_Bean> getEVSSelRowVector(HttpServletRequest req, Vector<EVS_Bean> vList) throws Exception { HttpSession session = req.getSession(); // get the result vector from the session Vector vRSel = (Vector) session.getAttribute("vACSearch"); if (vRSel == null) vRSel = new Vector(); // get the array from teh hidden list String selRows[] = req.getParameterValues("hiddenSelRow"); if (selRows == null) storeStatusMsg("Unable to select Concept, please try again"); else { // loop through the array of strings for (int i = 0; i < selRows.length; i++) { String thisRow = selRows[i]; int iRow = Integer.parseInt(thisRow); // Integer IRow = new Integer(thisRow); // int iRow = IRow.intValue(); if (iRow < 0 || iRow > vRSel.size()) { storeStatusMsg(iRow + " Row size is either too big or too small."); logger.fatal(iRow + " CurationServelt - getEVSSelRowVector: Row size is either too big or too small."); } else { EVS_Bean eBean = (EVS_Bean) vRSel.elementAt(iRow); // send it back if unable to obtion the concept if (eBean == null || eBean.getLONG_NAME() == null) { storeStatusMsg("Unable to obtain concept from the " + thisRow + " row of the search results.\\n" + "Please try again."); logger.fatal(thisRow + " CurationServelt - getEVSSelRowVector: Unable to obtain concept from the results."); continue; } vList.addElement(eBean); } } //add duplicate checks logic here EVSSearch serEVS = new EVSSearch(m_classReq, m_classRes, this); if (vList != null && vList.size() > 0) vList = serEVS.getNCIPrefConcepts(vList); } return vList; } /** * fills in the non evs parent attributes and sends back to create non evs parent page to view details * * @param req * HttpServletRequest object * @param res * HttpServletResponse object * @throws java.lang.Exception */ private void doNonEVSPageAction(HttpServletRequest req, HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); String sPageAct = (String) req.getParameter("actSelect"); if (sPageAct.equals("viewParent")) { VD_Bean vd = (VD_Bean) session.getAttribute("m_VD"); Vector<EVS_Bean> vParentCon = vd.getReferenceConceptList(); // (Vector)session.getAttribute("VDParentConcept"); if (vParentCon != null) { String selName = (String) req.getParameter("txtRefName"); for (int i = 0; i < vParentCon.size(); i++) { EVS_Bean eBean = (EVS_Bean) vParentCon.elementAt(i); String thisName = eBean.getLONG_NAME(); String sDB = eBean.getEVS_DATABASE(); // get the selected name from the vector if (selName != null && thisName != null && sDB != null && selName.equals(thisName) && sDB.equals("Non_EVS")) { req.setAttribute("SelectedVDParent", eBean); break; } } } this.ForwardJSP(req, res, "/NonEVSSearchPage.jsp"); } else { // send back to block search for parent ForwardJSP(req, res, "/OpenSearchWindowBlocks.jsp"); } } /** * to store the selected value meanings from EVS into pv bean to submit later. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @param sPVAction * string pv action * */ public void doSelectVMConcept(HttpServletRequest req, HttpServletResponse res, String sPVAction) { try { //InsACService insAC = new InsACService(req, res, this); HttpSession session = req.getSession(); DataManager.setAttribute(session, "PVAction", sPVAction); VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); // new VD_Bean(); // get the existing pvs from the session Vector<PV_Bean> vVDPVList = m_VD.getVD_PV_List(); // (Vector)session.getAttribute("VDPVList"); if (vVDPVList == null) vVDPVList = new Vector<PV_Bean>(); // get the VMs selected from EVS from the page. Vector<EVS_Bean> vEVSList = this.getEVSSelRowVector(req, new Vector<EVS_Bean>()); if (vEVSList != null && vEVSList.size() > 0) { // get the parent concept which is same for all the selected values String sSelectedParentName = (String) session.getAttribute("SelectedParentName"); String sSelectedParentCC = (String) session.getAttribute("SelectedParentCC"); String sSelectedParentDB = (String) session.getAttribute("SelectedParentDB"); String sSelectedParentMetaSource = (String) session.getAttribute("SelectedParentMetaSource"); // get the parent concept EVS_Bean parConcept = new EVS_Bean(); if (sSelectedParentName != null && !sSelectedParentName.equals("")) { parConcept.setLONG_NAME(sSelectedParentName); parConcept.setCONCEPT_IDENTIFIER(sSelectedParentCC); parConcept.setEVS_DATABASE(sSelectedParentDB); parConcept.setEVS_CONCEPT_SOURCE(sSelectedParentMetaSource); } String notUpdateVDPVs = ""; // String updatedVDPVs = ""; for (int i = 0; i < vEVSList.size(); i++) { EVS_Bean eBean = (EVS_Bean) vEVSList.elementAt(i); EVS_UserBean eUser = (EVS_UserBean) this.sessionData.EvsUsrBean; // if (eUser == null) eUser = new EVS_UserBean(); // get the nci vocab if it meta or other vocab only if not referenced if (sSelectedParentName == null || sSelectedParentName.equals("")) { // get teh right vocab name String eDB = eBean.getVocabAttr(eUser, eBean.getEVS_ORIGIN(), EVSSearch.VOCAB_NAME, EVSSearch.VOCAB_DBORIGIN); // "vocabName", "vocabDBOrigin"); if (eDB.equals(EVSSearch.META_VALUE)) // "MetaValue")) eDB = eBean.getEVS_ORIGIN(); eBean.setEVS_DATABASE(eDB); // eBean.getEVS_ORIGIN()); // get the thesaurus term EVSSearch evs = new EVSSearch(req, res, this); eBean = evs.getThesaurusConcept(eBean); } // get cadsr data ConceptAction conact = new ConceptAction(); ConceptForm data = new ConceptForm(); //data.setDBConnection(this.connectDB(req, res)); data.setDBConnection(m_conn); data.setCurationServlet(this); eBean = conact.getCaDSRConcept(eBean, eUser, data); //this.freeConnection(data.getDBConnection()); String errMsg = data.getStatusMsg(); if (!errMsg.equals("")) storeStatusMsg(errMsg + "\\n"); String sValue = eBean.getLONG_NAME(); String sMean = eBean.getLONG_NAME(); System.out.println(sValue + " selectVMConcept " + sMean); // add the level to the value if parent exists to update the value if (sSelectedParentName != null && !sSelectedParentName.equals("")) { Integer iLevel = new Integer(eBean.getLEVEL()); sValue = sValue + " [" + iLevel.toString() + "]"; } boolean isExist = false; boolean isUpdated = false; // int updRow = -1; for (int j = 0; j < vVDPVList.size(); j++) // check if the concept already exists. { PV_Bean pvBean = new PV_Bean(); pvBean = (PV_Bean) vVDPVList.elementAt(j); VM_Bean vdVM = pvBean.getPV_VM(); String vdValue = pvBean.getPV_VALUE(); String vdMean = ""; if (vdVM != null) vdMean = vdVM.getVM_LONG_NAME();//vdVM.getVM_SHORT_MEANING(); // pvBean.getPV_SHORT_MEANING(); // check if value meaning was already existed if (vdMean != null && vdMean.equalsIgnoreCase(sMean)) { String pvSubmit = pvBean.getVP_SUBMIT_ACTION(); // put back the deleted pv if it has same value-vm pair if (pvSubmit != null && pvSubmit.equals("DEL") && vdValue.equalsIgnoreCase(sValue)) { // set to update if idseq is non evs and is from cadsr if (pvBean.getPV_PV_IDSEQ() != null && !pvBean.getPV_PV_IDSEQ().equals("EVS_" + sValue)) pvBean.setVP_SUBMIT_ACTION("UPD"); else pvBean.setVP_SUBMIT_ACTION("INS"); // evs term // mark as deleted isUpdated = true; // updRow = j; //need this to update the vector this.storePVinVDPVList(vVDPVList, pvBean, eBean, parConcept, sValue, sMean, j, true); } else if (pvSubmit != null && !pvSubmit.equals("DEL") && vdValue.equalsIgnoreCase(sValue)) // was not deleted { String sValMean = "\\tValue: " + sValue + " and Meaning: " + sMean + "\\n"; notUpdateVDPVs += sValMean; isExist = true; } } } // add to the bean if not exists if (isExist == false && !isUpdated) { this.storePVinVDPVList(vVDPVList, new PV_Bean(), eBean, parConcept, sValue, sMean, -1, false); } } // System.out.println(updatedVDPVs + " selMinVD " + vVDPVList.size()); // DataManager.setAttribute(session, "VDPVList", vVDPVList); m_VD.setVD_PV_List(vVDPVList); DataManager.setAttribute(session, "m_VD", m_VD); // alert if value meaning alredy exists but updated with concept info /* * if (updatedVDPVs != null && !updatedVDPVs.equals("")) { String stMsg = "The following Value and * Meaning is updated with the Concept Relationship. \\n"; InsACService insAC = new InsACService(req, * res, this); insAC.storeStatusMsg(stMsg + updatedVDPVs); } */// alert if value meaning alredy exists for pv on the page if (notUpdateVDPVs != null && !notUpdateVDPVs.equals("")) { String stMsg = "The following Value and Meaning already exists in the Value Domain.\\n"; storeStatusMsg(stMsg + notUpdateVDPVs); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); logger.fatal("ERROR - ", e); } } /** * stores the selected pvs from concepts search in vdpv list * @param vVPList Vector<PV_Bean> object * @param pBean PV_Bean permissible value object * @param eBean EVS_Bean concept object * @param parBean EVS_Bean parent concept * @param sValue String value * @param sMean String value meaning * @param updRow int single row * @param isUpdated boolean value of updated or not * @return Vector<PV_Bean> object */ private Vector<PV_Bean> storePVinVDPVList(Vector<PV_Bean> vVPList, PV_Bean pBean, EVS_Bean eBean, EVS_Bean parBean, String sValue, String sMean, int updRow, boolean isUpdated) { try { if (!isUpdated) // do not update these if { // store concept name as value and vm in the pv bean // pBean = new PV_Bean(); pBean.setPV_PV_IDSEQ("EVS_" + sValue); // store id as EVS pBean.setPV_VALUE(sValue); pBean.setPV_SHORT_MEANING(sMean); pBean.setVP_SUBMIT_ACTION("INS"); } // allow to update the definition if different description for evs selected items pBean.setPV_MEANING_DESCRIPTION(eBean.getPREFERRED_DEFINITION()); // these are for vd-pvs SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); if (pBean.getVP_SUBMIT_ACTION().equals("INS")) pBean.setPV_BEGIN_DATE(formatter.format(new java.util.Date())); // add evs bean to pv bean VM_Bean vm = new VM_Bean(); // vm.setVM_SHORT_MEANING(pBean.getPV_SHORT_MEANING()); vm.setVM_LONG_NAME(pBean.getPV_SHORT_MEANING()); // vm.setVM_DESCRIPTION(pBean.getPV_MEANING_DESCRIPTION()); vm.setVM_PREFERRED_DEFINITION(pBean.getPV_MEANING_DESCRIPTION()); vm.setVM_CONDR_IDSEQ(eBean.getCONDR_IDSEQ()); Vector<EVS_Bean> vmCon = new Vector<EVS_Bean>(); vmCon.addElement(eBean); vm.setVM_CONCEPT_LIST(vmCon); vm.setVM_SUBMIT_ACTION(VMForm.CADSR_ACTION_INS); pBean.setPV_VM(vm); System.out.println(eBean.getCONCEPT_IDENTIFIER() + " vm concepts " + vmCon.size()); // pBean.setVM_CONCEPT(eBean); pBean.setPARENT_CONCEPT(parBean); if (isUpdated) vVPList.setElementAt(pBean, updRow); // udpate the vector else vVPList.addElement(pBean); // store bean in vector } catch (Exception e) { logger.fatal("Error - store value and meaning in vdpv list: Value - " + sValue + " and Meaning - " + sMean, e); } return vVPList; } /** * called after setDEC or setVD to reset EVS session attributes * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ /* public void resetEVSBeans(HttpServletRequest req, @SuppressWarnings("unused") HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); EVS_Bean m_OC = new EVS_Bean(); DataManager.setAttribute(session, "m_OC", m_OC); EVS_Bean m_PC = new EVS_Bean(); DataManager.setAttribute(session, "m_PC", m_PC); EVS_Bean m_Rep = new EVS_Bean(); DataManager.setAttribute(session, "m_Rep", m_Rep); EVS_Bean m_OCQ = new EVS_Bean(); DataManager.setAttribute(session, "m_OCQ", m_OCQ); EVS_Bean m_PCQ = new EVS_Bean(); DataManager.setAttribute(session, "m_PCQ", m_PCQ); EVS_Bean m_REPQ = new EVS_Bean(); DataManager.setAttribute(session, "m_REPQ", m_REPQ); DataManager.setAttribute(session, "selPropRow", ""); DataManager.setAttribute(session, "selPropQRow", ""); DataManager.setAttribute(session, "selObjQRow", ""); DataManager.setAttribute(session, "selObjRow", ""); DataManager.setAttribute(session, "selRepQRow", ""); DataManager.setAttribute(session, "selRepRow", ""); } */ /** * gets the point or whole version number from old version for block versioning. * * @param version * Version of the selected from the page either point or whole * @param lastVersion * old Version number of the selected bean. * * @return newVersion version number that need to updated to. * @throws Exception */ protected String getNewVersionNumber(String version, String lastVersion) throws Exception { int index = -1; String pointStr = "."; String strWhBegNumber = ""; int iWhBegNumber = 0; index = lastVersion.indexOf(pointStr); String strPtBegNumber = lastVersion.substring(0, index); String afterDecimalNumber = lastVersion.substring((index + 1), (index + 2)); if (index == 1) strWhBegNumber = ""; else if (index == 2) { strWhBegNumber = lastVersion.substring(0, index - 1); Integer WhBegNumber = new Integer(strWhBegNumber); iWhBegNumber = WhBegNumber.intValue(); } String strWhEndNumber = ".0"; String beforeDecimalNumber = lastVersion.substring((index - 1), (index)); String sNewVersion = ""; Integer IadNumber = new Integer(0); Integer IbdNumber = new Integer(0); String strIncADNumber = ""; String strIncBDNumber = ""; if (version == null) version = ""; else if (version.equals("Point")) { // Point new version int incrementADNumber = 0; int incrementBDNumber = 0; Integer adNumber = new Integer(afterDecimalNumber); Integer bdNumber = new Integer(strPtBegNumber); int iADNumber = adNumber.intValue(); // after decimal int iBDNumber = bdNumber.intValue(); // before decimal if (iADNumber != 9) { incrementADNumber = iADNumber + 1; IadNumber = new Integer(incrementADNumber); strIncADNumber = IadNumber.toString(); sNewVersion = strPtBegNumber + "." + strIncADNumber; // + strPtEndNumber; } else // adNumber == 9 { incrementADNumber = 0; incrementBDNumber = iBDNumber + 1; IbdNumber = new Integer(incrementBDNumber); strIncBDNumber = IbdNumber.toString(); IadNumber = new Integer(incrementADNumber); strIncADNumber = IadNumber.toString(); sNewVersion = strIncBDNumber + "." + strIncADNumber; // + strPtEndNumber; } // DEBeanSR.setDE_VERSION(sNewVersion); } else if (version.equals("Whole")) { // Whole new version Integer bdNumber = new Integer(beforeDecimalNumber); int iBDNumber = bdNumber.intValue(); int incrementBDNumber = iBDNumber + 1; if (iBDNumber != 9) { IbdNumber = new Integer(incrementBDNumber); strIncBDNumber = IbdNumber.toString(); sNewVersion = strWhBegNumber + strIncBDNumber + strWhEndNumber; } else // before decimal number == 9 { int incrementWhBegNumber = iWhBegNumber + 1; Integer IWhBegNumber = new Integer(incrementWhBegNumber); String strIncWhBegNumber = IWhBegNumber.toString(); IbdNumber = new Integer(0); strIncBDNumber = IbdNumber.toString(); sNewVersion = strIncWhBegNumber + strIncBDNumber + strWhEndNumber; } // DEBeanSR.setDE_VERSION(sNewVersion); } return sNewVersion; } /** * The doSuggestionDE method forwards to EVSSearch jsp * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ protected void doSuggestionDE(HttpServletRequest req, HttpServletResponse res) throws Exception { ForwardJSP(req, res, "/EVSSearch.jsp"); } /** * The doOpenCreatePVPage method gets the session, gets some values from the createVD page and stores in bean m_VD, * sets some session attributes, then forwards to CreatePV page * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @param sPVAction * string pv action * @param vdPage * string opened vd page * * @throws Exception */ protected void doOpenCreatePVPage(HttpServletRequest req, HttpServletResponse res, String sPVAction, String vdPage) throws Exception { HttpSession session = req.getSession(); DataManager.setAttribute(session, "PVAction", sPVAction); VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); // new VD_Bean(); m_setAC.setVDValueFromPage(req, res, m_VD); // store VD bean DataManager.setAttribute(session, "VDPageAction", "validate"); DataManager.setAttribute(session, "m_VD", m_VD); // call the method to add/remove pvs. m_setAC.addRemovePageVDPVs(req, res); if (sPVAction.equals("removePV")) { if (vdPage.equals("editVD")) ForwardJSP(req, res, "/EditVDPage.jsp"); else ForwardJSP(req, res, "/CreateVDPage.jsp"); } else { // store the old pv in another session PV_Bean pvBean = (PV_Bean) session.getAttribute("m_PV"); if (pvBean == null) pvBean = new PV_Bean(); // copy the pv session attributes to store that can be used for clear button PV_Bean pageBean = new PV_Bean(); pageBean = pageBean.copyBean(pvBean); DataManager.setAttribute(session, "pageOpenBean", pageBean); ForwardJSP(req, res, "/CreatePVPage.jsp"); } } /** * The doJspErrorAction method is called when there is an error on a jsp page. User is forwarded to * SearchResultsPage * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ public void doJspErrorAction(HttpServletRequest req, HttpServletResponse res) throws Exception { // doOpenSearchPage(req, res); Later*** } /** * The doSearchPV method gets the session, gets some values from the createVD page and stores in bean m_VD, sets * some session attributes, then forwards to CreatePV page * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ /* public void doSearchPV(HttpServletRequest req, HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); // new VD_Bean(); EVS_Bean m_OC = new EVS_Bean(); EVS_Bean m_PC = new EVS_Bean(); EVS_Bean m_REP = new EVS_Bean(); EVS_Bean m_OCQ = new EVS_Bean(); EVS_Bean m_PCQ = new EVS_Bean(); EVS_Bean m_REPQ = new EVS_Bean(); m_setAC.setVDValueFromPage(req, res, m_VD); // store VD bean DataManager.setAttribute(session, "VDPageAction", "searchValues"); DataManager.setAttribute(session, "m_VD", m_VD); DataManager.setAttribute(session, "m_OC", m_OC); DataManager.setAttribute(session, "m_PC", m_PC); DataManager.setAttribute(session, "m_REP", m_REP); DataManager.setAttribute(session, "m_OCQ", m_OCQ); DataManager.setAttribute(session, "m_PCQ", m_PCQ); DataManager.setAttribute(session, "m_REPQ", m_REPQ); DataManager.setAttribute(session, "PValue", ""); ForwardJSP(req, res, "/SearchResultsPage.jsp"); } */ /** * The doOpenCreateVMPage method gets the session, gets some values from the createVD page and stores in bean m_VD, * sets some session attributes, then forwards to CreateVM page * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @param origin * * @throws Exception */ protected void doOpenCreateVMPage(HttpServletRequest req, HttpServletResponse res, @SuppressWarnings("unused") String origin) throws Exception { HttpSession session = req.getSession(); String sOrigin = (String) session.getAttribute("originAction"); PV_Bean m_PV = new PV_Bean(); SetACService setAC = new SetACService(this); setAC.setPVValueFromPage(req, res, m_PV); DataManager.setAttribute(session, "m_PV", m_PV); // reset vm bean VM_Bean VMBean = new VM_Bean(); // get cd value from the VD bean and make it default for VM VD_Bean VDBean = (VD_Bean) session.getAttribute("m_VD"); VMBean.setVM_CD_NAME(VDBean.getVD_CD_NAME()); VMBean.setVM_CD_IDSEQ(VDBean.getVD_CD_IDSEQ()); // store the bean in the session DataManager.setAttribute(session, "m_VM", VMBean); DataManager.setAttribute(session, "creSearchAC", "EVSValueMeaning"); if (sOrigin.equals("CreateInSearch")) ForwardJSP(req, res, "/CreateVMSearchPage.jsp"); else ForwardJSP(req, res, "/CreateVMPage.jsp"); } /** * method to call all evs actions * * @param reqType * String evs search action * @param req * HttpServletRequest * @param res * HttpServletResponse */ protected void doEVSSearchActions(String reqType, HttpServletRequest req, HttpServletResponse res) { try { // System.out.println("evs search " + reqType); EVSSearch evs = new EVSSearch(req, res, this); if (reqType.equals("getSuperConcepts")) evs.doGetSuperConcepts(); else if (reqType.equals("getSubConcepts")) evs.doGetSubConcepts(); else if (reqType.equals("treeSearch")) evs.doTreeSearchRequest("", "", "", ""); else if (reqType.equals("treeRefresh")) evs.doTreeRefreshRequest(); else if (reqType.equals("treeExpand")) evs.doTreeExpandRequest(); else if (reqType.equals("treeCollapse")) evs.doTreeCollapseRequest(); else if (reqType.equals("OpenTreeToConcept")) evs.openTreeToConcept(reqType); else if (reqType.equals("OpenTreeToParentConcept")) evs.openTreeToConcept(reqType); // else if (reqType.equals("OpenTreeToParentConcept")) // evs.openTreeToParentConcept(reqType); else if (reqType.equals("term") || reqType.equals("tree")) { String dtsVocab = req.getParameter("listContextFilterVocab"); evs.doCollapseAllNodes(dtsVocab); evs.doTreeSearch(reqType, "Blocks"); } else if (reqType.equals("defaultBlock")) { String dtsVocab = req.getParameter("listContextFilterVocab"); evs.doCollapseAllNodes(dtsVocab); } else if (reqType.equals("showConceptInTree")) evs.showConceptInTree(reqType); } catch (Exception ex) { // System.out.println("doEVSSearchActions : " + ex.toString()); logger.fatal("doEVSSearchActions : " + ex.toString(), ex); // this.ForwardErrorJSP(req, res, ex.getMessage()); } } /** * resorts the display attributes from the component attributes after add/remove attributes of selected attribute * vector. * * @param vCompAttr * list of attributes of the selected component * @param vSelectAttr * list of selected attributes of according to the action * * @return return the sorted selected attributes list * * @throws Exception */ public Vector<String> resortDisplayAttributes(Vector<String> vCompAttr, Vector<String> vSelectAttr) throws Exception { // resort the display attributes Vector<String> vReSort = new Vector<String>(); if (vCompAttr != null) { for (int j = 0; j < vCompAttr.size(); j++) { String thisAttr = (String) vCompAttr.elementAt(j); // add this attr to a vector if it is a selected attr if (vSelectAttr.contains(thisAttr)) vReSort.addElement(thisAttr); } } return vReSort; } /** * To search results by clicking on the column heading. Called from 'service' method where reqType is 'searchEVS' * forwards page 'EVSSearchPage.jsp'. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doSearchEVS(HttpServletRequest req, HttpServletResponse res) throws Exception { //HttpSession session = req.getSession(); //Vector vResults = new Vector(); try { GetACSearch getACSearch = new GetACSearch(req, res, this); getACSearch.doSearchEVS(req, res); } catch (Exception e) { // System.err.println("EVS Search : " + e); this.logger.fatal("ERROR - EVS Search : " + e.toString(), e); } ForwardJSP(req, res, "/EVSSearchPage.jsp"); // ForwardJSP(req, res, "/OpenSearchWindow.jsp"); } /** * To search a component or to display more attributes after the serach. Called from 'service' method where reqType * is 'searchACs' calls 'getACSearch.getACKeywordResult' method when the action is a new search. calls * 'getACSearch.getACShowResult' method when the action is a display attributes. forwards JSP * 'SearchResultsPage.jsp' if the action is not searchForCreate. if action is searchForCreate forwards * OpenSearchWindow.jsp * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ /* public void doQualifierSearchActions(HttpServletRequest req, HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); String actType = (String) req.getParameter("actSelect"); String menuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); GetACSearch getACSearch = new GetACSearch(req, res, this); if ((menuAction != null) && (actType != null)) { if (actType.equals("Search")) { if (menuAction.equals("searchForCreate")) { getACSearch.getACSearchForCreate(req, res, false); ForwardJSP(req, res, "/OpenSearchWindowQualifiers.jsp"); } else { getACSearch.getACKeywordResult(req, res); ForwardJSP(req, res, "/SearchResultsPage2.jsp"); } } else if (actType.equals("Attribute")) { getACSearch.getACShowResult(req, res, "Attribute"); if (menuAction.equals("searchForCreate")) ForwardJSP(req, res, "/OpenSearchWindowQualifiers.jsp"); else ForwardJSP(req, res, "/SearchResultsPage2.jsp"); } } else ForwardJSP(req, res, "/ErrorPage.jsp"); } */ /** * Sets a session attribute for a Building Block search. Called from 'service' method where reqType is 'newSearchBB' * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ /* public void doNewSearchBB(HttpServletRequest req, HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); DEC_Bean m_DEC = (DEC_Bean) session.getAttribute("m_DEC"); if (m_DEC == null) m_DEC = new DEC_Bean(); // EVS_Bean m_OC = new EVS_Bean(); // EVS_Bean m_PC = new EVS_Bean(); // EVS_Bean m_OCQ = new EVS_Bean(); // EVS_Bean m_PCQ = new EVS_Bean(); // GetACService getAC = new GetACService(req, res, this); m_setAC.setDECValueFromPage(req, res, m_DEC); DataManager.setAttribute(session, "m_DEC", m_DEC); String searchComp = (String) req.getParameter("searchComp"); if (searchComp.equals("ObjectClass")) DataManager.setAttribute(session, "creSearchAC", "ObjectClass"); else if (searchComp.equals("Property")) DataManager.setAttribute(session, "creSearchAC", "Property"); else if (searchComp.equals("ObjectQualifier")) DataManager.setAttribute(session, "creSearchAC", "ObjectQualifier"); else if (searchComp.equals("PropertyQualifier")) DataManager.setAttribute(session, "creSearchAC", "PropertyQualifier"); ForwardJSP(req, res, "/CreateDECPage.jsp"); } */ /** * to get reference documents for the selected ac and doc type called when the reference docuemnts window opened * first time and calls 'getAC.getReferenceDocuments' forwards page back to reference documents * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doRefDocSearchActions(HttpServletRequest req, HttpServletResponse res) throws Exception { GetACSearch getAC = new GetACSearch(req, res, this); String acID = req.getParameter("acID"); String itemType = req.getParameter("itemType"); @SuppressWarnings("unused") Vector vRef = getAC.doRefDocSearch(acID, itemType, "open"); ForwardJSP(req, res, "/ReferenceDocumentWindow.jsp"); } /** * to get alternate names for the selected ac and doc type called when the alternate names window opened first time * and calls 'getAC.getAlternateNames' forwards page back to alternate name window jsp * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doAltNameSearchActions(HttpServletRequest req, HttpServletResponse res) throws Exception { GetACSearch getAC = new GetACSearch(req, res, this); String acID = req.getParameter("acID"); String CD_ID = req.getParameter("CD_ID"); if (CD_ID == null) CD_ID = ""; String itemType = req.getParameter("itemType"); if (itemType != null && itemType.equals("ALL")) itemType = ""; @SuppressWarnings("unused") Vector vAlt = getAC.doAltNameSearch(acID, itemType, CD_ID, "other", "open"); ForwardJSP(req, res, "/AlternateNameWindow.jsp"); } /** * to get Permissible Values for the selected ac called when the permissible value window opened first time and * calls 'getAC.doPVACSearch' forwards page back to Permissible Value window jsp * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doPermValueSearchActions(HttpServletRequest req, HttpServletResponse res) throws Exception { // GetACSearch getAC = new GetACSearch(req, res, this); String acID = req.getParameter("acID"); String acName = req.getParameter("itemType"); // ac name for pv if (acName != null && acName.equals("ALL")) acName = "-"; String sConteIdseq = (String) req.getParameter("sConteIdseq"); if (sConteIdseq == null) sConteIdseq = ""; ValueDomainServlet vdServ = (ValueDomainServlet) this.getACServlet("ValueDomain"); PVServlet pvser = new PVServlet(req, res, vdServ); pvser.searchVersionPV(null, 0, acID, acName); ForwardJSP(req, res, "/PermissibleValueWindow.jsp"); } /** * display all the concepts for the selected ac from search results page * * @param req * HttpServletRequest * @param res * HttpServletResponse * @throws Exception */ private void doConClassSearchActions(HttpServletRequest req, HttpServletResponse res) throws Exception { GetACSearch getAC = new GetACSearch(req, res, this); String acID = req.getParameter("acID"); // dec id String ac2ID = req.getParameter("ac2ID"); // vd id //String acType = req.getParameter("acType"); // actype to search String acName = req.getParameter("acName"); // ac name for pv // call the api to return concept attributes according to ac type and ac idseq Vector<EVS_Bean> conList = new Vector<EVS_Bean>(); conList = getAC.do_ConceptSearch("", "", "", "", "", acID, ac2ID, conList); req.setAttribute("ConceptClassList", conList); req.setAttribute("ACName", acName); // store them in request parameter to display and forward the page ForwardJSP(req, res, "/ConceptClassDetailWindow.jsp"); } /** * display conceptual for the selected vm from the search results. * * @param req * HttpServletRequest * @param res * HttpServletResponse * @throws Exception */ private void doConDomainSearchActions(HttpServletRequest req, HttpServletResponse res) throws Exception { GetACSearch getAC = new GetACSearch(req, res, this); String sVM = req.getParameter("acName"); // ac name for pv // call the api to return concept attributes according to ac type and ac idseq Vector cdList = new Vector(); cdList = getAC.doCDSearch("", "", "", "", "", "", "", "", "", "", "", "", "", "", 0, "", "", sVM, cdList); // get // the // list // of // Conceptual // Domains req.setAttribute("ConDomainList", cdList); req.setAttribute("VMName", sVM); // store them in request parameter to display and forward the page ForwardJSP(req, res, "/ConDomainDetailWindow.jsp"); } /** * contact action from create and edit ac pages to either remove the selected contact or store the modified contact * back in the ac bean * * @param req * HttpServletRequest * @param sAct * String AC contact update action from create and edit pages * @return Hashtable of contact name and contact bean object */ @SuppressWarnings("unchecked") protected Hashtable<String, AC_CONTACT_Bean> doContactACUpdates(HttpServletRequest req, String sAct) { HttpSession session = req.getSession(); Hashtable<String, AC_CONTACT_Bean> hConts = (Hashtable) session.getAttribute("AllContacts"); if (hConts == null) hConts = new Hashtable<String, AC_CONTACT_Bean>(); try { String sCont = ""; AC_CONTACT_Bean accBean = new AC_CONTACT_Bean(); if (sAct.equals("removeContact")) { sCont = (String) req.getParameter("selContact"); if (sCont != null && !sCont.equals("") && hConts.containsKey(sCont)) accBean = accBean.copyContacts((AC_CONTACT_Bean) hConts.get(sCont)); accBean.setACC_SUBMIT_ACTION("DEL"); } else { sCont = (String) session.getAttribute("selContactKey"); accBean = accBean.copyContacts((AC_CONTACT_Bean) session.getAttribute("selACContact")); if (accBean == null) accBean = new AC_CONTACT_Bean(); // new contact if (sCont == null || sCont.equals("")) { Hashtable hOrg = (Hashtable) session.getAttribute("Organizations"); Hashtable hPer = (Hashtable) session.getAttribute("Persons"); sCont = accBean.getPERSON_IDSEQ(); if (sCont != null && !sCont.equals("") && hPer.containsKey(sCont)) sCont = (String) hPer.get(sCont); else { sCont = accBean.getORG_IDSEQ(); if (sCont != null && !sCont.equals("") && hOrg.containsKey(sCont)) sCont = (String) hOrg.get(sCont); } accBean.setACC_SUBMIT_ACTION("INS"); } else accBean.setACC_SUBMIT_ACTION("UPD"); } // put it back in teh hash table if (sCont != null && !sCont.equals("")) hConts.put(sCont, accBean); } catch (Exception e) { logger.fatal("Error - doContactACUpdates : " + e.toString(), e); } DataManager.setAttribute(session, "selContactKey", ""); // remove the attributes DataManager.setAttribute(session, "selACContact", null); // session.removeAttribute("selContactKey"); //remove the attributes // session.removeAttribute("selACContact"); return hConts; } /** * Contact edit action including open, view, edit comm, edit addr and change organization etc * * @param req * HttpServletRequest * @param res * HttpServletResponse * @throws Exception */ @SuppressWarnings("unchecked") private void doContactEditActions(HttpServletRequest req, HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); // get all the contacts from the session attribute set in create/edit page of the ac Hashtable hConts = (Hashtable) session.getAttribute("AllContacts"); if (hConts == null) hConts = new Hashtable(); // get the page action String sPgAct = (String) req.getParameter("pageAction"); if (sPgAct != null && !sPgAct.equals("")) { try { // get request and session attributes String sContAct = (String) req.getParameter("contAction"); if (sContAct == null || sContAct.equals("")) sContAct = "new"; AC_CONTACT_Bean accBean = (AC_CONTACT_Bean) session.getAttribute("selACContact"); if (accBean == null) accBean = new AC_CONTACT_Bean(); // if page action contact action is edit pull out contact bean from the all contacts for selected contxt if (sPgAct.equals("openPage")) // && sContAct.equals("view")) { if (sContAct.equals("view")) // edit contact { String selCont = (String) req.getParameter("selContact"); if (selCont != null && hConts.containsKey(selCont)) { accBean = accBean.copyContacts((AC_CONTACT_Bean) hConts.get(selCont)); DataManager.setAttribute(session, "selContactKey", selCont); } // System.out.println(sContAct + " contat sele " + selCont + " contains " + // hConts.containsKey(selCont)); } else // new contact { accBean = new AC_CONTACT_Bean(); DataManager.setAttribute(session, "selContactKey", ""); } } else // if (!sPgAct.equals("openPage")) //if not opening the page store the changed data in teh bean { String conOrder = (String) req.getParameter("rank"); if (conOrder != null && !conOrder.equals("")) accBean.setRANK_ORDER(conOrder); String conPer = (String) req.getParameter("selPer"); if (conPer == null) conPer = ""; accBean.setPERSON_IDSEQ(conPer); String conOrg = (String) req.getParameter("selOrg"); if (conOrg == null) conOrg = ""; accBean.setORG_IDSEQ(conOrg); String conRole = (String) req.getParameter("selRole"); if (conRole != null && !conRole.equals("")) accBean.setCONTACT_ROLE(conRole); } // change the radio button action if (sPgAct.equals("changeType")) { String sType = (String) req.getParameter("rType"); if (sType != null && !sType.equals("")) req.setAttribute("TypeSelected", sType); } // get the comm and addr info for the selected contact else if (sPgAct.equals("changeContact")) { String perID = accBean.getPERSON_IDSEQ(); String orgID = accBean.getORG_IDSEQ(); if ((perID != null && !perID.equals("")) || (orgID != null && !orgID.equals(""))) { GetACSearch getAC = new GetACSearch(req, res, this); Vector<AC_COMM_Bean> vComm = getAC.getContactComm("", orgID, perID); if (vComm == null) vComm = new Vector<AC_COMM_Bean>(); accBean.setACC_COMM_List(vComm); Vector<AC_ADDR_Bean> vAddr = getAC.getContactAddr("", orgID, perID); if (vAddr == null) vAddr = new Vector<AC_ADDR_Bean>(); accBean.setACC_ADDR_List(vAddr); } } // adding comm attributes to com bean else if (sPgAct.indexOf("Comm") > -1) accBean = this.doContCommAction(req, accBean, sPgAct); // adding comm attributes to com bean else if (sPgAct.indexOf("Addr") > -1) accBean = this.doContAddrAction(req, accBean, sPgAct); // store contact changes with all contacts as new or update else if (sPgAct.equals("updContact")) { sContAct = "doContactUpd"; String sMsg = "Contact Information updated successfully, \\n" + "but will not be associated to the Administered Component (AC) \\n" + "or written to the database until the AC has been successfully submitted."; DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, sMsg); } // store the acc bean in teh request (sends back empty if new action) DataManager.setAttribute(session, "selACContact", accBean); req.setAttribute("ContAction", sContAct); } catch (Exception e) { logger.fatal("Error - doContactEditActions : " + e.toString(), e); } } ForwardJSP(req, res, "/EditACContact.jsp"); } /** * Contact communication change actions * * @param req * HttpServletRequest * @param ACBean * AC_CONTACT_Bean * @param sAct * String communication action * @return AC_CONTACT_Bean */ private AC_CONTACT_Bean doContCommAction(HttpServletRequest req, AC_CONTACT_Bean ACBean, String sAct) { try { Vector<AC_COMM_Bean> vComm = ACBean.getACC_COMM_List(); if (vComm == null) vComm = new Vector<AC_COMM_Bean>(); AC_COMM_Bean commB = new AC_COMM_Bean(); int selInd = -1; for (int j = 0; j < vComm.size(); j++) // loop through existing lists { String rSel = (String) req.getParameter("com" + j); // check if this id is selected if (rSel != null) { commB = commB.copyComms((AC_COMM_Bean) vComm.elementAt(j)); selInd = j; break; } } // System.out.println(selInd + " commAct " + sAct); // if editComm action set comm bean in teh request and return back if (sAct.equals("editComm") && selInd > -1) { req.setAttribute("CommForEdit", commB); req.setAttribute("CommCheckForEdit", "com" + selInd); return ACBean; } // handle remove or add selection actions if (commB == null) commB = new AC_COMM_Bean(); if (sAct.equals("removeComm")) // remove the item and exit commB.setCOMM_SUBMIT_ACTION("DEL"); else if (sAct.equals("addComm")) // udpate or adding new { // get the attributes from the page String cType = (String) req.getParameter("selCommType"); if (cType == null) cType = ""; String cOrd = (String) req.getParameter("comOrder"); if (cOrd == null) cOrd = ""; String cCyber = (String) req.getParameter("comCyber"); if (cCyber == null) cCyber = ""; String sCommName = cType + "_" + cOrd + "_" + cCyber; // check these attributes already exist in the list boolean wasDeleted = false; for (int k = 0; k < vComm.size(); k++) { AC_COMM_Bean exComm = (AC_COMM_Bean) vComm.elementAt(k); String ct = exComm.getCTL_NAME(); if (ct == null) ct = ""; String cc = exComm.getCYBER_ADDR(); if (cc == null) cc = ""; String co = exComm.getRANK_ORDER(); // leave this for now till confirmed if (co == null) co = ""; String exCommName = cType + "_" + cOrd + "_" + cCyber; if (sCommName.equals(exCommName)) { // allow to create duplicates but undelete if it was deleted String exSubmit = commB.getCOMM_SUBMIT_ACTION(); if (exSubmit != null && exSubmit.equals("DEL")) { wasDeleted = true; commB = commB.copyComms((AC_COMM_Bean) vComm.elementAt(k)); if (commB.getAC_COMM_IDSEQ() == null || commB.getAC_COMM_IDSEQ().equals(exCommName)) commB.setCOMM_SUBMIT_ACTION("INS"); else commB.setCOMM_SUBMIT_ACTION("UPD"); selInd = k; // reset the index } break; } } // update or add new attributes if was not deleted if (!wasDeleted) { commB.setCTL_NAME(cType); commB.setRANK_ORDER(cOrd); commB.setCYBER_ADDR(cCyber); if (selInd > -1) commB.setCOMM_SUBMIT_ACTION("UPD"); else commB.setCOMM_SUBMIT_ACTION("INS"); } } // set the vector if (selInd > -1) vComm.setElementAt(commB, selInd); else vComm.addElement(commB); ACBean.setACC_COMM_List(vComm); // set the bean } catch (Exception e) { logger.fatal("Error - doContCommAction : " + e.toString(), e); } return ACBean; } /** * Contact address change action * * @param req * HttpServletRequest * @param ACBean * AC_CONTACT_Bean * @param sAct * String address edit action * @return AC_CONTACT_Bean */ private AC_CONTACT_Bean doContAddrAction(HttpServletRequest req, AC_CONTACT_Bean ACBean, String sAct) { try { Vector<AC_ADDR_Bean> vAddr = ACBean.getACC_ADDR_List(); if (vAddr == null) vAddr = new Vector<AC_ADDR_Bean>(); AC_ADDR_Bean addrB = new AC_ADDR_Bean(); int selInd = -1; for (int j = 0; j < vAddr.size(); j++) // loop through existing lists { String rSel = (String) req.getParameter("addr" + j); // check if this id is selected if (rSel != null) { addrB = addrB.copyAddress((AC_ADDR_Bean) vAddr.elementAt(j)); selInd = j; break; } } // System.out.println(selInd + " addrAct " + sAct); // if editAddr action set addr bean in teh request and return back if (sAct.equals("editAddr") && selInd > -1) { req.setAttribute("AddrForEdit", addrB); req.setAttribute("AddrCheckForEdit", "addr" + selInd); return ACBean; } // handle remove or add selection actions if (addrB == null) addrB = new AC_ADDR_Bean(); if (sAct.equals("removeAddr")) // remove the item and exit addrB.setADDR_SUBMIT_ACTION("DEL"); else if (sAct.equals("addAddr")) // udpate or adding new { // get the attributes from the page String aType = (String) req.getParameter("selAddrType"); if (aType == null) aType = ""; String aOrd = (String) req.getParameter("txtPrimOrder"); if (aOrd == null) aOrd = ""; String aAddr1 = (String) req.getParameter("txtAddr1"); if (aAddr1 == null) aAddr1 = ""; String aAddr2 = (String) req.getParameter("txtAddr2"); if (aAddr2 == null) aAddr2 = ""; String aCity = (String) req.getParameter("txtCity"); if (aCity == null) aCity = ""; String aState = (String) req.getParameter("txtState"); if (aState == null) aState = ""; String aCntry = (String) req.getParameter("txtCntry"); if (aCntry == null) aCntry = ""; String aPost = (String) req.getParameter("txtPost"); if (aPost == null) aPost = ""; String selAddrName = aType + "_" + aOrd + "_" + aAddr1 + "_" + aAddr2 + "_" + aCity + "_" + aState + "_" + aCntry + "_" + aPost; // check these attributes already exist in the list boolean wasDeleted = false; for (int k = 0; k < vAddr.size(); k++) { AC_ADDR_Bean exAddr = (AC_ADDR_Bean) vAddr.elementAt(k); String at = exAddr.getATL_NAME(); if (at == null) at = ""; String ao = exAddr.getRANK_ORDER(); if (ao == null) ao = ""; String aA1 = exAddr.getADDR_LINE1(); if (aA1 == null) aA1 = ""; String aA2 = exAddr.getADDR_LINE2(); if (aA2 == null) aA2 = ""; String aCy = exAddr.getCITY(); if (aCy == null) aCy = ""; String aS = exAddr.getSTATE_PROV(); if (aS == null) aS = ""; String aCny = exAddr.getCOUNTRY(); if (aCny == null) aCny = ""; String aP = exAddr.getPOSTAL_CODE(); if (aP == null) aP = ""; String exAddrName = at + "_" + ao + "_" + aA1 + "_" + aA2 + "_" + aCy + "_" + aS + "_" + aCny + "_" + aP; // compare the two to check if exists if (selAddrName.equals(exAddrName)) { // allow to create duplicates but undelete if it was deleted String exSubmit = addrB.getADDR_SUBMIT_ACTION(); if (exSubmit != null && exSubmit.equals("DEL")) { wasDeleted = true; addrB = addrB.copyAddress((AC_ADDR_Bean) vAddr.elementAt(k)); if (addrB.getAC_ADDR_IDSEQ() == null || addrB.getAC_ADDR_IDSEQ().equals(exAddrName)) addrB.setADDR_SUBMIT_ACTION("INS"); else addrB.setADDR_SUBMIT_ACTION("UPD"); selInd = k; // reset the index } break; } } // update or add new attributes if was not deleted if (!wasDeleted) { addrB.setATL_NAME(aType); addrB.setRANK_ORDER(aOrd); addrB.setADDR_LINE1(aAddr1); addrB.setADDR_LINE2(aAddr2); addrB.setCITY(aCity); addrB.setSTATE_PROV(aState); addrB.setCOUNTRY(aCntry); addrB.setPOSTAL_CODE(aPost); if (selInd > -1) addrB.setADDR_SUBMIT_ACTION("UPD"); else addrB.setADDR_SUBMIT_ACTION("INS"); } } // set the vector if (selInd > -1) vAddr.setElementAt(addrB, selInd); else vAddr.addElement(addrB); ACBean.setACC_ADDR_List(vAddr); // set the bean } catch (Exception e) { logger.fatal("Error - doContAddrAction : " + e.toString(), e); } return ACBean; } /** * to get Protocol CRF for the selected ac called when the ProtoCRF window opened first time and calls * 'getAC.doProtoCRFSearch' forwards page back to ProtoCRFwindow jsp * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doProtoCRFSearchActions(HttpServletRequest req, HttpServletResponse res) throws Exception { GetACSearch getAC = new GetACSearch(req, res, this); String acID = req.getParameter("acID"); String acName = req.getParameter("itemType"); // ac name for proto crf if (acName != null && acName.equals("ALL")) acName = "-"; @SuppressWarnings("unused") Integer pvCount = getAC.doProtoCRFSearch(acID, acName); ForwardJSP(req, res, "/ProtoCRFWindow.jsp"); } /** * Monitor the user selected items with a Sentinel Alert. * * @param req * The session request. * @param res * The session response. */ protected void doMonitor(HttpServletRequest req, HttpServletResponse res) { // Init main variables. HttpSession session = req.getSession(); String msg = null; Vector<String> vCheckList = new Vector<String>(); while (true) { // Be sure something was selected by the user. Vector vSRows = (Vector) session.getAttribute("vSelRows"); if (vSRows == null || vSRows.size() == 0) { msg = "No items were selected from the Search Results."; break; } // Get session information. UserBean Userbean = new UserBean(); Userbean = (UserBean) session.getAttribute("Userbean"); if (Userbean == null) { msg = "User session information is missing."; break; } CallableStatement stmt = null; try { // Get the selected items and associate each with the appropriate CSI String user = Userbean.getUsername(); user = user.toUpperCase(); // Add the selected items to the CSI String csi_idseq = null; int ndx = 0; stmt = m_conn.prepareCall("begin SBREXT_CDE_CURATOR_PKG.ADD_TO_SENTINEL_CS(?,?,?); end;"); stmt.registerOutParameter(3, java.sql.Types.VARCHAR); stmt.setString(2, user); try { vCheckList = new Vector<String>(); for (ndx = 0; ndx < vSRows.size(); ++ndx) { String temp; String ckName = ("CK" + ndx); temp = req.getParameter(ckName); if (temp != null) { AC_Bean bean = (AC_Bean) vSRows.elementAt(ndx); temp = bean.getIDSEQ(); stmt.setString(1, temp); stmt.execute(); temp = stmt.getString(3); vCheckList.addElement(ckName); if (temp != null) csi_idseq = temp; } } DataManager.setAttribute(session, "CheckList", vCheckList); // add the check list in the session. } catch (ClassCastException e) { // This happens when the selected element does not extend the AC_Bean abstract class. csi_idseq = ""; } if (csi_idseq == null) { msg = "None of the selected items can be added to your Reserved CSI."; } else if (csi_idseq.length() == 0) { msg = "The selected items are not supported for the Monitor feature."; } else { // Have the Sentinel watch the CSI. DSRAlert sentinel = DSRAlertImpl.factory(m_conn); ndx = sentinel.createAlert(user, csi_idseq); switch (ndx) { case DSRAlert.RC_FAILED: msg = "An error occurred attempting to create the Alert Definition."; break; case DSRAlert.RC_INCOMPATIBLE: msg = "The Sentinel API server does not support this request."; break; case DSRAlert.RC_UNAUTHORIZED: msg = "You are not authorized to create a Sentinel Alert."; break; default: String itemTxt = (vSRows.size() == 1) ? "item is" : "items are"; msg = "The selected " + itemTxt + " now monitored by the Alert Definition \"" + sentinel.getAlertName() + "\""; msg = msg.replaceAll("[\"]", "\\\\\""); break; } } } catch (Exception e) { msg = "An unexpected exception occurred, please notify the Help Desk. Details have been written to the log."; logger.fatal("cdecurate: doMonitor(): " + e.toString(), e); } finally{ SQLHelper.closeCallableStatement(stmt); } break; } // Send the message back to the user. GetACSearch getACSearch = new GetACSearch(req, res, this); getACSearch.getACShowResult2(req, res, "Monitor"); DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, msg); ForwardJSP(req, res, "/SearchResultsPage.jsp"); } /** * Unmonitor the user selected items with a Sentinel Alert. * * @param req * The session request. * @param res * The session response. */ protected void doUnmonitor(HttpServletRequest req, HttpServletResponse res) { // Init main variables. HttpSession session = req.getSession(); String msg = null; Vector<String> vCheckList = new Vector<String>(); while (true) { // Be sure something was selected by the user. Vector vSRows = (Vector) session.getAttribute("vSelRows"); if (vSRows == null || vSRows.size() == 0) { msg = "No items were selected from the Search Results."; break; } // Get session information. UserBean Userbean = new UserBean(); Userbean = (UserBean) session.getAttribute("Userbean"); if (Userbean == null) { msg = "User session information is missing."; break; } // Get list of selected AC's. Vector<String> list = new Vector<String>(); for (int ndx = 0; ndx < vSRows.size(); ++ndx) { try { String temp; String ckName = ("CK" + ndx); temp = req.getParameter(ckName); if (temp != null) { AC_Bean bean = (AC_Bean) vSRows.elementAt(ndx); temp = bean.getIDSEQ(); list.add(temp); vCheckList.addElement(ckName); } } catch (ClassCastException e) { } } DataManager.setAttribute(session, "CheckList", vCheckList); // add the check list in the session. if (list.size() == 0) { msg = "None of the selected AC's were previously Monitored."; break; } // Update the database - remove the CSI association to the AC's. String user = Userbean.getUsername(); user = user.toUpperCase(); CallableStatement stmt=null; for (int ndx = 0; ndx < list.size(); ++ndx) { try { String temp = list.elementAt(ndx); stmt = m_conn.prepareCall("begin SBREXT_CDE_CURATOR_PKG.REMOVE_FROM_SENTINEL_CS('" + temp + "','" + user + "'); END;"); stmt.execute(); SQLHelper.closeCallableStatement(stmt); msg = "The selected item is no longer monitored by the Alert Definition"; } catch (Exception e) { msg = "An unexpected exception occurred, please notify the Help Desk. Details have been written to the log."; logger.fatal("cdecurate: doUnmonitor(): " + e.toString(), e); }finally{ SQLHelper.closeCallableStatement(stmt); } } break; } // Send the message back to the user. GetACSearch getACSearch = new GetACSearch(req, res, this); getACSearch.getACShowResult2(req, res, "Monitor"); DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, msg); ForwardJSP(req, res, "/SearchResultsPage.jsp"); } /** * The doRefreshPVSearchPage method forwards crfValue search page with refreshed list updates the quest value bean * with searched/created pv data, * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @param m_PV * PV_Bean searched/created pv data * @param Origin * String origin of the action * * @throws Exception */ public void doRefreshPVSearchPage(HttpServletRequest req, HttpServletResponse res, PV_Bean m_PV, String Origin) throws Exception { HttpSession session = req.getSession(); if (Origin.equals("CreateNew")) { DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, "Value created and inserted successfully."); Vector<String> vNewPV = new Vector<String>(); vNewPV.addElement(m_PV.getPV_PV_IDSEQ()); vNewPV.addElement(m_PV.getPV_VALUE()); vNewPV.addElement(m_PV.getPV_SHORT_MEANING()); req.setAttribute("newPVData", vNewPV); } // get the selected pv data from the request else { // using designation hidden fields to get the selected value & meanings String sPVID = (String) req.getParameter("desName"); if (sPVID != null) m_PV.setPV_PV_IDSEQ(sPVID); String sPValue = (String) req.getParameter("desContext"); if (sPValue != null) m_PV.setPV_VALUE(sPValue); String sPVMean = (String) req.getParameter("desContextID"); if (sPVMean != null) m_PV.setPV_SHORT_MEANING(sPVMean); } // forwards the page to regular pv search if not questions String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); if (Origin.equals("CreateNew") && !sMenuAction.equals("Questions")) ForwardJSP(req, res, "/OpenSearchWindow.jsp"); else { // get the selected crf value and update its attribute with the selected/created pvvalue String selCRFValue = (String) session.getAttribute("selCRFValueID"); if (selCRFValue != null) { // get the crf value vector to update Vector vQuestValue = (Vector) session.getAttribute("vQuestValue"); if (vQuestValue != null) { for (int i = 0; i < (vQuestValue.size()); i++) { Quest_Value_Bean QuestValueBean = new Quest_Value_Bean(); QuestValueBean = (Quest_Value_Bean) vQuestValue.elementAt(i); // update the quest bean with the new value meaning if (QuestValueBean.getQUESTION_VALUE_IDSEQ().equalsIgnoreCase(selCRFValue)) { QuestValueBean.setPERM_VALUE_IDSEQ(m_PV.getPV_PV_IDSEQ()); QuestValueBean.setPERMISSIBLE_VALUE(m_PV.getPV_VALUE()); QuestValueBean.setVALUE_MEANING(m_PV.getPV_SHORT_MEANING()); break; } } DataManager.setAttribute(session, "vQuestValue", vQuestValue); } } ForwardJSP(req, res, "/CRFValueSearchWindow.jsp"); } } /** * gets the selected row from the search result to forward the data. Called from 'doSearchResultsAction' method * where actType is 'edit' calls 'getACSearch.getSelRowToEdit' method to get the row bean. if user doesn't have * permission to write to the selected context goes back to search page. otherwise forwards to create/edit pages for * the selected component. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ protected void doSearchSelectionAction(HttpServletRequest req, HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); String sSearchAC = (String) session.getAttribute("searchAC"); // get the selected component CurationServlet acServlet = getACServlet(sSearchAC); // gets the bean for the row selected GetACSearch getACSearch = new GetACSearch(req, res, acServlet); if (getACSearch.getSelRowToEdit(req, res, "") == false) ForwardJSP(req, res, "/SearchResultsPage.jsp"); else { // String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); // get the selected // menu action // String sButtonPressed = (String) session.getAttribute("LastMenuButtonPressed"); // String sOriginAction = (String) session.getAttribute("sOriginAction"); // call method to handle DE actions. if (sSearchAC.equals("DataElement")) this.doSerSelectActDE(req, res); else if (sSearchAC.equals("DataElementConcept")) this.doSerSelectActDEC(req, res); else if (sSearchAC.equals("ValueDomain")) this.doSerSelectActVD(req, res); else if (sSearchAC.equals("ValueMeaning")) this.doSerSelectActVM(req, res); else if (sSearchAC.equals("Questions")) { // DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, ""); // get status indicatior from the quest bean Quest_Bean QuestBean = (Quest_Bean) session.getAttribute("m_Quest"); String sStatus = QuestBean.getSTATUS_INDICATOR(); // forward the page to createDE if new or existing or to edit page if edit if (sStatus.equals("Edit")) ForwardJSP(req, res, "/EditDEPage.jsp"); else ForwardJSP(req, res, "/CreateDEPage.jsp"); } else { DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, "Unable to open the Create or Edit page.\n" + "Please try again."); ForwardJSP(req, res, "/SearchResultsPage.jsp"); } } } /** * gets the selected row from the search result to forward the data. Called from 'doSearchResultsAction' method * where actType is 'edit' calls 'getACSearch.getSelRowToEdit' method to get the row bean. if user doesn't have * permission to write to the selected context goes back to search page. otherwise forwards to create/edit pages for * the selected component. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ protected void doSearchSelectionBEAction() throws Exception { HttpSession session = m_classReq.getSession(); // gets the bean for the row selected GetACSearch getACSearch = new GetACSearch(m_classReq, m_classRes, this); if (getACSearch.getSelRowToEdit(m_classReq, m_classRes, "BlockEdit") == false) ForwardJSP(m_classReq, m_classRes, "/SearchResultsPage.jsp"); else { // String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); // get the selected // menu action String sSearchAC = (String) session.getAttribute("searchAC"); // get the selected component // String sButtonPressed = (String) session.getAttribute("LastMenuButtonPressed"); if (sSearchAC.equals("DataElement")) { // open the edit page DE_Bean DEBean = (DE_Bean) session.getAttribute("m_DE"); DEBean.setDE_DEC_IDSEQ(""); DEBean.setDE_DEC_NAME(""); DEBean.setDE_VD_IDSEQ(""); DEBean.setDE_VD_NAME(""); DataManager.setAttribute(session, "m_DE", DEBean); // users need cs-csi to view DataManager.setAttribute(session, "originAction", "BlockEditDE"); DataManager.setAttribute(session, "DEEditAction", ""); ForwardJSP(m_classReq, m_classRes, "/EditDEPage.jsp"); } else if (sSearchAC.equals("DataElementConcept")) { DataManager.setAttribute(session, "originAction", "BlockEditDEC"); this.clearBuildingBlockSessionAttributes(m_classReq, m_classRes); ForwardJSP(m_classReq, m_classRes, "/EditDECPage.jsp"); } else if (sSearchAC.equals("ValueDomain")) { DataManager.setAttribute(session, "vRepTerm", null); DataManager.setAttribute(session, "newRepTerm", ""); DataManager.setAttribute(session, "originAction", "BlockEditVD"); ForwardJSP(m_classReq, m_classRes, "/EditVDPage.jsp"); } else { DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, "Unable to open the Create or Edit page.\\n" + "Please try again."); ForwardJSP(m_classReq, m_classRes, "/SearchResultsPage.jsp"); } } } /** * get the definition property from the setting * * @return the DEDefinition value */ public String getPropertyDefinition() { return NCICurationServlet.m_settings.getProperty("DEDefinition"); } /** * does the search selection action for the Data element search forward the page according to the action * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doSerSelectActDE(HttpServletRequest req, HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); // get the selected menu // action String sButtonPressed = (String) session.getAttribute("LastMenuButtonPressed"); // make sure the menu action is for DE, set it otherwise if (sMenuAction.equalsIgnoreCase("NewDECTemplate") || (sMenuAction.equalsIgnoreCase("NewVDTemplate"))) sMenuAction = "NewDETemplate"; else if (sMenuAction.equalsIgnoreCase("NewDECVersion") || (sMenuAction.equalsIgnoreCase("NewVDVersion"))) sMenuAction = "NewDEVersion"; else if (sMenuAction.equalsIgnoreCase("editDEC") || (sMenuAction.equalsIgnoreCase("editVD"))) sMenuAction = "editDE"; // set the menuaction session attribute DataManager.setAttribute(session, Session_Data.SESSION_MENU_ACTION, sMenuAction); // forward to create DE page if template or version if ((sMenuAction.equals("NewDETemplate")) || (sMenuAction.equals("NewDEVersion"))) { // DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, ""); DataManager.setAttribute(session, "sCDEAction", "validate"); ForwardJSP(req, res, "/CreateDEPage.jsp"); DataManager.setAttribute(session, "originAction", "NewDE"); } // forward to edit DE page if editing else if (sMenuAction.equals("editDE") || sMenuAction.equals("nothing")) { DataManager.setAttribute(session, "originAction", "EditDE"); ForwardJSP(req, res, "/EditDEPage.jsp"); } else if (sButtonPressed.equals("Search")) { DataManager.setAttribute(session, "originAction", "EditDE"); ForwardJSP(req, res, "/EditDEPage.jsp"); } else { DataManager.setAttribute(session, "originAction", "EditDE"); DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, "Unable to open the Create or Edit page.\\n" + "Please try again."); ForwardJSP(req, res, "/SearchResultsPage.jsp"); } } /** * does the search selection action for the Data element concept search forward the page according to the action * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doSerSelectActDEC(HttpServletRequest req, HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); // get the selected menu // action String sButtonPressed = (String) session.getAttribute("LastMenuButtonPressed"); // make sure the menu action is for DEC, set it otherwise if (sMenuAction.equalsIgnoreCase("NewDETemplate") || (sMenuAction.equalsIgnoreCase("NewVDTemplate"))) sMenuAction = "NewDECTemplate"; else if (sMenuAction.equalsIgnoreCase("NewDEVersion") || (sMenuAction.equalsIgnoreCase("NewVDVersion"))) sMenuAction = "NewDECVersion"; else if (sMenuAction.equalsIgnoreCase("editDE") || (sMenuAction.equalsIgnoreCase("editVD"))) sMenuAction = "editDEC"; // set the menuaction session attribute DataManager.setAttribute(session, Session_Data.SESSION_MENU_ACTION, sMenuAction); // forward to create DEC page if template or version if ((sMenuAction.equals("NewDECTemplate")) || (sMenuAction.equals("NewDECVersion"))) { DataManager.setAttribute(session, "DECPageAction", "validate"); ForwardJSP(req, res, "/CreateDECPage.jsp"); // DataManager.setAttribute(session, "originAction", "NewDEC"); } // forward to edit DEC page if editing else if (sMenuAction.equals("editDEC") || sMenuAction.equals("nothing")) { DataManager.setAttribute(session, "originAction", "EditDEC"); ForwardJSP(req, res, "/EditDECPage.jsp"); } else if (sButtonPressed.equals("Search")) { DataManager.setAttribute(session, "originAction", "EditDEC"); ForwardJSP(req, res, "/EditDECPage.jsp"); } else { DataManager.setAttribute(session, "originAction", "EditDEC"); DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, "Unable to open the Create or Edit page.\\n" + "Please try again."); ForwardJSP(req, res, "/SearchResultsPage.jsp"); } } /** * does the search selection action for the Value Domain search forward the page according to the action * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doSerSelectActVD(HttpServletRequest req, HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); // get the selected menu // action String sButtonPressed = (String) session.getAttribute("LastMenuButtonPressed"); // make sure the menu action is for DE, set it otherwise if (sMenuAction.equalsIgnoreCase("NewDETemplate") || (sMenuAction.equalsIgnoreCase("NewDECTemplate"))) sMenuAction = "NewVDTemplate"; else if (sMenuAction.equalsIgnoreCase("NewDEVersion") || (sMenuAction.equalsIgnoreCase("NewDECVersion"))) sMenuAction = "NewVDVersion"; else if (sMenuAction.equalsIgnoreCase("editDE") || (sMenuAction.equalsIgnoreCase("editDEC"))) sMenuAction = "editVD"; // set the menuaction session attribute DataManager.setAttribute(session, Session_Data.SESSION_MENU_ACTION, sMenuAction); // forward to create VD page if template or version if ((sMenuAction.equals("NewVDTemplate")) || (sMenuAction.equals("NewVDVersion"))) { DataManager.setAttribute(session, "VDPageAction", "validate"); ForwardJSP(req, res, "/CreateVDPage.jsp"); DataManager.setAttribute(session, "originAction", "NewVD"); } // forward to edit VD page if editing else if (sMenuAction.equals("editVD") || sMenuAction.equals("nothing")) { DataManager.setAttribute(session, "originAction", "EditVD"); ForwardJSP(req, res, "/EditVDPage.jsp"); } else if (sButtonPressed.equals("Search")) { DataManager.setAttribute(session, "originAction", "EditVD"); ForwardJSP(req, res, "/EditVDPage.jsp"); } else { DataManager.setAttribute(session, "originAction", "EditVD"); DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, "Unable to open the Create or Edit page.\\n" + "Please try again."); ForwardJSP(req, res, "/SearchResultsPage.jsp"); } } /** * does the search selection action for the Value Meaning search forward the page according to the action * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doSerSelectActVM(HttpServletRequest req, HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); // get the selected menu // action String sButtonPressed = (String) session.getAttribute("LastMenuButtonPressed"); // make sure the menu action is for DE, set it otherwise if (sMenuAction.equalsIgnoreCase("NewDETemplate") || (sMenuAction.equalsIgnoreCase("NewDECTemplate"))) sMenuAction = "NewVMTemplate"; else if (sMenuAction.equalsIgnoreCase("NewDEVersion") || (sMenuAction.equalsIgnoreCase("NewDECVersion"))) sMenuAction = "NewVMVersion"; else if (sMenuAction.equalsIgnoreCase("editDE") || (sMenuAction.equalsIgnoreCase("editDEC"))) sMenuAction = "editVM"; // set the menuaction session attribute DataManager.setAttribute(session, Session_Data.SESSION_MENU_ACTION, sMenuAction); // forward to create VM page if template or version if ((sMenuAction.equals("NewVMTemplate")) || (sMenuAction.equals("NewVMVersion"))) { DataManager.setAttribute(session, "VMPageAction", "validate"); ForwardJSP(req, res, "/CreateVMPage.jsp"); DataManager.setAttribute(session, "originAction", "NewVM"); } // forward to edit VM page if editing else if (sMenuAction.equals("editVM") || sMenuAction.equals("nothing")) { DataManager.setAttribute(session, "originAction", "EditVM"); ForwardJSP(req, res, "/ValueMeaningDetail.jsp"); } else if (sButtonPressed.equals("Search")) { DataManager.setAttribute(session, "originAction", "EditVM"); ForwardJSP(req, res, "/ValueMeaningDetail.jsp"); } else { DataManager.setAttribute(session, "originAction", "EditVM"); DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, "Unable to open the Create or Edit page.\\n" + "Please try again."); ForwardJSP(req, res, "/SearchResultsPage.jsp"); } } /** * stores status message in the session * @param sMsg string message to append to. */ @SuppressWarnings("unchecked") public void storeStatusMsg(String sMsg) { try { HttpSession session = m_classReq.getSession(); UtilService util = new UtilService(); Vector<String> vStatMsg = (Vector)session.getAttribute("vStatMsg"); String statusMsg = (String)session.getAttribute(Session_Data.SESSION_STATUS_MESSAGE); if (statusMsg == null) statusMsg = ""; //parse single double quotes and new line char if any String alrtMsg = sMsg; if (!alrtMsg.equalsIgnoreCase("\\n")) alrtMsg = util.parsedStringAlertNewLine(alrtMsg); alrtMsg = util.parsedStringDoubleQuote(alrtMsg); alrtMsg = util.parsedStringSingleQuote(alrtMsg); if (vStatMsg == null) vStatMsg = new Vector<String>(); //add message to both to string status message and vector stats message if not too big if (vStatMsg.size() < 35) { if (sMsg.equalsIgnoreCase("\\n")) statusMsg = statusMsg + alrtMsg; else statusMsg = statusMsg + alrtMsg + "\\n"; DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, statusMsg); } //remove tab and newline from the msg for vector if (!sMsg.equalsIgnoreCase("\\n") && !sMsg.equalsIgnoreCase("\n")) sMsg = util.parsedStringMsgVectorTabs(sMsg, vStatMsg); if (!sMsg.equals("")) vStatMsg.addElement(sMsg); DataManager.setAttribute(session, "vStatMsg", vStatMsg); //add this message to the logger logger.info("Log Status Message " + sMsg); } catch(Exception e) { logger.fatal("ERROR in CurationServlet-storeStatusMsg for exception : " + e.toString(), e); // m_classReq.setAttribute("retcode", "Message Exception"); } } /** * To clear session attributes when a main Menu button/item is selected. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @throws Exception */ protected void clearSessionAttributes(HttpServletRequest req, @SuppressWarnings("unused") HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); DataManager.setAttribute(session, "vSearchIDStack", null); DataManager.setAttribute(session, "SearchID", null); DataManager.setAttribute(session, "vSearchNameStack", null); DataManager.setAttribute(session, "SearchName", null); DataManager.setAttribute(session, "sSearchACStack", null); DataManager.setAttribute(session, "vACSearchStack", null); DataManager.setAttribute(session, "vSearchASLStack", null); DataManager.setAttribute(session, "vACSearch", null); DataManager.setAttribute(session, "vSelRowsStack", null); DataManager.setAttribute(session, "vResultStack", null); DataManager.setAttribute(session, "vCompAttrStack", null); DataManager.setAttribute(session, "backFromGetAssociated", ""); DataManager.setAttribute(session, "GetAssocSearchAC", ""); DataManager.setAttribute(session, "results", null); DataManager.setAttribute(session, "vSelRows", null); DataManager.setAttribute(session, "selCS", ""); DataManager.setAttribute(session, "serSelectedCD", ""); // parent concept for the VD // DataManager.setAttribute(session, "VDParentConcept", new Vector()); DataManager.setAttribute(session, "vParentList", null); DataManager.setAttribute(session, "vParentNames", null); DataManager.setAttribute(session, "vParentCodes", null); DataManager.setAttribute(session, "vParentDB", null); DataManager.setAttribute(session, "vParentMetaSource", null); DataManager.setAttribute(session, "SelectedParentName", ""); DataManager.setAttribute(session, "SelectedParentCC", ""); DataManager.setAttribute(session, "SelectedParentDB", ""); DataManager.setAttribute(session, "ParentMetaSource", null); // pv list for the vd // DataManager.setAttribute(session, "VDPVList", new Vector()); // DataManager.setAttribute(session, "PVIDList", new Vector()); DataManager.setAttribute(session, "m_OC", null); DataManager.setAttribute(session, "selObjRow", null); DataManager.setAttribute(session, "m_PC", null); DataManager.setAttribute(session, "selPropRow", null); DataManager.setAttribute(session, "vObjectClass", null); DataManager.setAttribute(session, "vProperty", null); DataManager.setAttribute(session, "m_DEC", null); DataManager.setAttribute(session, "m_REP", null); DataManager.setAttribute(session, "selRepRow", null); DataManager.setAttribute(session, "m_OCQ", null); DataManager.setAttribute(session, "selObjQRow", null); DataManager.setAttribute(session, "m_PCQ", null); DataManager.setAttribute(session, "selPropQRow", null); DataManager.setAttribute(session, "m_REPQ", null); DataManager.setAttribute(session, "selRepQRow", null); DataManager.setAttribute(session, "creKeyword", ""); DataManager.setAttribute(session, "serKeyword", ""); DataManager.setAttribute(session, "EVSresults", null); DataManager.setAttribute(session, "VDEditAction", null); DataManager.setAttribute(session, "DEEditAction", null); DataManager.setAttribute(session, "DECEditAction", null); DataManager.setAttribute(session, "ParentConceptCode", null); DataManager.setAttribute(session, "VMForm.SESSION_RET_PAGE", null); // DataManager.setAttribute(session, "OpenTreeToConcept", ""); } /** * To clear session attributes when a main Menu button/item is selected. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @throws Exception */ public void clearBuildingBlockSessionAttributes(HttpServletRequest req, @SuppressWarnings("unused") HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); DataManager.setAttribute(session, "m_OC", null); DataManager.setAttribute(session, "selObjRow", null); DataManager.setAttribute(session, "m_PC", null); DataManager.setAttribute(session, "selPropRow", null); DataManager.setAttribute(session, "vObjResults", null); DataManager.setAttribute(session, "vPropResults", null); DataManager.setAttribute(session, "vRepResults", null); DataManager.setAttribute(session, "m_REP", null); DataManager.setAttribute(session, "selRepRow", null); DataManager.setAttribute(session, "vObjQResults", null); DataManager.setAttribute(session, "m_OCQ", null); DataManager.setAttribute(session, "selObjQRow", null); DataManager.setAttribute(session, "vPropQResults", null); DataManager.setAttribute(session, "m_PCQ", null); DataManager.setAttribute(session, "selPropQRow", null); DataManager.setAttribute(session, "vRepQResults", null); DataManager.setAttribute(session, "m_REPQ", null); DataManager.setAttribute(session, "selRepQRow", null); DataManager.setAttribute(session, "vObjectClass", null); DataManager.setAttribute(session, "newObjectClass", ""); DataManager.setAttribute(session, "RemoveOCBlock", ""); DataManager.setAttribute(session, "vProperty", null); DataManager.setAttribute(session, "newProperty", ""); DataManager.setAttribute(session, "RemovePropBlock", ""); DataManager.setAttribute(session, "vRepTerm", null); DataManager.setAttribute(session, "newRepTerm", ""); DataManager.setAttribute(session, "ConceptLevel", "0"); DataManager.setAttribute(session, "creMetaCodeSearch", null); DataManager.setAttribute(session, "creKeyword", ""); DataManager.setAttribute(session, "serKeyword", ""); DataManager.setAttribute(session, "EVSresults", null); DataManager.setAttribute(session, "ParentMetaSource", null); DataManager.setAttribute(session, "ParentConceptCode", null); } /** * To clear session attributes when a main Menu button/item is selected. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @throws Exception */ protected void clearCreateSessionAttributes(HttpServletRequest req, @SuppressWarnings("unused") HttpServletResponse res) throws Exception { HttpSession session = req.getSession(); // parent concept for the VD // DataManager.setAttribute(session, "VDParentConcept", new Vector()); DataManager.setAttribute(session, "SelectedParentName", ""); DataManager.setAttribute(session, "SelectedParentCC", ""); DataManager.setAttribute(session, "SelectedParentDB", ""); // pv list for the vd // DataManager.setAttribute(session, "VDPVList", new Vector()); DataManager.setAttribute(session, "PVIDList", new Vector()); DataManager.setAttribute(session, "creKeyword", ""); DataManager.setAttribute(session, "serKeyword", ""); DataManager.setAttribute(session, "EVSresults", null); DataManager.setAttribute(session, "OpenTreeToConcept", ""); DataManager.setAttribute(session, "labelKeyword", ""); // clear altname refdoc attributes after creating, editing, or back DataManager.setAttribute(session, "AllAltNameList", new Vector()); DataManager.setAttribute(session, "AllRefDocList", new Vector()); DataManager.setAttribute(session, "vACId", new Vector()); DataManager.setAttribute(session, "vACName", new Vector()); DataManager.setAttribute(session, "TabFocus", "VD"); // clear vm attribute DataManager.setAttribute(session, VMForm.SESSION_SELECT_VM, new VM_Bean()); } /** * This method forwards to an Error page. Called from 'service' method where reqType is 'actionFromMenu' forwards * page 'ErrorLoginPage.jsp'. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * */ public void ErrorLogin(HttpServletRequest req, HttpServletResponse res) { // capture the stack in logger try { throw new Exception("Error Login used in various methods"); } catch (Exception e) { logger.fatal("Error Caught : ", e); } // forward to error jsp try { ForwardErrorJSP(req, res, "Session Terminated. Please log in again."); } catch (Exception e) { // System.err.println("ERROR - ErrorLogin: " + e); this.logger.fatal("ERROR - ErrorLogin: " + e.toString(), e); } } /** * The destroy method closes a connection pool to db. */ public void destroy() { SQLHelper.closeConnection(m_conn); } /** * doLogout method closes the connection and forwards to Login page Called from Logout button on Titlebar.jsp * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * * @throws Exception */ private void doLogout(HttpServletRequest req, HttpServletResponse res) throws Exception { try { HttpSession session = req.getSession(); session.invalidate(); ForwardErrorJSP(req, res, "Logged out."); } catch (Exception e) { logger.fatal("ERROR - ErrorLogin: " + e.toString(), e); } } /** * The ForwardJSP method forwards to a jsp page. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @param sJSPPage * The JSP page to which to forward. */ public void ForwardJSP(HttpServletRequest req, HttpServletResponse res, String sJSPPage) { try { // forward to the jsp (or htm) HttpSession session = req.getSession(); String sMsg = (String) session.getAttribute(Session_Data.SESSION_STATUS_MESSAGE); if (sMsg != null && !sMsg.equals("")) { sMsg += "\\n\\nPlease use Ctrl+C to copy the message to a text file"; DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, sMsg); } // store the session data object in the session at the end of the request DataManager.setAttribute(session, Session_Data.CURATION_SESSION_ATTR, this.sessionData); String fullPage = "/jsp" + sJSPPage; // ServletContext sc = this.getServletContext(); RequestDispatcher rd = this.m_servletContext.getRequestDispatcher(fullPage); rd.forward(req, res); return; } catch (Exception e) { // e.printStackTrace(); this.logger.fatal("Servlet-ForwardJSP : " + e.toString(), e); } } /** * The ForwardErrorJSP method forwards to a jsp page. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @param errMsg * String error message * @throws Exception */ public void ForwardErrorJSP(HttpServletRequest req, HttpServletResponse res, String errMsg) throws Exception { try { HttpSession session; session = req.getSession(true); String fullPage = "/"; String reqMsg = (String) req.getAttribute("ReqErrorMessage"); if (reqMsg != null && !reqMsg.equals("")) errMsg = reqMsg; DataManager.setAttribute(session, "ErrorMessage", errMsg); if (!(errMsg).equals("Logged out.")) fullPage = "/jsp/ErrorPage.jsp"; //ServletContext sc = this.getServletContext(); RequestDispatcher rd = m_servletContext.getRequestDispatcher(fullPage); rd.forward(req, res); } catch (Exception e) { logger.fatal("Servlet-ForwardErrorJSP : " + e.toString(), e); } } /** * This is the primary method for handling requests from the Reference Document Attachments page. * * @param req * The HttpServletRequest from the client * @param res * The HttpServletResponse back to the client * @param sOrigin * The String controling weather this is a open action or other request type action */ protected void doRefDocumentUpload(HttpServletRequest req, HttpServletResponse res, String sOrigin) { String sAction; String msg = null; // HttpSession session = req.getSession(); RefDocAttachment refDocAt = new RefDocAttachment(req, res, this); msg = req.getContentType(); // upload file into the database as blob if (msg.startsWith("multipart/form-data")) { // file upload refDocAt.doFileUpload(); } else { // get action type if ((String) req.getParameter("newRefDocPageAction") != null) { sAction = (String) req.getParameter("newRefDocPageAction"); } else { sAction = "nothing"; } // Open the upload ref doc page if (sOrigin.equals("Open")) { refDocAt.doOpen(); } // Request from page to preform actions else if (sOrigin.equals("Request")) { // return to search results from upload page if (sAction.equals("backToSearch")) { refDocAt.doBack(); } // Delete ref doc attachment else if (sAction.equals("DeleteAttachment")) { refDocAt.doDeleteAttachment(); } // Catch any undefined action from page else { try { logger.fatal("Reference Document Attachments Upload: Unknown Request Type."); ForwardErrorJSP(req, res, "Unexpected Request. Session Terminated. Please login again."); } catch (Exception e) { logger.fatal("ERROR - ErrorLogin: " + e.toString(), e); } } } // catch unknown Ref type else { try { ForwardErrorJSP(req, res, "Unexpected Request. Session Terminated. Please login again."); logger.fatal("Reference Document Attachments Upload: Unknown Origin Type."); } catch (Exception e) { logger.fatal("ERROR - ErrorLogin: " + e.toString(), e); } } } } /** * @return the m_conn */ public Connection getConn() { return this.m_conn; } /** * @param m_conn the m_conn to set */ public void setConn(Connection conn) { this.m_conn = conn; } public void execute(ACRequestTypes reqType) throws Exception { System.out.println("curation servlet"); } public AC_Bean getACNames(EVS_Bean newBean, String nameAct, AC_Bean pageAC) { logger.debug("get name " + nameAct); return pageAC; } public AC_Bean getACNames(String nameAct, String origin, AC_Bean bean) { logger.debug("get name " + nameAct); return bean; } public AC_Bean getSystemName(AC_Bean ac, Vector<EVS_Bean> vParent) { logger.debug("get name "); return ac; } public CurationServlet getACServlet(String ac) { CurationServlet servObj = this; try { ACRequestTypes acrt = ACRequestTypes.valueOf(ac); if (acrt != null) { String className = acrt.getClassName(); servObj = (CurationServlet) Class.forName(className).newInstance(); servObj.init(m_classReq, m_classRes, this.m_servletContext); servObj.setConn(this.m_conn); servObj.sessionData = this.sessionData; } } catch (Exception e) { logger.error("Which AC " + e.toString()); } return servObj; } } // end of class
added the conceptclass create req type SVN-Revision: 839
src/gov/nih/nci/cadsr/cdecurate/tool/CurationServlet.java
added the conceptclass create req type
Java
mit
703615db0a45a214ca5a4b33e33daa263cc16667
0
ButterFaces/ButterFaces,ButterFaces/ButterFaces,ButterFaces/ButterFaces,ButterFaces/ButterFaces,ButterFaces/ButterFaces
package de.larmic.butterfaces.component.behavior; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import javax.faces.component.UIComponentBase; import javax.faces.component.behavior.AjaxBehavior; import javax.faces.component.behavior.ClientBehavior; import static de.larmic.butterfaces.util.StringUtils.isNotEmpty; import static java.util.Objects.requireNonNull; import de.larmic.butterfaces.resolver.UIComponentResolver; import de.larmic.butterfaces.util.StringJoiner; import de.larmic.butterfaces.util.StringUtils; /** * Builds an ajax request call that depends on the JSF Javascript API under * https://docs.oracle.com/cd/E17802_01/j2ee/javaee/javaserverfaces/2.0/docs/js-api/symbols/jsf.ajax.html#.request */ public class JsfAjaxRequest { private static UIComponentResolver uiComponentResolver; private final String source; private String event; private String execute; private String render; private List<String> onEventHandlers = new ArrayList<>(); private List<String> onErrorHandlers = new ArrayList<>(); private String params; private String behaviorEvent; /** * Constructor. * * @param source the DOM element that triggered this Ajax request, or an id string of the element to use as the triggering * element * @param isIdString if set to <code>true</code> the source string will be wrapped in '' */ public JsfAjaxRequest(String source, boolean isIdString) { this(source, isIdString, new UIComponentResolver()); } public JsfAjaxRequest(String source, boolean isIdString, UIComponentResolver uiComponentResolver) { requireNonNull(source, "source attribute may not be empty!"); if (isIdString) { this.source = "'" + source + "'"; } else { this.source = source; } this.uiComponentResolver = uiComponentResolver; } public JsfAjaxRequest(String source, boolean isIdString, AjaxBehavior ajaxBehavior, String event) { this(source, isIdString); if (!ajaxBehavior.isDisabled()) { if (ajaxBehavior.getExecute() != null) { this.setExecute(StringUtils.joinWithSpaceSeparator(ajaxBehavior.getExecute())); } if (ajaxBehavior.getRender() != null) { this.setRenderAsList(ajaxBehavior.getRender()); } if (ajaxBehavior.getOnevent() != null) { this.addOnEventHandler(ajaxBehavior.getOnevent()); } if (ajaxBehavior.getOnerror() != null) { this.addOnErrorHandler(ajaxBehavior.getOnerror()); } this.setEvent(event); this.setBehaviorEvent(event); } } /** * @param event The DOM event that triggered this Ajax request. * @return the actual instance of {@link JsfAjaxRequest} */ public JsfAjaxRequest setEvent(String event) { this.event = event; return this; } /** * @param execute space seperated list of client identifiers * @return the actual instance of {@link JsfAjaxRequest} */ public JsfAjaxRequest setExecute(String execute) { this.execute = getResolvedId(execute); return this; } /** * @param render space seperated list of client identifiers * @return the actual instance of {@link JsfAjaxRequest} */ public JsfAjaxRequest setRender(String render) { this.render = getResolvedId(render); return this; } public JsfAjaxRequest setRender(final UIComponentBase component, final String eventName) { this.render = StringJoiner.on(' ').join(createRerenderIds(component, eventName)).toString(); return this; } public static String getResolvedId(final String id) { if (id.equals("@all") || id.equals("@none") || id.equals("@form") || id.equals("@this")) { return id; } return uiComponentResolver.findComponentsClientId(id); } /** * @param renderIds list of client identifiers * @return the actual instance of {@link JsfAjaxRequest} */ public JsfAjaxRequest setRenderAsList(final Collection<String> renderIds) { if (!renderIds.isEmpty()) { StringJoiner joiner = StringJoiner.on(' '); for (String renderId : renderIds) { joiner = joiner.join(getResolvedId(renderId)); } render = joiner.toString(); } return this; } public JsfAjaxRequest addRender(final String render) { if (StringUtils.isNotEmpty(render)) { this.render = this.render == null ? getResolvedId(render) : this.render + " " + getResolvedId(render); } return this; } /** * @param params object containing parameters to include in the request * @return the actual instance of {@link JsfAjaxRequest} */ public JsfAjaxRequest setParams(String params) { this.params = params; return this; } /** * @param behaviorEvent ?? * @return the actual instance of {@link JsfAjaxRequest} */ public JsfAjaxRequest setBehaviorEvent(String behaviorEvent) { this.behaviorEvent = behaviorEvent; return this; } /** * @param functionString function to callback for event * @return the actual instance of {@link JsfAjaxRequest} */ public JsfAjaxRequest addOnEventHandler(String functionString) { if (StringUtils.isNotEmpty(functionString)) { onEventHandlers.add(functionString); } return this; } /** * @param functionString function to callback for error * @return the actual instance of {@link JsfAjaxRequest} */ public JsfAjaxRequest addOnErrorHandler(String functionString) { if (StringUtils.isNotEmpty(functionString)) { onErrorHandlers.add(functionString); } return this; } @Override public String toString() { final StringBuilder sb = new StringBuilder("jsf.ajax.request("); sb.append(source); if (isNotEmpty(event)) { sb.append(", '").append(event).append("'"); } if (hasOptions()) { sb.append(", {"); boolean isAtLeastOneOptionSet = false; if (isNotEmpty(execute)) { sb.append("execute: '").append(execute).append("'"); isAtLeastOneOptionSet = true; } if (isNotEmpty(render)) { writeSeparatorIfNecessary(sb, isAtLeastOneOptionSet); sb.append("render: '").append(render).append("'"); isAtLeastOneOptionSet = true; } if (!onEventHandlers.isEmpty()) { writeSeparatorIfNecessary(sb, isAtLeastOneOptionSet); sb.append("onevent: ").append(renderFunctionCalls(onEventHandlers)); isAtLeastOneOptionSet = true; } if (!onErrorHandlers.isEmpty()) { writeSeparatorIfNecessary(sb, isAtLeastOneOptionSet); sb.append("onerror: ").append(renderFunctionCalls(onErrorHandlers)); isAtLeastOneOptionSet = true; } if (isNotEmpty(params)) { writeSeparatorIfNecessary(sb, isAtLeastOneOptionSet); sb.append("params: ").append(params); isAtLeastOneOptionSet = true; } if (isNotEmpty(behaviorEvent)) { writeSeparatorIfNecessary(sb, isAtLeastOneOptionSet); sb.append("'javax.faces.behavior.event': '").append(behaviorEvent).append("'"); } sb.append("}"); } sb.append(");"); return sb.toString(); } public static AjaxBehavior findFirstActiveAjaxBehavior(final UIComponentBase component, final String eventName) { if (component != null) { final List<ClientBehavior> behaviors = component.getClientBehaviors().get(eventName); if (behaviors != null) { for (ClientBehavior behavior : behaviors) { if (behavior instanceof AjaxBehavior && !((AjaxBehavior) behavior).isDisabled()) { return (AjaxBehavior) behavior; } } } } return null; } public static List<String> createRerenderIds(final UIComponentBase component, final String eventName) { final List<String> idsToRender = new ArrayList<>(); final Map<String, List<ClientBehavior>> behaviors = component.getClientBehaviors(); final List<ClientBehavior> refreshBehaviors = behaviors.get(eventName); if (refreshBehaviors == null) { return new ArrayList<>(); //throw new IllegalArgumentException("Ajax event '" + eventName + "' not found on component '" + component.getClientId() + "'."); } boolean enabledAjaxEventFound = false; if (!refreshBehaviors.isEmpty()) { for (ClientBehavior refreshBehavior : refreshBehaviors) { if (refreshBehavior instanceof AjaxBehavior) { final AjaxBehavior ajaxBehavior = (AjaxBehavior) refreshBehavior; if (!ajaxBehavior.isDisabled()) { if (ajaxBehavior.getRender() != null && !ajaxBehavior.getRender().isEmpty()) { for (String singleRender : ajaxBehavior.getRender()) { idsToRender.add(getResolvedId(singleRender)); } } enabledAjaxEventFound = true; } } } } if (!enabledAjaxEventFound) { return new ArrayList<>(); //throw new IllegalStateException("Ajax event '" + eventName + "' on component '" + component.getClientId() + "' is disabled."); } return idsToRender; } private void writeSeparatorIfNecessary(StringBuilder sb, boolean isAtLeastOneOptionSet) { if (isAtLeastOneOptionSet) { sb.append(", "); } } private String renderFunctionCalls(List<String> functions) { final StringBuilder sb = new StringBuilder("function(data){"); for (String function : functions) { sb.append(function); if (!function.contains(")")) { // this is not a function call, so call it manually sb.append("(data)"); } sb.append(";"); } sb.append("}"); return sb.toString(); } private boolean hasOptions() { return isNotEmpty(execute) || isNotEmpty(render) || !onEventHandlers.isEmpty() || !onErrorHandlers.isEmpty() || isNotEmpty(params) || isNotEmpty(behaviorEvent); } }
components/src/main/java/de/larmic/butterfaces/component/behavior/JsfAjaxRequest.java
package de.larmic.butterfaces.component.behavior; import de.larmic.butterfaces.resolver.UIComponentResolver; import de.larmic.butterfaces.util.StringJoiner; import de.larmic.butterfaces.util.StringUtils; import javax.faces.component.UIComponentBase; import javax.faces.component.behavior.AjaxBehavior; import javax.faces.component.behavior.ClientBehavior; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import static de.larmic.butterfaces.util.StringUtils.isNotEmpty; import static java.util.Objects.requireNonNull; /** * Builds an ajax request call that depends on the JSF Javascript API under https://docs.oracle.com/cd/E17802_01/j2ee/javaee/javaserverfaces/2.0/docs/js-api/symbols/jsf.ajax.html#.request */ public class JsfAjaxRequest { private static UIComponentResolver uiComponentResolver; private final String source; private String event; private String execute; private String render; private List<String> onEventHandlers = new ArrayList<>(); private List<String> onErrorHandlers = new ArrayList<>(); private String params; private String behaviorEvent; /** * Constructor. * * @param source the DOM element that triggered this Ajax request, or an id string of the element to use as the triggering * element * @param isIdString if set to <code>true</code> the source string will be wrapped in '' */ public JsfAjaxRequest(String source, boolean isIdString) { this(source, isIdString, new UIComponentResolver()); } public JsfAjaxRequest(String source, boolean isIdString, UIComponentResolver uiComponentResolver) { requireNonNull(source, "source attribute may not be empty!"); if (isIdString) { this.source = "'" + source + "'"; } else { this.source = source; } this.uiComponentResolver = uiComponentResolver; } public JsfAjaxRequest(String source, boolean isIdString, AjaxBehavior ajaxBehavior, String event) { this(source, isIdString); if (!ajaxBehavior.isDisabled()) { if (ajaxBehavior.getExecute() != null) { this.setExecute(StringUtils.joinWithSpaceSeparator(ajaxBehavior.getExecute())); } if (ajaxBehavior.getRender() != null) { this.setRenderAsList(ajaxBehavior.getRender()); } if (ajaxBehavior.getOnevent() != null) { this.addOnEventHandler(ajaxBehavior.getOnevent()); } if (ajaxBehavior.getOnerror() != null) { this.addOnErrorHandler(ajaxBehavior.getOnerror()); } this.setEvent(event); this.setBehaviorEvent(event); } } /** * @param event The DOM event that triggered this Ajax request. * @return the actual instance of {@link JsfAjaxRequest} */ public JsfAjaxRequest setEvent(String event) { this.event = event; return this; } /** * @param execute space seperated list of client identifiers * @return the actual instance of {@link JsfAjaxRequest} */ public JsfAjaxRequest setExecute(String execute) { this.execute = getResolvedId(execute); return this; } /** * @param render space seperated list of client identifiers * @return the actual instance of {@link JsfAjaxRequest} */ public JsfAjaxRequest setRender(String render) { this.render = getResolvedId(render); return this; } public JsfAjaxRequest setRender(final UIComponentBase component, final String eventName) { this.render = StringJoiner.on(' ').join(createRerenderIds(component, eventName)).toString(); return this; } public static String getResolvedId(final String id) { if (id.equals("@all") || id.equals("@none") || id.equals("@form") || id.equals("@this")) { return id; } return uiComponentResolver.findComponentsClientId(id); } /** * @param renderIds list of client identifiers * @return the actual instance of {@link JsfAjaxRequest} */ public JsfAjaxRequest setRenderAsList(final Collection<String> renderIds) { if (!renderIds.isEmpty()) { StringJoiner joiner = StringJoiner.on(' '); for (String renderId : renderIds) { joiner = joiner.join(getResolvedId(renderId)); } render = joiner.toString(); } return this; } public JsfAjaxRequest addRender(final String render) { if (StringUtils.isNotEmpty(render)) { this.render = this.render == null ? getResolvedId(render) : this.render + " " + getResolvedId(render); } return this; } /** * @param params object containing parameters to include in the request * @return the actual instance of {@link JsfAjaxRequest} */ public JsfAjaxRequest setParams(String params) { this.params = params; return this; } /** * @param behaviorEvent ?? * @return the actual instance of {@link JsfAjaxRequest} */ public JsfAjaxRequest setBehaviorEvent(String behaviorEvent) { this.behaviorEvent = behaviorEvent; return this; } /** * @param functionString function to callback for event * @return the actual instance of {@link JsfAjaxRequest} */ public JsfAjaxRequest addOnEventHandler(String functionString) { if (StringUtils.isNotEmpty(functionString)) { onEventHandlers.add(functionString); } return this; } /** * @param functionString function to callback for error * @return the actual instance of {@link JsfAjaxRequest} */ public JsfAjaxRequest addOnErrorHandler(String functionString) { if (StringUtils.isNotEmpty(functionString)) { onErrorHandlers.add(functionString); } return this; } @Override public String toString() { final StringBuilder sb = new StringBuilder("jsf.ajax.request("); sb.append(source); if (isNotEmpty(event)) { sb.append(", '").append(event).append("'"); } if (hasOptions()) { sb.append(", {"); boolean isAtLeastOneOptionSet = false; if (isNotEmpty(execute)) { sb.append("execute: '").append(execute).append("'"); isAtLeastOneOptionSet = true; } if (isNotEmpty(render)) { writeSeparatorIfNecessary(sb, isAtLeastOneOptionSet); sb.append("render: '").append(render).append("'"); isAtLeastOneOptionSet = true; } if (!onEventHandlers.isEmpty()) { writeSeparatorIfNecessary(sb, isAtLeastOneOptionSet); sb.append("onevent: ").append(renderFunctionCalls(onEventHandlers)); isAtLeastOneOptionSet = true; } if (!onErrorHandlers.isEmpty()) { writeSeparatorIfNecessary(sb, isAtLeastOneOptionSet); sb.append("onerror: ").append(renderFunctionCalls(onErrorHandlers)); isAtLeastOneOptionSet = true; } if (isNotEmpty(params)) { writeSeparatorIfNecessary(sb, isAtLeastOneOptionSet); sb.append("params: ").append(params); isAtLeastOneOptionSet = true; } if (isNotEmpty(behaviorEvent)) { writeSeparatorIfNecessary(sb, isAtLeastOneOptionSet); sb.append("'javax.faces.behavior.event': '").append(behaviorEvent).append("'"); } sb.append("}"); } sb.append(");"); return sb.toString(); } public static AjaxBehavior findFirstActiveAjaxBehavior(final UIComponentBase component, final String eventName) { if (component != null) { final List<ClientBehavior> behaviors = component.getClientBehaviors().get(eventName); if (behaviors != null) { for (ClientBehavior behavior : behaviors) { if (behavior instanceof AjaxBehavior && !((AjaxBehavior) behavior).isDisabled()) { return (AjaxBehavior) behavior; } } } } return null; } public static List<String> createRerenderIds(final UIComponentBase component, final String eventName) { final List<String> idsToRender = new ArrayList<>(); final Map<String, List<ClientBehavior>> behaviors = component.getClientBehaviors(); final List<ClientBehavior> refreshBehaviors = behaviors.get(eventName); if (refreshBehaviors == null) { return new ArrayList<>(); //throw new IllegalArgumentException("Ajax event '" + eventName + "' not found on component '" + component.getClientId() + "'."); } boolean enabledAjaxEventFound = false; if (!refreshBehaviors.isEmpty()) { for (ClientBehavior refreshBehavior : refreshBehaviors) { if (refreshBehavior instanceof AjaxBehavior) { final AjaxBehavior ajaxBehavior = (AjaxBehavior) refreshBehavior; if (!ajaxBehavior.isDisabled()) { if (ajaxBehavior.getRender() != null && !ajaxBehavior.getRender().isEmpty()) { for (String singleRender : ajaxBehavior.getRender()) { idsToRender.add(getResolvedId(singleRender)); } } enabledAjaxEventFound = true; } } } } if (!enabledAjaxEventFound) { return new ArrayList<>(); //throw new IllegalStateException("Ajax event '" + eventName + "' on component '" + component.getClientId() + "' is disabled."); } return idsToRender; } private void writeSeparatorIfNecessary(StringBuilder sb, boolean isAtLeastOneOptionSet) { if (isAtLeastOneOptionSet) { sb.append(", "); } } private String renderFunctionCalls(List<String> functions) { final StringBuilder sb = new StringBuilder("function(data){"); for (String function : functions) { sb.append(function); if (!function.contains(")")) { // this is not a function call, so call it manually sb.append("(data)"); } sb.append(";"); } sb.append("}"); return sb.toString(); } private boolean hasOptions() { return isNotEmpty(execute) || isNotEmpty(render) || !onEventHandlers.isEmpty() || !onErrorHandlers.isEmpty() || isNotEmpty(params) || isNotEmpty(behaviorEvent); } }
Documentation ...
components/src/main/java/de/larmic/butterfaces/component/behavior/JsfAjaxRequest.java
Documentation ...
Java
mit
a44fc9bd83edd61e72413d05b06e8a34c1fe549f
0
aldenml/frostwire-jlibtorrent,gubatron/frostwire-jlibtorrent,gubatron/frostwire-jlibtorrent,aldenml/frostwire-jlibtorrent,frostwire/frostwire-jlibtorrent,aldenml/frostwire-jlibtorrent,gubatron/frostwire-jlibtorrent,frostwire/frostwire-jlibtorrent,frostwire/frostwire-jlibtorrent
package com.frostwire.jlibtorrent; import com.frostwire.jlibtorrent.alerts.*; import com.frostwire.jlibtorrent.plugins.Plugin; import com.frostwire.jlibtorrent.plugins.SwigPlugin; import com.frostwire.jlibtorrent.swig.*; import com.frostwire.jlibtorrent.swig.session_handle.options_t; import java.io.File; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * The session holds all state that spans multiple torrents. Among other * things it runs the network loop and manages all torrents. Once it's * created, the session object will spawn the main thread that will do all * the work. The main thread will be idle as long it doesn't have any * torrents to participate in. * <p/> * This class belongs to a middle logical layer of abstraction. It's a wrapper * of the underlying swig session object (from libtorrent), but it does not * expose all the raw features, not expose a very high level interface * like {@link com.frostwire.jlibtorrent.DHT DHT} or * {@link com.frostwire.jlibtorrent.Downloader Downloader}. * * @author gubatron * @author aldenml */ public final class Session extends SessionHandle { private static final Logger LOG = Logger.getLogger(Session.class); private static final long REQUEST_STATS_RESOLUTION_MILLIS = 1000; private static final long ALERTS_LOOP_WAIT_MILLIS = 500; private final session s; private final JavaStat stat; private final SessionStats stats; private long lastStatsRequestTime; private long lastStatSecondTick; private final SparseArray<ArrayList<AlertListener>> listeners; private final SparseArray<AlertListener[]> listenerSnapshots; private boolean running; private final LinkedList<SwigPlugin> plugins; /** * The flag alert_mask is always set to all_categories. * * @param settings * @param logging */ public Session(SettingsPack settings, boolean logging) { super(createSession(settings, logging)); this.s = (session) super.s; this.stat = new JavaStat(); this.stats = new SessionStats(stat); this.listeners = new SparseArray<ArrayList<AlertListener>>(); this.listenerSnapshots = new SparseArray<AlertListener[]>(); this.running = true; alertsLoop(); for (Pair<String, Integer> router : defaultRouters()) { s.add_dht_router(router.to_string_int_pair()); } this.plugins = new LinkedList<SwigPlugin>(); } @Deprecated public Session(Fingerprint print, Pair<Integer, Integer> prange, String iface, List<Pair<String, Integer>> routers, boolean logging) { super(createSessionDeprecated(print, prange, iface, routers, logging)); this.s = (session) super.s; this.stat = new JavaStat(); this.stats = new SessionStats(stat); this.listeners = new SparseArray<ArrayList<AlertListener>>(); this.listenerSnapshots = new SparseArray<AlertListener[]>(); this.running = true; alertsLoop(); for (Pair<String, Integer> router : routers) { s.add_dht_router(router.to_string_int_pair()); } this.plugins = new LinkedList<SwigPlugin>(); } public Session(Fingerprint print, Pair<Integer, Integer> prange, String iface, List<Pair<String, Integer>> routers) { this(print, prange, iface, routers, false); } public Session(Fingerprint print, Pair<Integer, Integer> prange, String iface) { this(print, prange, iface, defaultRouters()); } public Session(Fingerprint print) { this(print, new Pair<Integer, Integer>(0, 0), "0.0.0.0"); } public Session(Pair<Integer, Integer> prange, String iface) { this(new Fingerprint(), prange, iface); } public Session() { this(new SettingsPack(), false); } public session getSwig() { return s; } public void addListener(AlertListener listener) { modifyListeners(true, listener); } public void removeListener(AlertListener listener) { modifyListeners(false, listener); } /** * You add torrents through the add_torrent() function where you give an * object with all the parameters. The add_torrent() overloads will block * until the torrent has been added (or failed to be added) and returns * an error code and a torrent_handle. In order to add torrents more * efficiently, consider using async_add_torrent() which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as add_torrent_alert. * <p/> * The overload that does not take an error_code throws an exception on * error and is not available when building without exception support. * The torrent_handle returned by add_torrent() can be used to retrieve * information about the torrent's progress, its peers etc. It is also * used to abort a torrent. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * <p/> * all torrent_handles must be destructed before the session is destructed! * * @param ti * @param saveDir * @param priorities * @param resumeFile * @return */ public TorrentHandle addTorrent(TorrentInfo ti, File saveDir, Priority[] priorities, File resumeFile) { return addTorrentSupport(ti, saveDir, priorities, resumeFile, false); } /** * You add torrents through the add_torrent() function where you give an * object with all the parameters. The add_torrent() overloads will block * until the torrent has been added (or failed to be added) and returns * an error code and a torrent_handle. In order to add torrents more * efficiently, consider using async_add_torrent() which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as add_torrent_alert. * <p/> * The overload that does not take an error_code throws an exception on * error and is not available when building without exception support. * The torrent_handle returned by add_torrent() can be used to retrieve * information about the torrent's progress, its peers etc. It is also * used to abort a torrent. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * <p/> * all torrent_handles must be destructed before the session is destructed! * * @param torrent * @param saveDir * @param resumeFile * @return */ public TorrentHandle addTorrent(File torrent, File saveDir, File resumeFile) { return addTorrent(new TorrentInfo(torrent), saveDir, null, resumeFile); } /** * You add torrents through the add_torrent() function where you give an * object with all the parameters. The add_torrent() overloads will block * until the torrent has been added (or failed to be added) and returns * an error code and a torrent_handle. In order to add torrents more * efficiently, consider using async_add_torrent() which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as add_torrent_alert. * <p/> * The overload that does not take an error_code throws an exception on * error and is not available when building without exception support. * The torrent_handle returned by add_torrent() can be used to retrieve * information about the torrent's progress, its peers etc. It is also * used to abort a torrent. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * <p/> * all torrent_handles must be destructed before the session is destructed! * * @param torrent * @param saveDir * @return */ public TorrentHandle addTorrent(File torrent, File saveDir) { return addTorrent(torrent, saveDir, null); } /** * In order to add torrents more efficiently, consider using this which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as {@link com.frostwire.jlibtorrent.alerts.AddTorrentAlert}. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * * @param ti * @param saveDir * @param priorities * @param resumeFile */ public void asyncAddTorrent(TorrentInfo ti, File saveDir, Priority[] priorities, File resumeFile) { addTorrentSupport(ti, saveDir, priorities, resumeFile, true); } /** * You add torrents through the add_torrent() function where you give an * object with all the parameters. The add_torrent() overloads will block * until the torrent has been added (or failed to be added) and returns * an error code and a torrent_handle. In order to add torrents more * efficiently, consider using async_add_torrent() which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as add_torrent_alert. * <p/> * The overload that does not take an error_code throws an exception on * error and is not available when building without exception support. * The torrent_handle returned by add_torrent() can be used to retrieve * information about the torrent's progress, its peers etc. It is also * used to abort a torrent. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * <p/> * all torrent_handles must be destructed before the session is destructed! * * @param torrent * @param saveDir * @param resumeFile */ public void asyncAddTorrent(File torrent, File saveDir, File resumeFile) { asyncAddTorrent(new TorrentInfo(torrent), saveDir, null, resumeFile); } /** * You add torrents through the add_torrent() function where you give an * object with all the parameters. The add_torrent() overloads will block * until the torrent has been added (or failed to be added) and returns * an error code and a torrent_handle. In order to add torrents more * efficiently, consider using async_add_torrent() which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as add_torrent_alert. * <p/> * The overload that does not take an error_code throws an exception on * error and is not available when building without exception support. * The torrent_handle returned by add_torrent() can be used to retrieve * information about the torrent's progress, its peers etc. It is also * used to abort a torrent. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * <p/> * all torrent_handles must be destructed before the session is destructed! * * @param torrent * @param saveDir */ public void asyncAddTorrent(File torrent, File saveDir) { asyncAddTorrent(torrent, saveDir, null); } /** * This method will close all peer connections associated with the torrent and tell the * tracker that we've stopped participating in the swarm. This operation cannot fail. * When it completes, you will receive a torrent_removed_alert. * <p/> * The optional second argument options can be used to delete all the files downloaded * by this torrent. To do so, pass in the value session::delete_files. The removal of * the torrent is asyncronous, there is no guarantee that adding the same torrent immediately * after it was removed will not throw a libtorrent_exception exception. Once the torrent * is deleted, a torrent_deleted_alert is posted. * * @param th */ public void removeTorrent(TorrentHandle th, Options options) { s.remove_torrent(th.getSwig(), options.getSwig()); } /** * This method will close all peer connections associated with the torrent and tell the * tracker that we've stopped participating in the swarm. This operation cannot fail. * When it completes, you will receive a torrent_removed_alert. * * @param th */ public void removeTorrent(TorrentHandle th) { if (th.isValid()) { s.remove_torrent(th.getSwig()); } } /** * Applies the settings specified by the settings_pack ``sp``. This is an * asynchronous operation that will return immediately and actually apply * the settings to the main thread of libtorrent some time later. * * @param sp */ public void applySettings(SettingsPack sp) { s.apply_settings(sp.getSwig()); } /** * In case you want to destruct the session asynchrounously, you can * request a session destruction proxy. If you don't do this, the * destructor of the session object will block while the trackers are * contacted. If you keep one ``session_proxy`` to the session when * destructing it, the destructor will not block, but start to close down * the session, the destructor of the proxy will then synchronize the * threads. So, the destruction of the session is performed from the * ``session`` destructor call until the ``session_proxy`` destructor * call. The ``session_proxy`` does not have any operations on it (since * the session is being closed down, no operations are allowed on it). * The only valid operation is calling the destructor:: * * @return */ public SessionProxy abort() { running = false; return new SessionProxy(s.abort()); } /** * Pausing the session has the same effect as pausing every torrent in * it, except that torrents will not be resumed by the auto-manage * mechanism. */ public void pause() { s.pause(); } /** * Resuming will restore the torrents to their previous paused * state. i.e. the session pause state is separate from the torrent pause * state. A torrent is inactive if it is paused or if the session is * paused. */ public void resume() { s.resume(); } public boolean isPaused() { return s.is_paused(); } /** * returns the port we ended up listening on. Since you * just pass a port-range to the constructor and to ``listen_on()``, to * know which port it ended up using, you have to ask the session using * this function. * * @return */ public int getListenPort() { return s.listen_port(); } public int getSslListenPort() { return s.ssl_listen_port(); } /** * will tell you whether or not the session has * successfully opened a listening port. If it hasn't, this function will * return false, and then you can use ``listen_on()`` to make another * attempt. * * @return */ public boolean isListening() { return s.is_listening(); } /** * Loads and saves all session settings, including dht_settings, * encryption settings and proxy settings. ``save_state`` writes all keys * to the ``entry`` that's passed in, which needs to either not be * initialized, or initialized as a dictionary. * <p/> * ``load_state`` expects a lazy_entry which can be built from a bencoded * buffer with lazy_bdecode(). * <p/> * The ``flags`` arguments passed in to ``save_state`` can be used to * filter which parts of the session state to save. By default, all state * is saved (except for the individual torrents). see save_state_flags_t * * @return */ public byte[] saveState() { entry e = new entry(); s.save_state(e); return Vectors.char_vector2bytes(e.bencode()); } /** * Loads and saves all session settings, including dht_settings, * encryption settings and proxy settings. ``save_state`` writes all keys * to the ``entry`` that's passed in, which needs to either not be * initialized, or initialized as a dictionary. * <p/> * ``load_state`` expects a lazy_entry which can be built from a bencoded * buffer with lazy_bdecode(). * <p/> * The ``flags`` arguments passed in to ``save_state`` can be used to * filter which parts of the session state to save. By default, all state * is saved (except for the individual torrents). see save_state_flags_t * * @param data */ public void loadState(byte[] data) { char_vector buffer = Vectors.bytes2char_vector(data); bdecode_node n = new bdecode_node(); error_code ec = new error_code(); int ret = bdecode_node.bdecode(buffer, n, ec); if (ret == 0) { s.load_state(n); } else { LOG.error("failed to decode torrent: " + ec.message()); } } /** * This functions instructs the session to post the state_update_alert, * containing the status of all torrents whose state changed since the * last time this function was called. * <p/> * Only torrents who has the state subscription flag set will be * included. This flag is on by default. See add_torrent_params. * the ``flags`` argument is the same as for torrent_handle::status(). * see torrent_handle::status_flags_t. * * @param flags */ public void postTorrentUpdates(TorrentHandle.StatusFlags flags) { s.post_torrent_updates(flags.getSwig()); } /** * This functions instructs the session to post the state_update_alert, * containing the status of all torrents whose state changed since the * last time this function was called. * <p/> * Only torrents who has the state subscription flag set will be * included. */ public void postTorrentUpdates() { s.post_torrent_updates(); } /** * This function will post a {@link com.frostwire.jlibtorrent.alerts.SessionStatsAlert} object, containing a * snapshot of the performance counters from the internals of libtorrent. * To interpret these counters, query the session via * session_stats_metrics(). */ public void postSessionStats() { s.post_session_stats(); } /** * This will cause a dht_stats_alert to be posted. */ public void postDHTStats() { s.post_dht_stats(); } /** * Looks for a torrent with the given info-hash. In * case there is such a torrent in the session, a torrent_handle to that * torrent is returned. * <p/> * In case the torrent cannot be found, a null is returned. * * @param infoHash * @return */ public TorrentHandle findTorrent(Sha1Hash infoHash) { torrent_handle th = s.find_torrent(infoHash.getSwig()); return th != null && th.is_valid() ? new TorrentHandle(th) : null; } /** * Returns a list of torrent handles to all the * torrents currently in the session. * * @return */ public List<TorrentHandle> getTorrents() { torrent_handle_vector v = s.get_torrents(); long size = v.size(); List<TorrentHandle> l = new ArrayList<TorrentHandle>((int) size); for (int i = 0; i < size; i++) { l.add(new TorrentHandle(v.get(i))); } return l; } // starts/stops UPnP, NATPMP or LSD port mappers they are stopped by // default These functions are not available in case // ``TORRENT_DISABLE_DHT`` is defined. ``start_dht`` starts the dht node // and makes the trackerless service available to torrents. The startup // state is optional and can contain nodes and the node id from the // previous session. The dht node state is a bencoded dictionary with the // following entries: // // nodes // A list of strings, where each string is a node endpoint encoded in // binary. If the string is 6 bytes long, it is an IPv4 address of 4 // bytes, encoded in network byte order (big endian), followed by a 2 // byte port number (also network byte order). If the string is 18 // bytes long, it is 16 bytes of IPv6 address followed by a 2 bytes // port number (also network byte order). // // node-id // The node id written as a readable string as a hexadecimal number. // // ``dht_state`` will return the current state of the dht node, this can // be used to start up the node again, passing this entry to // ``start_dht``. It is a good idea to save this to disk when the session // is closed, and read it up again when starting. // // If the port the DHT is supposed to listen on is already in use, and // exception is thrown, ``asio::error``. // // ``stop_dht`` stops the dht node. // // ``add_dht_node`` adds a node to the routing table. This can be used if // your client has its own source of bootstrapping nodes. // // ``set_dht_settings`` sets some parameters availavle to the dht node. // See dht_settings for more information. // // ``is_dht_running()`` returns true if the DHT support has been started // and false // otherwise. void setDHTSettings(DHTSettings settings) { s.set_dht_settings(settings.getSwig()); } public boolean isDHTRunning() { return s.is_dht_running(); } /** * takes a host name and port pair. That endpoint will be * pinged, and if a valid DHT reply is received, the node will be added to * the routing table. * * @param node */ public void addDHTNode(Pair<String, Integer> node) { s.add_dht_node(node.to_string_int_pair()); } /** * adds the given endpoint to a list of DHT router nodes. * If a search is ever made while the routing table is empty, those nodes will * be used as backups. Nodes in the router node list will also never be added * to the regular routing table, which effectively means they are only used * for bootstrapping, to keep the load off them. * <p/> * An example routing node that you could typically add is * ``router.bittorrent.com``. * * @param node */ public void addDHTRouter(Pair<String, Integer> node) { s.add_dht_router(node.to_string_int_pair()); } /** * Query the DHT for an immutable item at the target hash. * the result is posted as a {@link DhtImmutableItemAlert}. * * @param target */ public void dhtGetItem(Sha1Hash target) { s.dht_get_item(target.getSwig()); } /** * Query the DHT for a mutable item under the public key ``key``. * this is an ed25519 key. ``salt`` is optional and may be left * as an empty string if no salt is to be used. * if the item is found in the DHT, a dht_mutable_item_alert is * posted. * * @param key */ public void dhtGetItem(byte[] key) { s.dht_get_item(Vectors.bytes2char_vector(key)); } /** * Query the DHT for a mutable item under the public key ``key``. * this is an ed25519 key. ``salt`` is optional and may be left * as an empty string if no salt is to be used. * if the item is found in the DHT, a dht_mutable_item_alert is * posted. * * @param key * @param salt */ public void dhtGetItem(byte[] key, String salt) { s.dht_get_item(Vectors.bytes2char_vector(key), salt); } /** * Store the given bencoded data as an immutable item in the DHT. * the returned hash is the key that is to be used to look the item * up agan. It's just the sha-1 hash of the bencoded form of the * structure. * * @param entry * @return */ public Sha1Hash dhtPutItem(Entry entry) { return new Sha1Hash(s.dht_put_item(entry.getSwig())); } // store an immutable item. The ``key`` is the public key the blob is // to be stored under. The optional ``salt`` argument is a string that // is to be mixed in with the key when determining where in the DHT // the value is to be stored. The callback function is called from within // the libtorrent network thread once we've found where to store the blob, // possibly with the current value stored under the key. // The values passed to the callback functions are: // // entry& value // the current value stored under the key (may be empty). Also expected // to be set to the value to be stored by the function. // // boost::array<char,64>& signature // the signature authenticating the current value. This may be zeroes // if there is currently no value stored. The functon is expected to // fill in this buffer with the signature of the new value to store. // To generate the signature, you may want to use the // ``sign_mutable_item`` function. // // boost::uint64_t& seq // current sequence number. May be zero if there is no current value. // The function is expected to set this to the new sequence number of // the value that is to be stored. Sequence numbers must be monotonically // increasing. Attempting to overwrite a value with a lower or equal // sequence number will fail, even if the signature is correct. // // std::string const& salt // this is the salt that was used for this put call. // // Since the callback function ``cb`` is called from within libtorrent, // it is critical to not perform any blocking operations. Ideally not // even locking a mutex. Pass any data required for this function along // with the function object's context and make the function entirely // self-contained. The only reason data blobs' values are computed // via a function instead of just passing in the new value is to avoid // race conditions. If you want to *update* the value in the DHT, you // must first retrieve it, then modify it, then write it back. The way // the DHT works, it is natural to always do a lookup before storing and // calling the callback in between is convenient. public void dhtPutItem(byte[] publicKey, byte[] privateKey, Entry entry) { s.dht_put_item(Vectors.bytes2char_vector(publicKey), Vectors.bytes2char_vector(privateKey), entry.getSwig()); } // store an immutable item. The ``key`` is the public key the blob is // to be stored under. The optional ``salt`` argument is a string that // is to be mixed in with the key when determining where in the DHT // the value is to be stored. The callback function is called from within // the libtorrent network thread once we've found where to store the blob, // possibly with the current value stored under the key. // The values passed to the callback functions are: // // entry& value // the current value stored under the key (may be empty). Also expected // to be set to the value to be stored by the function. // // boost::array<char,64>& signature // the signature authenticating the current value. This may be zeroes // if there is currently no value stored. The functon is expected to // fill in this buffer with the signature of the new value to store. // To generate the signature, you may want to use the // ``sign_mutable_item`` function. // // boost::uint64_t& seq // current sequence number. May be zero if there is no current value. // The function is expected to set this to the new sequence number of // the value that is to be stored. Sequence numbers must be monotonically // increasing. Attempting to overwrite a value with a lower or equal // sequence number will fail, even if the signature is correct. // // std::string const& salt // this is the salt that was used for this put call. // // Since the callback function ``cb`` is called from within libtorrent, // it is critical to not perform any blocking operations. Ideally not // even locking a mutex. Pass any data required for this function along // with the function object's context and make the function entirely // self-contained. The only reason data blobs' values are computed // via a function instead of just passing in the new value is to avoid // race conditions. If you want to *update* the value in the DHT, you // must first retrieve it, then modify it, then write it back. The way // the DHT works, it is natural to always do a lookup before storing and // calling the callback in between is convenient. public void dhtPutItem(byte[] publicKey, byte[] privateKey, Entry entry, String salt) { s.dht_put_item(Vectors.bytes2char_vector(publicKey), Vectors.bytes2char_vector(privateKey), entry.getSwig(), salt); } public void dhtGetPeers(Sha1Hash infoHash) { s.dht_get_peers(infoHash.getSwig()); } public void dhtAnnounce(Sha1Hash infoHash, int port, int flags) { s.dht_announce(infoHash.getSwig(), port, flags); } public void dhtAnnounce(Sha1Hash infoHash) { s.dht_announce(infoHash.getSwig()); } public void dhtDirectRequest(UdpEndpoint endp, Entry entry) { s.dht_direct_request(endp.getSwig(), entry.getSwig()); } public void addExtension(Plugin p) { SwigPlugin sp = new SwigPlugin(p); s.add_swig_extension(sp); plugins.add(sp); } /** * add_port_mapping adds a port forwarding on UPnP and/or NAT-PMP, * whichever is enabled. The return value is a handle referring to the * port mapping that was just created. Pass it to delete_port_mapping() * to remove it. * * @param t * @param externalPort * @param localPort * @return */ public int addPortMapping(ProtocolType t, int externalPort, int localPort) { return s.add_port_mapping(t.getSwig(), externalPort, localPort); } public void deletePortMapping(int handle) { s.delete_port_mapping(handle); } public SessionStats getStats() { return stats; } public SettingsPack getSettingsPack() { return new SettingsPack(s.get_settings()); } @Deprecated public SessionSettings getSettings() { return new SessionSettings(s.get_settings()); } @Deprecated public ProxySettings getProxy() { return new ProxySettings(new settings_pack()); } @Deprecated public void setProxy(ProxySettings s) { this.s.apply_settings(s.getSwig()); } @Deprecated public void setSettings(SessionSettings s) { this.applySettings(s.toPack()); } @Deprecated public SessionStatus getStatus() { return new SessionStatus(stats); } // You add torrents through the add_torrent() function where you give an // object with all the parameters. The add_torrent() overloads will block // until the torrent has been added (or failed to be added) and returns // an error code and a torrent_handle. In order to add torrents more // efficiently, consider using async_add_torrent() which returns // immediately, without waiting for the torrent to add. Notification of // the torrent being added is sent as add_torrent_alert. // // The overload that does not take an error_code throws an exception on // error and is not available when building without exception support. // The torrent_handle returned by add_torrent() can be used to retrieve // information about the torrent's progress, its peers etc. It is also // used to abort a torrent. // // If the torrent you are trying to add already exists in the session (is // either queued for checking, being checked or downloading) // ``add_torrent()`` will throw libtorrent_exception which derives from // ``std::exception`` unless duplicate_is_error is set to false. In that // case, add_torrent() will return the handle to the existing torrent. // // all torrent_handles must be destructed before the session is destructed! public TorrentHandle addTorrent(AddTorrentParams params) { return new TorrentHandle(s.add_torrent(params.getSwig())); } public TorrentHandle addTorrent(AddTorrentParams params, ErrorCode ec) { return new TorrentHandle(s.add_torrent(params.getSwig(), ec.getSwig())); } public void asyncAddTorrent(AddTorrentParams params) { s.async_add_torrent(params.getSwig()); } @Override protected void finalize() throws Throwable { this.running = false; super.finalize(); } void fireAlert(Alert<?> a) { int type = a.getSwig() != null ? a.getSwig().type() : a.getType().getSwig(); fireAlert(a, type); fireAlert(a, -1); } private void fireAlert(Alert<?> a, int type) { AlertListener[] listeners = listenerSnapshots.get(type); if (listeners != null) { for (int i = 0; i < listeners.length; i++) { try { AlertListener l = listeners[i]; if (l != null) { l.alert(a); } } catch (Throwable e) { LOG.warn("Error calling alert listener", e); } } } } private TorrentHandle addTorrentSupport(TorrentInfo ti, File saveDir, Priority[] priorities, File resumeFile, boolean async) { String savePath = null; if (saveDir != null) { savePath = saveDir.getAbsolutePath(); } else if (resumeFile == null) { throw new IllegalArgumentException("Both saveDir and resumeFile can't be null at the same time"); } add_torrent_params p = add_torrent_params.create_instance(); p.set_ti(ti.getSwig()); if (savePath != null) { p.setSave_path(savePath); } if (priorities != null) { p.setFile_priorities(Vectors.priorities2unsigned_char_vector(priorities)); } p.setStorage_mode(storage_mode_t.storage_mode_sparse); long flags = p.getFlags(); flags &= ~add_torrent_params.flags_t.flag_auto_managed.swigValue(); if (resumeFile != null) { try { byte[] data = Files.bytes(resumeFile); p.setResume_data(Vectors.bytes2char_vector(data)); flags |= add_torrent_params.flags_t.flag_use_resume_save_path.swigValue(); } catch (Throwable e) { LOG.warn("Unable to set resume data", e); } } p.setFlags(flags); if (async) { s.async_add_torrent(p); return null; } else { torrent_handle th = s.add_torrent(p); return new TorrentHandle(th); } } private void alertsLoop() { Runnable r = new Runnable() { @Override public void run() { alert_ptr_vector vector = new alert_ptr_vector(); high_resolution_clock.duration max_wait = libtorrent.to_milliseconds(ALERTS_LOOP_WAIT_MILLIS); while (running) { alert ptr = s.wait_for_alert(max_wait); if (ptr != null) { s.pop_alerts(vector); long size = vector.size(); for (int i = 0; i < size; i++) { alert swigAlert = vector.get(i); int type = swigAlert.type(); Alert<?> alert = null; if (type == AlertType.SESSION_STATS.getSwig()) { alert = Alerts.cast(swigAlert); updateSessionStat((SessionStatsAlert) alert); } if (listeners.indexOfKey(type) >= 0) { if (alert == null) { alert = Alerts.cast(swigAlert); } fireAlert(alert, type); } if (type != AlertType.SESSION_STATS.getSwig() && listeners.indexOfKey(-1) >= 0) { if (alert == null) { alert = Alerts.cast(swigAlert); } fireAlert(alert, -1); } } vector.clear(); } long now = System.currentTimeMillis(); if ((now - lastStatsRequestTime) >= REQUEST_STATS_RESOLUTION_MILLIS) { lastStatsRequestTime = now; postSessionStats(); } } } }; Thread t = new Thread(r, "Session-alertsLoop"); t.setDaemon(true); t.start(); } private void modifyListeners(boolean adding, AlertListener listener) { if (listener != null) { int[] types = listener.types(); //all alert-type including listener if (types == null) { modifyListeners(adding, -1, listener); } else { for (int i = 0; i < types.length; i++) { if (types[i] == -1) { throw new IllegalArgumentException("Type can't be the key of all (-1)"); } modifyListeners(adding, types[i], listener); } } } } private void modifyListeners(boolean adding, int type, AlertListener listener) { ArrayList<AlertListener> l = listeners.get(type); if (l == null) { l = new ArrayList<AlertListener>(); listeners.append(type, l); } if (adding) { l.add(listener); } else { l.remove(listener); } listenerSnapshots.append(type, l.toArray(new AlertListener[0])); } private static List<Pair<String, Integer>> defaultRouters() { List<Pair<String, Integer>> list = new LinkedList<Pair<String, Integer>>(); list.add(new Pair<String, Integer>("router.bittorrent.com", 6881)); list.add(new Pair<String, Integer>("dht.transmissionbt.com", 6881)); return list; } private void updateSessionStat(SessionStatsAlert alert) { long now = System.currentTimeMillis(); long tickIntervalMs = now - lastStatSecondTick; lastStatSecondTick = now; long received = alert.value(counters.stats_counter_t.recv_bytes.swigValue()); long payload = alert.value(counters.stats_counter_t.recv_payload_bytes.swigValue()); long protocol = received - payload; long ip = alert.value(counters.stats_counter_t.recv_ip_overhead_bytes.swigValue()); payload -= stat.downloadPayload(); protocol -= stat.downloadProtocol(); ip -= stat.downloadIPProtocol(); stat.received(payload, protocol, ip); long sent = alert.value(counters.stats_counter_t.sent_bytes.swigValue()); payload = alert.value(counters.stats_counter_t.sent_payload_bytes.swigValue()); protocol = sent - payload; ip = alert.value(counters.stats_counter_t.sent_ip_overhead_bytes.swigValue()); payload -= stat.uploadPayload(); protocol -= stat.uploadProtocol(); ip -= stat.uploadIPProtocol(); stat.sent(payload, protocol, ip); stat.secondTick(tickIntervalMs); } private static session createSession(SettingsPack settings, boolean logging) { settings_pack sp = settings.getSwig(); int alert_mask = alert.category_t.all_categories.swigValue(); if (!logging) { int log_mask = alert.category_t.session_log_notification.swigValue() | alert.category_t.torrent_log_notification.swigValue() | alert.category_t.peer_log_notification.swigValue() | alert.category_t.dht_log_notification.swigValue() | alert.category_t.port_mapping_log_notification.swigValue(); alert_mask = alert_mask & ~log_mask; } // we always override alert_mask since we use it for our internal operations sp.set_int(settings_pack.int_types.alert_mask.swigValue(), alert_mask); return new session(sp); } private static session createSessionDeprecated(Fingerprint print, Pair<Integer, Integer> prange, String iface, List<Pair<String, Integer>> routers, boolean logging) { int alert_mask = alert.category_t.all_categories.swigValue(); if (!logging) { int log_mask = alert.category_t.session_log_notification.swigValue() | alert.category_t.torrent_log_notification.swigValue() | alert.category_t.peer_log_notification.swigValue() | alert.category_t.dht_log_notification.swigValue() | alert.category_t.port_mapping_log_notification.swigValue(); alert_mask = alert_mask & ~log_mask; } settings_pack sp = new settings_pack(); sp.set_int(settings_pack.int_types.alert_mask.swigValue(), alert_mask); sp.set_int(settings_pack.int_types.max_retry_port_bind.swigValue(), prange.second - prange.first); sp.set_str(settings_pack.string_types.peer_fingerprint.swigValue(), print.toString()); String if_string = String.format("%s:%d", iface, prange.first); sp.set_str(settings_pack.string_types.listen_interfaces.swigValue(), if_string); return new session(sp); } /** * Flags to be passed in to remove_torrent(). */ public enum Options { /** * Delete the files belonging to the torrent from disk. */ DELETE_FILES(options_t.delete_files.swigValue()), /** * */ UNKNOWN(-1); Options(int swigValue) { this.swigValue = swigValue; } private final int swigValue; public int getSwig() { return swigValue; } } /** * protocols used by add_port_mapping(). */ public enum ProtocolType { UDP(session.protocol_type.udp), TCP(session.protocol_type.tcp); ProtocolType(session.protocol_type swigObj) { this.swigObj = swigObj; } private final session.protocol_type swigObj; public session.protocol_type getSwig() { return swigObj; } } }
src/main/java/com/frostwire/jlibtorrent/Session.java
package com.frostwire.jlibtorrent; import com.frostwire.jlibtorrent.alerts.*; import com.frostwire.jlibtorrent.plugins.Plugin; import com.frostwire.jlibtorrent.plugins.SwigPlugin; import com.frostwire.jlibtorrent.swig.*; import com.frostwire.jlibtorrent.swig.session_handle.options_t; import java.io.File; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * The session holds all state that spans multiple torrents. Among other * things it runs the network loop and manages all torrents. Once it's * created, the session object will spawn the main thread that will do all * the work. The main thread will be idle as long it doesn't have any * torrents to participate in. * <p/> * This class belongs to a middle logical layer of abstraction. It's a wrapper * of the underlying swig session object (from libtorrent), but it does not * expose all the raw features, not expose a very high level interface * like {@link com.frostwire.jlibtorrent.DHT DHT} or * {@link com.frostwire.jlibtorrent.Downloader Downloader}. * * @author gubatron * @author aldenml */ public final class Session extends SessionHandle { private static final Logger LOG = Logger.getLogger(Session.class); private static final long REQUEST_STATS_RESOLUTION_MILLIS = 1000; private static final long ALERTS_LOOP_WAIT_MILLIS = 500; private final session s; private final JavaStat stat; private final SessionStats stats; private long lastStatsRequestTime; private long lastStatSecondTick; private final SparseArray<ArrayList<AlertListener>> listeners; private final SparseArray<AlertListener[]> listenerSnapshots; private boolean running; private final LinkedList<SwigPlugin> plugins; /** * The flag alert_mask is always set to all_categories. * * @param settings * @param logging */ public Session(SettingsPack settings, boolean logging) { super(createSession(settings, logging)); this.s = (session) super.s; this.stat = new JavaStat(); this.stats = new SessionStats(stat); this.listeners = new SparseArray<ArrayList<AlertListener>>(); this.listenerSnapshots = new SparseArray<AlertListener[]>(); this.running = true; alertsLoop(); for (Pair<String, Integer> router : defaultRouters()) { s.add_dht_router(router.to_string_int_pair()); } this.plugins = new LinkedList<SwigPlugin>(); } @Deprecated public Session(Fingerprint print, Pair<Integer, Integer> prange, String iface, List<Pair<String, Integer>> routers, boolean logging) { super(createSessionDeprecated(print, prange, iface, routers, logging)); this.s = (session) super.s; this.stat = new JavaStat(); this.stats = new SessionStats(stat); this.listeners = new SparseArray<ArrayList<AlertListener>>(); this.listenerSnapshots = new SparseArray<AlertListener[]>(); this.running = true; alertsLoop(); for (Pair<String, Integer> router : routers) { s.add_dht_router(router.to_string_int_pair()); } this.plugins = new LinkedList<SwigPlugin>(); } public Session(Fingerprint print, Pair<Integer, Integer> prange, String iface, List<Pair<String, Integer>> routers) { this(print, prange, iface, routers, false); } public Session(Fingerprint print, Pair<Integer, Integer> prange, String iface) { this(print, prange, iface, defaultRouters()); } public Session(Fingerprint print) { this(print, new Pair<Integer, Integer>(0, 0), "0.0.0.0"); } public Session(Pair<Integer, Integer> prange, String iface) { this(new Fingerprint(), prange, iface); } public Session() { this(new SettingsPack(), false); } public session getSwig() { return s; } public void addListener(AlertListener listener) { modifyListeners(true, listener); } public void removeListener(AlertListener listener) { modifyListeners(false, listener); } /** * You add torrents through the add_torrent() function where you give an * object with all the parameters. The add_torrent() overloads will block * until the torrent has been added (or failed to be added) and returns * an error code and a torrent_handle. In order to add torrents more * efficiently, consider using async_add_torrent() which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as add_torrent_alert. * <p/> * The overload that does not take an error_code throws an exception on * error and is not available when building without exception support. * The torrent_handle returned by add_torrent() can be used to retrieve * information about the torrent's progress, its peers etc. It is also * used to abort a torrent. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * <p/> * all torrent_handles must be destructed before the session is destructed! * * @param ti * @param saveDir * @param priorities * @param resumeFile * @return */ public TorrentHandle addTorrent(TorrentInfo ti, File saveDir, Priority[] priorities, File resumeFile) { return addTorrentSupport(ti, saveDir, priorities, resumeFile, false); } /** * You add torrents through the add_torrent() function where you give an * object with all the parameters. The add_torrent() overloads will block * until the torrent has been added (or failed to be added) and returns * an error code and a torrent_handle. In order to add torrents more * efficiently, consider using async_add_torrent() which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as add_torrent_alert. * <p/> * The overload that does not take an error_code throws an exception on * error and is not available when building without exception support. * The torrent_handle returned by add_torrent() can be used to retrieve * information about the torrent's progress, its peers etc. It is also * used to abort a torrent. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * <p/> * all torrent_handles must be destructed before the session is destructed! * * @param torrent * @param saveDir * @param resumeFile * @return */ public TorrentHandle addTorrent(File torrent, File saveDir, File resumeFile) { return addTorrent(new TorrentInfo(torrent), saveDir, null, resumeFile); } /** * You add torrents through the add_torrent() function where you give an * object with all the parameters. The add_torrent() overloads will block * until the torrent has been added (or failed to be added) and returns * an error code and a torrent_handle. In order to add torrents more * efficiently, consider using async_add_torrent() which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as add_torrent_alert. * <p/> * The overload that does not take an error_code throws an exception on * error and is not available when building without exception support. * The torrent_handle returned by add_torrent() can be used to retrieve * information about the torrent's progress, its peers etc. It is also * used to abort a torrent. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * <p/> * all torrent_handles must be destructed before the session is destructed! * * @param torrent * @param saveDir * @return */ public TorrentHandle addTorrent(File torrent, File saveDir) { return addTorrent(torrent, saveDir, null); } /** * In order to add torrents more efficiently, consider using this which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as {@link com.frostwire.jlibtorrent.alerts.AddTorrentAlert}. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * * @param ti * @param saveDir * @param priorities * @param resumeFile */ public void asyncAddTorrent(TorrentInfo ti, File saveDir, Priority[] priorities, File resumeFile) { addTorrentSupport(ti, saveDir, priorities, resumeFile, true); } /** * You add torrents through the add_torrent() function where you give an * object with all the parameters. The add_torrent() overloads will block * until the torrent has been added (or failed to be added) and returns * an error code and a torrent_handle. In order to add torrents more * efficiently, consider using async_add_torrent() which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as add_torrent_alert. * <p/> * The overload that does not take an error_code throws an exception on * error and is not available when building without exception support. * The torrent_handle returned by add_torrent() can be used to retrieve * information about the torrent's progress, its peers etc. It is also * used to abort a torrent. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * <p/> * all torrent_handles must be destructed before the session is destructed! * * @param torrent * @param saveDir * @param resumeFile */ public void asyncAddTorrent(File torrent, File saveDir, File resumeFile) { asyncAddTorrent(new TorrentInfo(torrent), saveDir, null, resumeFile); } /** * You add torrents through the add_torrent() function where you give an * object with all the parameters. The add_torrent() overloads will block * until the torrent has been added (or failed to be added) and returns * an error code and a torrent_handle. In order to add torrents more * efficiently, consider using async_add_torrent() which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as add_torrent_alert. * <p/> * The overload that does not take an error_code throws an exception on * error and is not available when building without exception support. * The torrent_handle returned by add_torrent() can be used to retrieve * information about the torrent's progress, its peers etc. It is also * used to abort a torrent. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * <p/> * all torrent_handles must be destructed before the session is destructed! * * @param torrent * @param saveDir */ public void asyncAddTorrent(File torrent, File saveDir) { asyncAddTorrent(torrent, saveDir, null); } /** * This method will close all peer connections associated with the torrent and tell the * tracker that we've stopped participating in the swarm. This operation cannot fail. * When it completes, you will receive a torrent_removed_alert. * <p/> * The optional second argument options can be used to delete all the files downloaded * by this torrent. To do so, pass in the value session::delete_files. The removal of * the torrent is asyncronous, there is no guarantee that adding the same torrent immediately * after it was removed will not throw a libtorrent_exception exception. Once the torrent * is deleted, a torrent_deleted_alert is posted. * * @param th */ public void removeTorrent(TorrentHandle th, Options options) { s.remove_torrent(th.getSwig(), options.getSwig()); } /** * This method will close all peer connections associated with the torrent and tell the * tracker that we've stopped participating in the swarm. This operation cannot fail. * When it completes, you will receive a torrent_removed_alert. * * @param th */ public void removeTorrent(TorrentHandle th) { if (th.isValid()) { s.remove_torrent(th.getSwig()); } } /** * Applies the settings specified by the settings_pack ``sp``. This is an * asynchronous operation that will return immediately and actually apply * the settings to the main thread of libtorrent some time later. * * @param sp */ public void applySettings(SettingsPack sp) { s.apply_settings(sp.getSwig()); } /** * In case you want to destruct the session asynchrounously, you can * request a session destruction proxy. If you don't do this, the * destructor of the session object will block while the trackers are * contacted. If you keep one ``session_proxy`` to the session when * destructing it, the destructor will not block, but start to close down * the session, the destructor of the proxy will then synchronize the * threads. So, the destruction of the session is performed from the * ``session`` destructor call until the ``session_proxy`` destructor * call. The ``session_proxy`` does not have any operations on it (since * the session is being closed down, no operations are allowed on it). * The only valid operation is calling the destructor:: * * @return */ public SessionProxy abort() { running = false; return new SessionProxy(s.abort()); } /** * Pausing the session has the same effect as pausing every torrent in * it, except that torrents will not be resumed by the auto-manage * mechanism. */ public void pause() { s.pause(); } /** * Resuming will restore the torrents to their previous paused * state. i.e. the session pause state is separate from the torrent pause * state. A torrent is inactive if it is paused or if the session is * paused. */ public void resume() { s.resume(); } public boolean isPaused() { return s.is_paused(); } /** * returns the port we ended up listening on. Since you * just pass a port-range to the constructor and to ``listen_on()``, to * know which port it ended up using, you have to ask the session using * this function. * * @return */ public int getListenPort() { return s.listen_port(); } public int getSslListenPort() { return s.ssl_listen_port(); } /** * will tell you whether or not the session has * successfully opened a listening port. If it hasn't, this function will * return false, and then you can use ``listen_on()`` to make another * attempt. * * @return */ public boolean isListening() { return s.is_listening(); } /** * Loads and saves all session settings, including dht_settings, * encryption settings and proxy settings. ``save_state`` writes all keys * to the ``entry`` that's passed in, which needs to either not be * initialized, or initialized as a dictionary. * <p/> * ``load_state`` expects a lazy_entry which can be built from a bencoded * buffer with lazy_bdecode(). * <p/> * The ``flags`` arguments passed in to ``save_state`` can be used to * filter which parts of the session state to save. By default, all state * is saved (except for the individual torrents). see save_state_flags_t * * @return */ public byte[] saveState() { entry e = new entry(); s.save_state(e); return Vectors.char_vector2bytes(e.bencode()); } /** * Loads and saves all session settings, including dht_settings, * encryption settings and proxy settings. ``save_state`` writes all keys * to the ``entry`` that's passed in, which needs to either not be * initialized, or initialized as a dictionary. * <p/> * ``load_state`` expects a lazy_entry which can be built from a bencoded * buffer with lazy_bdecode(). * <p/> * The ``flags`` arguments passed in to ``save_state`` can be used to * filter which parts of the session state to save. By default, all state * is saved (except for the individual torrents). see save_state_flags_t * * @param data */ public void loadState(byte[] data) { char_vector buffer = Vectors.bytes2char_vector(data); bdecode_node n = new bdecode_node(); error_code ec = new error_code(); int ret = bdecode_node.bdecode(buffer, n, ec); if (ret == 0) { s.load_state(n); } else { LOG.error("failed to decode torrent: " + ec.message()); } } /** * This functions instructs the session to post the state_update_alert, * containing the status of all torrents whose state changed since the * last time this function was called. * <p/> * Only torrents who has the state subscription flag set will be * included. This flag is on by default. See add_torrent_params. * the ``flags`` argument is the same as for torrent_handle::status(). * see torrent_handle::status_flags_t. * * @param flags */ public void postTorrentUpdates(TorrentHandle.StatusFlags flags) { s.post_torrent_updates(flags.getSwig()); } /** * This functions instructs the session to post the state_update_alert, * containing the status of all torrents whose state changed since the * last time this function was called. * <p/> * Only torrents who has the state subscription flag set will be * included. */ public void postTorrentUpdates() { s.post_torrent_updates(); } /** * This function will post a {@link com.frostwire.jlibtorrent.alerts.SessionStatsAlert} object, containing a * snapshot of the performance counters from the internals of libtorrent. * To interpret these counters, query the session via * session_stats_metrics(). */ public void postSessionStats() { s.post_session_stats(); } /** * This will cause a dht_stats_alert to be posted. */ public void postDHTStats() { s.post_dht_stats(); } /** * Looks for a torrent with the given info-hash. In * case there is such a torrent in the session, a torrent_handle to that * torrent is returned. * <p/> * In case the torrent cannot be found, a null is returned. * * @param infoHash * @return */ public TorrentHandle findTorrent(Sha1Hash infoHash) { torrent_handle th = s.find_torrent(infoHash.getSwig()); return th != null && th.is_valid() ? new TorrentHandle(th) : null; } /** * Returns a list of torrent handles to all the * torrents currently in the session. * * @return */ public List<TorrentHandle> getTorrents() { torrent_handle_vector v = s.get_torrents(); long size = v.size(); List<TorrentHandle> l = new ArrayList<TorrentHandle>((int) size); for (int i = 0; i < size; i++) { l.add(new TorrentHandle(v.get(i))); } return l; } // starts/stops UPnP, NATPMP or LSD port mappers they are stopped by // default These functions are not available in case // ``TORRENT_DISABLE_DHT`` is defined. ``start_dht`` starts the dht node // and makes the trackerless service available to torrents. The startup // state is optional and can contain nodes and the node id from the // previous session. The dht node state is a bencoded dictionary with the // following entries: // // nodes // A list of strings, where each string is a node endpoint encoded in // binary. If the string is 6 bytes long, it is an IPv4 address of 4 // bytes, encoded in network byte order (big endian), followed by a 2 // byte port number (also network byte order). If the string is 18 // bytes long, it is 16 bytes of IPv6 address followed by a 2 bytes // port number (also network byte order). // // node-id // The node id written as a readable string as a hexadecimal number. // // ``dht_state`` will return the current state of the dht node, this can // be used to start up the node again, passing this entry to // ``start_dht``. It is a good idea to save this to disk when the session // is closed, and read it up again when starting. // // If the port the DHT is supposed to listen on is already in use, and // exception is thrown, ``asio::error``. // // ``stop_dht`` stops the dht node. // // ``add_dht_node`` adds a node to the routing table. This can be used if // your client has its own source of bootstrapping nodes. // // ``set_dht_settings`` sets some parameters availavle to the dht node. // See dht_settings for more information. // // ``is_dht_running()`` returns true if the DHT support has been started // and false // otherwise. void setDHTSettings(DHTSettings settings) { s.set_dht_settings(settings.getSwig()); } public boolean isDHTRunning() { return s.is_dht_running(); } /** * takes a host name and port pair. That endpoint will be * pinged, and if a valid DHT reply is received, the node will be added to * the routing table. * * @param node */ public void addDHTNode(Pair<String, Integer> node) { s.add_dht_node(node.to_string_int_pair()); } /** * adds the given endpoint to a list of DHT router nodes. * If a search is ever made while the routing table is empty, those nodes will * be used as backups. Nodes in the router node list will also never be added * to the regular routing table, which effectively means they are only used * for bootstrapping, to keep the load off them. * <p/> * An example routing node that you could typically add is * ``router.bittorrent.com``. * * @param node */ public void addDHTRouter(Pair<String, Integer> node) { s.add_dht_router(node.to_string_int_pair()); } /** * Query the DHT for an immutable item at the target hash. * the result is posted as a {@link DhtImmutableItemAlert}. * * @param target */ public void dhtGetItem(Sha1Hash target) { s.dht_get_item(target.getSwig()); } /** * Query the DHT for a mutable item under the public key ``key``. * this is an ed25519 key. ``salt`` is optional and may be left * as an empty string if no salt is to be used. * if the item is found in the DHT, a dht_mutable_item_alert is * posted. * * @param key */ public void dhtGetItem(byte[] key) { s.dht_get_item(Vectors.bytes2char_vector(key)); } /** * Query the DHT for a mutable item under the public key ``key``. * this is an ed25519 key. ``salt`` is optional and may be left * as an empty string if no salt is to be used. * if the item is found in the DHT, a dht_mutable_item_alert is * posted. * * @param key * @param salt */ public void dhtGetItem(byte[] key, String salt) { s.dht_get_item(Vectors.bytes2char_vector(key), salt); } /** * Store the given bencoded data as an immutable item in the DHT. * the returned hash is the key that is to be used to look the item * up agan. It's just the sha-1 hash of the bencoded form of the * structure. * * @param entry * @return */ public Sha1Hash dhtPutItem(Entry entry) { return new Sha1Hash(s.dht_put_item(entry.getSwig())); } // store an immutable item. The ``key`` is the public key the blob is // to be stored under. The optional ``salt`` argument is a string that // is to be mixed in with the key when determining where in the DHT // the value is to be stored. The callback function is called from within // the libtorrent network thread once we've found where to store the blob, // possibly with the current value stored under the key. // The values passed to the callback functions are: // // entry& value // the current value stored under the key (may be empty). Also expected // to be set to the value to be stored by the function. // // boost::array<char,64>& signature // the signature authenticating the current value. This may be zeroes // if there is currently no value stored. The functon is expected to // fill in this buffer with the signature of the new value to store. // To generate the signature, you may want to use the // ``sign_mutable_item`` function. // // boost::uint64_t& seq // current sequence number. May be zero if there is no current value. // The function is expected to set this to the new sequence number of // the value that is to be stored. Sequence numbers must be monotonically // increasing. Attempting to overwrite a value with a lower or equal // sequence number will fail, even if the signature is correct. // // std::string const& salt // this is the salt that was used for this put call. // // Since the callback function ``cb`` is called from within libtorrent, // it is critical to not perform any blocking operations. Ideally not // even locking a mutex. Pass any data required for this function along // with the function object's context and make the function entirely // self-contained. The only reason data blobs' values are computed // via a function instead of just passing in the new value is to avoid // race conditions. If you want to *update* the value in the DHT, you // must first retrieve it, then modify it, then write it back. The way // the DHT works, it is natural to always do a lookup before storing and // calling the callback in between is convenient. public void dhtPutItem(byte[] publicKey, byte[] privateKey, Entry entry) { s.dht_put_item(Vectors.bytes2char_vector(publicKey), Vectors.bytes2char_vector(privateKey), entry.getSwig()); } // store an immutable item. The ``key`` is the public key the blob is // to be stored under. The optional ``salt`` argument is a string that // is to be mixed in with the key when determining where in the DHT // the value is to be stored. The callback function is called from within // the libtorrent network thread once we've found where to store the blob, // possibly with the current value stored under the key. // The values passed to the callback functions are: // // entry& value // the current value stored under the key (may be empty). Also expected // to be set to the value to be stored by the function. // // boost::array<char,64>& signature // the signature authenticating the current value. This may be zeroes // if there is currently no value stored. The functon is expected to // fill in this buffer with the signature of the new value to store. // To generate the signature, you may want to use the // ``sign_mutable_item`` function. // // boost::uint64_t& seq // current sequence number. May be zero if there is no current value. // The function is expected to set this to the new sequence number of // the value that is to be stored. Sequence numbers must be monotonically // increasing. Attempting to overwrite a value with a lower or equal // sequence number will fail, even if the signature is correct. // // std::string const& salt // this is the salt that was used for this put call. // // Since the callback function ``cb`` is called from within libtorrent, // it is critical to not perform any blocking operations. Ideally not // even locking a mutex. Pass any data required for this function along // with the function object's context and make the function entirely // self-contained. The only reason data blobs' values are computed // via a function instead of just passing in the new value is to avoid // race conditions. If you want to *update* the value in the DHT, you // must first retrieve it, then modify it, then write it back. The way // the DHT works, it is natural to always do a lookup before storing and // calling the callback in between is convenient. public void dhtPutItem(byte[] publicKey, byte[] privateKey, Entry entry, String salt) { s.dht_put_item(Vectors.bytes2char_vector(publicKey), Vectors.bytes2char_vector(privateKey), entry.getSwig(), salt); } public void dhtGetPeers(Sha1Hash infoHash) { s.dht_get_peers(infoHash.getSwig()); } public void dhtAnnounce(Sha1Hash infoHash, int port, int flags) { s.dht_announce(infoHash.getSwig(), port, flags); } public void dhtAnnounce(Sha1Hash infoHash) { s.dht_announce(infoHash.getSwig()); } public void dhtDirectRequest(UdpEndpoint endp, Entry entry) { s.dht_direct_request(endp.getSwig(), entry.getSwig()); } public void addExtension(Plugin p) { SwigPlugin sp = new SwigPlugin(p); s.add_swig_extension(sp); plugins.add(sp); } /** * add_port_mapping adds a port forwarding on UPnP and/or NAT-PMP, * whichever is enabled. The return value is a handle referring to the * port mapping that was just created. Pass it to delete_port_mapping() * to remove it. * * @param t * @param externalPort * @param localPort * @return */ public int addPortMapping(ProtocolType t, int externalPort, int localPort) { return s.add_port_mapping(t.getSwig(), externalPort, localPort); } public void deletePortMapping(int handle) { s.delete_port_mapping(handle); } public SessionStats getStats() { return stats; } public SettingsPack getSettingsPack() { return new SettingsPack(getSwig().get_settings()); } @Deprecated public SessionSettings getSettings() { return new SessionSettings(s.get_settings()); } @Deprecated public ProxySettings getProxy() { return new ProxySettings(new settings_pack()); } @Deprecated public void setProxy(ProxySettings s) { this.s.apply_settings(s.getSwig()); } @Deprecated public void setSettings(SessionSettings s) { this.applySettings(s.toPack()); } @Deprecated public SessionStatus getStatus() { return new SessionStatus(stats); } // You add torrents through the add_torrent() function where you give an // object with all the parameters. The add_torrent() overloads will block // until the torrent has been added (or failed to be added) and returns // an error code and a torrent_handle. In order to add torrents more // efficiently, consider using async_add_torrent() which returns // immediately, without waiting for the torrent to add. Notification of // the torrent being added is sent as add_torrent_alert. // // The overload that does not take an error_code throws an exception on // error and is not available when building without exception support. // The torrent_handle returned by add_torrent() can be used to retrieve // information about the torrent's progress, its peers etc. It is also // used to abort a torrent. // // If the torrent you are trying to add already exists in the session (is // either queued for checking, being checked or downloading) // ``add_torrent()`` will throw libtorrent_exception which derives from // ``std::exception`` unless duplicate_is_error is set to false. In that // case, add_torrent() will return the handle to the existing torrent. // // all torrent_handles must be destructed before the session is destructed! public TorrentHandle addTorrent(AddTorrentParams params) { return new TorrentHandle(s.add_torrent(params.getSwig())); } public TorrentHandle addTorrent(AddTorrentParams params, ErrorCode ec) { return new TorrentHandle(s.add_torrent(params.getSwig(), ec.getSwig())); } public void asyncAddTorrent(AddTorrentParams params) { s.async_add_torrent(params.getSwig()); } @Override protected void finalize() throws Throwable { this.running = false; super.finalize(); } void fireAlert(Alert<?> a) { int type = a.getSwig() != null ? a.getSwig().type() : a.getType().getSwig(); fireAlert(a, type); fireAlert(a, -1); } private void fireAlert(Alert<?> a, int type) { AlertListener[] listeners = listenerSnapshots.get(type); if (listeners != null) { for (int i = 0; i < listeners.length; i++) { try { AlertListener l = listeners[i]; if (l != null) { l.alert(a); } } catch (Throwable e) { LOG.warn("Error calling alert listener", e); } } } } private TorrentHandle addTorrentSupport(TorrentInfo ti, File saveDir, Priority[] priorities, File resumeFile, boolean async) { String savePath = null; if (saveDir != null) { savePath = saveDir.getAbsolutePath(); } else if (resumeFile == null) { throw new IllegalArgumentException("Both saveDir and resumeFile can't be null at the same time"); } add_torrent_params p = add_torrent_params.create_instance(); p.set_ti(ti.getSwig()); if (savePath != null) { p.setSave_path(savePath); } if (priorities != null) { p.setFile_priorities(Vectors.priorities2unsigned_char_vector(priorities)); } p.setStorage_mode(storage_mode_t.storage_mode_sparse); long flags = p.getFlags(); flags &= ~add_torrent_params.flags_t.flag_auto_managed.swigValue(); if (resumeFile != null) { try { byte[] data = Files.bytes(resumeFile); p.setResume_data(Vectors.bytes2char_vector(data)); flags |= add_torrent_params.flags_t.flag_use_resume_save_path.swigValue(); } catch (Throwable e) { LOG.warn("Unable to set resume data", e); } } p.setFlags(flags); if (async) { s.async_add_torrent(p); return null; } else { torrent_handle th = s.add_torrent(p); return new TorrentHandle(th); } } private void alertsLoop() { Runnable r = new Runnable() { @Override public void run() { alert_ptr_vector vector = new alert_ptr_vector(); high_resolution_clock.duration max_wait = libtorrent.to_milliseconds(ALERTS_LOOP_WAIT_MILLIS); while (running) { alert ptr = s.wait_for_alert(max_wait); if (ptr != null) { s.pop_alerts(vector); long size = vector.size(); for (int i = 0; i < size; i++) { alert swigAlert = vector.get(i); int type = swigAlert.type(); Alert<?> alert = null; if (type == AlertType.SESSION_STATS.getSwig()) { alert = Alerts.cast(swigAlert); updateSessionStat((SessionStatsAlert) alert); } if (listeners.indexOfKey(type) >= 0) { if (alert == null) { alert = Alerts.cast(swigAlert); } fireAlert(alert, type); } if (type != AlertType.SESSION_STATS.getSwig() && listeners.indexOfKey(-1) >= 0) { if (alert == null) { alert = Alerts.cast(swigAlert); } fireAlert(alert, -1); } } vector.clear(); } long now = System.currentTimeMillis(); if ((now - lastStatsRequestTime) >= REQUEST_STATS_RESOLUTION_MILLIS) { lastStatsRequestTime = now; postSessionStats(); } } } }; Thread t = new Thread(r, "Session-alertsLoop"); t.setDaemon(true); t.start(); } private void modifyListeners(boolean adding, AlertListener listener) { if (listener != null) { int[] types = listener.types(); //all alert-type including listener if (types == null) { modifyListeners(adding, -1, listener); } else { for (int i = 0; i < types.length; i++) { if (types[i] == -1) { throw new IllegalArgumentException("Type can't be the key of all (-1)"); } modifyListeners(adding, types[i], listener); } } } } private void modifyListeners(boolean adding, int type, AlertListener listener) { ArrayList<AlertListener> l = listeners.get(type); if (l == null) { l = new ArrayList<AlertListener>(); listeners.append(type, l); } if (adding) { l.add(listener); } else { l.remove(listener); } listenerSnapshots.append(type, l.toArray(new AlertListener[0])); } private static List<Pair<String, Integer>> defaultRouters() { List<Pair<String, Integer>> list = new LinkedList<Pair<String, Integer>>(); list.add(new Pair<String, Integer>("router.bittorrent.com", 6881)); list.add(new Pair<String, Integer>("dht.transmissionbt.com", 6881)); return list; } private void updateSessionStat(SessionStatsAlert alert) { long now = System.currentTimeMillis(); long tickIntervalMs = now - lastStatSecondTick; lastStatSecondTick = now; long received = alert.value(counters.stats_counter_t.recv_bytes.swigValue()); long payload = alert.value(counters.stats_counter_t.recv_payload_bytes.swigValue()); long protocol = received - payload; long ip = alert.value(counters.stats_counter_t.recv_ip_overhead_bytes.swigValue()); payload -= stat.downloadPayload(); protocol -= stat.downloadProtocol(); ip -= stat.downloadIPProtocol(); stat.received(payload, protocol, ip); long sent = alert.value(counters.stats_counter_t.sent_bytes.swigValue()); payload = alert.value(counters.stats_counter_t.sent_payload_bytes.swigValue()); protocol = sent - payload; ip = alert.value(counters.stats_counter_t.sent_ip_overhead_bytes.swigValue()); payload -= stat.uploadPayload(); protocol -= stat.uploadProtocol(); ip -= stat.uploadIPProtocol(); stat.sent(payload, protocol, ip); stat.secondTick(tickIntervalMs); } private static session createSession(SettingsPack settings, boolean logging) { settings_pack sp = settings.getSwig(); int alert_mask = alert.category_t.all_categories.swigValue(); if (!logging) { int log_mask = alert.category_t.session_log_notification.swigValue() | alert.category_t.torrent_log_notification.swigValue() | alert.category_t.peer_log_notification.swigValue() | alert.category_t.dht_log_notification.swigValue() | alert.category_t.port_mapping_log_notification.swigValue(); alert_mask = alert_mask & ~log_mask; } // we always override alert_mask since we use it for our internal operations sp.set_int(settings_pack.int_types.alert_mask.swigValue(), alert_mask); return new session(sp); } private static session createSessionDeprecated(Fingerprint print, Pair<Integer, Integer> prange, String iface, List<Pair<String, Integer>> routers, boolean logging) { int alert_mask = alert.category_t.all_categories.swigValue(); if (!logging) { int log_mask = alert.category_t.session_log_notification.swigValue() | alert.category_t.torrent_log_notification.swigValue() | alert.category_t.peer_log_notification.swigValue() | alert.category_t.dht_log_notification.swigValue() | alert.category_t.port_mapping_log_notification.swigValue(); alert_mask = alert_mask & ~log_mask; } settings_pack sp = new settings_pack(); sp.set_int(settings_pack.int_types.alert_mask.swigValue(), alert_mask); sp.set_int(settings_pack.int_types.max_retry_port_bind.swigValue(), prange.second - prange.first); sp.set_str(settings_pack.string_types.peer_fingerprint.swigValue(), print.toString()); String if_string = String.format("%s:%d", iface, prange.first); sp.set_str(settings_pack.string_types.listen_interfaces.swigValue(), if_string); return new session(sp); } /** * Flags to be passed in to remove_torrent(). */ public enum Options { /** * Delete the files belonging to the torrent from disk. */ DELETE_FILES(options_t.delete_files.swigValue()), /** * */ UNKNOWN(-1); Options(int swigValue) { this.swigValue = swigValue; } private final int swigValue; public int getSwig() { return swigValue; } } /** * protocols used by add_port_mapping(). */ public enum ProtocolType { UDP(session.protocol_type.udp), TCP(session.protocol_type.tcp); ProtocolType(session.protocol_type swigObj) { this.swigObj = swigObj; } private final session.protocol_type swigObj; public session.protocol_type getSwig() { return swigObj; } } }
refactor
src/main/java/com/frostwire/jlibtorrent/Session.java
refactor
Java
mit
27cc26335c66f7f7b7352d9ffa2816fc80b2fe7f
0
jaredlll08/ModTweaker2,yrsegal/ModTweaker2,elucent/ModTweaker,jaredlll08/ModTweaker
package modtweaker2.mods.forestry.handlers; import static modtweaker2.helpers.InputHelper.toFluid; import static modtweaker2.helpers.InputHelper.toILiquidStack; import static modtweaker2.helpers.InputHelper.toIItemStack; import static modtweaker2.helpers.InputHelper.toStack; import static modtweaker2.helpers.InputHelper.toStacks; import static modtweaker2.helpers.StackHelper.matches; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import minetweaker.MineTweakerAPI; import minetweaker.api.item.IIngredient; import minetweaker.api.item.IItemStack; import minetweaker.api.item.WeightedItemStack; import minetweaker.api.liquid.ILiquidStack; import modtweaker2.helpers.LogHelper; import modtweaker2.utils.BaseListAddition; import modtweaker2.utils.BaseListRemoval; import stanhebben.zenscript.annotations.Optional; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; import forestry.factory.gadgets.MachineSqueezer; import forestry.factory.gadgets.MachineSqueezer.Recipe; import forestry.factory.gadgets.MachineSqueezer.RecipeManager; @ZenClass("mods.forestry.Squeezer") public class Squeezer { public static final String name = "Forestry Squeezer"; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * Adds a recipe without additional item output * * @param fluidOutput recipe fluid amount * @param ingredients recipe ingredients * @param timePerItem time per crafting operation */ @ZenMethod public static void addRecipe(ILiquidStack fluidOutput, int timePerItem, IItemStack[] ingredients) { MineTweakerAPI.apply(new Add( new Recipe(timePerItem, toStacks(ingredients), toFluid(fluidOutput), null, 0) )); } /** * Adds a recipe with additional item output * * @param fluidOutput recipe fluid amount * @param itemOutput recipe output * @param ingredients recipe ingredients * @param timePerItem time per crafting operation */ @ZenMethod public static void addRecipe(ILiquidStack fluidOutput, WeightedItemStack itemOutput, IItemStack[] ingredients, int timePerItem) { MineTweakerAPI.apply(new Add(new Recipe(timePerItem, toStacks(ingredients), toFluid(fluidOutput), toStack(itemOutput.getStack()), (int) itemOutput.getPercent()))); } @ZenMethod @Deprecated public static void addRecipe(int timePerItem, IItemStack[] resources, ILiquidStack liquid, IItemStack remnants, int chance) { MineTweakerAPI.apply(new Add(new Recipe(timePerItem, toStacks(resources), toFluid(liquid), toStack(remnants), chance))); } private static class Add extends BaseListAddition<Recipe> { public Add(Recipe recipe) { super(Squeezer.name, MachineSqueezer.RecipeManager.recipes); recipes.add(recipe); } @Override public void apply() { super.apply(); for (Recipe recipe : recipes) { RecipeManager.recipeInputs.addAll(Arrays.asList(recipe.resources)); } } @Override public void undo() { super.undo(); for (Recipe recipe : recipes) { RecipeManager.recipeInputs.removeAll(Arrays.asList(recipe.resources)); } } @Override public String getRecipeInfo(Recipe recipe) { return LogHelper.getStackDescription(recipe.liquid); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Removes a recipe for the Centrifuge * * @param liquid liquid output * @param ingredients list of ingredients */ @ZenMethod public static void removeRecipe(IIngredient liquid, @Optional IIngredient[] ingredients) { List<Recipe> recipes = new LinkedList<Recipe>(); for (Recipe r : RecipeManager.recipes) { if (r != null && r.liquid != null && matches(liquid, toILiquidStack(r.liquid))) { // optional check for ingredients if (ingredients != null) { boolean matched = false; for (int i = 0; i < ingredients.length; i++) { if ( matches(ingredients[i], toIItemStack(r.resources[i])) ) matched = true; else { matched = false; // if one ingredients doesn't match abort all further checks break; } } // if some ingredient doesn't match, the last one is false if (matched) recipes.add(r); } else { recipes.add(r); } } } if(!recipes.isEmpty()) { MineTweakerAPI.apply(new Remove(recipes)); } else { LogHelper.logWarning(String.format("No %s Recipe found for %s. Command ignored!", Squeezer.name, liquid.toString())); } } private static class Remove extends BaseListRemoval<Recipe> { public Remove(List<Recipe> recipes) { super(Squeezer.name, MachineSqueezer.RecipeManager.recipes, recipes); } @Override public void apply() { super.apply(); for (Recipe recipe : recipes) { RecipeManager.recipeInputs.removeAll(Arrays.asList(recipe.resources)); } } @Override public void undo() { super.undo(); for (Recipe recipe : recipes) { RecipeManager.recipeInputs.addAll(Arrays.asList(recipe.resources)); } } @Override public String getRecipeInfo(Recipe recipe) { return LogHelper.getStackDescription(recipe.liquid); } } }
src/main/java/modtweaker2/mods/forestry/handlers/Squeezer.java
package modtweaker2.mods.forestry.handlers; import static modtweaker2.helpers.InputHelper.getFluid; import static modtweaker2.helpers.InputHelper.toFluid; import static modtweaker2.helpers.InputHelper.toILiquidStack; import static modtweaker2.helpers.InputHelper.toIItemStack; import static modtweaker2.helpers.InputHelper.toStack; import static modtweaker2.helpers.InputHelper.toStacks; import static modtweaker2.helpers.StackHelper.matches; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import minetweaker.MineTweakerAPI; import minetweaker.api.item.IIngredient; import minetweaker.api.item.IItemStack; import minetweaker.api.item.WeightedItemStack; import minetweaker.api.liquid.ILiquidStack; import modtweaker2.helpers.LogHelper; import modtweaker2.utils.BaseListAddition; import modtweaker2.utils.BaseListRemoval; import stanhebben.zenscript.annotations.Optional; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; import forestry.factory.gadgets.MachineSqueezer; import forestry.factory.gadgets.MachineSqueezer.Recipe; import forestry.factory.gadgets.MachineSqueezer.RecipeManager; @ZenClass("mods.forestry.Squeezer") public class Squeezer { public static final String name = "Forestry Squeezer"; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Adds a recipe with additional item output * * @param fluidOutput recipe fluid amount * @param itemOutput recipe output * @param ingredients recipe ingredients * @param timePerItem time per crafting operation */ @ZenMethod public static void addRecipe(ILiquidStack fluidOutput, WeightedItemStack itemOutput, IItemStack[] ingredients, int timePerItem) { MineTweakerAPI.apply(new Add( new Recipe(timePerItem, toStacks(ingredients), toFluid(fluidOutput), toStack(itemOutput.getStack()), (int) itemOutput.getPercent()) )); //TODO: this should definitiv solved somehow better MachineSqueezer.RecipeManager.recipeFluids.add(getFluid(fluidOutput)); MachineSqueezer.RecipeManager.recipeInputs.addAll(Arrays.asList(toStacks(ingredients))); } @ZenMethod @Deprecated public static void addRecipe(int timePerItem, IItemStack[] resources, ILiquidStack liquid, IItemStack remnants, int chance) { MineTweakerAPI.apply(new Add(new Recipe(timePerItem, toStacks(resources), toFluid(liquid), toStack(remnants), chance))); //TODO: this should definitiv solved somehow better MachineSqueezer.RecipeManager.recipeFluids.add(getFluid(liquid)); MachineSqueezer.RecipeManager.recipeInputs.addAll(Arrays.asList(toStacks(resources))); } private static class Add extends BaseListAddition<Recipe> { public Add(Recipe recipe) { super(Squeezer.name, MachineSqueezer.RecipeManager.recipes); recipes.add(recipe); } @Override public String getRecipeInfo(Recipe recipe) { return LogHelper.getStackDescription(recipe.liquid); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Removes a recipe for the Centrifuge * * @param liquid liquid output * @param ingredients list of ingredients */ @ZenMethod public static void removeRecipe(IIngredient liquid, @Optional IIngredient[] ingredients) { List<Recipe> recipes = new LinkedList<Recipe>(); for (Recipe r : RecipeManager.recipes) { if (r != null && r.liquid != null && matches(liquid, toILiquidStack(r.liquid))) { // optional check for ingredients if (ingredients != null) { boolean matched = false; for (int i = 0; i < ingredients.length; i++) { if ( matches(ingredients[i], toIItemStack(r.resources[i])) ) matched = true; else { matched = false; // if one ingredients doesn't match abort all further checks break; } } // if some ingredient doesn't match, the last one is false if (matched) recipes.add(r); } else { recipes.add(r); } } } if(!recipes.isEmpty()) { MineTweakerAPI.apply(new Remove(recipes)); } else { LogHelper.logWarning(String.format("No %s Recipe found for %s. Command ignored!", Squeezer.name, liquid.toString())); } } private static class Remove extends BaseListRemoval<Recipe> { public Remove(List<Recipe> recipes) { super(Squeezer.name, MachineSqueezer.RecipeManager.recipes, recipes); } @Override public void apply() { super.apply(); } @Override public String getRecipeInfo(Recipe recipe) { return LogHelper.getStackDescription(recipe.liquid); } } }
improved: Forestry Squeezer - bring back the addRecipe variant without itemOutput
src/main/java/modtweaker2/mods/forestry/handlers/Squeezer.java
improved: Forestry Squeezer - bring back the addRecipe variant without itemOutput
Java
mit
939f54e4a002cfe43cb2615863569df45204fe88
0
1fish2/BBQTimer,1fish2/BBQTimer,1fish2/BBQTimer
/* * The MIT License (MIT) * * Copyright (c) 2017 Jerry Morrison * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.onefishtwo.bbqtimer; import android.content.Context; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import androidx.annotation.NonNull; import androidx.test.core.app.ApplicationProvider; import androidx.test.espresso.ViewInteraction; import androidx.test.ext.junit.rules.ActivityScenarioRule; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.filters.LargeTest; import androidx.test.platform.app.InstrumentationRegistry; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.click; import static androidx.test.espresso.action.ViewActions.doubleClick; import static androidx.test.espresso.action.ViewActions.longClick; import static androidx.test.espresso.action.ViewActions.pressImeActionButton; import static androidx.test.espresso.action.ViewActions.typeTextIntoFocusedView; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.doesNotHaveFocus; import static androidx.test.espresso.matcher.ViewMatchers.hasFocus; import static androidx.test.espresso.matcher.ViewMatchers.isChecked; import static androidx.test.espresso.matcher.ViewMatchers.isClickable; import static androidx.test.espresso.matcher.ViewMatchers.isCompletelyDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.isEnabled; import static androidx.test.espresso.matcher.ViewMatchers.isNotChecked; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withText; import static com.onefishtwo.bbqtimer.CustomMatchers.withCompoundDrawable; import static com.onefishtwo.bbqtimer.CustomViewActions.waitMsec; import static com.onefishtwo.bbqtimer.TimeIntervalMatcher.inTimeInterval; import static com.onefishtwo.bbqtimer.TimeIntervalMatcher.inWholeTimeInterval; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertEquals; /** Within-app Espresso UI tests. */ // TODO: Test the app's home screen widget. // TODO: Add a multi-app test that checks the app's notifications. @LargeTest @RunWith(AndroidJUnit4.class) public class InAppUITest { private static final TimeIntervalMatcher TIME_ZERO = inTimeInterval(0, 0); // supports locales private ViewInteraction playPauseButton; // play/pause, formerly known as start/stop private ViewInteraction resetButton; // reset (pause @ 00:00); pause/replay icon or hidden private ViewInteraction stopButton; // stop @ 00:00 private ViewInteraction timeView; private ViewInteraction enableRemindersToggle; private ViewInteraction alarmPeriodTextField; private ViewInteraction countdownDisplay; private ViewInteraction background; @NonNull @Rule public final ActivityScenarioRule<MainActivity> activityScenarioRule = new ActivityScenarioRule<>(MainActivity.class); @Before public void setUp() { playPauseButton = onView(withId(R.id.pauseResumeButton)); resetButton = onView(withId(R.id.resetButton)); stopButton = onView(withId(R.id.stopButton)); timeView = onView(withId(R.id.countUpDisplay)); enableRemindersToggle = onView(withId(R.id.enableReminders)); alarmPeriodTextField = onView(withId(R.id.alarmPeriod)); countdownDisplay = onView(withId(R.id.countdownDisplay)); background = onView(withId(R.id.main_container)); } @After public void tearDown() { playPauseButton = null; resetButton = null; stopButton = null; timeView = null; enableRemindersToggle = null; alarmPeriodTextField = null; countdownDisplay = null; background = null; } // MainActivity's FSM: // // Stopped @ 00:00 |> || --> Playing, Reset (= Paused @ 0:00) // // Reset @ 00:00 |> [] --> Playing, Stopped // // Playing hh:mm++ || [] --> Paused, Stopped // // Paused > 00:00 |> ⟲ [] --> Playing, Reset, Stopped /** * Tests all the nodes and arcs in the app's play/pause/reset/stop FSM. * <p/> * NOTE: Testing the timer is inherently timing-dependent. A test run could fail by not * allowing the app enough time to respond. ARM emulators need extra response time. Mocking * the TimeCounter clock might fix this even with MainActivity's Handler. */ @Test public void playPauseStopUITest() { final long minutes5 = 5 * 60_000L; checkStopped(); // Stopped checkReminder(true); alarmPeriodTextField.check(matches(withText("05:00"))); countdownDisplay.check(matches(withText("05:00"))); countdownDisplay.check(matches(withText(inWholeTimeInterval(minutes5, minutes5)))); enableRemindersToggle.perform(click()); checkReminder(false); enableRemindersToggle.perform(click()); checkReminder(true); resetButton.perform(click()); // Pause/Reset checkPausedAt0(); stopButton.perform(click()); // Stop checkStopped(); playPauseButton.perform(click()); // Play checkPlaying(); playPauseButton.perform(waitMsec(1000)); TimeIntervalMatcher time1 = inTimeInterval(1000, 1800); checkPlayingAt(time1); stopButton.perform(click()); // Stop checkStopped(); playPauseButton.perform(waitMsec(100)); checkStopped(); resetButton.perform(click()); // Pause/Reset checkPausedAt0(); playPauseButton.perform(waitMsec(100)); checkPausedAt0(); playPauseButton.perform(click()); // Play checkPlaying(); playPauseButton.perform(waitMsec(1000)); checkPlayingAt(time1); playPauseButton.perform(click()); // Pause TimeIntervalMatcher time2 = inTimeInterval(time1.time, time1.time + 300); checkPausedAt(time2); playPauseButton.perform(waitMsec(100)); TimeIntervalMatcher time3 = inTimeInterval(time2.time, time2.time); // same time checkPausedAt(time3); playPauseButton.perform(click()); // Play checkPlaying(); playPauseButton.perform(waitMsec(1000)); TimeIntervalMatcher time4 = inTimeInterval(time3.time + 1000, time3.time + 1700); checkPlayingAt(time4); playPauseButton.perform(click()); // Pause TimeIntervalMatcher time5 = inTimeInterval(time4.time, time4.time + 500); checkPausedAt(time5); long downFrom5lo = (minutes5 - time5.time - 100L) / 1000L * 1000L; long downFrom5hi = (minutes5 - time5.time ) / 1000L * 1000L + 1000L; TimeIntervalMatcher countdown5 = inWholeTimeInterval(downFrom5lo, downFrom5hi); countdownDisplay.check(matches(withText(countdown5))); resetButton.perform(click()); // Reset checkPausedAt0(); playPauseButton.perform(click()); // Play checkPlaying(); playPauseButton.perform(waitMsec(1000)); checkPlayingAt(time1); playPauseButton.perform(click()); // Pause TimeIntervalMatcher time6 = inTimeInterval(time1.time, time1.time + 200); checkPausedAt(time6); stopButton.perform(click()); // Stop checkStopped(); countdownDisplay.perform(click()); // Play checkPlaying(); countdownDisplay.perform(waitMsec(1000)); countdownDisplay.perform(click()); // Pause checkPausedAt(time1); } /** Checks the enable-reminders checkbox and related widgets. */ private void checkReminder(boolean expectEnabled) { enableRemindersToggle.check(matches(isCompletelyDisplayed())); if (expectEnabled) { enableRemindersToggle.check(matches(isChecked())); countdownDisplay.check(matches(isCompletelyDisplayed())); countdownDisplay.check(matches(isClickable())); } else { enableRemindersToggle.check(matches(isNotChecked())); countdownDisplay.check(matches(not(isDisplayed()))); } alarmPeriodTextField.check(matches(isCompletelyDisplayed())); alarmPeriodTextField.check(matches(isEnabled())); } /** Checks that the UI is in the fully Stopped at 00:00 state. */ private void checkStopped() { playPauseButton.check(matches(isCompletelyDisplayed())); resetButton.check(matches(isCompletelyDisplayed())); stopButton.check(matches(not(isDisplayed()))); timeView.check(matches(withText(TIME_ZERO))); playPauseButton.check(matches(withCompoundDrawable(R.drawable.ic_play))); resetButton.check(matches(withCompoundDrawable(R.drawable.ic_pause))); checkReminder(true); // TODO: Check timeView's color state. } /** Checks that the UI is in the Paused @ 00:00 state, aka the Reset state. */ private void checkPausedAt0() { playPauseButton.check(matches(isCompletelyDisplayed())); resetButton.check(matches(not(isDisplayed()))); stopButton.check(matches(isCompletelyDisplayed())); timeView.check(matches(withText(TIME_ZERO))); playPauseButton.check(matches(withCompoundDrawable(R.drawable.ic_play))); stopButton.check(matches(withCompoundDrawable(R.drawable.ic_stop))); checkReminder(true); // TODO: Check timeView's color state, flashing between either of two color states. } /** Checks that the UI is in the Playing state, aka Run. */ private void checkPlaying() { playPauseButton.check(matches(isCompletelyDisplayed())); resetButton.check(matches(not(isDisplayed()))); stopButton.check(matches(isCompletelyDisplayed())); playPauseButton.check(matches(withCompoundDrawable(R.drawable.ic_pause))); stopButton.check(matches(withCompoundDrawable(R.drawable.ic_stop))); checkReminder(true); // TODO: Check timeView's color state. } /** Checks that the UI is in the Playing state at a matching time value. */ private void checkPlayingAt(@NonNull TimeIntervalMatcher time) { checkPlaying(); timeView.check(matches(withText(time))); } /** Checks that the UI is in the Paused state at a matching time value. */ private void checkPausedAt(@NonNull TimeIntervalMatcher time) { playPauseButton.check(matches(isCompletelyDisplayed())); resetButton.check(matches(isCompletelyDisplayed())); stopButton.check(matches(isCompletelyDisplayed())); playPauseButton.check(matches(withCompoundDrawable(R.drawable.ic_play))); resetButton.check(matches(withCompoundDrawable(R.drawable.ic_replay))); stopButton.check(matches(withCompoundDrawable(R.drawable.ic_stop))); timeView.check(matches(withText(time))); checkReminder(true); // TODO: Check timeView's color state, flashing between either of two color states. } /** Tests the alarm time interval TextEdit field and enableRemindersToggle widgets. */ @Test public void alarmTimeUITest() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.onefishtwo.bbqtimer", appContext.getPackageName()); Context appContext2 = ApplicationProvider.getApplicationContext(); assertEquals("com.onefishtwo.bbqtimer", appContext2.getPackageName()); checkReminder(true); alarmPeriodTextField.check(matches(withText("05:00"))); enableRemindersToggle.perform(click()); checkReminder(false); enableRemindersToggle.perform(click()); checkReminder(true); checkStopped(); // NOTE: Changing the EditText to a Material EditText with a Clear (X) button made this test // fragile, so longClick() or doubleClick() alone fails to select the text. // doubleClick() is understandable since the first click shows the (X) and slides the text // leftwards. alarmPeriodTextField.check(matches(not(hasFocus()))); alarmPeriodTextField.perform(click()); alarmPeriodTextField.check(matches(hasFocus())); alarmPeriodTextField.perform(longClick()); alarmPeriodTextField.check(matches(hasFocus())); alarmPeriodTextField.perform(typeTextIntoFocusedView("1:2:35\n")); alarmPeriodTextField.check(matches(withText("1:02:35"))); alarmPeriodTextField.check(matches(doesNotHaveFocus())); // Adding the click() avoids on SDK 22 "SecurityException: Injecting to another application // requires INJECT_EVENTS permission" from innerInjectMotionEvent(). alarmPeriodTextField.perform(click()); alarmPeriodTextField.perform(doubleClick()); alarmPeriodTextField.check(matches(hasFocus())); alarmPeriodTextField.perform(typeTextIntoFocusedView(":5")); // This background click might accept input and might de-focus the text field: // background.perform(click()) // so do this instead: alarmPeriodTextField.perform(pressImeActionButton()); // Since background.perform(click()) hasn't yet worked in this test, do something with the // background View to avoid a "Field is assigned but never accessed" inspection warning. // // BEWARE: Attempts to do background.perform(waitMsec(...)) before the click() or instead of // the playPauseButton.perform(waitMsec(...)) can make the "wait" occur BEFORE the click and // thus break the test! Why? background.check(matches(isDisplayed())); alarmPeriodTextField.check(matches(withText("00:05"))); // normalized alarmPeriodTextField.check(matches(doesNotHaveFocus())); playPauseButton.perform(waitMsec(100)); // work around Espresso test flakiness playPauseButton.perform(click()); // Play playPauseButton.perform(waitMsec(6_000)); // *** TODO: Test that it alarmed once ** playPauseButton.perform(click()); // Pause TimeIntervalMatcher time6 = inTimeInterval(6_000, 7_000); checkPausedAt(time6); // TODO: Test cancelling text input by tapping the Periodic Alarm checkbox. // TODO: Test moving focus with TAB and arrow keys. } }
app/src/androidTest/java/com/onefishtwo/bbqtimer/InAppUITest.java
/* * The MIT License (MIT) * * Copyright (c) 2017 Jerry Morrison * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.onefishtwo.bbqtimer; import android.content.Context; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import androidx.annotation.NonNull; import androidx.test.core.app.ApplicationProvider; import androidx.test.espresso.ViewInteraction; import androidx.test.ext.junit.rules.ActivityScenarioRule; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.filters.LargeTest; import androidx.test.platform.app.InstrumentationRegistry; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.click; import static androidx.test.espresso.action.ViewActions.doubleClick; import static androidx.test.espresso.action.ViewActions.longClick; import static androidx.test.espresso.action.ViewActions.pressImeActionButton; import static androidx.test.espresso.action.ViewActions.typeTextIntoFocusedView; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.doesNotHaveFocus; import static androidx.test.espresso.matcher.ViewMatchers.hasFocus; import static androidx.test.espresso.matcher.ViewMatchers.isChecked; import static androidx.test.espresso.matcher.ViewMatchers.isClickable; import static androidx.test.espresso.matcher.ViewMatchers.isCompletelyDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.isEnabled; import static androidx.test.espresso.matcher.ViewMatchers.isNotChecked; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withText; import static com.onefishtwo.bbqtimer.CustomMatchers.withCompoundDrawable; import static com.onefishtwo.bbqtimer.CustomViewActions.waitMsec; import static com.onefishtwo.bbqtimer.TimeIntervalMatcher.inTimeInterval; import static com.onefishtwo.bbqtimer.TimeIntervalMatcher.inWholeTimeInterval; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertEquals; /** Within-app Espresso UI tests. */ // TODO: Test the app's home screen widget. // TODO: Add a multi-app test that checks the app's notifications. @LargeTest @RunWith(AndroidJUnit4.class) public class InAppUITest { private static final TimeIntervalMatcher TIME_ZERO = inTimeInterval(0, 0); // supports locales private ViewInteraction playPauseButton; // play/pause, formerly known as start/stop private ViewInteraction resetButton; // reset (pause @ 00:00); pause/replay icon or hidden private ViewInteraction stopButton; // stop @ 00:00 private ViewInteraction timeView; private ViewInteraction enableRemindersToggle; private ViewInteraction alarmPeriodTextField; private ViewInteraction countdownDisplay; private ViewInteraction background; @NonNull @Rule public final ActivityScenarioRule<MainActivity> activityScenarioRule = new ActivityScenarioRule<>(MainActivity.class); @Before public void setUp() { playPauseButton = onView(withId(R.id.pauseResumeButton)); resetButton = onView(withId(R.id.resetButton)); stopButton = onView(withId(R.id.stopButton)); timeView = onView(withId(R.id.countUpDisplay)); enableRemindersToggle = onView(withId(R.id.enableReminders)); alarmPeriodTextField = onView(withId(R.id.alarmPeriod)); countdownDisplay = onView(withId(R.id.countdownDisplay)); background = onView(withId(R.id.main_container)); } @After public void tearDown() { playPauseButton = null; resetButton = null; stopButton = null; timeView = null; enableRemindersToggle = null; alarmPeriodTextField = null; countdownDisplay = null; background = null; } // MainActivity's FSM: // // Stopped @ 00:00 |> || --> Playing, Reset (= Paused @ 0:00) // // Reset @ 00:00 |> [] --> Playing, Stopped // // Playing hh:mm++ || [] --> Paused, Stopped // // Paused > 00:00 |> ⟲ [] --> Playing, Reset, Stopped /** * Tests all the nodes and arcs in the app's play/pause/reset/stop FSM. * <p/> * NOTE: Testing the timer is inherently timing-dependent. A test run could fail by not * allowing the app enough time to respond. ARM emulators need extra response time. Mocking * the TimeCounter clock might fix this even with MainActivity's Handler. */ @Test public void playPauseStopUITest() { final long minutes5 = 5 * 60_000L; checkStopped(); // Stopped checkReminder(true); alarmPeriodTextField.check(matches(withText("05:00"))); countdownDisplay.check(matches(withText("05:00"))); countdownDisplay.check(matches(withText(inWholeTimeInterval(minutes5, minutes5)))); enableRemindersToggle.perform(click()); checkReminder(false); enableRemindersToggle.perform(click()); checkReminder(true); resetButton.perform(click()); // Pause/Reset checkPausedAt0(); stopButton.perform(click()); // Stop checkStopped(); playPauseButton.perform(click()); // Play checkPlaying(); playPauseButton.perform(waitMsec(1000)); TimeIntervalMatcher time1 = inTimeInterval(1000, 1800); checkPlayingAt(time1); stopButton.perform(click()); // Stop checkStopped(); playPauseButton.perform(waitMsec(100)); checkStopped(); resetButton.perform(click()); // Pause/Reset checkPausedAt0(); playPauseButton.perform(waitMsec(100)); checkPausedAt0(); playPauseButton.perform(click()); // Play checkPlaying(); playPauseButton.perform(waitMsec(1000)); checkPlayingAt(time1); playPauseButton.perform(click()); // Pause TimeIntervalMatcher time2 = inTimeInterval(time1.time, time1.time + 300); checkPausedAt(time2); playPauseButton.perform(waitMsec(100)); TimeIntervalMatcher time3 = inTimeInterval(time2.time, time2.time); // same time checkPausedAt(time3); playPauseButton.perform(click()); // Play checkPlaying(); playPauseButton.perform(waitMsec(1000)); TimeIntervalMatcher time4 = inTimeInterval(time3.time + 1000, time3.time + 1700); checkPlayingAt(time4); playPauseButton.perform(click()); // Pause TimeIntervalMatcher time5 = inTimeInterval(time4.time, time4.time + 500); checkPausedAt(time5); long downFrom5lo = (minutes5 - time5.time - 100L) / 1000L * 1000L; long downFrom5hi = (minutes5 - time5.time ) / 1000L * 1000L + 1000L; TimeIntervalMatcher countdown5 = inWholeTimeInterval(downFrom5lo, downFrom5hi); countdownDisplay.check(matches(withText(countdown5))); resetButton.perform(click()); // Reset checkPausedAt0(); playPauseButton.perform(click()); // Play checkPlaying(); playPauseButton.perform(waitMsec(1000)); checkPlayingAt(time1); playPauseButton.perform(click()); // Pause TimeIntervalMatcher time6 = inTimeInterval(time1.time, time1.time + 200); checkPausedAt(time6); stopButton.perform(click()); // Stop checkStopped(); countdownDisplay.perform(click()); // Play checkPlaying(); countdownDisplay.perform(waitMsec(1000)); countdownDisplay.perform(click()); // Pause checkPausedAt(time1); } /** Checks the enable-reminders checkbox and related widgets. */ private void checkReminder(boolean expectEnabled) { enableRemindersToggle.check(matches(isCompletelyDisplayed())); if (expectEnabled) { enableRemindersToggle.check(matches(isChecked())); countdownDisplay.check(matches(isCompletelyDisplayed())); countdownDisplay.check(matches(isClickable())); } else { enableRemindersToggle.check(matches(isNotChecked())); countdownDisplay.check(matches(not(isDisplayed()))); } alarmPeriodTextField.check(matches(isCompletelyDisplayed())); alarmPeriodTextField.check(matches(isEnabled())); } /** Checks that the UI is in the fully Stopped at 00:00 state. */ private void checkStopped() { playPauseButton.check(matches(isCompletelyDisplayed())); resetButton.check(matches(isCompletelyDisplayed())); stopButton.check(matches(not(isDisplayed()))); timeView.check(matches(withText(TIME_ZERO))); playPauseButton.check(matches(withCompoundDrawable(R.drawable.ic_play))); resetButton.check(matches(withCompoundDrawable(R.drawable.ic_pause))); checkReminder(true); // TODO: Check timeView's color state. } /** Checks that the UI is in the Paused @ 00:00 state, aka the Reset state. */ private void checkPausedAt0() { playPauseButton.check(matches(isCompletelyDisplayed())); resetButton.check(matches(not(isDisplayed()))); stopButton.check(matches(isCompletelyDisplayed())); timeView.check(matches(withText(TIME_ZERO))); playPauseButton.check(matches(withCompoundDrawable(R.drawable.ic_play))); stopButton.check(matches(withCompoundDrawable(R.drawable.ic_stop))); checkReminder(true); // TODO: Check timeView's color state, flashing between either of two color states. } /** Checks that the UI is in the Playing state, aka Run. */ private void checkPlaying() { playPauseButton.check(matches(isCompletelyDisplayed())); resetButton.check(matches(not(isDisplayed()))); stopButton.check(matches(isCompletelyDisplayed())); playPauseButton.check(matches(withCompoundDrawable(R.drawable.ic_pause))); stopButton.check(matches(withCompoundDrawable(R.drawable.ic_stop))); checkReminder(true); // TODO: Check timeView's color state. } /** Checks that the UI is in the Playing state at a matching time value. */ private void checkPlayingAt(@NonNull TimeIntervalMatcher time) { checkPlaying(); timeView.check(matches(withText(time))); } /** Checks that the UI is in the Paused state at a matching time value. */ private void checkPausedAt(@NonNull TimeIntervalMatcher time) { playPauseButton.check(matches(isCompletelyDisplayed())); resetButton.check(matches(isCompletelyDisplayed())); stopButton.check(matches(isCompletelyDisplayed())); playPauseButton.check(matches(withCompoundDrawable(R.drawable.ic_play))); resetButton.check(matches(withCompoundDrawable(R.drawable.ic_replay))); stopButton.check(matches(withCompoundDrawable(R.drawable.ic_stop))); timeView.check(matches(withText(time))); checkReminder(true); // TODO: Check timeView's color state, flashing between either of two color states. } /** Tests the alarm time interval TextEdit field and enableRemindersToggle widgets. */ @Test public void alarmTimeUITest() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.onefishtwo.bbqtimer", appContext.getPackageName()); Context appContext2 = ApplicationProvider.getApplicationContext(); assertEquals("com.onefishtwo.bbqtimer", appContext2.getPackageName()); checkReminder(true); alarmPeriodTextField.check(matches(withText("05:00"))); enableRemindersToggle.perform(click()); checkReminder(false); enableRemindersToggle.perform(click()); checkReminder(true); checkStopped(); // NOTE: Changing the EditText to a Material EditText with a Clear (X) button made this test // fragile, so longClick() or doubleClick() alone fails to select the text. // doubleClick() is understandable since the first click shows the (X) and slides the text // leftwards. alarmPeriodTextField.check(matches(not(hasFocus()))); alarmPeriodTextField.perform(click()); alarmPeriodTextField.check(matches(hasFocus())); alarmPeriodTextField.perform(longClick()); alarmPeriodTextField.check(matches(hasFocus())); alarmPeriodTextField.perform(typeTextIntoFocusedView("1:2:35\n")); alarmPeriodTextField.check(matches(withText("1:02:35"))); alarmPeriodTextField.check(matches(doesNotHaveFocus())); alarmPeriodTextField.perform(doubleClick()); alarmPeriodTextField.check(matches(hasFocus())); alarmPeriodTextField.perform(typeTextIntoFocusedView(":5")); // This background click might accept input and might de-focus the text field: // background.perform(click()) // so do this instead: alarmPeriodTextField.perform(pressImeActionButton()); // Since background.perform(click()) hasn't yet worked in this test, do something with the // background View to avoid a "Field is assigned but never accessed" inspection warning. // // BEWARE: Attempts to do background.perform(waitMsec(...)) before the click() or instead of // the playPauseButton.perform(waitMsec(...)) can make the "wait" occur BEFORE the click and // thus break the test! Why? background.check(matches(isDisplayed())); alarmPeriodTextField.check(matches(withText("00:05"))); // normalized alarmPeriodTextField.check(matches(doesNotHaveFocus())); playPauseButton.perform(waitMsec(100)); // work around Espresso test flakiness playPauseButton.perform(click()); // Play playPauseButton.perform(waitMsec(6_000)); // *** TODO: Test that it alarmed once ** playPauseButton.perform(click()); // Pause TimeIntervalMatcher time6 = inTimeInterval(6_000, 7_000); checkPausedAt(time6); // TODO: Test cancelling text input by tapping the Periodic Alarm checkbox. // TODO: Test moving focus with TAB and arrow keys. } }
workaround Espresso flakiness
app/src/androidTest/java/com/onefishtwo/bbqtimer/InAppUITest.java
workaround Espresso flakiness
Java
mit
928d4238f569cb1a67e424c451baa9cd4501a7cf
0
jenkinsci/proxmox-plugin,jenkinsci/proxmox-plugin
package org.jenkinsci.plugins.proxmox.pve2api; import static us.monoid.web.Resty.form; import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import javax.security.auth.login.LoginException; import us.monoid.json.JSONArray; import us.monoid.json.JSONException; import us.monoid.json.JSONObject; import us.monoid.web.JSONResource; import us.monoid.web.Resty; public class Connector { public static final long WAIT_TIME_MS = 1000; protected Integer port; protected String username; protected String realm; protected String password; protected String baseURL; private String authTicket; private Date authTicketIssuedTimestamp; private String csrfPreventionToken; private static SSLSocketFactory cachedSSLSocketFactory = null; private static HostnameVerifier cachedHostnameVerifier = null; private static void ignoreAllCerts() { if (cachedSSLSocketFactory == null) cachedSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory(); if (cachedHostnameVerifier == null) cachedHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier(); TrustManager trm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] certs, String authType) {} public void checkServerTrusted(X509Certificate[] certs, String authType) {} public X509Certificate[] getAcceptedIssuers() { return null; } }; HostnameVerifier hnv = new HostnameVerifier() { public boolean verify(String s, SSLSession sslSession) { return true; } }; SSLContext sc; try { sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[] { trm }, null); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(hnv); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } public static void resetCachedSSLHelperObjects() { if (cachedSSLSocketFactory != null) HttpsURLConnection.setDefaultSSLSocketFactory(cachedSSLSocketFactory); if (cachedHostnameVerifier != null) HttpsURLConnection.setDefaultHostnameVerifier(cachedHostnameVerifier); } public Connector(String hostname, String username, String realm, String password) { this(hostname, username, realm, password, false); } public Connector(String hostname, String username, String realm, String password, Boolean ignoreSSL) { this.port = 8006; // Parse hostname for port information try { URI uri = new URI("https://" + hostname); if (uri.getPort() != -1) { hostname = uri.getHost(); port = uri.getPort(); } } catch (URISyntaxException e) { e.printStackTrace(); } this.username = username; this.realm = realm; this.password = password; if (ignoreSSL) ignoreAllCerts(); else resetCachedSSLHelperObjects(); this.authTicketIssuedTimestamp = null; this.baseURL = "https://" + hostname + ":" + port.toString() + "/api2/json/"; } public void login() throws IOException, LoginException { Resty r = new Resty(); JSONResource authTickets = r.json(baseURL + "access/ticket", form("username=" + username + "@" + realm + "&password=" + password)); try { authTicket = authTickets.get("data.ticket").toString(); csrfPreventionToken = authTickets.get("data.CSRFPreventionToken").toString(); authTicketIssuedTimestamp = new Date(); } catch (Exception e) { throw new LoginException("Failed reading JSON response"); } } public void checkIfAuthTicketIsValid() throws IOException, LoginException { //Authentication ticket has a lifetime of 2 hours, so login again when it expires if (authTicketIssuedTimestamp == null || authTicketIssuedTimestamp.getTime() <= (new Date().getTime() - (120 * 60 * 1000))) { login(); } } private Resty authedClient() throws IOException, LoginException { checkIfAuthTicketIsValid(); Resty r = new Resty(); r.withHeader("Cookie", "PVEAuthCookie=" + authTicket); r.withHeader("CSRFPreventionToken", csrfPreventionToken); return r; } private JSONResource getJSONResource(String resource) throws IOException, LoginException { return authedClient().json(baseURL + resource); } public List<String> getNodes() throws IOException, LoginException, JSONException { List<String> res = new ArrayList<String>(); JSONArray nodes = getJSONResource("nodes").toObject().getJSONArray("data"); for (int i = 0; i < nodes.length(); i++) { res.add(nodes.getJSONObject(i).getString("node")); } return res; } public JSONObject getTaskStatus(String node, String taskId) throws IOException, LoginException, JSONException { JSONResource response = getJSONResource("nodes/" + node + "/tasks/" + taskId + "/status"); return response.toObject().getJSONObject("data"); } public JSONObject getQemuMachineStatus(String node, Integer vmid) throws IOException, LoginException, JSONException { JSONResource response = getJSONResource("nodes/" + node + "/qemu/" + vmid + "/status/current"); return response.toObject().getJSONObject("data"); } public Boolean isQemuMachineRunning(String node, Integer vmid) throws IOException, LoginException, JSONException { JSONObject QemuMachineStatus = null; Boolean isRunning = true; QemuMachineStatus = getQemuMachineStatus(node, vmid); isRunning = (QemuMachineStatus.getString("status").equals("running")); return isRunning; } public JSONObject waitForTaskToFinish(String node, String taskId) throws IOException, LoginException, JSONException, InterruptedException { JSONObject lastTaskStatus = null; Boolean isRunning = true; while (isRunning) { lastTaskStatus = getTaskStatus(node, taskId); isRunning = (lastTaskStatus.getString("status").equals("running")); if (isRunning) { Thread.sleep(WAIT_TIME_MS); } } return lastTaskStatus; } public HashMap<String, Integer> getQemuMachines(String node) throws IOException, LoginException, JSONException { HashMap<String, Integer> res = new HashMap<String, Integer>(); JSONArray qemuVMs = getJSONResource("nodes/" + node + "/qemu").toObject().getJSONArray("data"); for (int i = 0; i < qemuVMs.length(); i++) { JSONObject vm = qemuVMs.getJSONObject(i); res.put(vm.getString("name"), vm.getInt("vmid")); } return res; } public List<String> getQemuMachineSnapshots(String node, Integer vmid) throws IOException, LoginException, JSONException { List<String> res = new ArrayList<String>(); JSONArray snapshots = getJSONResource("nodes/" + node + "/qemu/" + vmid.toString() + "/snapshot") .toObject().getJSONArray("data"); for (int i = 0; i < snapshots.length(); i++) { res.add(snapshots.getJSONObject(i).getString("name")); } return res; } public String rollbackQemuMachineSnapshot(String node, Integer vmid, String snapshotName) throws IOException, LoginException, JSONException { Resty r = authedClient(); String resource = "nodes/" + node + "/qemu/" + vmid.toString() + "/snapshot/" + snapshotName + "/rollback"; JSONResource response = r.json(baseURL + resource, form("")); return response.toObject().getString("data"); } public String startQemuMachine(String node, Integer vmid) throws IOException, LoginException, JSONException { Resty r = authedClient(); String resource = "nodes/" + node + "/qemu/" + vmid.toString() + "/status/start"; JSONResource response = r.json(baseURL + resource, form("")); return response.toObject().getString("data"); } public String stopQemuMachine(String node, Integer vmid) throws IOException, LoginException, JSONException { Resty r = authedClient(); String resource = "nodes/" + node + "/qemu/" + vmid.toString() + "/status/stop"; JSONResource response = r.json(baseURL + resource, form("")); return response.toObject().getString("data"); } public String shutdownQemuMachine(String node, Integer vmid) throws IOException, LoginException, JSONException { Resty r = authedClient(); String resource = "nodes/" + node + "/qemu/" + vmid.toString() + "/status/shutdown"; JSONResource response = r.json(baseURL + resource, form("")); return response.toObject().getString("data"); } }
src/main/java/org/jenkinsci/plugins/proxmox/pve2api/Connector.java
package org.jenkinsci.plugins.proxmox.pve2api; import static us.monoid.web.Resty.form; import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import javax.security.auth.login.LoginException; import us.monoid.json.JSONArray; import us.monoid.json.JSONException; import us.monoid.json.JSONObject; import us.monoid.web.JSONResource; import us.monoid.web.Resty; public class Connector { public static final long WAIT_TIME_MS = 1000; protected Integer port; protected String username; protected String realm; protected String password; protected String baseURL; private String authTicket; private Date authTicketIssuedTimestamp; private String csrfPreventionToken; private static SSLSocketFactory cachedSSLSocketFactory = null; private static HostnameVerifier cachedHostnameVerifier = null; private static void ignoreAllCerts() { if (cachedSSLSocketFactory == null) cachedSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory(); if (cachedHostnameVerifier == null) cachedHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier(); TrustManager trm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] certs, String authType) {} public void checkServerTrusted(X509Certificate[] certs, String authType) {} public X509Certificate[] getAcceptedIssuers() { return null; } }; HostnameVerifier hnv = new HostnameVerifier() { public boolean verify(String s, SSLSession sslSession) { return true; } }; SSLContext sc; try { sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[] { trm }, null); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(hnv); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } public static void resetCachedSSLHelperObjects() { if (cachedSSLSocketFactory != null) HttpsURLConnection.setDefaultSSLSocketFactory(cachedSSLSocketFactory); if (cachedHostnameVerifier != null) HttpsURLConnection.setDefaultHostnameVerifier(cachedHostnameVerifier); } public Connector(String hostname, String username, String realm, String password) { this(hostname, username, realm, password, false); } public Connector(String hostname, String username, String realm, String password, Boolean ignoreSSL) { //TODO: Split the hostname to check for a port. this.port = 8006; this.username = username; this.realm = realm; this.password = password; if (ignoreSSL) ignoreAllCerts(); else resetCachedSSLHelperObjects(); this.authTicketIssuedTimestamp = null; this.baseURL = "https://" + hostname + ":" + port.toString() + "/api2/json/"; } public void login() throws IOException, LoginException { Resty r = new Resty(); JSONResource authTickets = r.json(baseURL + "access/ticket", form("username=" + username + "@" + realm + "&password=" + password)); try { authTicket = authTickets.get("data.ticket").toString(); csrfPreventionToken = authTickets.get("data.CSRFPreventionToken").toString(); authTicketIssuedTimestamp = new Date(); } catch (Exception e) { throw new LoginException("Failed reading JSON response"); } } public void checkIfAuthTicketIsValid() throws IOException, LoginException { //Authentication ticket has a lifetime of 2 hours, so login again when it expires if (authTicketIssuedTimestamp == null || authTicketIssuedTimestamp.getTime() <= (new Date().getTime() - (120 * 60 * 1000))) { login(); } } private Resty authedClient() throws IOException, LoginException { checkIfAuthTicketIsValid(); Resty r = new Resty(); r.withHeader("Cookie", "PVEAuthCookie=" + authTicket); r.withHeader("CSRFPreventionToken", csrfPreventionToken); return r; } private JSONResource getJSONResource(String resource) throws IOException, LoginException { return authedClient().json(baseURL + resource); } public List<String> getNodes() throws IOException, LoginException, JSONException { List<String> res = new ArrayList<String>(); JSONArray nodes = getJSONResource("nodes").toObject().getJSONArray("data"); for (int i = 0; i < nodes.length(); i++) { res.add(nodes.getJSONObject(i).getString("node")); } return res; } public JSONObject getTaskStatus(String node, String taskId) throws IOException, LoginException, JSONException { JSONResource response = getJSONResource("nodes/" + node + "/tasks/" + taskId + "/status"); return response.toObject().getJSONObject("data"); } public JSONObject getQemuMachineStatus(String node, Integer vmid) throws IOException, LoginException, JSONException { JSONResource response = getJSONResource("nodes/" + node + "/qemu/" + vmid + "/status/current"); return response.toObject().getJSONObject("data"); } public Boolean isQemuMachineRunning(String node, Integer vmid) throws IOException, LoginException, JSONException { JSONObject QemuMachineStatus = null; Boolean isRunning = true; QemuMachineStatus = getQemuMachineStatus(node, vmid); isRunning = (QemuMachineStatus.getString("status").equals("running")); return isRunning; } public JSONObject waitForTaskToFinish(String node, String taskId) throws IOException, LoginException, JSONException, InterruptedException { JSONObject lastTaskStatus = null; Boolean isRunning = true; while (isRunning) { lastTaskStatus = getTaskStatus(node, taskId); isRunning = (lastTaskStatus.getString("status").equals("running")); if (isRunning) { Thread.sleep(WAIT_TIME_MS); } } return lastTaskStatus; } public HashMap<String, Integer> getQemuMachines(String node) throws IOException, LoginException, JSONException { HashMap<String, Integer> res = new HashMap<String, Integer>(); JSONArray qemuVMs = getJSONResource("nodes/" + node + "/qemu").toObject().getJSONArray("data"); for (int i = 0; i < qemuVMs.length(); i++) { JSONObject vm = qemuVMs.getJSONObject(i); res.put(vm.getString("name"), vm.getInt("vmid")); } return res; } public List<String> getQemuMachineSnapshots(String node, Integer vmid) throws IOException, LoginException, JSONException { List<String> res = new ArrayList<String>(); JSONArray snapshots = getJSONResource("nodes/" + node + "/qemu/" + vmid.toString() + "/snapshot") .toObject().getJSONArray("data"); for (int i = 0; i < snapshots.length(); i++) { res.add(snapshots.getJSONObject(i).getString("name")); } return res; } public String rollbackQemuMachineSnapshot(String node, Integer vmid, String snapshotName) throws IOException, LoginException, JSONException { Resty r = authedClient(); String resource = "nodes/" + node + "/qemu/" + vmid.toString() + "/snapshot/" + snapshotName + "/rollback"; JSONResource response = r.json(baseURL + resource, form("")); return response.toObject().getString("data"); } public String startQemuMachine(String node, Integer vmid) throws IOException, LoginException, JSONException { Resty r = authedClient(); String resource = "nodes/" + node + "/qemu/" + vmid.toString() + "/status/start"; JSONResource response = r.json(baseURL + resource, form("")); return response.toObject().getString("data"); } public String stopQemuMachine(String node, Integer vmid) throws IOException, LoginException, JSONException { Resty r = authedClient(); String resource = "nodes/" + node + "/qemu/" + vmid.toString() + "/status/stop"; JSONResource response = r.json(baseURL + resource, form("")); return response.toObject().getString("data"); } public String shutdownQemuMachine(String node, Integer vmid) throws IOException, LoginException, JSONException { Resty r = authedClient(); String resource = "nodes/" + node + "/qemu/" + vmid.toString() + "/status/shutdown"; JSONResource response = r.json(baseURL + resource, form("")); return response.toObject().getString("data"); } }
Parse port from hostname to avoid forced port 8006
src/main/java/org/jenkinsci/plugins/proxmox/pve2api/Connector.java
Parse port from hostname to avoid forced port 8006
Java
mit
8b3a1dacf323cd333be0ffe4b968796c3e418f38
0
DominikRidder/ImageExtractor
package gui; import imagehandling.Image; import java.awt.Dimension; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.nio.file.Files; import java.util.HashSet; import java.util.Stack; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingUtilities; public class ImageSearch extends JFrame implements ActionListener, Runnable { /** * */ private static final long serialVersionUID = -6770567548026413228L; JFileChooser filechoose = new JFileChooser(); JTextField searchin; JTextField filter; JTextArea outputArea; JScrollPane outputScroller; JButton startButton; JCheckBox searchAll; boolean stop = false; public ImageSearch() { this.setTitle("ImageSearch"); searchin = new JTextField(); searchin.setMaximumSize(new Dimension(Integer.MAX_VALUE, 75)); searchin.setMinimumSize(new Dimension(300, 75)); // upperleft rectangle filter = new JTextField(""); filter.setEditable(true); filter.setMaximumSize(new Dimension(Integer.MAX_VALUE, 75)); filter.setMinimumSize(new Dimension(300, 75)); startButton = new JButton("Start Search"); startButton.addActionListener(this); searchAll = new JCheckBox(); // // creating the output area outputArea = new JTextArea(); outputArea.setEditable(false); outputArea.setMargin(new Insets(0, 0, 0, 0)); outputScroller = new JScrollPane(outputArea); outputScroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); panel.add(addDescription(searchin, "Directory:")); panel.add(Box.createVerticalStrut(10)); panel.add(addDescription(filter, "Filter:")); panel.add(Box.createVerticalStrut(10)); panel.add(addDescription(searchAll, "Full Search")); panel.add(Box.createVerticalStrut(10)); panel.add(startButton); panel.add(Box.createVerticalStrut(10)); panel.add(outputScroller); // adding everythis to this (class) this.add(panel); this.setSize(500, 400); this.setVisible(true); } public JPanel addDescription(JComponent textfield, String desc) { JPanel row = new JPanel(); row.setLayout(new BoxLayout(row, BoxLayout.LINE_AXIS)); row.setMinimumSize(new Dimension(300, 75)); JLabel label = new JLabel(desc); row.add(label); row.add(textfield); return row; } public void actionPerformed(ActionEvent e) { switch(e.getActionCommand()) { case "Start Search": stop = false; Thread t = new Thread(this); t.start(); break; case "Cancle": stop = true; startButton.setText("Start Search"); break; } } public void run() { startButton.setText("Cancle"); search(); startButton.setText("Start Search"); } public void search() { outputArea.setText(""); String dir = searchin.getText(); String filterStr = filter.getText(); HashSet<String> alreadyOutput = new HashSet<String>(); boolean fullsearch = searchAll.isSelected(); for (String test : filterStr.split("&")){ String parts[] = test.split("="); if (parts.length < 2) { outputArea.setText("Invalid filter component. Please use: <Keyword> = <Value>"); outputArea.setText(outputArea.getText()+"\nor multiple: <Keyword> = <Value> & <Keyword> = <Value> & ..."); return; } String key = parts[0].trim(); String val = parts[1].trim().toLowerCase(); if (key.equals("")) { outputArea.setText("No key is given before '='"); return; } if (val.equals("")) { outputArea.setText("No value is given behind '='"); return; } } if (dir.equals("")) { outputArea.setText("Directory not set"); return; } Stack<File> nextFolders = new Stack<File>(); String path; File file = new File(dir); if (!file.exists() || !file.isDirectory()) { outputArea.setText("Invalid Directory"); return; } nextFolders.push(file); File[] list; boolean warnedKey = false; while (!nextFolders.isEmpty()) { boolean foundAImage = false; file = nextFolders.pop(); list = file.listFiles(); if (list == null) { // Maybe we dont have a Directory than continue; } if (stop) { return; } outer: for (File potentialDicom : list) { path = potentialDicom.getAbsolutePath(); // if (!fullsearch && !potentialDicom.isDirectory() && foundAImage) { // continue; if (!fullsearch && foundAImage) { break; } else if (potentialDicom.isDirectory()){ if (!Files.isSymbolicLink(potentialDicom.toPath())) { nextFolders.push(potentialDicom); } } else if (!potentialDicom.isDirectory() && !alreadyOutput.contains(potentialDicom.getParentFile().getAbsolutePath()) && (path.endsWith(".dcm") || path.endsWith(".IMA") || Image .isDicom(potentialDicom.toPath()))) { foundAImage = true; try { Image img = new Image(potentialDicom.getAbsolutePath()); for (String test : filterStr.split("&")){ String parts[] = test.split("="); String key = parts[0].trim(); String val = parts[1].trim().toLowerCase(); String extracted = img.getAttribute(key).toLowerCase().trim(); if (!warnedKey && extracted.equals("")) { outputArea.setText("WARNING: Key "+key+" is maybe not correct spelled!\n"+outputArea.getText()); warnedKey = true; } if (!extracted.contains(val)) { continue outer; } } outputArea.setText(outputArea.getText()+"\n"+potentialDicom.getParentFile().getAbsolutePath()); repaint(); alreadyOutput.add(potentialDicom.getParentFile().getAbsolutePath()); } catch (Exception err) { continue; } } } } } }
src/gui/ImageSearch.java
package gui; import imagehandling.Image; import java.awt.Dimension; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.nio.file.Files; import java.util.HashSet; import java.util.Stack; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingUtilities; public class ImageSearch extends JFrame implements ActionListener, Runnable { /** * */ private static final long serialVersionUID = -6770567548026413228L; JFileChooser filechoose = new JFileChooser(); JTextField searchin; JTextField filter; JTextArea outputArea; JScrollPane outputScroller; JButton startButton; JCheckBox searchAll; boolean stop = false; public ImageSearch() { this.setTitle("ImageSearch"); searchin = new JTextField(); searchin.setMaximumSize(new Dimension(Integer.MAX_VALUE, 75)); searchin.setMinimumSize(new Dimension(300, 75)); // upperleft rectangle filter = new JTextField(""); filter.setEditable(true); filter.setMaximumSize(new Dimension(Integer.MAX_VALUE, 75)); filter.setMinimumSize(new Dimension(300, 75)); startButton = new JButton("Start Search"); startButton.addActionListener(this); searchAll = new JCheckBox(); // // creating the output area outputArea = new JTextArea(); outputArea.setEditable(false); outputArea.setMargin(new Insets(0, 0, 0, 0)); outputScroller = new JScrollPane(outputArea); outputScroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); panel.add(addDescription(searchin, "Directory:")); panel.add(Box.createVerticalStrut(10)); panel.add(addDescription(filter, "Filter:")); panel.add(Box.createVerticalStrut(10)); panel.add(addDescription(searchAll, "Full Search")); panel.add(Box.createVerticalStrut(10)); panel.add(startButton); panel.add(Box.createVerticalStrut(10)); panel.add(outputScroller); // adding everythis to this (class) this.add(panel); this.setSize(500, 400); this.setVisible(true); } public JPanel addDescription(JComponent textfield, String desc) { JPanel row = new JPanel(); row.setLayout(new BoxLayout(row, BoxLayout.LINE_AXIS)); row.setMinimumSize(new Dimension(300, 75)); JLabel label = new JLabel(desc); row.add(label); row.add(textfield); return row; } public void actionPerformed(ActionEvent e) { switch(e.getActionCommand()) { case "Start Search": stop = false; Thread t = new Thread(this); t.start(); break; case "Cancle": stop = true; startButton.setText("Start Search"); break; } } public void run() { startButton.setText("Cancle"); search(); startButton.setText("Start Search"); } public void search() { outputArea.setText(""); String dir = searchin.getText(); String filterStr = filter.getText(); HashSet<String> alreadyOutput = new HashSet<String>(); boolean fullsearch = searchAll.isSelected(); for (String test : filterStr.split("&")){ String parts[] = test.split("="); if (parts.length < 2) { outputArea.setText("Invalid filter component. Please use: <Keyword> = <Value>"); outputArea.setText(outputArea.getText()+"\nor multiple: <Keyword> = <Value> & <Keyword> = <Value> & ..."); return; } String key = parts[0].trim(); String val = parts[1].trim().toLowerCase(); if (key.equals("")) { outputArea.setText("No key is given before '='"); return; } if (val.equals("")) { outputArea.setText("No value is given behind '='"); return; } } if (dir.equals("")) { outputArea.setText("Directory not set"); return; } Stack<File> nextFolders = new Stack<File>(); String path; File file = new File(dir); if (!file.exists() || !file.isDirectory()) { outputArea.setText("Invalid Directory"); return; } nextFolders.push(file); File[] list; boolean warnedKey = false; while (!nextFolders.isEmpty()) { boolean foundAImage = false; file = nextFolders.pop(); list = file.listFiles(); if (list == null) { // Maybe we dont have a Directory than continue; } if (stop) { return; } outer: for (File potentialDicom : list) { path = potentialDicom.getAbsolutePath(); if (!fullsearch && !potentialDicom.isDirectory() && foundAImage) { continue; } else if (potentialDicom.isDirectory()){ if (!Files.isSymbolicLink(potentialDicom.toPath())) { nextFolders.push(potentialDicom); } } else if (!potentialDicom.isDirectory() && !alreadyOutput.contains(potentialDicom.getParentFile().getAbsolutePath()) && (path.endsWith(".dcm") || path.endsWith(".IMA") || Image .isDicom(potentialDicom.toPath()))) { foundAImage = true; try { Image img = new Image(potentialDicom.getAbsolutePath()); for (String test : filterStr.split("&")){ String parts[] = test.split("="); String key = parts[0].trim(); String val = parts[1].trim().toLowerCase(); String extracted = img.getAttribute(key).toLowerCase().trim(); if (!warnedKey && extracted.equals("")) { outputArea.setText("WARNING: Key "+key+" is maybe not correct spelled!"); warnedKey = true; } if (!extracted.contains(val)) { continue outer; } } outputArea.setText(outputArea.getText()+"\n"+potentialDicom.getParentFile().getAbsolutePath()); repaint(); alreadyOutput.add(potentialDicom.getParentFile().getAbsolutePath()); } catch (Exception err) { continue; } } } } } }
Speedup for the not fullsearch option
src/gui/ImageSearch.java
Speedup for the not fullsearch option
Java
mit
396830fb7c1572024cd93ddec6234039645a4e7d
0
allan-stewart/java-katas
package com.github.allan.stewart.kata.roman; import org.junit.Assert; import org.junit.Test; public class RomanNumeralConverterTest { @Test public void intToRoman_primaryNumerals() { Assert.assertEquals("I", RomanNumeralConverter.intToRoman(1)); Assert.assertEquals("V", RomanNumeralConverter.intToRoman(5)); Assert.assertEquals("X", RomanNumeralConverter.intToRoman(10)); Assert.assertEquals("L", RomanNumeralConverter.intToRoman(50)); Assert.assertEquals("C", RomanNumeralConverter.intToRoman(100)); Assert.assertEquals("D", RomanNumeralConverter.intToRoman(500)); Assert.assertEquals("M", RomanNumeralConverter.intToRoman(1000)); } @Test public void intToRoman_additive() { Assert.assertEquals("II", RomanNumeralConverter.intToRoman(2)); Assert.assertEquals("III", RomanNumeralConverter.intToRoman(3)); Assert.assertEquals("XX", RomanNumeralConverter.intToRoman(20)); Assert.assertEquals("XXX", RomanNumeralConverter.intToRoman(30)); Assert.assertEquals("CC", RomanNumeralConverter.intToRoman(200)); Assert.assertEquals("CCC", RomanNumeralConverter.intToRoman(300)); Assert.assertEquals("MM", RomanNumeralConverter.intToRoman(2000)); Assert.assertEquals("MMM", RomanNumeralConverter.intToRoman(3000)); } @Test public void intToRoman_subtractive() { Assert.assertEquals("IV", RomanNumeralConverter.intToRoman(4)); Assert.assertEquals("IX", RomanNumeralConverter.intToRoman(9)); Assert.assertEquals("XL", RomanNumeralConverter.intToRoman(40)); Assert.assertEquals("XC", RomanNumeralConverter.intToRoman(90)); Assert.assertEquals("CD", RomanNumeralConverter.intToRoman(400)); Assert.assertEquals("CM", RomanNumeralConverter.intToRoman(900)); } @Test public void intToRoman_combinations() { Assert.assertEquals("MMXIV", RomanNumeralConverter.intToRoman(2014)); Assert.assertEquals("MMDCCCLXXVII", RomanNumeralConverter.intToRoman(2877)); } }
src/test/java/com/github/allan/stewart/kata/roman/RomanNumeralConverterTest.java
package com.github.allan.stewart.kata.roman; import org.junit.Assert; import org.junit.Test; public class RomanNumeralConverterTest { @Test public void primary_numerals() { Assert.assertEquals("I", RomanNumeralConverter.intToRoman(1)); Assert.assertEquals("V", RomanNumeralConverter.intToRoman(5)); Assert.assertEquals("X", RomanNumeralConverter.intToRoman(10)); Assert.assertEquals("L", RomanNumeralConverter.intToRoman(50)); Assert.assertEquals("C", RomanNumeralConverter.intToRoman(100)); Assert.assertEquals("D", RomanNumeralConverter.intToRoman(500)); Assert.assertEquals("M", RomanNumeralConverter.intToRoman(1000)); } @Test public void additive() { Assert.assertEquals("II", RomanNumeralConverter.intToRoman(2)); Assert.assertEquals("III", RomanNumeralConverter.intToRoman(3)); Assert.assertEquals("XX", RomanNumeralConverter.intToRoman(20)); Assert.assertEquals("XXX", RomanNumeralConverter.intToRoman(30)); Assert.assertEquals("CC", RomanNumeralConverter.intToRoman(200)); Assert.assertEquals("CCC", RomanNumeralConverter.intToRoman(300)); Assert.assertEquals("MM", RomanNumeralConverter.intToRoman(2000)); Assert.assertEquals("MMM", RomanNumeralConverter.intToRoman(3000)); } @Test public void subtractive() { Assert.assertEquals("IV", RomanNumeralConverter.intToRoman(4)); Assert.assertEquals("IX", RomanNumeralConverter.intToRoman(9)); Assert.assertEquals("XL", RomanNumeralConverter.intToRoman(40)); Assert.assertEquals("XC", RomanNumeralConverter.intToRoman(90)); Assert.assertEquals("CD", RomanNumeralConverter.intToRoman(400)); Assert.assertEquals("CM", RomanNumeralConverter.intToRoman(900)); } @Test public void combinations() { Assert.assertEquals("MMXIV", RomanNumeralConverter.intToRoman(2014)); Assert.assertEquals("MMDCCCLXXVII", RomanNumeralConverter.intToRoman(2877)); } }
Renamed test methods.
src/test/java/com/github/allan/stewart/kata/roman/RomanNumeralConverterTest.java
Renamed test methods.
Java
cc0-1.0
ca055f672d06d86cd9c501c616ce7b0df98c6089
0
nees-ufal/JOINT
package wwwc.nees.joint.module.kao; import wwwc.nees.joint.module.kao.retrieve.QueryRunner; import wwwc.nees.joint.module.kao.retrieve.RetrieveOperations; import wwwc.nees.joint.module.kao.retrieve.SPARQLQueryRunnerImpl; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.openrdf.model.URI; import org.openrdf.model.impl.URIImpl; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.TupleQueryResultHandlerException; import org.openrdf.query.UpdateExecutionException; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; /** * Abstract class KAO, for operations in the persistence with SESAME and Alibaba * * @author Olavo Holanda * @version 1.0 - 15/01/2012 */ public abstract class AbstractKAO { // VARIABLES // ------------------------------------------------------------------------- // Variable to connect with the repository private final Repository repository; // Variable to do operations in the repository private RepositoryConnection connection; // Variable with the desired class to be implemented private Class<?> classe; // Interface to perform queries in the repository private final QueryRunner queryRunner; // URI[] of graph to save triples private URI[] contexts; // CONSTRUCTOR // ------------------------------------------------------------------------- /** * Class Constructor, starts the <code>Repository</code> and creates a * <code>ObjectConnection</code>, to do persistence operations. * * @param classe the class to be implemented. * */ public <T> AbstractKAO(Class<T> classe) { this.classe = classe; // Retrieves the repository in the server this.repository = RepositoryFactory.getRepository(); // Creates a QueryRunner with SPARQL implementation this.queryRunner = new SPARQLQueryRunnerImpl(); this.contexts = new URI[]{}; } // METHODS // ------------------------------------------------------------------------- /** * Creates a new instance in the repository with the specified name. * * @param instanceName a <code>String</code> with the instance name. * @param ontologyURI a <code>String</code> with the instance name. * @param contexts <code>URI</code> represent the graphs in which the query * will be performed. * @return T the new instance. */ public <T> T create(String ontologyURI, String instanceName, java.net.URI... contexts) { return create(ontologyURI + instanceName, contexts); } /** * Creates a new instance in the repository with the specified uri. * * @param instanceURI a <code>String</code> with the instance uri. * @param contexts <code>URI</code> represent the graphs in which the query * will be performed. * @return T the new instance. */ public <T> T create(String instanceURI, java.net.URI... contexts) { setContexts(contexts); Object ob = null; try { connection = this.repository.getConnection(); try { connection.begin(); ob = new CreateOperations().create(connection, instanceURI, this.classe, this.getContexts()); connection.commit(); } catch (Exception e) { // If throws any exception rollback connection.rollback(); Logger .getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, e); } finally { connection.close(); } } catch (RepositoryException eR) { // If throws repository Exception the the connection is not inialized Logger.getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, eR); } return (T) ob; } /** * Creates a new instance with a unique ID in the repository with the * specified prefix. * * @param instancePrefix a <code>String</code> with the prefix name. * @param ontologyURI a <code>String</code> with the instance name. * @param contexts <code>URI</code> represent the graphs in which the query * will be performed. * @return T the new instance. */ public <T> T createWithUniqueID(String ontologyURI, String instancePrefix, java.net.URI... contexts) { setContexts(contexts); Object ob = null; try { connection = this.repository.getConnection(); try { connection.begin(); ob = new CreateOperations().createWithUniqueID(connection, ontologyURI, instancePrefix, this.classe, this.getContexts()); connection.commit(); } catch (Exception e) { // If throws any exception rollback connection.rollback(); Logger .getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, e); } finally { connection.close(); } } catch (RepositoryException eR) { // If throws repository Exception the the connection is not inialized Logger.getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, eR); } return (T) ob; } /** * Removes the desired instance in the repository, must be saved after. * * @param ontologyURI is the URI from the ontology which represents the * instance. * @param instanceName a <code>String</code> with the instance name. * @param contexts <code>URI</code> represent the graphs in which the query * will be performed. */ public void delete(String ontologyURI, String instanceName, java.net.URI... contexts) { delete(ontologyURI + instanceName, contexts); } public void delete(String instanceURI, java.net.URI... contexts) { setContexts(contexts); try { connection = this.repository.getConnection(); try { //gets connection connection.begin(); //removes the quads that have the corresponding subject // removeOpe.remove(ontologyURI, instanceName, con, this.getContexts()); new RemoveOperations().remove_SPARQLUpdate(connection, instanceURI, this.getContexts()); // Saves the object in the repository connection.commit(); } catch (RepositoryException | MalformedQueryException | UpdateExecutionException e) { // If throws any exception rollback connection.rollback(); Logger .getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, e); } finally { connection.close(); } } catch (RepositoryException eR) { // If throws repository Exception the the connection is not inialized Logger.getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, eR); } } /** * Removes the desired instance in the repository, must be saved after. * * @param instance an object T with the instance * @param contexts the graphs in which the instance is removed. */ public <T> void delete(T instance, java.net.URI... contexts) { try { setContexts(contexts); connection = this.repository.getConnection(); try { //gets connection connection.begin(); new RemoveOperations().remove_SPARQLUpdate(connection, instance.toString(), this.getContexts()); // removeOpe.remove(instance, con, this.getContexts()); // Saves the object in the repository connection.commit(); } catch (RepositoryException | MalformedQueryException | UpdateExecutionException e) { // If throws any exception rollback connection.rollback(); Logger .getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, e); } finally { connection.close(); } } catch (RepositoryException eR) { // If throws repository Exception the the connection is not inialized Logger.getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, eR); } } /** * Retrieves the desired instance in the repository. * * @param ontologyURI : a <code>String</code> with the ontology base URI * @param instanceName a <code>String</code> with the instance name. * @param contexts the graphs in which the instance is removed. * @return T the desired instance. */ public <T> T retrieveInstance(String ontologyURI, String instanceName, java.net.URI... contexts) { return retrieveInstance(ontologyURI + instanceName, contexts); } /** * Retrieves the desired instance in the repository. * * @param instanceURI a <code>String</code> with the instance name. * @param contexts the graphs in which the instance is removed. * @return T the desired instance. */ public <T> T retrieveInstance(String instanceURI, java.net.URI... contexts) { Object ob = null; try { setContexts(contexts); connection = this.repository.getConnection(); try { //gets connection connection.begin(); ob = new RetrieveOperations().retrieveInstance(connection, instanceURI, classe, this.getContexts()); // Saves the object in the repository connection.commit(); } catch (Exception e) { // If throws any exception rollback connection.rollback(); Logger .getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, e); } finally { connection.close(); } } catch (RepositoryException eR) { // If throws repository Exception the the connection is not inialized Logger.getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, eR); } return (T) ob; } /** * Retrieves all the instances of the class, passed in the constructor. * * @param contexts <code>URI</code> represent the graphs in which the query * will be performed. * @return <code>List</code> a List with the instances. */ public <T> List<T> retrieveAllInstances(java.net.URI... contexts) { setContexts(contexts); // Creates a new java.util.List List<T> listInstances = new ArrayList<>(); try { connection = this.repository.getConnection(); try { //gets connection connection.begin(); listInstances = (List<T>) new RetrieveOperations().retrieveAllInstances(connection, classe, this.getContexts()); // Saves the object in the repository connection.commit(); } catch (Exception e) { // If throws any exception rollback connection.rollback(); Logger .getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, e); } finally { connection.close(); } } catch (RepositoryException eR) { // If throws repository Exception the the connection is not inialized Logger.getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, eR); } return listInstances; } /** * Saves the uncommitted changes in the repository and close the connection * with it. * * @param instance is the object which will be updated * @param contexts <code>URI</code> represent the graphs in which the query * will be updated. */ public <T> T update(T instance, java.net.URI... contexts) { setContexts(contexts); Object ob = null; try { //gets connection connection = this.repository.getConnection(); try { connection.begin(); ob = new UpdateOperations().updateDettachedInstance(connection, instance, classe, this.getContexts()); // Saves the object in the repository connection.commit(); } catch (Exception e) { // If throws any exception rollback connection.rollback(); Logger .getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, e); } finally { connection.close(); } } catch (RepositoryException eR) { // If throws repository Exception the the connection is not inialized Logger.getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, eR); } return (T) ob; } /** * Performs queries in the repository, returning a single result. * * @param query the <code>String</code> with the query to be performed. * * @return object <code>Object</code> result. */ public Object executeSPARQLquerySingleResult(String query) { Object object = null; try { //retrieves a connection with the repository connection = this.repository.getConnection(); try { //starts a transaction connection.begin(); //performs the query object = this.queryRunner.executeQueryAsSingleResult(connection, query); connection.commit(); } catch (Exception ex) { connection.rollback(); Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } finally { connection.close(); } } catch (RepositoryException ex) { Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } return object; } /** * Performs queries in the repository, returning a java.util.List of * results. * * @param query the <code>String</code> with the query to be performed. * @param contexts <code>URI</code> represent the graphs in which the query * will be performed. * * @return <code>List</code> a java.util.List with the results. */ public List executeSPARQLqueryResultList(String query, java.net.URI... contexts) { setContexts(contexts); List<Object> objects = null; try { //retrieves a connection with the repository connection = this.repository.getConnection(); try { //starts a transaction connection.begin(); //performs the query objects = this.queryRunner.executeQueryAsList(connection, query, this.getContexts()); connection.commit(); } catch (Exception ex) { connection.rollback(); Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } finally { connection.close(); } } catch (RepositoryException ex) { Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } return objects; } public List executeSPARQLqueryResultList2(String query, java.net.URI... contexts) { setContexts(contexts); List<Object> objects = null; try { //retrieves a connection with the repository connection = this.repository.getConnection(); try { //starts a transaction connection.begin(); //performs the query objects = this.queryRunner.executeQueryAsList2(connection, query, this.getContexts()); connection.commit(); } catch (Exception ex) { connection.rollback(); Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } finally { connection.close(); } } catch (RepositoryException ex) { Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } return objects; } public String executeSPARQLtupleQueryAsJSONString(String query) { String results = null; try { //retrieves a connection with the repository connection = this.repository.getConnection(); try { //starts a transaction connection.begin(); //performs the query results = this.queryRunner.executeTupleQueryAsJSON(connection, query).replaceAll("=", ":"); connection.commit(); } catch (RepositoryException | MalformedQueryException | QueryEvaluationException | TupleQueryResultHandlerException ex) { connection.rollback(); Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } finally { connection.close(); } } catch (RepositoryException ex) { Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } return results; } /** * Performs query in the repository, returning the results in an adapted * format from JSON-LD specification * * @param query the String with the query to be performed. * @return a JSON as String */ public String executeSPARQLgraphQueryAsJSONLDString(String query) { return executeSPARQLgraphQueryAsJSONLDString(query, true); } /** * Performs query in the repository, returning the results in an adapted * format from JSON-LD specification * * @param query the String with the query to be performed. * @param graphAsJSONArray defines if the <b><code>@graph</code> key</b> is * a JSON Array. If value is true, then is an array, else, is a JSON Object * where the <b><code>@id</code> key</b> are the keys of the objects. <b>By * default it's <code>true</code></b>. * @return a JSON as String */ public String executeSPARQLgraphQueryAsJSONLDString(String query, boolean graphAsJSONArray) { String results = null; try { //retrieves a connection with the repository connection = this.repository.getConnection(); try { //starts a transaction connection.begin(); //performs the query results = this.queryRunner.executeGraphQueryAsJSONLD(connection, query, graphAsJSONArray); connection.commit(); } catch (Exception ex) { connection.rollback(); Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } finally { connection.close(); } } catch (RepositoryException ex) { Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } return results; } /** * Performs queries in the repository, returning a java.util.Iterator with * the results. * * @param query the <code>String</code> with the query to be performed. * @param contexts <code>URI</code> represent the graphs in which the query * will be performed. * * @return <code>Iterator</code> a java.util.List with the results. */ public Iterator executeQueryAsIterator(String query, java.net.URI... contexts) { //Converter to Iterator and return return executeSPARQLqueryResultList(query, contexts).iterator(); } /** * Performs SPARQL queries in the repository, returning a boolean with the * result. * * @param query the <code>String</code> with the query to be performed. * * @return <code>boolean</code> true or false. */ public boolean executeBooleanQuery(String query) { boolean result = false; try { //retrieves a connection with the repository connection = this.repository.getConnection(); try { //starts a transaction connection.begin(); //performs the query result = this.queryRunner.executeBooleanQuery(connection, query); connection.commit(); } catch (Exception ex) { connection.rollback(); Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } finally { connection.close(); } } catch (RepositoryException ex) { Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } return result; } /** * Performs SPARQL update queries in the repository, returning a boolean * true if the query was performed with successful or false otherwise. * * @param query the <code>String</code> with the query to be performed. */ public void executeSPARQLUpdateQuery(String query) { try { //retrieves a connection with the repository connection = this.repository.getConnection(); try { //starts a transaction connection.begin(); //performs the query this.queryRunner.executeUpdateQuery(connection, query); connection.commit(); } catch (Exception ex) { connection.rollback(); Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } finally { connection.close(); } } catch (RepositoryException ex) { Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } } /** * Gets contexts from quadstore. * * @param containsTerm is a regular expression that must be matched with the * contexts * @return an URI list * @throws NullPointerException occurs when the containsTerm is null. */ public List<java.net.URI> getContexts(String containsTerm) { List<java.net.URI> allContexts = null; try { //retrieves a connection with the repository connection = this.repository.getConnection(); try { //starts a transaction connection.begin(); //performs the query allContexts = new RetrieveOperations().getContexts(connection, containsTerm); connection.commit(); } catch (RepositoryException | NullPointerException ex) { connection.rollback(); Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { connection.rollback(); Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } finally { connection.close(); } } catch (RepositoryException ex) { Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } return allContexts; } /** * Changes the class that will be used for CRUD operations. * * @param classe the class to be implemented. */ public <T> void setClasse(Class<T> classe) { this.classe = classe; } /** * Retrieves the current class that will be used for CRUD operations. * * @return classe the class to be implemented. */ public Class<?> retrieveClass() { return this.classe; } private URI[] getContexts() { return contexts; } public void setContexts(java.net.URI[] contexts) { this.contexts = new URI[]{}; if (contexts != null) { List<URI> uris = new ArrayList<>(); for (java.net.URI uri : contexts) { uris.add(new URIImpl(uri.toString())); } this.contexts = uris.toArray(this.contexts); } } }
src/wwwc/nees/joint/module/kao/AbstractKAO.java
package wwwc.nees.joint.module.kao; import wwwc.nees.joint.module.kao.retrieve.QueryRunner; import wwwc.nees.joint.module.kao.retrieve.RetrieveOperations; import wwwc.nees.joint.module.kao.retrieve.SPARQLQueryRunnerImpl; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.openrdf.model.URI; import org.openrdf.model.impl.URIImpl; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.TupleQueryResultHandlerException; import org.openrdf.query.UpdateExecutionException; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; /** * Abstract class KAO, for operations in the persistence with SESAME and Alibaba * * @author Olavo Holanda * @version 1.0 - 15/01/2012 */ public abstract class AbstractKAO { // VARIABLES // ------------------------------------------------------------------------- // Variable to connect with the repository private final Repository repository; // Variable to do operations in the repository private RepositoryConnection connection; // Variable with the desired class to be implemented private Class<?> classe; // Interface to perform queries in the repository private final QueryRunner queryRunner; // URI[] of graph to save triples private URI[] contexts; // CONSTRUCTOR // ------------------------------------------------------------------------- /** * Class Constructor, starts the <code>Repository</code> and creates a * <code>ObjectConnection</code>, to do persistence operations. * * @param classe the class to be implemented. * */ public <T> AbstractKAO(Class<T> classe) { this.classe = classe; // Retrieves the repository in the server this.repository = RepositoryFactory.getRepository(); // Creates a QueryRunner with SPARQL implementation this.queryRunner = new SPARQLQueryRunnerImpl(); this.contexts = new URI[]{}; } // METHODS // ------------------------------------------------------------------------- /** * Creates a new instance in the repository with the specified name. * * @param instanceName a <code>String</code> with the instance name. * @param ontologyURI a <code>String</code> with the instance name. * @param contexts <code>URI</code> represent the graphs in which the query * will be performed. * @return T the new instance. */ public <T> T create(String ontologyURI, String instanceName, java.net.URI... contexts) { return create(ontologyURI + instanceName, contexts); } /** * Creates a new instance in the repository with the specified uri. * * @param instanceURI a <code>String</code> with the instance uri. * @param contexts <code>URI</code> represent the graphs in which the query * will be performed. * @return T the new instance. */ public <T> T create(String instanceURI, java.net.URI... contexts) { setContexts(contexts); Object ob = null; try { connection = this.repository.getConnection(); try { connection.begin(); ob = new CreateOperations().create(connection, instanceURI, this.classe, this.getContexts()); connection.commit(); } catch (Exception e) { // If throws any exception rollback connection.rollback(); Logger .getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, e); } finally { connection.close(); } } catch (RepositoryException eR) { // If throws repository Exception the the connection is not inialized Logger.getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, eR); } return (T) ob; } /** * Creates a new instance with a unique ID in the repository with the * specified prefix. * * @param instancePrefix a <code>String</code> with the prefix name. * @param ontologyURI a <code>String</code> with the instance name. * @param contexts <code>URI</code> represent the graphs in which the query * will be performed. * @return T the new instance. */ public <T> T createWithUniqueID(String ontologyURI, String instancePrefix, java.net.URI... contexts) { setContexts(contexts); Object ob = null; try { connection = this.repository.getConnection(); try { connection.begin(); ob = new CreateOperations().createWithUniqueID(connection, ontologyURI, instancePrefix, this.classe, this.getContexts()); connection.commit(); } catch (Exception e) { // If throws any exception rollback connection.rollback(); Logger .getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, e); } finally { connection.close(); } } catch (RepositoryException eR) { // If throws repository Exception the the connection is not inialized Logger.getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, eR); } return (T) ob; } /** * Removes the desired instance in the repository, must be saved after. * * @param ontologyURI is the URI from the ontology which represents the * instance. * @param instanceName a <code>String</code> with the instance name. * @param contexts <code>URI</code> represent the graphs in which the query * will be performed. */ public void delete(String ontologyURI, String instanceName, java.net.URI... contexts) { delete(ontologyURI + instanceName, contexts); } public void delete(String instanceURI, java.net.URI... contexts) { setContexts(contexts); try { connection = this.repository.getConnection(); try { //gets connection connection.begin(); //removes the quads that have the corresponding subject // removeOpe.remove(ontologyURI, instanceName, con, this.getContexts()); new RemoveOperations().remove_SPARQLUpdate(connection, instanceURI, this.getContexts()); // Saves the object in the repository connection.commit(); } catch (RepositoryException | MalformedQueryException | UpdateExecutionException e) { // If throws any exception rollback connection.rollback(); Logger .getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, e); } finally { connection.close(); } } catch (RepositoryException eR) { // If throws repository Exception the the connection is not inialized Logger.getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, eR); } } /** * Removes the desired instance in the repository, must be saved after. * * @param instance an object T with the instance * @param contexts the graphs in which the instance is removed. */ public <T> void delete(T instance, java.net.URI... contexts) { try { setContexts(contexts); connection = this.repository.getConnection(); try { //gets connection connection.begin(); new RemoveOperations().remove_SPARQLUpdate(connection, instance.toString(), this.getContexts()); // removeOpe.remove(instance, con, this.getContexts()); // Saves the object in the repository connection.commit(); } catch (RepositoryException | MalformedQueryException | UpdateExecutionException e) { // If throws any exception rollback connection.rollback(); Logger .getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, e); } finally { connection.close(); } } catch (RepositoryException eR) { // If throws repository Exception the the connection is not inialized Logger.getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, eR); } } /** * Retrieves the desired instance in the repository. * * @param ontologyURI : a <code>String</code> with the ontology base URI * @param instanceName a <code>String</code> with the instance name. * @param contexts the graphs in which the instance is removed. * @return T the desired instance. */ public <T> T retrieveInstance(String ontologyURI, String instanceName, java.net.URI... contexts) { return retrieveInstance(ontologyURI + instanceName, contexts); } /** * Retrieves the desired instance in the repository. * * @param instanceURI a <code>String</code> with the instance name. * @param contexts the graphs in which the instance is removed. * @return T the desired instance. */ public <T> T retrieveInstance(String instanceURI, java.net.URI... contexts) { Object ob = null; try { setContexts(contexts); connection = this.repository.getConnection(); try { //gets connection connection.begin(); ob = new RetrieveOperations().retrieveInstance(connection, instanceURI, classe, this.getContexts()); // Saves the object in the repository connection.commit(); } catch (Exception e) { // If throws any exception rollback connection.rollback(); Logger .getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, e); } finally { connection.close(); } } catch (RepositoryException eR) { // If throws repository Exception the the connection is not inialized Logger.getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, eR); } return (T) ob; } /** * Retrieves all the instances of the class, passed in the constructor. * * @param contexts <code>URI</code> represent the graphs in which the query * will be performed. * @return <code>List</code> a List with the instances. */ public <T> List<T> retrieveAllInstances(java.net.URI... contexts) { setContexts(contexts); // Creates a new java.util.List List<T> listInstances = new ArrayList<>(); try { connection = this.repository.getConnection(); try { //gets connection connection.begin(); listInstances = (List<T>) new RetrieveOperations().retrieveAllInstances(connection, classe, this.getContexts()); // Saves the object in the repository connection.commit(); } catch (Exception e) { // If throws any exception rollback connection.rollback(); Logger .getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, e); } finally { connection.close(); } } catch (RepositoryException eR) { // If throws repository Exception the the connection is not inialized Logger.getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, eR); } return listInstances; } /** * Saves the uncommitted changes in the repository and close the connection * with it. * * @param instance is the object which will be updated * @param contexts <code>URI</code> represent the graphs in which the query * will be updated. */ public <T> T update(T instance, java.net.URI... contexts) { setContexts(contexts); Object ob = null; try { //gets connection connection = this.repository.getConnection(); try { connection.begin(); ob = new UpdateOperations().updateDettachedInstance(connection, instance, classe, this.getContexts()); // Saves the object in the repository connection.commit(); } catch (Exception e) { // If throws any exception rollback connection.rollback(); Logger .getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, e); } finally { connection.close(); } } catch (RepositoryException eR) { // If throws repository Exception the the connection is not inialized Logger.getLogger(AbstractKAO.class .getName()).log(Level.SEVERE, null, eR); } return (T) ob; } /** * Performs queries in the repository, returning a single result. * * @param query the <code>String</code> with the query to be performed. * * @return object <code>Object</code> result. */ public Object executeSPARQLquerySingleResult(String query) { Object object = null; try { try { //retrieves a connection with the repository connection = this.repository.getConnection(); //starts a transaction connection.begin(); //performs the query object = this.queryRunner.executeQueryAsSingleResult(connection, query); connection.commit(); } catch (Exception ex) { connection.rollback(); Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } finally { connection.close(); } } catch (RepositoryException ex) { Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } return object; } /** * Performs queries in the repository, returning a java.util.List of * results. * * @param query the <code>String</code> with the query to be performed. * @param contexts <code>URI</code> represent the graphs in which the query * will be performed. * * @return <code>List</code> a java.util.List with the results. */ public List executeSPARQLqueryResultList(String query, java.net.URI... contexts) { setContexts(contexts); List<Object> objects = null; try { try { //retrieves a connection with the repository connection = this.repository.getConnection(); //starts a transaction connection.begin(); //performs the query objects = this.queryRunner.executeQueryAsList(connection, query, this.getContexts()); connection.commit(); } catch (Exception ex) { connection.rollback(); Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } finally { connection.close(); } } catch (RepositoryException ex) { Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } return objects; } public List executeSPARQLqueryResultList2(String query, java.net.URI... contexts) { setContexts(contexts); List<Object> objects = null; try { try { //retrieves a connection with the repository connection = this.repository.getConnection(); //starts a transaction connection.begin(); //performs the query objects = this.queryRunner.executeQueryAsList2(connection, query, this.getContexts()); connection.commit(); } catch (Exception ex) { connection.rollback(); Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } finally { connection.close(); } } catch (RepositoryException ex) { Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } return objects; } public String executeSPARQLtupleQueryAsJSONString(String query) { String results = null; try { try { //retrieves a connection with the repository connection = this.repository.getConnection(); //starts a transaction connection.begin(); //performs the query results = this.queryRunner.executeTupleQueryAsJSON(connection, query).replaceAll("=", ":"); connection.commit(); } catch (RepositoryException | MalformedQueryException | QueryEvaluationException | TupleQueryResultHandlerException ex) { connection.rollback(); Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } finally { connection.close(); } } catch (RepositoryException ex) { Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } return results; } /** * Performs query in the repository, returning the results in an adapted * format from JSON-LD specification * * @param query the String with the query to be performed. * @return a JSON as String */ public String executeSPARQLgraphQueryAsJSONLDString(String query) { return executeSPARQLgraphQueryAsJSONLDString(query, true); } /** * Performs query in the repository, returning the results in an adapted * format from JSON-LD specification * * @param query the String with the query to be performed. * @param graphAsJSONArray defines if the <b><code>@graph</code> key</b> is * a JSON Array. If value is true, then is an array, else, is a JSON Object * where the <b><code>@id</code> key</b> are the keys of the objects. <b>By * default it's <code>true</code></b>. * @return a JSON as String */ public String executeSPARQLgraphQueryAsJSONLDString(String query, boolean graphAsJSONArray) { String results = null; try { try { //retrieves a connection with the repository connection = this.repository.getConnection(); //starts a transaction connection.begin(); //performs the query results = this.queryRunner.executeGraphQueryAsJSONLD(connection, query, graphAsJSONArray); connection.commit(); } catch (Exception ex) { connection.rollback(); Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } finally { connection.close(); } } catch (RepositoryException ex) { Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } return results; } /** * Performs queries in the repository, returning a java.util.Iterator with * the results. * * @param query the <code>String</code> with the query to be performed. * @param contexts <code>URI</code> represent the graphs in which the query * will be performed. * * @return <code>Iterator</code> a java.util.List with the results. */ public Iterator executeQueryAsIterator(String query, java.net.URI... contexts) { //Converter to Iterator and return return executeSPARQLqueryResultList(query, contexts).iterator(); } /** * Performs SPARQL queries in the repository, returning a boolean with the * result. * * @param query the <code>String</code> with the query to be performed. * * @return <code>boolean</code> true or false. */ public boolean executeBooleanQuery(String query) { boolean result = false; try { try { //retrieves a connection with the repository connection = this.repository.getConnection(); //starts a transaction connection.begin(); //performs the query result = this.queryRunner.executeBooleanQuery(connection, query); connection.commit(); } catch (Exception ex) { connection.rollback(); Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } finally { connection.close(); } } catch (RepositoryException ex) { Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } return result; } /** * Performs SPARQL update queries in the repository, returning a boolean * true if the query was performed with successful or false otherwise. * * @param query the <code>String</code> with the query to be performed. */ public void executeSPARQLUpdateQuery(String query) { try { try { //retrieves a connection with the repository connection = this.repository.getConnection(); //starts a transaction connection.begin(); //performs the query this.queryRunner.executeUpdateQuery(connection, query); connection.commit(); } catch (Exception ex) { connection.rollback(); Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } finally { connection.close(); } } catch (RepositoryException ex) { Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } } /** * Gets contexts from quadstore. * * @param containsTerm is a regular expression that must be matched with the * contexts * @return an URI list * @throws NullPointerException occurs when the containsTerm is null. */ public List<java.net.URI> getContexts(String containsTerm) { List<java.net.URI> allContexts = null; try { try { //retrieves a connection with the repository connection = this.repository.getConnection(); //starts a transaction connection.begin(); //performs the query allContexts = new RetrieveOperations().getContexts(connection, containsTerm); connection.commit(); } catch (RepositoryException | NullPointerException ex) { connection.rollback(); Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { connection.rollback(); Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } finally { connection.close(); } } catch (RepositoryException ex) { Logger.getLogger(AbstractKAO.class.getName()).log(Level.SEVERE, null, ex); } return allContexts; } /** * Changes the class that will be used for CRUD operations. * * @param classe the class to be implemented. */ public <T> void setClasse(Class<T> classe) { this.classe = classe; } /** * Retrieves the current class that will be used for CRUD operations. * * @return classe the class to be implemented. */ public Class<?> retrieveClass() { return this.classe; } private URI[] getContexts() { return contexts; } public void setContexts(java.net.URI[] contexts) { this.contexts = new URI[]{}; if (contexts != null) { List<URI> uris = new ArrayList<>(); for (java.net.URI uri : contexts) { uris.add(new URIImpl(uri.toString())); } this.contexts = uris.toArray(this.contexts); } } }
Fixed bug in AbstractKAO
src/wwwc/nees/joint/module/kao/AbstractKAO.java
Fixed bug in AbstractKAO
Java
mpl-2.0
4aade5f0e586c97661fa9e8471d3126511bd51db
0
richardwilkes/gcs,richardwilkes/gcs
/* * Copyright ©1998-2022 by Richard A. Wilkes. All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, version 2.0. If a copy of the MPL was not distributed with * this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This Source Code Form is "Incompatible With Secondary Licenses", as * defined by the Mozilla Public License, version 2.0. */ package com.trollworks.gcs.body; import com.trollworks.gcs.character.GURPSCharacter; import com.trollworks.gcs.feature.DRBonus; import com.trollworks.gcs.utility.json.JsonMap; import com.trollworks.gcs.utility.json.JsonWriter; import com.trollworks.gcs.utility.text.Numbers; import com.trollworks.gcs.utility.text.NumericComparator; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; public class HitLocation implements Cloneable, Comparable<HitLocation> { public static final String KEY_PREFIX = "hit_location."; private static final String KEY_ID = "id"; private static final String KEY_CHOICE_NAME = "choice_name"; private static final String KEY_TABLE_NAME = "table_name"; private static final String KEY_SLOTS = "slots"; private static final String KEY_HIT_PENALTY = "hit_penalty"; private static final String KEY_DR_BONUS = "dr_bonus"; private static final String KEY_DESCRIPTION = "description"; private static final String KEY_SUB_TABLE = "sub_table"; private String mID; private String mChoiceName; private String mTableName; private int mSlots; private String mRollRange; private int mHitPenalty; private int mDRBonus; private String mDescription; private HitLocationTable mOwningTable; private HitLocationTable mSubTable; public HitLocation(String id, String name, int slots, int hitPenalty, int drBonus, String description) { this(id, name, name, slots, hitPenalty, drBonus, description); } public HitLocation(String id, String choiceName, String tableName, int slots, int hitPenalty, int drBonus, String description) { setID(id); mChoiceName = choiceName; mTableName = tableName; mSlots = slots; mHitPenalty = hitPenalty; mDRBonus = drBonus; mDescription = description; } public HitLocation(JsonMap m) { setID(m.getString(KEY_ID)); mChoiceName = m.getString(KEY_CHOICE_NAME); mTableName = m.getString(KEY_TABLE_NAME); mSlots = m.getInt(KEY_SLOTS); mHitPenalty = m.getInt(KEY_HIT_PENALTY); mDRBonus = m.getInt(KEY_DR_BONUS); mDescription = m.getString(KEY_DESCRIPTION); if (m.has(KEY_SUB_TABLE)) { setSubTable(new HitLocationTable(m.getMap(KEY_SUB_TABLE))); } } public void toJSON(JsonWriter w, GURPSCharacter character) throws IOException { w.startMap(); w.keyValue(KEY_ID, mID); w.keyValue(KEY_CHOICE_NAME, mChoiceName); w.keyValue(KEY_TABLE_NAME, mTableName); w.keyValue(KEY_SLOTS, mSlots); w.keyValue(KEY_HIT_PENALTY, mHitPenalty); w.keyValue(KEY_DR_BONUS, mDRBonus); w.keyValue(KEY_DESCRIPTION, mDescription); if (mSubTable != null) { w.key(KEY_SUB_TABLE); mSubTable.toJSON(w, character); } // Emit the calculated values for third parties w.key("calc"); w.startMap(); w.keyValue("roll_range", getRollRange()); if (character != null) { Map<String, Integer> dr = getDR(character, null, null); if (!dr.containsKey(DRBonus.ALL_SPECIALIZATION)) { dr.put(DRBonus.ALL_SPECIALIZATION, Integer.valueOf(0)); } List<String> keys = new ArrayList<>(dr.keySet()); Collections.sort(keys); w.key("dr"); w.startMap(); for (String key : keys) { w.keyValue(key, dr.get(key).intValue()); } w.endMap(); } w.endMap(); w.endMap(); } public String getID() { return mID; } public void setID(String id) { mID = com.trollworks.gcs.utility.ID.sanitize(id, null, false); } public String getChoiceName() { return mChoiceName; } public void setChoiceName(String name) { mChoiceName = name; } public String getTableName() { return mTableName; } public void setTableName(String name) { mTableName = name; } public int getSlots() { return mSlots; } public void setSlots(int slots) { mSlots = slots; } public String getRollRange() { return mRollRange; } public void setRollRange(String rollRange) { mRollRange = rollRange; } public int getHitPenalty() { return mHitPenalty; } public void setHitPenalty(int penalty) { mHitPenalty = penalty; } public Map<String, Integer> getDR(GURPSCharacter character, StringBuilder tooltip, Map<String, Integer> dr) { if (dr == null) { dr = new HashMap<>(); } if (mDRBonus != 0) { Integer value = dr.get(DRBonus.ALL_SPECIALIZATION); if (value == null) { value = Integer.valueOf(mDRBonus); } else { value = Integer.valueOf(value.intValue() + mDRBonus); } dr.put(DRBonus.ALL_SPECIALIZATION, value); if (tooltip != null) { tooltip.append(String.format("\n%s [%s against %s attacks]", mChoiceName, Numbers.formatWithForcedSign(mDRBonus), DRBonus.ALL_SPECIALIZATION)); } } dr = character.addDRBonusesFor(KEY_PREFIX + mID, tooltip, dr); if (mOwningTable != null) { HitLocation owningLocation = mOwningTable.getOwningLocation(); if (owningLocation != null) { dr = owningLocation.getDR(character, tooltip, dr); } } if (tooltip != null) { List<String> keys = new ArrayList<>(dr.keySet()); if (!keys.isEmpty()) { StringBuilder tt = new StringBuilder(); Collections.sort(keys); Integer base = dr.get(DRBonus.ALL_SPECIALIZATION); int baseDR = base == null ? 0 : base.intValue(); tt.append('\n'); for (String key : keys) { int value = dr.get(key).intValue(); if (!DRBonus.ALL_SPECIALIZATION.equalsIgnoreCase(key)) { value += baseDR; } tt.append(String.format("\n%s against %s attacks", Numbers.format(value), key)); } tt.append('\n'); tooltip.insert(0, tt); } } return dr; } public String getDisplayDR(GURPSCharacter character, StringBuilder tooltip) { Map<String, Integer> dr = getDR(character, tooltip, null); if (!dr.containsKey(DRBonus.ALL_SPECIALIZATION)) { dr.put(DRBonus.ALL_SPECIALIZATION, Integer.valueOf(0)); } int all = dr.get(DRBonus.ALL_SPECIALIZATION).intValue(); List<String> keys = new ArrayList<>(dr.keySet()); keys.remove(DRBonus.ALL_SPECIALIZATION); Collections.sort(keys); keys.add(0, DRBonus.ALL_SPECIALIZATION); StringBuilder buffer = new StringBuilder(); for (String key : keys) { int value = dr.get(key).intValue(); if (!DRBonus.ALL_SPECIALIZATION.equals(key)) { value += all; } if (!buffer.isEmpty()) { buffer.append("/"); } buffer.append(Numbers.format(value)); } return buffer.toString(); } public int getDRBonus() { return mDRBonus; } public void setDRBonus(int bonus) { mDRBonus = bonus; } public String getDescription() { return mDescription; } public void setDescription(String description) { mDescription = description; } public HitLocationTable getOwningTable() { return mOwningTable; } public void setOwningTable(HitLocationTable table) { mOwningTable = table; } public HitLocationTable getSubTable() { return mSubTable; } public void setSubTable(HitLocationTable table) { if (table == null && mSubTable != null) { mSubTable.setOwningLocation(null); } mSubTable = table; if (mSubTable != null) { mSubTable.setOwningLocation(this); } } protected void populateMap(Map<String, HitLocation> map) { map.put(mID, this); if (mSubTable != null) { mSubTable.populateMap(map); } } @SuppressWarnings("MethodDoesntCallSuperMethod") @Override public HitLocation clone() { HitLocation other = new HitLocation(mID, mChoiceName, mTableName, mSlots, mHitPenalty, mDRBonus, mDescription); other.mRollRange = mRollRange; if (mSubTable != null) { other.setSubTable(mSubTable.clone()); } return other; } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } HitLocation that = (HitLocation) other; if (mSlots != that.mSlots) { return false; } if (mHitPenalty != that.mHitPenalty) { return false; } if (mDRBonus != that.mDRBonus) { return false; } if (!mID.equals(that.mID)) { return false; } if (!mChoiceName.equals(that.mChoiceName)) { return false; } if (!mTableName.equals(that.mTableName)) { return false; } if (!mDescription.equals(that.mDescription)) { return false; } return Objects.equals(mSubTable, that.mSubTable); } @Override public int hashCode() { int result = mID.hashCode(); result = 31 * result + mChoiceName.hashCode(); result = 31 * result + mTableName.hashCode(); result = 31 * result + mSlots; result = 31 * result + mHitPenalty; result = 31 * result + mDRBonus; result = 31 * result + mDescription.hashCode(); result = 31 * result + (mSubTable != null ? mSubTable.hashCode() : 0); return result; } @Override public int compareTo(HitLocation other) { int result = NumericComparator.caselessCompareStrings(mChoiceName, other.mChoiceName); if (result == 0) { result = NumericComparator.caselessCompareStrings(mID, other.mID); } return result; } @Override public String toString() { return mChoiceName; } }
com.trollworks.gcs/src/com/trollworks/gcs/body/HitLocation.java
/* * Copyright ©1998-2022 by Richard A. Wilkes. All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, version 2.0. If a copy of the MPL was not distributed with * this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This Source Code Form is "Incompatible With Secondary Licenses", as * defined by the Mozilla Public License, version 2.0. */ package com.trollworks.gcs.body; import com.trollworks.gcs.character.GURPSCharacter; import com.trollworks.gcs.feature.DRBonus; import com.trollworks.gcs.utility.json.JsonMap; import com.trollworks.gcs.utility.json.JsonWriter; import com.trollworks.gcs.utility.text.Numbers; import com.trollworks.gcs.utility.text.NumericComparator; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; public class HitLocation implements Cloneable, Comparable<HitLocation> { public static final String KEY_PREFIX = "hit_location."; private static final String KEY_ID = "id"; private static final String KEY_CHOICE_NAME = "choice_name"; private static final String KEY_TABLE_NAME = "table_name"; private static final String KEY_SLOTS = "slots"; private static final String KEY_HIT_PENALTY = "hit_penalty"; private static final String KEY_DR_BONUS = "dr_bonus"; private static final String KEY_DESCRIPTION = "description"; private static final String KEY_SUB_TABLE = "sub_table"; private String mID; private String mChoiceName; private String mTableName; private int mSlots; private String mRollRange; private int mHitPenalty; private int mDRBonus; private String mDescription; private HitLocationTable mOwningTable; private HitLocationTable mSubTable; public HitLocation(String id, String name, int slots, int hitPenalty, int drBonus, String description) { this(id, name, name, slots, hitPenalty, drBonus, description); } public HitLocation(String id, String choiceName, String tableName, int slots, int hitPenalty, int drBonus, String description) { setID(id); mChoiceName = choiceName; mTableName = tableName; mSlots = slots; mHitPenalty = hitPenalty; mDRBonus = drBonus; mDescription = description; } public HitLocation(JsonMap m) { setID(m.getString(KEY_ID)); mChoiceName = m.getString(KEY_CHOICE_NAME); mTableName = m.getString(KEY_TABLE_NAME); mSlots = m.getInt(KEY_SLOTS); mHitPenalty = m.getInt(KEY_HIT_PENALTY); mDRBonus = m.getInt(KEY_DR_BONUS); mDescription = m.getString(KEY_DESCRIPTION); if (m.has(KEY_SUB_TABLE)) { setSubTable(new HitLocationTable(m.getMap(KEY_SUB_TABLE))); } } public void toJSON(JsonWriter w, GURPSCharacter character) throws IOException { w.startMap(); w.keyValue(KEY_ID, mID); w.keyValue(KEY_CHOICE_NAME, mChoiceName); w.keyValue(KEY_TABLE_NAME, mTableName); w.keyValue(KEY_SLOTS, mSlots); w.keyValue(KEY_HIT_PENALTY, mHitPenalty); w.keyValue(KEY_DR_BONUS, mDRBonus); w.keyValue(KEY_DESCRIPTION, mDescription); if (mSubTable != null) { w.key(KEY_SUB_TABLE); mSubTable.toJSON(w, character); } // Emit the calculated values for third parties w.key("calc"); w.startMap(); w.keyValue("roll_range", getRollRange()); if (character != null) { Map<String, Integer> dr = getDR(character, null, null); if (!dr.containsKey(DRBonus.ALL_SPECIALIZATION)) { dr.put(DRBonus.ALL_SPECIALIZATION, Integer.valueOf(0)); } List<String> keys = new ArrayList<>(dr.keySet()); Collections.sort(keys); w.key("dr"); w.startMap(); for (String key : keys) { w.keyValue(key, dr.get(key).intValue()); } w.endMap(); } w.endMap(); w.endMap(); } public String getID() { return mID; } public void setID(String id) { mID = com.trollworks.gcs.utility.ID.sanitize(id, null, false); } public String getChoiceName() { return mChoiceName; } public void setChoiceName(String name) { mChoiceName = name; } public String getTableName() { return mTableName; } public void setTableName(String name) { mTableName = name; } public int getSlots() { return mSlots; } public void setSlots(int slots) { mSlots = slots; } public String getRollRange() { return mRollRange; } public void setRollRange(String rollRange) { mRollRange = rollRange; } public int getHitPenalty() { return mHitPenalty; } public void setHitPenalty(int penalty) { mHitPenalty = penalty; } public Map<String, Integer> getDR(GURPSCharacter character, StringBuilder tooltip, Map<String, Integer> dr) { if (dr == null) { dr = new HashMap<>(); } if (mDRBonus != 0) { Integer value = dr.get(DRBonus.ALL_SPECIALIZATION); if (value == null) { value = Integer.valueOf(mDRBonus); } else { value = Integer.valueOf(value.intValue() + mDRBonus); } dr.put(DRBonus.ALL_SPECIALIZATION, value); if (tooltip != null) { tooltip.append(String.format("\n%s [%s against %s attacks]", mChoiceName, DRBonus.ALL_SPECIALIZATION, Numbers.formatWithForcedSign(mDRBonus))); } } dr = character.addDRBonusesFor(KEY_PREFIX + mID, tooltip, dr); if (mOwningTable != null) { HitLocation owningLocation = mOwningTable.getOwningLocation(); if (owningLocation != null) { dr = owningLocation.getDR(character, tooltip, dr); } } if (tooltip != null) { List<String> keys = new ArrayList<>(dr.keySet()); if (!keys.isEmpty()) { StringBuilder tt = new StringBuilder(); Collections.sort(keys); Integer base = dr.get(DRBonus.ALL_SPECIALIZATION); int baseDR = base == null ? 0 : base.intValue(); tt.append('\n'); for (String key : keys) { int value = dr.get(key).intValue(); if (!DRBonus.ALL_SPECIALIZATION.equalsIgnoreCase(key)) { value += baseDR; } tt.append(String.format("\n%s against %s attacks", Numbers.format(value), key)); } tt.append('\n'); tooltip.insert(0, tt); } } return dr; } public String getDisplayDR(GURPSCharacter character, StringBuilder tooltip) { Map<String, Integer> dr = getDR(character, tooltip, null); if (!dr.containsKey(DRBonus.ALL_SPECIALIZATION)) { dr.put(DRBonus.ALL_SPECIALIZATION, Integer.valueOf(0)); } int all = dr.get(DRBonus.ALL_SPECIALIZATION).intValue(); List<String> keys = new ArrayList<>(dr.keySet()); keys.remove(DRBonus.ALL_SPECIALIZATION); Collections.sort(keys); keys.add(0, DRBonus.ALL_SPECIALIZATION); StringBuilder buffer = new StringBuilder(); for (String key : keys) { int value = dr.get(key).intValue(); if (!DRBonus.ALL_SPECIALIZATION.equals(key)) { value += all; } if (!buffer.isEmpty()) { buffer.append("/"); } buffer.append(Numbers.format(value)); } return buffer.toString(); } public int getDRBonus() { return mDRBonus; } public void setDRBonus(int bonus) { mDRBonus = bonus; } public String getDescription() { return mDescription; } public void setDescription(String description) { mDescription = description; } public HitLocationTable getOwningTable() { return mOwningTable; } public void setOwningTable(HitLocationTable table) { mOwningTable = table; } public HitLocationTable getSubTable() { return mSubTable; } public void setSubTable(HitLocationTable table) { if (table == null && mSubTable != null) { mSubTable.setOwningLocation(null); } mSubTable = table; if (mSubTable != null) { mSubTable.setOwningLocation(this); } } protected void populateMap(Map<String, HitLocation> map) { map.put(mID, this); if (mSubTable != null) { mSubTable.populateMap(map); } } @SuppressWarnings("MethodDoesntCallSuperMethod") @Override public HitLocation clone() { HitLocation other = new HitLocation(mID, mChoiceName, mTableName, mSlots, mHitPenalty, mDRBonus, mDescription); other.mRollRange = mRollRange; if (mSubTable != null) { other.setSubTable(mSubTable.clone()); } return other; } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } HitLocation that = (HitLocation) other; if (mSlots != that.mSlots) { return false; } if (mHitPenalty != that.mHitPenalty) { return false; } if (mDRBonus != that.mDRBonus) { return false; } if (!mID.equals(that.mID)) { return false; } if (!mChoiceName.equals(that.mChoiceName)) { return false; } if (!mTableName.equals(that.mTableName)) { return false; } if (!mDescription.equals(that.mDescription)) { return false; } return Objects.equals(mSubTable, that.mSubTable); } @Override public int hashCode() { int result = mID.hashCode(); result = 31 * result + mChoiceName.hashCode(); result = 31 * result + mTableName.hashCode(); result = 31 * result + mSlots; result = 31 * result + mHitPenalty; result = 31 * result + mDRBonus; result = 31 * result + mDescription.hashCode(); result = 31 * result + (mSubTable != null ? mSubTable.hashCode() : 0); return result; } @Override public int compareTo(HitLocation other) { int result = NumericComparator.caselessCompareStrings(mChoiceName, other.mChoiceName); if (result == 0) { result = NumericComparator.caselessCompareStrings(mID, other.mID); } return result; } @Override public String toString() { return mChoiceName; } }
Fix formatting of DR tooltip
com.trollworks.gcs/src/com/trollworks/gcs/body/HitLocation.java
Fix formatting of DR tooltip
Java
lgpl-2.1
fc6becc501e5d783d20e23d5af26c0f1e04e7449
0
OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs
package opendap.bes.caching; import opendap.bes.BES; import opendap.bes.BESError; import opendap.bes.BadConfigurationException; import opendap.bes.dap2Responders.BesApi; import opendap.ppt.PPTException; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * An in-memory cache for BES showNode responses. This class is a singleton. */ public class BesNodeCache { public static final String NODE_CACHE_ELEMENT_NAME = "NodeCache"; private static final String MAX_ENTRIES_ATTRIBUTE_NAME = "maxEntries"; private static final String REFRESH_INTERVAL_ATTRIBUTE_NAME = "refreshInterval"; private static final long NODE_CACHE_MAX_ENTRIES_DEFAULT = 2000; private static final long NODE_CACHE_REFRESH_INTERVAL_DEFAULT = 600; private static final ReentrantReadWriteLock RWLOCK = new ReentrantReadWriteLock(); private static final ReentrantLock LOCK = new ReentrantLock(); private static final Logger LOG = LoggerFactory.getLogger(NODE_CACHE_ELEMENT_NAME); private static final ConcurrentHashMap<String,NodeTransaction> NODE_CACHE = new ConcurrentHashMap<>(); private static final ConcurrentSkipListSet<NodeTransaction> MOST_RECENTLY_ACCESSED = new ConcurrentSkipListSet<>(); private static final AtomicLong MAX_CACHE_ENTRIES = new AtomicLong(50); // # of entries in cache private static final AtomicLong UPDATE_INTERVAL = new AtomicLong(10); // Update interval in seconds private static final double CACHE_REDUCTION_FACTOR = 0.2; // Amount to reduce cache when purging private static final AtomicBoolean ENABLED = new AtomicBoolean(false); private static final long nanoInSeconds = 1000000000; /** * This is a singleton class and as such all methods are static and the constructor is private because an * instance should never be created. */ private BesNodeCache(){} /** * Initialize the Node Cache using an XML Element. * @param config The "NodeCache" configuration element * @throws BadConfigurationException When the configuration is broken. */ public static void init(Element config) throws BadConfigurationException { if (config == null || !config.getName().equals(NODE_CACHE_ELEMENT_NAME)) throw new BadConfigurationException("BesNodeCache must be passed a non-null configuration " + "element named " + NODE_CACHE_ELEMENT_NAME); long maxEntries = NODE_CACHE_MAX_ENTRIES_DEFAULT; String maxEntriesString = config.getAttributeValue(MAX_ENTRIES_ATTRIBUTE_NAME); try { maxEntries = Long.parseLong(maxEntriesString); if (maxEntries <= 0) { maxEntries = NODE_CACHE_MAX_ENTRIES_DEFAULT; String msg = "Failed to parse value of " + NODE_CACHE_ELEMENT_NAME + "@" + MAX_ENTRIES_ATTRIBUTE_NAME + "! " + "Value must be an integer > 0. Using default value: " + maxEntries; LOG.error(msg); } } catch (NumberFormatException nfe) { LOG.error("Failed to parse value of NodeCache@maxEntries! Value must" + " be an integer. Using default value: {}", maxEntries); } long refreshInterval = NODE_CACHE_REFRESH_INTERVAL_DEFAULT; String refreshIntervalString = config.getAttributeValue(REFRESH_INTERVAL_ATTRIBUTE_NAME); try { refreshInterval = Long.parseLong(refreshIntervalString); if (refreshInterval <= 0) { refreshInterval = NODE_CACHE_REFRESH_INTERVAL_DEFAULT; String msg = "Failed to parse value of " + NODE_CACHE_ELEMENT_NAME + "@" + REFRESH_INTERVAL_ATTRIBUTE_NAME + "! " + "Value must be an integer > 0. Using default value: " + refreshInterval; LOG.error(msg); } } catch (NumberFormatException nfe) { LOG.error("Failed to parse value of NodeCache@refreshInterval! Value" + " must be an integer. Using default value: {}", refreshInterval); } init(maxEntries, refreshInterval); } /** * The _actual_ init method that sets up the cache. This must be called * prior to using the cache. * @param maxEntries The maximum number of entries in the cache * @param updateIntervalSeconds The time any object may reside in the cache before it is removed. */ public static void init(long maxEntries, long updateIntervalSeconds) { RWLOCK.writeLock().lock(); try { if (ENABLED.get()) { LOG.error("BesNodeCache has already been initialized! " + "MAX_CACHE_ENTRIES: {} UPDATE_INTERVAL: {} s", MAX_CACHE_ENTRIES.get(), UPDATE_INTERVAL.get()/(nanoInSeconds*1.0)); return; } MAX_CACHE_ENTRIES.set(maxEntries); UPDATE_INTERVAL.set(updateIntervalSeconds * nanoInSeconds); ENABLED.set(true); LOG.debug("INITIALIZED MAX_CACHE_ENTRIES: {} UPDATE_INTERVAL: {} s", MAX_CACHE_ENTRIES.get(), UPDATE_INTERVAL.get()/(nanoInSeconds*1.0)); } finally { RWLOCK.writeLock().unlock(); } } /** * The primary public method used to retrieve BES showNode command responses. Caching happens within this call. * @param key The name of the BES node to retrieve. * @return The BES showNode response for "key" */ public static Element getNode(String key) throws JDOMException, BadConfigurationException, PPTException, IOException, BESError { if(!ENABLED.get()) return null; if(key==null) throw new IOException("The BesApi.getNode() method was passed a key value of null. That's bad."); RWLOCK.readLock().lock(); try { LOG.debug("BEGIN NODE_CACHE.size(): {} MOST_RECENTLY_ACCESSED.size(): {}", NODE_CACHE.size(), MOST_RECENTLY_ACCESSED.size()); NodeTransaction nodeTransaction = NODE_CACHE.get(key); if(isStaleNodeTransaction(nodeTransaction)){ RWLOCK.readLock().unlock(); RWLOCK.writeLock().lock(); try { if (isStaleNodeTransaction(nodeTransaction)) { dropStaleNodeTransaction(nodeTransaction); LOG.debug("Dropping stale NodeTransaction[{}] from cache!",key); nodeTransaction = getAndCacheNodeTransaction(key); } RWLOCK.readLock().lock(); } finally { RWLOCK.writeLock().unlock(); } } updateMostRecentlyAccessed(nodeTransaction); // Now we need to sort out the response - Document or Error? Object responseObject = nodeTransaction.getResponse(); if(responseObject instanceof Document){ Document cachedNodeDoc = (Document)responseObject; Element root = cachedNodeDoc.getRootElement(); Element newRoot = (Element) root.clone(); newRoot.detach(); return newRoot; } if (responseObject instanceof BESError) { LOG.info("Cache contains BESError object. dataSource=\"" + key + "\""); throw (BESError) responseObject; } // The responseObject should only ever be a Document or a BESError throw new IOException("Cached object is of unexpected type! " + "This is a bad thing! Object: "+responseObject.getClass().getCanonicalName()); } finally { LOG.debug("END NODE_CACHE.size(): {} MOST_RECENTLY_ACCESSED.size(): {}", NODE_CACHE.size(), MOST_RECENTLY_ACCESSED.size()); RWLOCK.readLock().unlock(); } } /** * Solicits a showNode response from the BES for the passed parameter key. Once the response is received the response * is used to make a new NodeTransaction which is then placed in the cache associated with the value of key. * If the BES returns an error that is handled the same way, the error object is used to make a new NodeTransaction * which is placed in the cache associated with the value of key. * @param key The name of the node to retrieve from the BES using the showNode command. * @return The NodeTransaction built from the BES response. * @throws BadConfigurationException When a BES cannot be located. * @throws PPTException When the PPT exchange between the BES process and the OLFS fails. * @throws JDOMException When the documents cannot be parsed. * @throws IOException When theings cannot be read or written. */ private static NodeTransaction getAndCacheNodeTransaction(String key) throws BadConfigurationException, PPTException, JDOMException, IOException { BES bes = BesApi.getBES(key); Document showNodeRequestDoc = BesApi.getShowNodeRequestDocument(key); Document response = new Document(); NodeTransaction result; try { bes.besTransaction(showNodeRequestDoc, response); // Get the root element. Element root = response.getRootElement(); if (root == null) throw new IOException("BES showNode response for " + key + " was empty! No root element"); Element showNode = root.getChild("showNode", opendap.namespaces.BES.BES_NS); if (showNode == null) throw new IOException("BES showNode response for " + key + " was malformed! No showNode element"); showNode.setAttribute("prefix", bes.getPrefix()); LOG.info("Caching copy of BES showNode response for key: \"{}\"",key); result = putNodeTransaction(key, showNodeRequestDoc, response.clone()); } catch (BESError be) { LOG.info("The BES returned a BESError for key: \"{} \" CACHING BESError",key); result = putNodeTransaction(key, showNodeRequestDoc, be); } return result; } /** * Check to see if the passed NodeTransaction is stale. This is based * comparing its time in the cache with the UPDATE_INTERVAL. * * @param nodeTransaction The NodeTransaction to test. * @return Returns true is the NodeTransaction has been in the cache longer * the UPDATE_INTERVAL. */ private static boolean isStaleNodeTransaction(NodeTransaction nodeTransaction){ boolean isStale = true; // if it's null it's stale... if(nodeTransaction!=null) { long timeInCache = System.nanoTime() - nodeTransaction.getLastUpdateTime(); LOG.debug("nodeTransaction[{}] has been in cache {} s", nodeTransaction.getKey(), timeInCache / (nanoInSeconds * 1.0)); // Is it stale? isStale = timeInCache > UPDATE_INTERVAL.get(); } return isStale; } /** * Removes the passed NodeTransaction from both the cache (NODE_CACHE) and * from the most recently accessed list (MOST_RECENTLY_ACCESSED). If a null * value is passed, nothing is done and the method returns. * * @param nodeTransaction The NodeTransaction to drop from the cache. */ private static void dropStaleNodeTransaction(NodeTransaction nodeTransaction){ if(nodeTransaction==null){ // a null value is a noop, but not an error return; } NodeTransaction nt = NODE_CACHE.remove(nodeTransaction.getKey()); LOG.debug("Remove NodeTransaction[{}] from NODE_CACHE returned: {}", nodeTransaction.getKey(), (nt == null) ? "NULL" : nt); LOG.debug("NODE_CACHE.size(): {}", NODE_CACHE.size()); if (MOST_RECENTLY_ACCESSED.remove(nodeTransaction)) { LOG.debug("Successfully dropped NodeTransaction[{}] from MOST_RECENTLY_ACCESSED (size: {})", nodeTransaction.getKey(), MOST_RECENTLY_ACCESSED.size()); } else { LOG.error("FAILED to drop NodeTransaction[{}] from MOST_RECENTLY_ACCESSED (size: {})", nodeTransaction.getKey(), MOST_RECENTLY_ACCESSED.size()); } } /** * Updates the MOST_RECENTLY_ACCESSED list by dropping the passed * CatalogTransaction from the MOST_RECENTLY_ACCESSED list, updating * the CatalogTransaction's access time and then adding the updated * CatalogTransaction back to the MOST_RECENTLY_ACCESSED list. * @param nodeTransaction The CatalogTransaction whose access time needs * updating. */ private static void updateMostRecentlyAccessed(NodeTransaction nodeTransaction){ boolean status; LOCK.lock(); try { LOG.debug("Updating MOST_RECENTLY_ACCESSED list. MOST_RECENTLY_ACCESSED.size(): {}", MOST_RECENTLY_ACCESSED.size()); status = MOST_RECENTLY_ACCESSED.remove(nodeTransaction); if(status) { LOG.debug("Removed NodeTransaction[{},{}] from MOST_RECENTLY_ACCESSED", nodeTransaction.getKey(),nodeTransaction); } else { LOG.debug("The NodeTransaction[{},{}] was not found in MOST_RECENTLY_ACCESSED", nodeTransaction.getKey(),nodeTransaction); } LOG.debug("MOST_RECENTLY_ACCESSED list updated. MOST_RECENTLY_ACCESSED.size(): {}", MOST_RECENTLY_ACCESSED.size()); nodeTransaction.updateAccessedTime(); status = MOST_RECENTLY_ACCESSED.add(nodeTransaction); LOG.debug("{} NodeTransaction[{}] to MOST_RECENTLY_ACCESSED",status?"Added":"FAILED to add",nodeTransaction.getKey()); LOG.debug("MOST_RECENTLY_ACCESSED list updated. MOST_RECENTLY_ACCESSED.size(): {}", MOST_RECENTLY_ACCESSED.size()); } finally { LOCK.unlock(); } } /** * Takes a node response (Document or BESError) and tucks it into the NodeCache * @param key The name of the node that was retrieved. * @param request The BES showNode request document used to elicit the response. * @param response The object (either a Document or a BESError) returned by the BES transaction. */ private static NodeTransaction putNodeTransaction(String key, Document request, Object response) { LOG.debug("BEGIN NODE_CACHE.size(): {} ", NODE_CACHE.size()); // Make sure the cache has not grown too large. purgeLeastRecentlyAccessed(); NodeTransaction nodeTransaction = new NodeTransaction(key, request, response); LOG.debug("Created nodeTransaction[{}] @ {}", key, nodeTransaction.getLastUpdateTime()); NodeTransaction previous = NODE_CACHE.put(key, nodeTransaction); if (nodeTransaction == previous) { LOG.warn("NodeTransaction cache updated with new (replacement) object for key: \"{}\"",key); } else { LOG.debug("NodeTransaction cache updated by adding new object to cache using key \"{}\"",key); } LOG.debug("END NODE_CACHE.size(): {}", NODE_CACHE.size()); return nodeTransaction; } /** * If the cache is smaller than MAX_CACHE_ENTRIES then this is a no-op. * If the cache has grown larger than MAX_CACHE_ENTRIES then it will be reduced by * rsize = (CACHE_REDUCTION_FACTOR * MAX_CACHE_ENTRIES) entries. The reduction is done by iterating over the * MOST_RECENTLY_ACCESSED list, from oldest (longest since accessed) to newest (least time since access) and * collecting "rsize" NodeTransactions and removing them from both the NODE_CACHE and the MOST_RECENTLY_ACCESSED * list. */ private static void purgeLeastRecentlyAccessed(){ // Cache not full? Then return... if (NODE_CACHE.size() < MAX_CACHE_ENTRIES.get()) return; int dropNum = (int) (MAX_CACHE_ENTRIES.get() * CACHE_REDUCTION_FACTOR); if(dropNum==0) { dropNum = 1; } LOG.debug("BEGIN NODE_CACHE.size(): {} MOST_RECENTLY_ACCESSED.size(): {}", NODE_CACHE.size(), MOST_RECENTLY_ACCESSED.size()); LOG.debug("dropNum: {}",dropNum); LOG.debug("Before purge NODE_CACHE.size(): {}", NODE_CACHE.size()); LOG.debug("Before purge MOST_RECENTLY_ACCESSED.size(): {}", MOST_RECENTLY_ACCESSED.size()); List<NodeTransaction> purgeList = new ArrayList<>(dropNum); Iterator<NodeTransaction> oldestToNewest = MOST_RECENTLY_ACCESSED.iterator(); for(int i=0; i<dropNum && oldestToNewest.hasNext(); i++ ){ NodeTransaction nodeTransaction = oldestToNewest.next(); purgeList.add(nodeTransaction); LOG.debug("Purging CatalogTransaction for key {}",nodeTransaction.getKey()); NODE_CACHE.remove(nodeTransaction.getKey()); } MOST_RECENTLY_ACCESSED.removeAll(purgeList); LOG.debug("After purge NODE_CACHE.size(): {}", NODE_CACHE.size()); LOG.debug("After purge MOST_RECENTLY_ACCESSED.size(): {}", MOST_RECENTLY_ACCESSED.size()); LOG.debug("END"); } /** * Drops all references from the cache. */ public void destroy(){ RWLOCK.writeLock().lock(); try { NODE_CACHE.clear(); MOST_RECENTLY_ACCESSED.clear(); } finally { RWLOCK.writeLock().unlock(); } } /** * This is a test method used to make a NodeTransaction without requiring a * running BES to receive a request and generate a response. THe point is * to provide a test fixture to allow the evaluation of the * NodeTransaction.comparable() interface for the purposes of sorting. * * @param id * @return */ private static NodeTransaction getDummyCachedNodeTransaction(String id){ Document request; Document response; Element e; request = new Document(); e=new Element("request"); e.setAttribute("id",id); request.setRootElement(e); response = new Document(); e= new Element("response"); e.setAttribute("id",id); response.setRootElement(e); return new NodeTransaction(id,request,response); } public static void main(String[] args) { Logger log = LoggerFactory.getLogger(BesNodeCache.class); TreeSet<NodeTransaction> set = new TreeSet<>(); String[] testKeys = {"foo", "bar", "moo", "soo", "bar", "baz"}; NodeTransaction nodeTransaction; NodeTransaction first = null; String msgFormat = "nodeTransaction - key: %s getLastAccessedTime(): %d set.size(): %d"; String msg; for(String key: testKeys){ nodeTransaction = getDummyCachedNodeTransaction(key); set.add(nodeTransaction); msg = String.format(msgFormat,nodeTransaction.getKey(),nodeTransaction.getLastAccessedTime(),set.size()); log.info(msg); if(first==null) first = nodeTransaction; } log.info("Original List: "); for(NodeTransaction nodeT: set){ log.info(" node[{}]: {}",nodeT.getKey(),nodeT.getLastAccessedTime()); } set.remove(first); first.updateAccessedTime(); set.add(first); log.info("List after remove and replace: "); for(NodeTransaction nodeT: set){ log.info(" node[{}]: {}",nodeT.getKey(),nodeT.getLastAccessedTime()); } } //################################################################################################################# //################################################################################################################# //################################################################################################################# //################################################################################################################# //################################################################################################################# //################################################################################################################# //################################################################################################################# //################################################################################################################# //################################################################################################################# }
src/opendap/bes/caching/BesNodeCache.java
package opendap.bes.caching; import opendap.bes.BES; import opendap.bes.BESError; import opendap.bes.BadConfigurationException; import opendap.bes.dap2Responders.BesApi; import opendap.ppt.PPTException; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * An in-memory cache for BES showNode responses. This class is a singleton. */ public class BesNodeCache { public static final String NODE_CACHE_ELEMENT_NAME = "NodeCache"; private static final String MAX_ENTRIES_ATTRIBUTE_NAME = "maxEntries"; private static final String REFRESH_INTERVAL_ATTRIBUTE_NAME = "refreshInterval"; private static final long NODE_CACHE_MAX_ENTRIES_DEFAULT = 2000; private static final long NODE_CACHE_REFRESH_INTERVAL_DEFAULT = 600; private static final ReentrantReadWriteLock RWLOCK = new ReentrantReadWriteLock(); private static final Logger LOG = LoggerFactory.getLogger(NODE_CACHE_ELEMENT_NAME); private static final ReentrantLock LOCK = new ReentrantLock(); private static final ConcurrentHashMap<String,NodeTransaction> NODE_CACHE = new ConcurrentHashMap<>(); private static final ConcurrentSkipListSet<NodeTransaction> MOST_RECENTLY_ACCESSED = new ConcurrentSkipListSet<>(); private static final AtomicLong MAX_CACHE_ENTRIES = new AtomicLong(50); // # of entries in cache private static final AtomicLong UPDATE_INTERVAL = new AtomicLong(10); // Update interval in seconds private static final double CACHE_REDUCTION_FACTOR = 0.2; // Amount to reduce cache when purging private static final AtomicBoolean ENABLED = new AtomicBoolean(false); private static final long nanoInSeconds = 1000000000; /** * This is a singleton class and as such all methods are static and the constructor is private because an * instance should never be created. */ private BesNodeCache(){} /** * Initialize the Node Cache using an XML Element. * @param config The "NodeCache" configuration element * @throws BadConfigurationException When the configuration is broken. */ public static void init(Element config) throws BadConfigurationException { if (config == null || !config.getName().equals(NODE_CACHE_ELEMENT_NAME)) throw new BadConfigurationException("BesNodeCache must be passed a non-null configuration " + "element named " + NODE_CACHE_ELEMENT_NAME); long maxEntries = NODE_CACHE_MAX_ENTRIES_DEFAULT; String maxEntriesString = config.getAttributeValue(MAX_ENTRIES_ATTRIBUTE_NAME); try { maxEntries = Long.parseLong(maxEntriesString); if (maxEntries <= 0) { maxEntries = NODE_CACHE_MAX_ENTRIES_DEFAULT; String msg = "Failed to parse value of " + NODE_CACHE_ELEMENT_NAME + "@" + MAX_ENTRIES_ATTRIBUTE_NAME + "! " + "Value must be an integer > 0. Using default value: " + maxEntries; LOG.error(msg); } } catch (NumberFormatException nfe) { LOG.error("Failed to parse value of NodeCache@maxEntries! Value must" + " be an integer. Using default value: {}", maxEntries); } long refreshInterval = NODE_CACHE_REFRESH_INTERVAL_DEFAULT; String refreshIntervalString = config.getAttributeValue(REFRESH_INTERVAL_ATTRIBUTE_NAME); try { refreshInterval = Long.parseLong(refreshIntervalString); if (refreshInterval <= 0) { refreshInterval = NODE_CACHE_REFRESH_INTERVAL_DEFAULT; String msg = "Failed to parse value of " + NODE_CACHE_ELEMENT_NAME + "@" + REFRESH_INTERVAL_ATTRIBUTE_NAME + "! " + "Value must be an integer > 0. Using default value: " + refreshInterval; LOG.error(msg); } } catch (NumberFormatException nfe) { LOG.error("Failed to parse value of NodeCache@refreshInterval! Value" + " must be an integer. Using default value: {}", refreshInterval); } init(maxEntries, refreshInterval); } /** * The _actual_ init method that sets up the cache. This must be called * prior to using the cache. * @param maxEntries The maximum number of entries in the cache * @param updateIntervalSeconds The time any object may reside in the cache before it is removed. */ public static void init(long maxEntries, long updateIntervalSeconds) { LOCK.lock(); try { if (ENABLED.get()) { LOG.error("BesNodeCache has already been initialized! " + "MAX_CACHE_ENTRIES: {} UPDATE_INTERVAL: {} s", MAX_CACHE_ENTRIES.get(), UPDATE_INTERVAL.get()/(nanoInSeconds*1.0)); return; } MAX_CACHE_ENTRIES.set(maxEntries); UPDATE_INTERVAL.set(updateIntervalSeconds * nanoInSeconds); ENABLED.set(true); LOG.debug("INITIALIZED MAX_CACHE_ENTRIES: {} UPDATE_INTERVAL: {} s", MAX_CACHE_ENTRIES.get(), UPDATE_INTERVAL.get()/(nanoInSeconds*1.0)); } finally { LOCK.unlock(); } } /** * The primary public method used to retrieve BES showNode command responses. Caching happens within this call. * @param key The name of the BES node to retrieve. * @return The BES showNode response for "key" */ public static Element getNode(String key) throws JDOMException, BadConfigurationException, PPTException, IOException, BESError { if(!ENABLED.get()) return null; if(key==null) throw new IOException("The BesApi.getNode() method was passed a key value of null. That's bad."); RWLOCK.readLock().lock(); try { LOG.debug("BEGIN NODE_CACHE.size(): {} MOST_RECENTLY_ACCESSED.size(): {}", NODE_CACHE.size(), MOST_RECENTLY_ACCESSED.size()); NodeTransaction nodeTransaction = NODE_CACHE.get(key); if(isStaleNodeTransaction(nodeTransaction)){ RWLOCK.readLock().unlock(); RWLOCK.writeLock().lock(); try { if (isStaleNodeTransaction(nodeTransaction)) { dropStaleNodeTransaction(nodeTransaction); LOG.debug("Dropping stale NodeTransaction[{}] from cache!",key); nodeTransaction = getAndCacheNodeTransaction(key); } RWLOCK.readLock().lock(); } finally { RWLOCK.writeLock().unlock(); } } updateMostRecentlyAccessed(nodeTransaction); // Now we need to sort out the response - Document or Error? Object responseObject = nodeTransaction.getResponse(); if(responseObject instanceof Document){ Document cachedNodeDoc = (Document)responseObject; Element root = cachedNodeDoc.getRootElement(); Element newRoot = (Element) root.clone(); newRoot.detach(); return newRoot; } if (responseObject instanceof BESError) { LOG.info("Cache contains BESError object. dataSource=\"" + key + "\""); throw (BESError) responseObject; } // The responseObject should only ever be a Document or a BESError throw new IOException("Cached object is of unexpected type! " + "This is a bad thing! Object: "+responseObject.getClass().getCanonicalName()); } finally { LOG.debug("END NODE_CACHE.size(): {} MOST_RECENTLY_ACCESSED.size(): {}", NODE_CACHE.size(), MOST_RECENTLY_ACCESSED.size()); RWLOCK.readLock().unlock(); } } /** * Solicits a showNode response from the BES for the passed parameter key. Once the response is received the response * is used to make a new NodeTransaction which is then placed in the cache associated with the value of key. * If the BES returns an error that is handled the same way, the error object is used to make a new NodeTransaction * which is placed in the cache associated with the value of key. * @param key The name of the node to retrieve from the BES using the showNode command. * @return The NodeTransaction built from the BES response. * @throws BadConfigurationException When a BES cannot be located. * @throws PPTException When the PPT exchange between the BES process and the OLFS fails. * @throws JDOMException When the documents cannot be parsed. * @throws IOException When theings cannot be read or written. */ private static NodeTransaction getAndCacheNodeTransaction(String key) throws BadConfigurationException, PPTException, JDOMException, IOException { LOG.info("Acquiring showNode response for key \"{}\"", key ); LOCK.lock(); try { BES bes = BesApi.getBES(key); Document showNodeRequestDoc = BesApi.getShowNodeRequestDocument(key); Document response = new Document(); NodeTransaction result; try { bes.besTransaction(showNodeRequestDoc, response); // Get the root element. Element root = response.getRootElement(); if (root == null) throw new IOException("BES showNode response for " + key + " was empty! No root element"); Element showNode = root.getChild("showNode", opendap.namespaces.BES.BES_NS); if (showNode == null) throw new IOException("BES showNode response for " + key + " was malformed! No showNode element"); showNode.setAttribute("prefix", bes.getPrefix()); LOG.info("Caching copy of BES showNode response for key: \"{}\"",key); result = putNodeTransaction(key, showNodeRequestDoc, response.clone()); } catch (BESError be) { LOG.info("The BES returned a BESError for key: \"{} \" CACHING BESError",key); result = putNodeTransaction(key, showNodeRequestDoc, be); } return result; } finally { LOCK.unlock(); } } /** * Check to see if the passed NodeTransaction is stale. This is based * comparing its time in the cache with the UPDATE_INTERVAL. * * @param nodeTransaction The NodeTransaction to test. * @return Returns true is the NodeTransaction has been in the cache longer * the UPDATE_INTERVAL. */ private static boolean isStaleNodeTransaction(NodeTransaction nodeTransaction){ boolean isStale = true; // if it's null it's stale... if(nodeTransaction!=null) { long timeInCache = System.nanoTime() - nodeTransaction.getLastUpdateTime(); LOG.debug("nodeTransaction[{}] has been in cache {} s", nodeTransaction.getKey(), timeInCache / (nanoInSeconds * 1.0)); // Is it stale? isStale = timeInCache > UPDATE_INTERVAL.get(); } return isStale; } /** * Removes the passed NodeTransaction from both the cache (NODE_CACHE) and * from the most recently accessed list (MOST_RECENTLY_ACCESSED). If a null * value is passed, nothing is done and the method returns. * * @param nodeTransaction The NodeTransaction to drop from the cache. */ private static void dropStaleNodeTransaction(NodeTransaction nodeTransaction){ if(nodeTransaction==null){ // a null value is a noop, but not an error return; } NodeTransaction nt = NODE_CACHE.remove(nodeTransaction.getKey()); LOG.debug("Remove NodeTransaction[{}] from NODE_CACHE returned: {}", nodeTransaction.getKey(), (nt == null) ? "NULL" : nt); LOG.debug("NODE_CACHE.size(): {}", NODE_CACHE.size()); if (MOST_RECENTLY_ACCESSED.remove(nodeTransaction)) { LOG.debug("Successfully dropped NodeTransaction[{}] from MOST_RECENTLY_ACCESSED (size: {})", nodeTransaction.getKey(), MOST_RECENTLY_ACCESSED.size()); } else { LOG.error("FAILED to drop NodeTransaction[{}] from MOST_RECENTLY_ACCESSED (size: {})", nodeTransaction.getKey(), MOST_RECENTLY_ACCESSED.size()); } } /** * Updates the MOST_RECENTLY_ACCESSED list by dropping the passed * CatalogTransaction from the MOST_RECENTLY_ACCESSED list, updating * the CatalogTransaction's access time and then adding the updated * CatalogTransaction back to the MOST_RECENTLY_ACCESSED list. * @param nodeTransaction The CatalogTransaction whose access time needs * updating. */ private static void updateMostRecentlyAccessed(NodeTransaction nodeTransaction){ boolean status; LOCK.lock(); try { LOG.debug("Updating MOST_RECENTLY_ACCESSED list. MOST_RECENTLY_ACCESSED.size(): {}", MOST_RECENTLY_ACCESSED.size()); status = MOST_RECENTLY_ACCESSED.remove(nodeTransaction); if(status) { LOG.debug("Removed NodeTransaction[{},{}] from MOST_RECENTLY_ACCESSED", nodeTransaction.getKey(),nodeTransaction); } else { LOG.debug("The NodeTransaction[{},{}] was not found in MOST_RECENTLY_ACCESSED", nodeTransaction.getKey(),nodeTransaction); } LOG.debug("MOST_RECENTLY_ACCESSED list updated. MOST_RECENTLY_ACCESSED.size(): {}", MOST_RECENTLY_ACCESSED.size()); nodeTransaction.updateAccessedTime(); status = MOST_RECENTLY_ACCESSED.add(nodeTransaction); LOG.debug("{} NodeTransaction[{}] to MOST_RECENTLY_ACCESSED",status?"Added":"FAILED to add",nodeTransaction.getKey()); LOG.debug("MOST_RECENTLY_ACCESSED list updated. MOST_RECENTLY_ACCESSED.size(): {}", MOST_RECENTLY_ACCESSED.size()); } finally { LOCK.unlock(); } } /** * Takes a node response (Document or BESError) and tucks it into the NodeCache * @param key The name of the node that was retrieved. * @param request The BES showNode request document used to elicit the response. * @param response The object (either a Document or a BESError) returned by the BES transaction. */ private static NodeTransaction putNodeTransaction(String key, Document request, Object response) { LOCK.lock(); try { LOG.debug("BEGIN NODE_CACHE.size(): {} ", NODE_CACHE.size()); // Make sure the cache has not grown too large. purgeLeastRecentlyAccessed(); NodeTransaction nodeTransaction = new NodeTransaction(key, request, response); LOG.debug("Created nodeTransaction[{}] @ {}", key, nodeTransaction.getLastUpdateTime()); NodeTransaction previous = NODE_CACHE.put(key, nodeTransaction); if (nodeTransaction == previous) { LOG.warn("NodeTransaction cache updated with new (replacement) object for key: \"{}\"",key); } else { LOG.debug("NodeTransaction cache updated by adding new object to cache using key \"{}\"",key); } LOG.debug("END NODE_CACHE.size(): {}", NODE_CACHE.size()); return nodeTransaction; } finally { LOCK.unlock(); } } /** * If the cache is smaller than MAX_CACHE_ENTRIES then this is a no-op. * If the cache has grown larger than MAX_CACHE_ENTRIES then it will be reduced by * rsize = (CACHE_REDUCTION_FACTOR * MAX_CACHE_ENTRIES) entries. The reduction is done by iterating over the * MOST_RECENTLY_ACCESSED list, from oldest (longest since accessed) to newest (least time since access) and * collecting "rsize" NodeTransactions and removing them from both the NODE_CACHE and the MOST_RECENTLY_ACCESSED * list. */ private static void purgeLeastRecentlyAccessed(){ LOCK.lock(); try { // Cache not full? Then return... if (NODE_CACHE.size() < MAX_CACHE_ENTRIES.get()) return; int dropNum = (int) (MAX_CACHE_ENTRIES.get() * CACHE_REDUCTION_FACTOR); if(dropNum==0) { dropNum = 1; } LOG.debug("BEGIN NODE_CACHE.size(): {} MOST_RECENTLY_ACCESSED.size(): {}", NODE_CACHE.size(), MOST_RECENTLY_ACCESSED.size()); LOG.debug("dropNum: {}",dropNum); LOG.debug("Before purge NODE_CACHE.size(): {}", NODE_CACHE.size()); LOG.debug("Before purge MOST_RECENTLY_ACCESSED.size(): {}", MOST_RECENTLY_ACCESSED.size()); List<NodeTransaction> purgeList = new ArrayList<>(dropNum); Iterator<NodeTransaction> oldestToNewest = MOST_RECENTLY_ACCESSED.iterator(); for(int i=0; i<dropNum && oldestToNewest.hasNext(); i++ ){ NodeTransaction nodeTransaction = oldestToNewest.next(); purgeList.add(nodeTransaction); LOG.debug("Purging CatalogTransaction for key {}",nodeTransaction.getKey()); NODE_CACHE.remove(nodeTransaction.getKey()); } MOST_RECENTLY_ACCESSED.removeAll(purgeList); LOG.debug("After purge NODE_CACHE.size(): {}", NODE_CACHE.size()); LOG.debug("After purge MOST_RECENTLY_ACCESSED.size(): {}", MOST_RECENTLY_ACCESSED.size()); LOG.debug("END"); } finally { LOCK.unlock(); } } /** * Drops all references from the cache. */ public void destroy(){ LOCK.lock(); try { NODE_CACHE.clear(); MOST_RECENTLY_ACCESSED.clear(); } finally { LOCK.unlock(); } } /** * This is a test method used to make a NodeTransaction without requiring a * running BES to receive a request and generate a response. THe point is * to provide a test fixture to allow the evaluation of the * NodeTransaction.comparable() interface for the purposes of sorting. * * @param id * @return */ private static NodeTransaction getDummyCachedNodeTransaction(String id){ Document request; Document response; Element e; request = new Document(); e=new Element("request"); e.setAttribute("id",id); request.setRootElement(e); response = new Document(); e= new Element("response"); e.setAttribute("id",id); response.setRootElement(e); return new NodeTransaction(id,request,response); } public static void main(String[] args) { Logger log = LoggerFactory.getLogger(BesNodeCache.class); TreeSet<NodeTransaction> set = new TreeSet<>(); String[] testKeys = {"foo", "bar", "moo", "soo", "bar", "baz"}; NodeTransaction nodeTransaction; NodeTransaction first = null; String msgFormat = "nodeTransaction - key: %s getLastAccessedTime(): %d set.size(): %d"; String msg; for(String key: testKeys){ nodeTransaction = getDummyCachedNodeTransaction(key); set.add(nodeTransaction); msg = String.format(msgFormat,nodeTransaction.getKey(),nodeTransaction.getLastAccessedTime(),set.size()); log.info(msg); if(first==null) first = nodeTransaction; } log.info("Original List: "); for(NodeTransaction nodeT: set){ log.info(" node[{}]: {}",nodeT.getKey(),nodeT.getLastAccessedTime()); } set.remove(first); first.updateAccessedTime(); set.add(first); log.info("List after remove and replace: "); for(NodeTransaction nodeT: set){ log.info(" node[{}]: {}",nodeT.getKey(),nodeT.getLastAccessedTime()); } } //################################################################################################################# //################################################################################################################# //################################################################################################################# //################################################################################################################# //################################################################################################################# //################################################################################################################# //################################################################################################################# //################################################################################################################# //################################################################################################################# /** * The primary public method used to retrieve BES showNode command responses. Caching happens within this call. * @param key The name of the BES node to retrieve. * @return The BES showNode response for "key" */ public static Element getNodeOLD(String key) throws JDOMException, BadConfigurationException, PPTException, IOException, BESError { if(!ENABLED.get()) return null; LOCK.lock(); try { LOG.debug("BEGIN NODE_CACHE.size(): {} MOST_RECENTLY_ACCESSED.size(): {}", NODE_CACHE.size(), MOST_RECENTLY_ACCESSED.size()); if(key==null) throw new IOException("The BesApi.getNode() method was passed a key value of null. That's bad."); NodeTransaction nodeTransaction = NODE_CACHE.get(key); if(nodeTransaction!=null) { LOG.debug("FOUND NodeTransaction[{}] in cache! w00t!",key); if(dropStaleNodeTransactionOLD(nodeTransaction)) { // It got dropped so we need to replace it LOG.debug("Dropping stale NodeTransaction[{}] from cache!",key); nodeTransaction = getAndCacheNodeTransaction(key); } } else { LOG.debug("NodeTransaction[{}] is not in NODE_CACHE, retrieving.",key); nodeTransaction = getAndCacheNodeTransaction(key); } updateMostRecentlyAccessed(nodeTransaction); // Now we need to sort out the response - Document or Error? Object responseObject = nodeTransaction.getResponse(); if(responseObject instanceof Document){ Document cachedNodeDoc = (Document)responseObject; Element root = cachedNodeDoc.getRootElement(); Element newRoot = (Element) root.clone(); newRoot.detach(); return newRoot; } if (responseObject instanceof BESError) { LOG.info("Cache contains BESError object. dataSource=\"" + key + "\""); throw (BESError) responseObject; } // The responseObject should only ever be a Document or a BESError throw new IOException("Cached object is of unexpected type! " + "This is a bad thing! Object: "+responseObject.getClass().getCanonicalName()); } finally { LOG.debug("END NODE_CACHE.size(): {} MOST_RECENTLY_ACCESSED.size(): {}", NODE_CACHE.size(), MOST_RECENTLY_ACCESSED.size()); LOCK.unlock(); } } /** * Removes the passed NodeTransaction from both the cache (NODE_CACHE) and from the most recently accessed list * (MOST_RECENTLY_ACCESSED) * @param nodeTransaction The NodeTransaction to drop from the cache. * @return True if the NodeTransaction was dropped from the cache, false otherwise. */ private static boolean dropStaleNodeTransactionOLD(NodeTransaction nodeTransaction){ LOCK.lock(); try { boolean dropped = false; if(isStaleNodeTransaction(nodeTransaction)) { NodeTransaction nt = NODE_CACHE.remove(nodeTransaction.getKey()); LOG.debug("Remove NodeTransaction[{}] from NODE_CACHE returned: {}", nodeTransaction.getKey(), (nt == null) ? "NULL" : nt); LOG.debug("NODE_CACHE.size(): {}", NODE_CACHE.size()); if (MOST_RECENTLY_ACCESSED.remove(nodeTransaction)) { LOG.debug("Successfully dropped NodeTransaction[{}] from MOST_RECENTLY_ACCESSED (size: {})", nodeTransaction.getKey(), MOST_RECENTLY_ACCESSED.size()); } else { LOG.error("FAILED to drop NodeTransaction[{}] from MOST_RECENTLY_ACCESSED (size: {})", nodeTransaction.getKey(), MOST_RECENTLY_ACCESSED.size()); } dropped = true; } return dropped; } finally { LOCK.unlock(); } } }
olfs: Revised locking strategy fo rBesNodeCache.
src/opendap/bes/caching/BesNodeCache.java
olfs: Revised locking strategy fo rBesNodeCache.
Java
apache-2.0
4cf0f982891ce4def69ae32fe0c01b219df13ba3
0
apache/activemq-cpp,apache/activemq-cpp,apache/activemq-cpp,apache/activemq-cpp
/* * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.openwire.tool; import java.io.File; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import org.codehaus.jam.JClass; import org.codehaus.jam.JProperty; /** * * @version $Revision: 409828 $ */ public class AmqCppClassesGenerator extends MultiSourceGenerator { protected String targetDir="./src/main"; public Object run() { filePostFix = getFilePostFix(); if (destDir == null) { destDir = new File( targetDir+"/activemq/connector/openwire/commands"); } return super.run(); } protected String getFilePostFix() { return ".cpp"; } protected String getProperBaseClassName( String className, String baseClass ) { if( baseClass == null || className == null ) { return null; } // The C++ BaseCommand class is a template, which requires either // transport::Command, or transport::Response. if( className.equals( "Response" ) ) { return "BaseCommand<transport::Response>"; } else if( baseClass.equals( "BaseCommand" ) ) { return "BaseCommand<transport::Command>"; } // No change. return baseClass; } public String toCppType(JClass type) { String name = type.getSimpleName(); if (name.equals("String")) { return "std::string"; } else if( type.isArrayType() ) { if( name.equals( "byte[]" ) ) name = "unsigned char[]"; JClass arrayClass = type.getArrayComponentType(); if( arrayClass.isPrimitiveType() ) { return "std::vector<" + name.substring(0, name.length()-2) + ">"; } else { return "std::vector<" + name.substring(0, name.length()-2) + "*>"; } } else if( name.equals( "Throwable" ) || name.equals( "Exception" ) ) { return "BrokerError"; } else if( name.equals("BaseDataStructure" ) ){ return "DataStructure"; } else if( name.equals("ByteSequence") ) { return "std::vector<unsigned char>"; } else if( name.equals("boolean") ) { return "bool"; } else if( name.equals("long") ) { return "long long"; } else if( name.equals("byte") ) { return "unsigned char"; } else if( !type.isPrimitiveType() ) { return name; } else { return name; } } /** * Converts the Java type to a C++ default value */ public String toCppDefaultValue(JClass type) { String name = type.getSimpleName(); if (name.equals("boolean")) { return "false"; } else if( name.equals("String") ) { return "\"\""; } else if( !type.isPrimitiveType() ) { return "NULL"; } else { return "0"; } } protected void generateLicence(PrintWriter out) { out.println("/*"); out.println(" * Licensed to the Apache Software Foundation (ASF) under one or more"); out.println(" * contributor license agreements. See the NOTICE file distributed with"); out.println(" * this work for additional information regarding copyright ownership."); out.println(" * The ASF licenses this file to You under the Apache License, Version 2.0"); out.println(" * (the \"License\"); you may not use this file except in compliance with"); out.println(" * the License. You may obtain a copy of the License at"); out.println(" *"); out.println(" * http://www.apache.org/licenses/LICENSE-2.0"); out.println(" *"); out.println(" * Unless required by applicable law or agreed to in writing, software"); out.println(" * distributed under the License is distributed on an \"AS IS\" BASIS,"); out.println(" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied."); out.println(" * See the License for the specific language governing permissions and"); out.println(" * limitations under the License."); out.println(" */"); } protected void generateFile(PrintWriter out) throws Exception { generateLicence(out); out.println("#include <activemq/connector/openwire/commands/"+className+".h>"); out.println("#include <activemq/exceptions/NullPointerException.h>"); out.println(""); out.println("using namespace std;"); out.println("using namespace activemq;"); out.println("using namespace activemq::exceptions;"); out.println("using namespace activemq::connector;"); out.println("using namespace activemq::connector::openwire;"); out.println("using namespace activemq::connector::openwire::commands;"); out.println(""); out.println("/*"); out.println(" *"); out.println(" * Command and marshaling code for OpenWire format for "+className+""); out.println(" *"); out.println(" *"); out.println(" * NOTE!: This file is autogenerated - do not modify!"); out.println(" * if you need to make a change, please see the Java Classes in the"); out.println(" * activemq-core module"); out.println(" *"); out.println(" */"); out.println("////////////////////////////////////////////////////////////////////////////////"); out.println(""+className+"::"+className+"()"); out.println("{"); List properties = getProperties(); for (Iterator iter = properties.iterator(); iter.hasNext();) { JProperty property = (JProperty) iter.next(); String type = toCppType(property.getType()); String value = toCppDefaultValue(property.getType()); String propertyName = property.getSimpleName(); String parameterName = decapitalize(propertyName); if( !type.startsWith("std::vector") ) { out.println(" this->"+parameterName+" = "+value+";"); } } out.println("}"); out.println(""); out.println("////////////////////////////////////////////////////////////////////////////////"); out.println(""+className+"::~"+className+"()"); out.println("{"); for( Iterator iter = properties.iterator(); iter.hasNext(); ) { JProperty property = (JProperty) iter.next(); String type = toCppType(property.getType()); String propertyName = property.getSimpleName(); String parameterName = decapitalize(propertyName); if( property.getType().isPrimitiveType() || property.getType().getSimpleName().equals("String") ) { continue; } if( !type.startsWith("std::vector" ) ) { out.println(" delete this->" + parameterName + ";"); } else if( type.contains( "*" ) ) { out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < " + parameterName + ".size(); ++i" + parameterName + " ) {"); out.println(" delete " + parameterName + "[i" + parameterName + "];"); out.println(" }"); } } out.println("}"); out.println(""); out.println("////////////////////////////////////////////////////////////////////////////////"); out.println("DataStructure* "+className+"::cloneDataStructure() const {"); String newInstance = decapitalize( className ); out.println(" "+className+"* "+newInstance+" = new "+className+"();"); out.println(""); out.println(" // Copy the data from the base class or classes"); out.println(" "+newInstance+"->copyDataStructure( this );"); out.println(""); out.println(" return "+newInstance+";"); out.println("}"); out.println(""); out.println("////////////////////////////////////////////////////////////////////////////////"); out.println("void "+className+"::copyDataStructure( const DataStructure* src ) {"); out.println(""); if( baseClass != null ) { out.println(" // Copy the data of the base class or classes"); out.println(" "+getProperBaseClassName( className, baseClass )+"::copyDataStructure( src );"); out.println(""); } out.println(" const "+className+"* srcPtr = dynamic_cast<const "+className+"*>( src );"); out.println(""); out.println(" if( srcPtr == NULL || src == NULL ) {"); out.println(" "); out.println(" throw exceptions::NullPointerException("); out.println(" __FILE__, __LINE__,"); out.println(" \""+className+"::copyDataStructure - src is NULL or invalid\" );"); out.println(" }"); for( Iterator iter = properties.iterator(); iter.hasNext(); ) { JProperty property = (JProperty) iter.next(); String type = toCppType(property.getType()); String propertyName = property.getSimpleName(); String parameterName = decapitalize(propertyName); String constNess = ""; String getter = property.getGetter().getSimpleName(); String setter = property.getSetter().getSimpleName(); if( property.getType().isPrimitiveType() || type.equals("std::string") || property.getType().getSimpleName().equals("ByteSequence") ){ out.println(" this->"+setter+"( srcPtr->"+getter+"() );"); } else if( property.getType().isArrayType() && !property.getType().getArrayComponentType().isPrimitiveType() ) { String arrayType = property.getType().getArrayComponentType().getSimpleName(); out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < srcPtr->"+getter+"().size(); ++i" + parameterName + " ) {"); out.println(" if( srcPtr->"+getter+"()[i"+parameterName+"] != NULL ) {"); out.println(" this->"+getter+"().push_back( "); out.println(" dynamic_cast<"+arrayType+"*>( "); out.println(" srcPtr->"+getter+"()[i"+parameterName+"]->cloneDataStructure() ) );"); out.println(" } else {"); out.println(" this->"+getter+"().push_back( NULL );"); out.println(" }"); out.println(" }"); } else if( property.getType().isArrayType() && property.getType().getArrayComponentType().isPrimitiveType() ) { out.println(" this->"+setter+"( srcPtr->"+getter+"() );"); } else { out.println(" if( srcPtr->"+getter+"() != NULL ) {"); out.println(" this->"+setter+"( "); out.println(" dynamic_cast<"+type+"*>( "); out.println(" srcPtr->"+getter+"()->cloneDataStructure() ) );"); out.println(" }"); } } out.println("}"); // getDataStructureType out.println(""); out.println("////////////////////////////////////////////////////////////////////////////////"); out.println("unsigned char "+className+"::getDataStructureType() const {"); out.println(" return "+className+"::ID_" + className.toUpperCase() + "; "); out.println("}"); // toString out.println(""); out.println("////////////////////////////////////////////////////////////////////////////////"); out.println("std::string "+className+"::toString() const {"); out.println(""); out.println(" ostringstream stream;" ); out.println(""); out.println(" stream << \"Begin Class = "+className+"\" << std::endl;" ); out.println(" stream << \" Value of "+className+"::ID_" + className.toUpperCase() + " = "+getOpenWireOpCode(jclass)+"\" << std::endl; "); for( Iterator iter = properties.iterator(); iter.hasNext(); ) { JProperty property = (JProperty) iter.next(); String type = toCppType(property.getType()); String propertyName = property.getSimpleName(); String parameterName = decapitalize(propertyName); String constNess = ""; String getter = property.getGetter().getSimpleName(); String setter = property.getSetter().getSimpleName(); if( property.getType().getSimpleName().equals("ByteSequence") ) { out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {"); out.println(" stream << \" Value of "+propertyName+"[\" << i" + parameterName+" << \"] = \" << this->"+getter+"()[i"+parameterName+"] << std::endl;" ); out.println(" }" ); } else if( property.getType().isPrimitiveType() || type.equals("std::string") ){ out.println(" stream << \" Value of "+propertyName+" = \" << this->"+getter+"() << std::endl;"); } else if( property.getType().isArrayType() && !property.getType().getArrayComponentType().isPrimitiveType() ) { String arrayType = property.getType().getArrayComponentType().getSimpleName(); out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {"); out.println(" stream << \" Value of "+propertyName+"[\" << i" + parameterName+" << \"] is Below:\" << std::endl;" ); out.println(" if( this->"+getter+"()[i"+parameterName+"] != NULL ) {"); out.println(" stream << this->"+getter+"()[i"+parameterName+"]->toString() << std::endl;"); out.println(" } else {"); out.println(" stream << \" Object is NULL\" << std::endl;"); out.println(" }"); out.println(" }"); } else if( property.getType().isArrayType() && property.getType().getArrayComponentType().isPrimitiveType() ) { out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {"); out.println(" stream << \" Value of "+propertyName+"[\" << i"+parameterName+" << \"] = \" << this->"+getter+"()[i"+parameterName+"] << std::endl;"); out.println(" }"); } else { out.println(" stream << \" Value of "+propertyName+" is Below:\" << std::endl;" ); out.println(" if( this->"+getter+"() != NULL ) {"); out.println(" stream << this->"+getter+"()->toString() << std::endl;"); out.println(" } else {"); out.println(" stream << \" Object is NULL\" << std::endl;"); out.println(" }"); } } if( baseClass != null ) { out.println(" stream << "+getProperBaseClassName( className, baseClass )+"::toString();"); } out.println(" stream << \"End Class = "+className+"\" << std::endl;" ); out.println(""); out.println(" return stream.str();"); out.println("}"); // equals out.println(""); out.println("////////////////////////////////////////////////////////////////////////////////"); out.println("bool "+className+"::equals( const DataStructure* value ) const {"); out.println(" const "+className+"* valuePtr = dynamic_cast<const "+className+"*>( value );"); out.println(""); out.println(" if( valuePtr == NULL || value == NULL ) {"); out.println(" return false;"); out.println(" }"); for( Iterator iter = properties.iterator(); iter.hasNext(); ) { JProperty property = (JProperty) iter.next(); String type = toCppType(property.getType()); String propertyName = property.getSimpleName(); String parameterName = decapitalize(propertyName); String constNess = ""; String getter = property.getGetter().getSimpleName(); String setter = property.getSetter().getSimpleName(); if( property.getType().getSimpleName().equals("ByteSequence") ) { out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {"); out.println(" if( this->"+getter+"()[i" + parameterName+"] != valuePtr->"+getter+"()[i"+parameterName+"] ) {" ); out.println(" return false;" ); out.println(" }" ); out.println(" }" ); } else if( property.getType().isPrimitiveType() || type.equals("std::string") ){ out.println(" if( this->"+getter+"() != valuePtr->"+getter+"() ) {"); out.println(" return false;" ); out.println(" }" ); } else if( property.getType().isArrayType() && !property.getType().getArrayComponentType().isPrimitiveType() ) { String arrayType = property.getType().getArrayComponentType().getSimpleName(); out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {"); out.println(" if( this->"+getter+"()[i"+parameterName+"] != NULL ) {" ); out.println(" if( !this->"+getter+"()[i"+parameterName+"]->equals( valuePtr->"+getter+"()[i"+parameterName+"] ) ) {" ); out.println(" return false;"); out.println(" }"); out.println(" } else if( valuePtr->"+getter+"()[i"+parameterName+"] != NULL ) {"); out.println(" return false;"); out.println(" }"); out.println(" }"); } else if( property.getType().isArrayType() && property.getType().getArrayComponentType().isPrimitiveType() ) { out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {"); out.println(" if( this->"+getter+"()[i"+parameterName+"] != valuePtr->"+getter+"()[i"+parameterName+"] ) {"); out.println(" return false;"); out.println(" }"); out.println(" }"); } else { out.println(" if( this->"+getter+"() != NULL ) {"); out.println(" if( !this->"+getter+"()->equals( valuePtr->"+getter+"() ) ) {" ); out.println(" return false;"); out.println(" }"); out.println(" } else if( valuePtr->"+getter+"() != NULL ) {"); out.println(" return false;"); out.println(" }"); } } if( baseClass != null ) { out.println(" if( !"+getProperBaseClassName( className, baseClass )+"::equals( value ) ) {"); out.println(" return false;"); out.println(" }"); } out.println(" return true;" ); out.println("}"); for( Iterator iter = properties.iterator(); iter.hasNext(); ) { JProperty property = (JProperty) iter.next(); String type = toCppType(property.getType()); String propertyName = property.getSimpleName(); String parameterName = decapitalize(propertyName); String getter = property.getGetter().getSimpleName(); String setter = property.getSetter().getSimpleName(); String constNess = ""; if( !property.getType().isPrimitiveType() && !property.getType().getSimpleName().equals("ByteSequence") && !property.getType().getSimpleName().equals("String") && !type.startsWith("std::vector") ) { type = type + "*"; } else if( property.getType().getSimpleName().equals("String") || type.startsWith( "std::vector") ) { type = type + "&"; constNess = "const "; } out.println(""); if( property.getType().isPrimitiveType() ) { out.println("////////////////////////////////////////////////////////////////////////////////"); out.println(type+" "+className+"::"+getter+"() const {"); out.println(" return "+parameterName+";"); out.println("}"); out.println(""); } else { out.println("////////////////////////////////////////////////////////////////////////////////"); out.println("const "+type+" "+className+"::"+getter+"() const {"); out.println(" return "+parameterName+";"); out.println("}"); out.println(""); out.println("////////////////////////////////////////////////////////////////////////////////"); out.println(""+type+" "+className+"::"+getter+"() {"); out.println(" return "+parameterName+";"); out.println("}"); out.println(""); } out.println("////////////////////////////////////////////////////////////////////////////////"); out.println("void " + className + "::" + setter+"(" + constNess + type+ " " + parameterName +" ) {"); out.println(" this->"+parameterName+" = "+parameterName+";"); out.println("}"); } out.println(""); } public String getTargetDir() { return targetDir; } public void setTargetDir(String targetDir) { this.targetDir = targetDir; } }
activemq-cpp/openwire-scripts/AmqCppClassesGenerator.java
/* * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.openwire.tool; import java.io.File; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import org.codehaus.jam.JClass; import org.codehaus.jam.JProperty; /** * * @version $Revision: 409828 $ */ public class AmqCppClassesGenerator extends MultiSourceGenerator { protected String targetDir="./src/main"; public Object run() { filePostFix = getFilePostFix(); if (destDir == null) { destDir = new File( targetDir+"/activemq/connector/openwire/commands"); } return super.run(); } protected String getFilePostFix() { return ".cpp"; } protected String getProperBaseClassName( String className, String baseClass ) { if( baseClass == null || className == null ) { return null; } // The C++ BaseCommand class is a template, which requires either // transport::Command, or transport::Response. if( className.equals( "Response" ) ) { return "BaseCommand<transport::Response>"; } else if( baseClass.equals( "BaseCommand" ) ) { return "BaseCommand<transport::Command>"; } // No change. return baseClass; } public String toCppType(JClass type) { String name = type.getSimpleName(); if (name.equals("String")) { return "std::string"; } else if( type.isArrayType() ) { if( name.equals( "byte[]" ) ) name = "unsigned char[]"; JClass arrayClass = type.getArrayComponentType(); if( arrayClass.isPrimitiveType() ) { return "std::vector<" + name.substring(0, name.length()-2) + ">"; } else { return "std::vector<" + name.substring(0, name.length()-2) + "*>"; } } else if( name.equals( "Throwable" ) || name.equals( "Exception" ) ) { return "BrokerError"; } else if( name.equals("BaseDataStructure" ) ){ return "DataStructure"; } else if( name.equals("ByteSequence") ) { return "std::vector<unsigned char>"; } else if( name.equals("boolean") ) { return "bool"; } else if( name.equals("long") ) { return "long long"; } else if( name.equals("byte") ) { return "unsigned char"; } else if( !type.isPrimitiveType() ) { return name; } else { return name; } } /** * Converts the Java type to a C++ default value */ public String toCppDefaultValue(JClass type) { String name = type.getSimpleName(); if (name.equals("boolean")) { return "false"; } else if( name.equals("String") ) { return "\"\""; } else if( !type.isPrimitiveType() ) { return "NULL"; } else { return "0"; } } protected void generateLicence(PrintWriter out) { out.println("/*"); out.println(" * Licensed to the Apache Software Foundation (ASF) under one or more"); out.println(" * contributor license agreements. See the NOTICE file distributed with"); out.println(" * this work for additional information regarding copyright ownership."); out.println(" * The ASF licenses this file to You under the Apache License, Version 2.0"); out.println(" * (the \"License\"); you may not use this file except in compliance with"); out.println(" * the License. You may obtain a copy of the License at"); out.println(" *"); out.println(" * http://www.apache.org/licenses/LICENSE-2.0"); out.println(" *"); out.println(" * Unless required by applicable law or agreed to in writing, software"); out.println(" * distributed under the License is distributed on an \"AS IS\" BASIS,"); out.println(" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied."); out.println(" * See the License for the specific language governing permissions and"); out.println(" * limitations under the License."); out.println(" */"); } protected void generateFile(PrintWriter out) throws Exception { generateLicence(out); out.println("#include <activemq/connector/openwire/commands/"+className+".h>"); out.println("#include <activemq/exceptions/NullPointerException.h>"); out.println(""); out.println("using namespace std;"); out.println("using namespace activemq;"); out.println("using namespace activemq::exceptions;"); out.println("using namespace activemq::connector;"); out.println("using namespace activemq::connector::openwire;"); out.println("using namespace activemq::connector::openwire::commands;"); out.println(""); out.println("/*"); out.println(" *"); out.println(" * Command and marshaling code for OpenWire format for "+className+""); out.println(" *"); out.println(" *"); out.println(" * NOTE!: This file is autogenerated - do not modify!"); out.println(" * if you need to make a change, please see the Java Classes in the"); out.println(" * activemq-core module"); out.println(" *"); out.println(" */"); out.println("////////////////////////////////////////////////////////////////////////////////"); out.println(""+className+"::"+className+"()"); out.println("{"); List properties = getProperties(); for (Iterator iter = properties.iterator(); iter.hasNext();) { JProperty property = (JProperty) iter.next(); String type = toCppType(property.getType()); String value = toCppDefaultValue(property.getType()); String propertyName = property.getSimpleName(); String parameterName = decapitalize(propertyName); if( !type.startsWith("std::vector") ) { out.println(" this->"+parameterName+" = "+value+";"); } } out.println("}"); out.println(""); out.println("////////////////////////////////////////////////////////////////////////////////"); out.println(""+className+"::~"+className+"()"); out.println("{"); for( Iterator iter = properties.iterator(); iter.hasNext(); ) { JProperty property = (JProperty) iter.next(); String type = toCppType(property.getType()); String propertyName = property.getSimpleName(); String parameterName = decapitalize(propertyName); if( property.getType().isPrimitiveType() || property.getType().getSimpleName().equals("String") ) { continue; } if( !type.startsWith("std::vector" ) ) { out.println(" delete this->" + parameterName + ";"); } else if( type.contains( "*" ) ) { out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < " + parameterName + ".size(); ++i" + parameterName + " ) {"); out.println(" delete " + parameterName + "[i" + parameterName + "];"); out.println(" }"); } } out.println("}"); out.println(""); out.println("////////////////////////////////////////////////////////////////////////////////"); out.println("DataStructure* "+className+"::cloneDataStructure() const {"); String newInstance = decapitalize( className ); out.println(" "+className+"* "+newInstance+" = new "+className+"();"); out.println(""); out.println(" // Copy the data from the base class or classes"); out.println(" "+newInstance+"->copyDataStructure( this );"); out.println(""); out.println(" return "+newInstance+";"); out.println("}"); out.println(""); out.println("////////////////////////////////////////////////////////////////////////////////"); out.println("void "+className+"::copyDataStructure( const DataStructure* src ) {"); out.println(""); if( baseClass != null ) { out.println(" // Copy the data of the base class or classes"); out.println(" "+getProperBaseClassName( className, baseClass )+"::copyDataStructure( src );"); out.println(""); } out.println(" const "+className+"* srcPtr = dynamic_cast<const "+className+"*>( src );"); out.println(""); out.println(" if( srcPtr == NULL || src == NULL ) {"); out.println(" "); out.println(" throw exceptions::NullPointerException("); out.println(" __FILE__, __LINE__,"); out.println(" \""+className+"::copyDataStructure - src is NULL or invalid\" );"); out.println(" }"); for( Iterator iter = properties.iterator(); iter.hasNext(); ) { JProperty property = (JProperty) iter.next(); String type = toCppType(property.getType()); String propertyName = property.getSimpleName(); String parameterName = decapitalize(propertyName); String constNess = ""; String getter = property.getGetter().getSimpleName(); String setter = property.getSetter().getSimpleName(); if( property.getType().isPrimitiveType() || type.equals("std::string") || property.getType().getSimpleName().equals("ByteSequence") ){ out.println(" this->"+setter+"( srcPtr->"+getter+"() );"); } else if( property.getType().isArrayType() && !property.getType().getArrayComponentType().isPrimitiveType() ) { String arrayType = property.getType().getArrayComponentType().getSimpleName(); out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < srcPtr->"+getter+"().size(); ++i" + parameterName + " ) {"); out.println(" if( srcPtr->"+getter+"()[i"+parameterName+"] != NULL ) {"); out.println(" this->"+getter+"().push_back( "); out.println(" dynamic_cast<"+arrayType+"*>( "); out.println(" srcPtr->"+getter+"()[i"+parameterName+"]->cloneDataStructure() ) );"); out.println(" } else {"); out.println(" this->"+getter+"().push_back( NULL );"); out.println(" }"); out.println(" }"); } else if( property.getType().isArrayType() && property.getType().getArrayComponentType().isPrimitiveType() ) { out.println(" this->"+setter+"( srcPtr->"+getter+"() );"); } else { out.println(" if( srcPtr->"+getter+"() != NULL ) {"); out.println(" this->"+setter+"( "); out.println(" dynamic_cast<"+type+"*>( "); out.println(" srcPtr->"+getter+"()->cloneDataStructure() ) );"); out.println(" }"); } } out.println("}"); // getDataStructureType out.println(""); out.println("////////////////////////////////////////////////////////////////////////////////"); out.println("unsigned char "+className+"::getDataStructureType() const {"); out.println(" return "+className+"::ID_" + className.toUpperCase() + "; "); out.println("}"); // toString out.println(""); out.println("////////////////////////////////////////////////////////////////////////////////"); out.println("std::string "+className+"::toString() const {"); out.println(""); out.println(" ostringstream stream;" ); out.println(""); out.println(" stream << \"Begin Class = "+className+"\" << std::endl;" ); out.println(" stream << \" Value of "+className+"::ID_" + className.toUpperCase() + " = "+getOpenWireOpCode(jclass)+"\" << std::endl; "); for( Iterator iter = properties.iterator(); iter.hasNext(); ) { JProperty property = (JProperty) iter.next(); String type = toCppType(property.getType()); String propertyName = property.getSimpleName(); String parameterName = decapitalize(propertyName); String constNess = ""; String getter = property.getGetter().getSimpleName(); String setter = property.getSetter().getSimpleName(); if( property.getType().getSimpleName().equals("ByteSequence") ) { out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {"); out.println(" stream << \" Value of "+propertyName+"[\" << i" + parameterName+" << \"] = \" << this->"+getter+"()[i"+parameterName+"] << std::endl;" ); out.println(" }" ); } else if( property.getType().isPrimitiveType() || type.equals("std::string") ){ out.println(" stream << \" Value of "+propertyName+" = \" << this->"+getter+"() << std::endl;"); } else if( property.getType().isArrayType() && !property.getType().getArrayComponentType().isPrimitiveType() ) { String arrayType = property.getType().getArrayComponentType().getSimpleName(); out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {"); out.println(" stream << \" Value of "+propertyName+"[\" << i" + parameterName+" << \"] is Below:\" << std::endl;" ); out.println(" if( this->"+getter+"()[i"+parameterName+"] != NULL ) {"); out.println(" stream << this->"+getter+"()[i"+parameterName+"]->toString() << std::endl;"); out.println(" } else {"); out.println(" stream << \" Object is NULL\" << std::endl;"); out.println(" }"); out.println(" }"); } else if( property.getType().isArrayType() && property.getType().getArrayComponentType().isPrimitiveType() ) { out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {"); out.println(" stream << \" Value of "+propertyName+"[\" << i"+parameterName+" << \"] = \" << this->"+getter+"()[i"+parameterName+"] << std::endl;"); out.println(" }"); } else { out.println(" stream << \" Value of "+propertyName+" is Below:\" << std::endl;" ); out.println(" if( this->"+getter+"() != NULL ) {"); out.println(" stream << this->"+getter+"()->toString() << std::endl;"); out.println(" } else {"); out.println(" stream << \" Object is NULL\" << std::endl;"); out.println(" }"); } } if( baseClass != null ) { out.println(" stream << "+getProperBaseClassName( className, baseClass )+"::toString();"); } out.println(" stream << \"End Class = "+className+"\" << std::endl;" ); out.println(""); out.println(" return stream.str();"); out.println("}"); // equals out.println(""); out.println("////////////////////////////////////////////////////////////////////////////////"); out.println("bool "+className+"::equals( const DataStructure* value ) const {"); out.println(" const "+className+"* valuePtr = dynamic_cast<const "+className+"*>( value );"); out.println(""); out.println(" if( valuePtr == NULL || value == NULL ) {"); out.println(" return false;"); out.println(" }"); for( Iterator iter = properties.iterator(); iter.hasNext(); ) { JProperty property = (JProperty) iter.next(); String type = toCppType(property.getType()); String propertyName = property.getSimpleName(); String parameterName = decapitalize(propertyName); String constNess = ""; String getter = property.getGetter().getSimpleName(); String setter = property.getSetter().getSimpleName(); if( property.getType().getSimpleName().equals("ByteSequence") ) { out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {"); out.println(" if( "+propertyName+"[i" + parameterName+"] != this->"+getter+"()[i"+parameterName+"] ) {" ); out.println(" return false;" ); out.println(" }" ); out.println(" }" ); } else if( property.getType().isPrimitiveType() || type.equals("std::string") ){ out.println(" if( "+propertyName+" != valuePtr->"+getter+"() ) {"); out.println(" return false;" ); out.println(" }" ); } else if( property.getType().isArrayType() && !property.getType().getArrayComponentType().isPrimitiveType() ) { String arrayType = property.getType().getArrayComponentType().getSimpleName(); out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {"); out.println(" if( this->"+getter+"()[i"+parameterName+"] != NULL )" ); out.println(" if( !( this->"+getter+"()[i"+parameterName+"]->equals( valuePtr->"+getter+"()[i"+parameterName+"] ) ) {" ); out.println(" return false;"); out.println(" }"); out.println(" } else if( valuePtr->"+getter+"()[i"+parameterName+"] != NULL ) {"); out.println(" return false;"); out.println(" }"); out.println(" }"); } else if( property.getType().isArrayType() && property.getType().getArrayComponentType().isPrimitiveType() ) { out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {"); out.println(" if( "+propertyName+"[i"+parameterName+"] != valuePtr->"+getter+"()[i"+parameterName+"] ) {"); out.println(" return false;"); out.println(" }"); out.println(" }"); } else { out.println(" if( this->"+getter+"() != NULL ) {"); out.println(" if( !( this->"+getter+"()[i"+parameterName+"]->equals( valuePtr->"+getter+"()[i"+parameterName+"] ) ) {" ); out.println(" return false;"); out.println(" }"); out.println(" } else if( valuePtr->"+getter+"()[i"+parameterName+"] != NULL ) {"); out.println(" return false;"); out.println(" }"); } } if( baseClass != null ) { out.println(" if( !"+getProperBaseClassName( className, baseClass )+"::equals( value ) ) {"); out.println(" return false;"); out.println(" }"); } out.println(" return true;" ); out.println("}"); for( Iterator iter = properties.iterator(); iter.hasNext(); ) { JProperty property = (JProperty) iter.next(); String type = toCppType(property.getType()); String propertyName = property.getSimpleName(); String parameterName = decapitalize(propertyName); String getter = property.getGetter().getSimpleName(); String setter = property.getSetter().getSimpleName(); String constNess = ""; if( !property.getType().isPrimitiveType() && !property.getType().getSimpleName().equals("ByteSequence") && !property.getType().getSimpleName().equals("String") && !type.startsWith("std::vector") ) { type = type + "*"; } else if( property.getType().getSimpleName().equals("String") || type.startsWith( "std::vector") ) { type = type + "&"; constNess = "const "; } out.println(""); if( property.getType().isPrimitiveType() ) { out.println("////////////////////////////////////////////////////////////////////////////////"); out.println(type+" "+className+"::"+getter+"() const {"); out.println(" return "+parameterName+";"); out.println("}"); out.println(""); } else { out.println("////////////////////////////////////////////////////////////////////////////////"); out.println("const "+type+" "+className+"::"+getter+"() const {"); out.println(" return "+parameterName+";"); out.println("}"); out.println(""); out.println("////////////////////////////////////////////////////////////////////////////////"); out.println(""+type+" "+className+"::"+getter+"() {"); out.println(" return "+parameterName+";"); out.println("}"); out.println(""); } out.println("////////////////////////////////////////////////////////////////////////////////"); out.println("void " + className + "::" + setter+"(" + constNess + type+ " " + parameterName +" ) {"); out.println(" this->"+parameterName+" = "+parameterName+";"); out.println("}"); } out.println(""); } public String getTargetDir() { return targetDir; } public void setTargetDir(String targetDir) { this.targetDir = targetDir; } }
http://issues.apache.org/activemq/browse/AMQCPP-30 git-svn-id: 0fb8a5a922afe2085ae9a967a0cf0864fe09ecff@507299 13f79535-47bb-0310-9956-ffa450edef68
activemq-cpp/openwire-scripts/AmqCppClassesGenerator.java
http://issues.apache.org/activemq/browse/AMQCPP-30
Java
apache-2.0
22b876ce5591604543e9da77dad6da378eed7287
0
vivosys/orientdb,nengxu/OrientDB,vivosys/orientdb,nengxu/OrientDB,nengxu/OrientDB,vivosys/orientdb,vivosys/orientdb,nengxu/OrientDB
/* * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.core.db.document; import java.util.Collection; import java.util.LinkedHashMap; import com.orientechnologies.orient.core.db.record.ODatabaseRecord; import com.orientechnologies.orient.core.id.ORID; import com.orientechnologies.orient.core.id.ORecordId; import com.orientechnologies.orient.core.record.ORecordFactory; import com.orientechnologies.orient.core.record.ORecordInternal; @SuppressWarnings({ "serial" }) public class OLazyRecordMap extends LinkedHashMap<String, Object> { private ODatabaseRecord<?> database; private byte recordType; private boolean converted = false; public OLazyRecordMap(final ODatabaseRecord<?> database, final byte iRecordType) { this.database = database; this.recordType = iRecordType; } @Override public boolean containsValue(final Object o) { convertAll(); return super.containsValue(o); } @Override public Object get(final Object iKey) { if (iKey == null) return null; final String key = iKey.toString(); convert(key); return super.get(key); } @Override public Object put(final String iKey, final Object iValue) { if (converted && iValue instanceof ORID) converted = false; return super.put(iKey, iValue); } @Override public Collection<Object> values() { convertAll(); return super.values(); } private void convertAll() { if (converted) return; for (String key : super.keySet()) convert(key); converted = true; } /** * Convert the item requested. * * @param iIndex * Position of the item to convert */ private void convert(final String iKey) { final Object o = super.get(iKey); if (o != null && o instanceof ORecordId) { final ORecordInternal<?> record = ORecordFactory.newInstance(recordType); final ORecordId rid = (ORecordId) o; record.setDatabase(database); record.setIdentity(rid); record.load(); super.put(iKey, record); } } }
core/src/main/java/com/orientechnologies/orient/core/db/document/OLazyRecordMap.java
/* * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.core.db.document; import java.util.LinkedHashMap; import com.orientechnologies.orient.core.db.record.ODatabaseRecord; import com.orientechnologies.orient.core.id.ORID; import com.orientechnologies.orient.core.id.ORecordId; import com.orientechnologies.orient.core.record.ORecordFactory; import com.orientechnologies.orient.core.record.ORecordInternal; @SuppressWarnings({ "serial" }) public class OLazyRecordMap extends LinkedHashMap<String, Object> { private ODatabaseRecord<?> database; private byte recordType; private boolean converted = false; public OLazyRecordMap(final ODatabaseRecord<?> database, final byte iRecordType) { this.database = database; this.recordType = iRecordType; } @Override public boolean containsValue(final Object o) { convertAll(); return super.containsValue(o); } @Override public Object get(final Object iKey) { if (iKey == null) return null; final String key = iKey.toString(); convert(key); return super.get(key); } @Override public Object put(final String iKey, final Object iValue) { if (converted && iValue instanceof ORID) converted = false; return super.put(iKey, iValue); } public void convertAll() { if (converted) return; for (String key : super.keySet()) convert(key); converted = true; } /** * Convert the item requested. * * @param iIndex * Position of the item to convert */ private void convert(final String iKey) { final Object o = super.get(iKey); if (o != null && o instanceof ORecordId) { final ORecordInternal<?> record = ORecordFactory.newInstance(recordType); final ORecordId rid = (ORecordId) o; record.setDatabase(database); record.setIdentity(rid); record.load(); super.put(iKey, record); } } }
Fixed issue on LINKMAP git-svn-id: 9ddf022f45b579842a47abc018ed2b18cdc52108@1631 3625ad7b-9c83-922f-a72b-73d79161f2ea
core/src/main/java/com/orientechnologies/orient/core/db/document/OLazyRecordMap.java
Fixed issue on LINKMAP
Java
apache-2.0
0f4b373bd66f45ab934edeff0124af09cca63acf
0
mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile
/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2016 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ package ti.modules.titanium.ui.widget.tableview; import java.util.ArrayList; import java.util.HashMap; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollPropertyChange; import org.appcelerator.kroll.common.Log; import org.appcelerator.titanium.TiApplication; import org.appcelerator.titanium.TiC; import org.appcelerator.titanium.TiDimension; import org.appcelerator.titanium.proxy.TiViewProxy; import org.appcelerator.titanium.util.TiConvert; import org.appcelerator.titanium.util.TiUIHelper; import org.appcelerator.titanium.view.TiCompositeLayout; import org.appcelerator.titanium.view.TiUIView; import ti.modules.titanium.ui.LabelProxy; import ti.modules.titanium.ui.TableViewProxy; import ti.modules.titanium.ui.TableViewRowProxy; import ti.modules.titanium.ui.widget.TiUILabel; import ti.modules.titanium.ui.widget.tableview.TableViewModel.Item; import android.app.Activity; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Handler; import android.support.v4.view.ViewCompat; import android.view.View; import android.widget.ImageView; public class TiTableViewRowProxyItem extends TiBaseTableViewItem { private static final String TAG = "TitaniumTableViewItem"; // Only check this once, since we potentially use this information // every time we add a row. No sense checking it each time. private static boolean ICS_OR_GREATER = (Build.VERSION.SDK_INT >= TiC.API_LEVEL_ICE_CREAM_SANDWICH); private static final String LEFT_MARGIN = "6dp"; private static final String RIGHT_MARGIN = "6dp"; private static final int MIN_HEIGHT = 48; private BitmapDrawable hasChildDrawable, hasCheckDrawable; private ImageView leftImage; private ImageView rightImage; private TiCompositeLayout content; private ArrayList<TiUIView> views; private TiDimension height = null; private Item item; private Object selectorSource; private Drawable selectorDrawable; public TiTableViewRowProxyItem(Activity activity) { super(activity); this.handler = new Handler(this); this.leftImage = new ImageView(activity); leftImage.setVisibility(GONE); addView(leftImage, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); this.content = new TiCompositeLayout(activity); addView(content, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); this.rightImage = new ImageView(activity); rightImage.setVisibility(GONE); addView(rightImage, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); } protected TableViewRowProxy getRowProxy() { return (TableViewRowProxy)item.proxy; } public void setRowData(Item item) { this.item = item; TableViewRowProxy rp = getRowProxy(); if (this != rp.getTableViewRowProxyItem()) { rp.setTableViewItem(this); } setRowData(rp); } public Item getRowData() { return this.item; } protected TiViewProxy addViewToOldRow(int index, TiUIView titleView, TiViewProxy newViewProxy) { Log.w(TAG, newViewProxy + " was added an old style row, reusing the title TiUILabel", Log.DEBUG_MODE); LabelProxy label = new LabelProxy(); label.handleCreationDict(titleView.getProxy().getProperties()); label.setView(titleView); label.setModelListener(titleView); titleView.setProxy(label); getRowProxy().getControls().add(index, label); views.add(newViewProxy.getOrCreateView()); return label; } /* * Check if the two proxies are compatible outerView wise */ private boolean checkBorderProps(TiViewProxy oldProxy, TiViewProxy newProxy){ KrollDict oldProperties = oldProxy.getProperties(); KrollDict newProperties = newProxy.getProperties(); boolean oldHasBorder = oldProperties.containsKeyAndNotNull(TiC.PROPERTY_BORDER_COLOR) || oldProperties.containsKeyAndNotNull(TiC.PROPERTY_BORDER_RADIUS) || oldProperties.containsKeyAndNotNull(TiC.PROPERTY_BORDER_WIDTH); boolean newHasBorder = newProperties.containsKeyAndNotNull(TiC.PROPERTY_BORDER_COLOR) || newProperties.containsKeyAndNotNull(TiC.PROPERTY_BORDER_RADIUS) || newProperties.containsKeyAndNotNull(TiC.PROPERTY_BORDER_WIDTH); return (oldHasBorder == newHasBorder); } /* * Check the view heirarchy */ private boolean checkViewHeirarchy(TiViewProxy oldProxy, TiViewProxy newProxy){ if (oldProxy == newProxy){ return true; } if(oldProxy.getClass() != newProxy.getClass()) { //Check for type return false; } else if (!checkBorderProps(oldProxy, newProxy)) { //Ensure they have compatible border props return false; } else { //Check children recursively TiViewProxy[] oldChildren = oldProxy.getChildren(); TiViewProxy[] newChildren = newProxy.getChildren(); if (oldChildren.length != newChildren.length) { return false; } else { int len = oldChildren.length; for (int i=0;i<len;i++) { if (!checkViewHeirarchy(oldChildren[i],newChildren[i])) { return false; } } } } //ok, all passed. Return true return true; } /* * Check if views can be reused. */ private boolean canUseExistingViews(ArrayList<TiViewProxy> proxies){ int len = proxies.size(); if(views != null && views.size() == len) { for (int i=0;i<len;i++) { TiUIView view = views.get(i); if (view.getProxy() == null) { return false; } else if (!checkViewHeirarchy(view.getProxy(), proxies.get(i))) { return false; } } return true; } return false; } private ArrayList<KrollPropertyChange> getChangeSet( KrollDict oldProps, KrollDict newProps) { ArrayList<KrollPropertyChange> propertyChanges = new ArrayList<KrollPropertyChange>(); /* //First get the values that changed from the oldProps to the newProps for (String name : oldProps.keySet()) { Object oldValue = oldProps.get(name); Object newValue = newProps.get(name); if (!(oldValue == null && newValue == null)) { if ((oldValue == null && newValue != null) || (newValue == null && oldValue != null) || (!oldValue.equals(newValue))) { KrollPropertyChange pch = new KrollPropertyChange(name, oldValue, newValue); propertyChanges.add(pch); } } } //Second get the properties that are only in the newProps for (String name : newProps.keySet()) { if (!oldProps.containsKey(name)) { KrollPropertyChange pch = new KrollPropertyChange(name, null, newProps.get(name)); propertyChanges.add(pch); } } */ /* What we should do is above. But since we do not handle null values properly in our SDK, we'll do it the short way which is an optimized version of doing processProperties. */ for (String name : newProps.keySet()) { Object oldValue = oldProps.get(name); Object newValue = newProps.get(name); if (!(oldValue == null && newValue == null)) { if ((oldValue == null && newValue != null) || (newValue == null && oldValue != null) || (!oldValue.equals(newValue))) { KrollPropertyChange pch = new KrollPropertyChange(name, oldValue, newValue); propertyChanges.add(pch); } } } return propertyChanges; } /* * Create views for measurement or for layout. For each view, apply the * properties from the appropriate proxy to the view. */ protected void createControls() { TableViewRowProxy parent = getRowProxy(); ArrayList<TiViewProxy> proxies = parent.getControls(); int len = proxies.size(); if (!canUseExistingViews(proxies)) { content.removeAllViews(); if(views == null) { views = new ArrayList<TiUIView>(len); } else { views.clear(); } for (int i=0;i<len;i++){ TiViewProxy proxy = proxies.get(i); TiBaseTableViewItem.clearChildViews(proxy); TiUIView view = proxy.forceCreateView(); views.add(view); View v = view.getOuterView(); if (v.getParent() == null) { content.addView(v, view.getLayoutParams()); } } } else { //Ok the view heirarchies are the same. //Transfer over the views and modelListeners from the old proxies to the new proxies for (int i=0;i<len;i++) { TiUIView view = views.get(i); TiViewProxy oldProxy = view.getProxy(); TiViewProxy newProxy = proxies.get(i); if (oldProxy != newProxy) { newProxy.transferView(view, oldProxy); view.setParent(parent); view.propertiesChanged(getChangeSet(oldProxy.getProperties(), newProxy.getProperties()), newProxy); //Need to apply child properties. applyChildProperties(newProxy, view); } } //Reset the content height and width so that it is calculated based on the children LayoutParams p = content.getLayoutParams(); p.height = -1; p.width = -1; content.setLayoutParams(p); } } protected void applyChildProperties(TiViewProxy viewProxy, TiUIView view) { int i = 0; TiViewProxy childProxies[] = viewProxy.getChildren(); for (TiUIView childView : view.getChildren()) { TiViewProxy childProxy = childProxies[i]; TiViewProxy oldProxy = childView.getProxy(); if (childProxy != oldProxy) { childProxy.transferView(childView, oldProxy); childView.setParent(viewProxy); childView.propertiesChanged(getChangeSet(oldProxy.getProperties(), childProxy.getProperties()), childProxy); applyChildProperties(childProxy, childView); } i++; } } protected void refreshOldStyleRow() { TableViewRowProxy rp = getRowProxy(); if (!rp.hasProperty(TiC.PROPERTY_TOUCH_ENABLED)) { // We have traditionally always made the label untouchable, but since // version 3.0.0 we support explore-by-touch on ICS and above, so for // accessibility purposes we should not be disabling touch if // accessibility is currently turned on. if (!ICS_OR_GREATER || !TiApplication.getInstance().getAccessibilityManager().isEnabled()) { rp.setProperty(TiC.PROPERTY_TOUCH_ENABLED, false); } } // Check if this was a regular row and the control was removed // if so, cleanup the views if (views != null && views.size() > 0) { TiUIView rv = views.get(0); if (!(rv instanceof TiUILabel)) { content.removeAllViews(); views.clear(); views = null; } } if (views == null) { views = new ArrayList<TiUIView>(); views.add(new TiUILabel(rp)); } TiUILabel t = (TiUILabel) views.get(0); t.setProxy(rp); t.processProperties(filterProperties(rp.getProperties())); View v = t.getOuterView(); if (v.getParent() == null) { TiCompositeLayout.LayoutParams params = (TiCompositeLayout.LayoutParams) t.getLayoutParams(); if (params.optionLeft == null) { params.optionLeft = new TiDimension(LEFT_MARGIN, TiDimension.TYPE_LEFT); } if (params.optionRight == null) { params.optionRight = new TiDimension(RIGHT_MARGIN, TiDimension.TYPE_RIGHT); } params.autoFillsWidth = true; content.addView(v, params); } } public void setRowData(TableViewRowProxy rp) { // hasControls = rp.hasControls(); Object newSelectorSource = null; if (rp.hasProperty(TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE)) { newSelectorSource = rp.getProperty(TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE); } else if (rp.hasProperty(TiC.PROPERTY_BACKGROUND_SELECTED_COLOR)) { newSelectorSource = rp.getProperty(TiC.PROPERTY_BACKGROUND_SELECTED_COLOR); } if (newSelectorSource == null || selectorSource != null && !selectorSource.equals(newSelectorSource)) { selectorDrawable = null; } selectorSource = newSelectorSource; if (selectorSource != null) { rp.getTable().getTableView().getTableView().enableCustomSelector(); } setBackgroundFromProxy(rp); // Handle right image boolean clearRightImage = true; // It's one or the other, check or child. If you set them both, child's gonna win. HashMap<String, Object> props = rp.getProperties(); if (props.containsKey(TiC.PROPERTY_HAS_CHECK)) { if (TiConvert.toBoolean(props, TiC.PROPERTY_HAS_CHECK)) { if (hasCheckDrawable == null) { hasCheckDrawable = createHasCheckDrawable(); } rightImage.setImageDrawable(hasCheckDrawable); rightImage.setVisibility(VISIBLE); clearRightImage = false; } } if (props.containsKey(TiC.PROPERTY_HAS_CHILD)) { if (TiConvert.toBoolean(props, TiC.PROPERTY_HAS_CHILD)) { if (hasChildDrawable == null) { hasChildDrawable = createHasChildDrawable(); } rightImage.setImageDrawable(hasChildDrawable); rightImage.setVisibility(VISIBLE); clearRightImage = false; } } if (props.containsKey(TiC.PROPERTY_RIGHT_IMAGE)) { String path = TiConvert.toString(props, TiC.PROPERTY_RIGHT_IMAGE); String url = rp.resolveUrl(null, path); Drawable d = loadDrawable(url); if (d != null) { rightImage.setImageDrawable(d); rightImage.setVisibility(VISIBLE); clearRightImage = false; } } if (clearRightImage) { rightImage.setImageDrawable(null); rightImage.setVisibility(GONE); } // Handle left image if (props.containsKey(TiC.PROPERTY_LEFT_IMAGE)) { String path = TiConvert.toString(props, TiC.PROPERTY_LEFT_IMAGE); String url = rp.resolveUrl(null, path); Drawable d = loadDrawable(url); if (d != null) { leftImage.setImageDrawable(d); leftImage.setVisibility(VISIBLE); } } else { leftImage.setImageDrawable(null); leftImage.setVisibility(GONE); } if (props.containsKey(TiC.PROPERTY_HEIGHT)) { if (!props.get(TiC.PROPERTY_HEIGHT).equals(TiC.SIZE_AUTO) && !props.get(TiC.PROPERTY_HEIGHT).equals(TiC.LAYOUT_SIZE)) { height = TiConvert.toTiDimension(TiConvert.toString(props, TiC.PROPERTY_HEIGHT), TiDimension.TYPE_HEIGHT); } } if (props.containsKey(TiC.PROPERTY_LAYOUT)) { content.setLayoutArrangement(TiConvert.toString(props, TiC.PROPERTY_LAYOUT)); } if (props.containsKey(TiC.PROPERTY_HORIZONTAL_WRAP)) { content.setEnableHorizontalWrap(TiConvert.toBoolean(props, TiC.PROPERTY_HORIZONTAL_WRAP)); } // hasControls() means that the proxy has children if (rp.hasControls()) { createControls(); } else { // no children means that this is an old-style row refreshOldStyleRow(); } if (ICS_OR_GREATER) { Object accessibilityHiddenVal = rp.getProperty(TiC.PROPERTY_ACCESSIBILITY_HIDDEN); if (accessibilityHiddenVal != null) { boolean hidden = TiConvert.toBoolean(accessibilityHiddenVal); if (hidden) { ViewCompat.setImportantForAccessibility(this, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO); } else { ViewCompat.setImportantForAccessibility(this, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO); } } } } protected boolean hasView(TiUIView view) { if (views == null) return false; for (TiUIView v : views) { if (v == view) { return true; } } return false; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int w = MeasureSpec.getSize(widthMeasureSpec); int wMode = MeasureSpec.getMode(widthMeasureSpec); int h = MeasureSpec.getSize(heightMeasureSpec); int hMode = MeasureSpec.getMode(heightMeasureSpec); int imageHMargin = 0; int leftImageWidth = 0; int leftImageHeight = 0; if (leftImage != null && leftImage.getVisibility() != View.GONE) { measureChild(leftImage, widthMeasureSpec, heightMeasureSpec); leftImageWidth = leftImage.getMeasuredWidth(); leftImageHeight = leftImage.getMeasuredHeight(); imageHMargin += new TiDimension(LEFT_MARGIN, TiDimension.TYPE_LEFT).getAsPixels(this); } int rightImageWidth = 0; int rightImageHeight = 0; if (rightImage != null && rightImage.getVisibility() != View.GONE) { measureChild(rightImage, widthMeasureSpec, heightMeasureSpec); rightImageWidth = rightImage.getMeasuredWidth(); rightImageHeight = rightImage.getMeasuredHeight(); imageHMargin += new TiDimension(RIGHT_MARGIN, TiDimension.TYPE_RIGHT).getAsPixels(this); } int adjustedWidth = w - leftImageWidth - rightImageWidth - imageHMargin; // int adjustedWidth = w; if (content != null) { // If there is a child view, we don't set a minimum height for the row. // Otherwise, we set a minimum height. boolean hasChildView = ((TableViewRowProxy) item.proxy).hasControls(); if (hasChildView) { content.setMinimumHeight(0); } else { content.setMinimumHeight(TiConvert.toTiDimension(MIN_HEIGHT, TiDimension.TYPE_HEIGHT).getAsPixels(this)); } measureChild(content, MeasureSpec.makeMeasureSpec(adjustedWidth, wMode), heightMeasureSpec); if (hMode == MeasureSpec.UNSPECIFIED) { TableViewProxy table = ((TableViewRowProxy) item.proxy).getTable(); int minRowHeight = -1; if (table != null && table.hasProperty(TiC.PROPERTY_MIN_ROW_HEIGHT)) { minRowHeight = TiConvert.toTiDimension( TiConvert.toString(table.getProperty(TiC.PROPERTY_MIN_ROW_HEIGHT)), TiDimension.TYPE_HEIGHT) .getAsPixels(this); } if (height == null) { // If measure spec is not specified, height should behave as Ti.UI.SIZE if (hMode == 0) { h = Math.max(content.getMeasuredHeight(), Math.max(leftImageHeight, rightImageHeight)); } else { h = Math.max(h, Math.max(content.getMeasuredHeight(), Math.max(leftImageHeight, rightImageHeight))); } h = Math.max(h, minRowHeight); } else { h = Math.max(minRowHeight, height.getAsPixels(this)); } // Make sure the height is greater than 1 (not 0 since image views default to 1) if (hasChildView && h > 1) { content.getLayoutParams().height = h; } if (Log.isDebugModeEnabled()) { Log.d(TAG, "Row content measure (" + adjustedWidth + "x" + h + ")", Log.DEBUG_MODE); } measureChild(content, MeasureSpec.makeMeasureSpec(adjustedWidth, wMode), MeasureSpec.makeMeasureSpec(h, hMode)); } } setMeasuredDimension(w, Math.max(h, Math.max(leftImageHeight, rightImageHeight))); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { // Make these associations here to avoid doing them on measurement passes getRowProxy().setTableViewItem(this); int contentLeft = left; int contentRight = right; bottom = bottom - top; top = 0; int height = bottom - top; if (leftImage != null && leftImage.getVisibility() != GONE) { int w = leftImage.getMeasuredWidth(); int h = leftImage.getMeasuredHeight(); int leftMargin = new TiDimension(LEFT_MARGIN, TiDimension.TYPE_LEFT).getAsPixels(this); contentLeft += w + leftMargin; int offset = (height - h) / 2; leftImage.layout(left+leftMargin, top+offset, left+leftMargin+w, top+offset+h); } if (rightImage != null && rightImage.getVisibility() != GONE) { int w = rightImage.getMeasuredWidth(); int h = rightImage.getMeasuredHeight(); int rightMargin = new TiDimension(RIGHT_MARGIN, TiDimension.TYPE_RIGHT).getAsPixels(this); contentRight -= w + rightMargin; int offset = (height - h) / 2; rightImage.layout(right-w-rightMargin, top+offset, right-rightMargin, top+offset+h); } // if (hasControls) { // contentLeft = left + new TiDimension(LEFT_MARGIN, TiDimension.TYPE_LEFT).getAsPixels(this); // contentRight = right - new TiDimension(RIGHT_MARGIN, TiDimension.TYPE_RIGHT).getAsPixels(this); // } if (content != null) { content.layout(contentLeft, top, contentRight, bottom); } if (changed) { TiUIHelper.firePostLayoutEvent(getRowProxy()); } } private static String[] filteredProperties = new String[]{ TiC.PROPERTY_BACKGROUND_IMAGE, TiC.PROPERTY_BACKGROUND_COLOR, TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE, TiC.PROPERTY_BACKGROUND_SELECTED_COLOR }; private KrollDict filterProperties(KrollDict d) { if (d == null) return new KrollDict(); KrollDict filtered = new KrollDict(d); for (int i = 0;i < filteredProperties.length; i++) { if (filtered.containsKey(filteredProperties[i])) { filtered.remove(filteredProperties[i]); } } return filtered; } @Override public boolean hasSelector() { TableViewRowProxy rowProxy = getRowProxy(); return rowProxy.hasProperty(TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE) || rowProxy.hasProperty(TiC.PROPERTY_BACKGROUND_SELECTED_COLOR); } @Override public Drawable getSelectorDrawable() { TableViewRowProxy rowProxy = getRowProxy(); if (selectorDrawable == null && selectorSource != null) { if (rowProxy.hasProperty(TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE)) { String path = TiConvert.toString( rowProxy.getProperty(TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE)); String url = rowProxy.resolveUrl(null, path); selectorDrawable = loadDrawable(url); } else if (rowProxy.hasProperty(TiC.PROPERTY_BACKGROUND_SELECTED_COLOR)) { int color = TiConvert.toColor(rowProxy.getProperty(TiC.PROPERTY_BACKGROUND_SELECTED_COLOR).toString()); selectorDrawable = new TiTableViewColorSelector(color); } } return selectorDrawable; } @Override public void release() { super.release(); if (views != null) { for (TiUIView view : views) { view.release(); } views = null; } if (content != null) { content.removeAllViews(); content = null; } if (hasCheckDrawable != null) { hasCheckDrawable.setCallback(null); hasCheckDrawable = null; } if (hasChildDrawable != null) { hasChildDrawable.setCallback(null); hasChildDrawable = null; } } }
android/modules/ui/src/java/ti/modules/titanium/ui/widget/tableview/TiTableViewRowProxyItem.java
/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2016 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ package ti.modules.titanium.ui.widget.tableview; import java.util.ArrayList; import java.util.HashMap; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollPropertyChange; import org.appcelerator.kroll.common.Log; import org.appcelerator.titanium.TiApplication; import org.appcelerator.titanium.TiC; import org.appcelerator.titanium.TiDimension; import org.appcelerator.titanium.proxy.TiViewProxy; import org.appcelerator.titanium.util.TiConvert; import org.appcelerator.titanium.util.TiUIHelper; import org.appcelerator.titanium.view.TiCompositeLayout; import org.appcelerator.titanium.view.TiUIView; import ti.modules.titanium.ui.LabelProxy; import ti.modules.titanium.ui.TableViewProxy; import ti.modules.titanium.ui.TableViewRowProxy; import ti.modules.titanium.ui.widget.TiUILabel; import ti.modules.titanium.ui.widget.tableview.TableViewModel.Item; import android.app.Activity; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Handler; import android.support.v4.view.ViewCompat; import android.view.View; import android.widget.ImageView; public class TiTableViewRowProxyItem extends TiBaseTableViewItem { private static final String TAG = "TitaniumTableViewItem"; // Only check this once, since we potentially use this information // every time we add a row. No sense checking it each time. private static boolean ICS_OR_GREATER = (Build.VERSION.SDK_INT >= TiC.API_LEVEL_ICE_CREAM_SANDWICH); private static final String LEFT_MARGIN = "6dp"; private static final String RIGHT_MARGIN = "6dp"; private static final String RIGHT_SIZE = "17dp"; private static final int MIN_HEIGHT = 48; private BitmapDrawable hasChildDrawable, hasCheckDrawable; private ImageView leftImage; private ImageView rightImage; private TiCompositeLayout content; private ArrayList<TiUIView> views; private TiDimension height = null; private Item item; private Object selectorSource; private Drawable selectorDrawable; public TiTableViewRowProxyItem(Activity activity) { super(activity); this.handler = new Handler(this); this.leftImage = new ImageView(activity); leftImage.setVisibility(GONE); addView(leftImage, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); this.content = new TiCompositeLayout(activity); addView(content, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); this.rightImage = new ImageView(activity); rightImage.setVisibility(GONE); addView(rightImage, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); } protected TableViewRowProxy getRowProxy() { return (TableViewRowProxy)item.proxy; } public void setRowData(Item item) { this.item = item; TableViewRowProxy rp = getRowProxy(); if (this != rp.getTableViewRowProxyItem()) { rp.setTableViewItem(this); } setRowData(rp); } public Item getRowData() { return this.item; } protected TiViewProxy addViewToOldRow(int index, TiUIView titleView, TiViewProxy newViewProxy) { Log.w(TAG, newViewProxy + " was added an old style row, reusing the title TiUILabel", Log.DEBUG_MODE); LabelProxy label = new LabelProxy(); label.handleCreationDict(titleView.getProxy().getProperties()); label.setView(titleView); label.setModelListener(titleView); titleView.setProxy(label); getRowProxy().getControls().add(index, label); views.add(newViewProxy.getOrCreateView()); return label; } /* * Check if the two proxies are compatible outerView wise */ private boolean checkBorderProps(TiViewProxy oldProxy, TiViewProxy newProxy){ KrollDict oldProperties = oldProxy.getProperties(); KrollDict newProperties = newProxy.getProperties(); boolean oldHasBorder = oldProperties.containsKeyAndNotNull(TiC.PROPERTY_BORDER_COLOR) || oldProperties.containsKeyAndNotNull(TiC.PROPERTY_BORDER_RADIUS) || oldProperties.containsKeyAndNotNull(TiC.PROPERTY_BORDER_WIDTH); boolean newHasBorder = newProperties.containsKeyAndNotNull(TiC.PROPERTY_BORDER_COLOR) || newProperties.containsKeyAndNotNull(TiC.PROPERTY_BORDER_RADIUS) || newProperties.containsKeyAndNotNull(TiC.PROPERTY_BORDER_WIDTH); return (oldHasBorder == newHasBorder); } /* * Check the view heirarchy */ private boolean checkViewHeirarchy(TiViewProxy oldProxy, TiViewProxy newProxy){ if (oldProxy == newProxy){ return true; } if(oldProxy.getClass() != newProxy.getClass()) { //Check for type return false; } else if (!checkBorderProps(oldProxy, newProxy)) { //Ensure they have compatible border props return false; } else { //Check children recursively TiViewProxy[] oldChildren = oldProxy.getChildren(); TiViewProxy[] newChildren = newProxy.getChildren(); if (oldChildren.length != newChildren.length) { return false; } else { int len = oldChildren.length; for (int i=0;i<len;i++) { if (!checkViewHeirarchy(oldChildren[i],newChildren[i])) { return false; } } } } //ok, all passed. Return true return true; } /* * Check if views can be reused. */ private boolean canUseExistingViews(ArrayList<TiViewProxy> proxies){ int len = proxies.size(); if(views != null && views.size() == len) { for (int i=0;i<len;i++) { TiUIView view = views.get(i); if (view.getProxy() == null) { return false; } else if (!checkViewHeirarchy(view.getProxy(), proxies.get(i))) { return false; } } return true; } return false; } private ArrayList<KrollPropertyChange> getChangeSet( KrollDict oldProps, KrollDict newProps) { ArrayList<KrollPropertyChange> propertyChanges = new ArrayList<KrollPropertyChange>(); /* //First get the values that changed from the oldProps to the newProps for (String name : oldProps.keySet()) { Object oldValue = oldProps.get(name); Object newValue = newProps.get(name); if (!(oldValue == null && newValue == null)) { if ((oldValue == null && newValue != null) || (newValue == null && oldValue != null) || (!oldValue.equals(newValue))) { KrollPropertyChange pch = new KrollPropertyChange(name, oldValue, newValue); propertyChanges.add(pch); } } } //Second get the properties that are only in the newProps for (String name : newProps.keySet()) { if (!oldProps.containsKey(name)) { KrollPropertyChange pch = new KrollPropertyChange(name, null, newProps.get(name)); propertyChanges.add(pch); } } */ /* What we should do is above. But since we do not handle null values properly in our SDK, we'll do it the short way which is an optimized version of doing processProperties. */ for (String name : newProps.keySet()) { Object oldValue = oldProps.get(name); Object newValue = newProps.get(name); if (!(oldValue == null && newValue == null)) { if ((oldValue == null && newValue != null) || (newValue == null && oldValue != null) || (!oldValue.equals(newValue))) { KrollPropertyChange pch = new KrollPropertyChange(name, oldValue, newValue); propertyChanges.add(pch); } } } return propertyChanges; } /* * Create views for measurement or for layout. For each view, apply the * properties from the appropriate proxy to the view. */ protected void createControls() { TableViewRowProxy parent = getRowProxy(); ArrayList<TiViewProxy> proxies = parent.getControls(); int len = proxies.size(); if (!canUseExistingViews(proxies)) { content.removeAllViews(); if(views == null) { views = new ArrayList<TiUIView>(len); } else { views.clear(); } for (int i=0;i<len;i++){ TiViewProxy proxy = proxies.get(i); TiBaseTableViewItem.clearChildViews(proxy); TiUIView view = proxy.forceCreateView(); views.add(view); View v = view.getOuterView(); if (v.getParent() == null) { content.addView(v, view.getLayoutParams()); } } } else { //Ok the view heirarchies are the same. //Transfer over the views and modelListeners from the old proxies to the new proxies for (int i=0;i<len;i++) { TiUIView view = views.get(i); TiViewProxy oldProxy = view.getProxy(); TiViewProxy newProxy = proxies.get(i); if (oldProxy != newProxy) { newProxy.transferView(view, oldProxy); view.setParent(parent); view.propertiesChanged(getChangeSet(oldProxy.getProperties(), newProxy.getProperties()), newProxy); //Need to apply child properties. applyChildProperties(newProxy, view); } } //Reset the content height and width so that it is calculated based on the children LayoutParams p = content.getLayoutParams(); p.height = -1; p.width = -1; content.setLayoutParams(p); } } protected void applyChildProperties(TiViewProxy viewProxy, TiUIView view) { int i = 0; TiViewProxy childProxies[] = viewProxy.getChildren(); for (TiUIView childView : view.getChildren()) { TiViewProxy childProxy = childProxies[i]; TiViewProxy oldProxy = childView.getProxy(); if (childProxy != oldProxy) { childProxy.transferView(childView, oldProxy); childView.setParent(viewProxy); childView.propertiesChanged(getChangeSet(oldProxy.getProperties(), childProxy.getProperties()), childProxy); applyChildProperties(childProxy, childView); } i++; } } protected void refreshOldStyleRow() { TableViewRowProxy rp = getRowProxy(); if (!rp.hasProperty(TiC.PROPERTY_TOUCH_ENABLED)) { // We have traditionally always made the label untouchable, but since // version 3.0.0 we support explore-by-touch on ICS and above, so for // accessibility purposes we should not be disabling touch if // accessibility is currently turned on. if (!ICS_OR_GREATER || !TiApplication.getInstance().getAccessibilityManager().isEnabled()) { rp.setProperty(TiC.PROPERTY_TOUCH_ENABLED, false); } } // Check if this was a regular row and the control was removed // if so, cleanup the views if (views != null && views.size() > 0) { TiUIView rv = views.get(0); if (!(rv instanceof TiUILabel)) { content.removeAllViews(); views.clear(); views = null; } } if (views == null) { views = new ArrayList<TiUIView>(); views.add(new TiUILabel(rp)); } TiUILabel t = (TiUILabel) views.get(0); t.setProxy(rp); t.processProperties(filterProperties(rp.getProperties())); View v = t.getOuterView(); if (v.getParent() == null) { TiCompositeLayout.LayoutParams params = (TiCompositeLayout.LayoutParams) t.getLayoutParams(); if (params.optionLeft == null) { params.optionLeft = new TiDimension(LEFT_MARGIN, TiDimension.TYPE_LEFT); } if (params.optionRight == null) { params.optionRight = new TiDimension(RIGHT_MARGIN, TiDimension.TYPE_RIGHT); } params.autoFillsWidth = true; content.addView(v, params); } } public void setRowData(TableViewRowProxy rp) { // hasControls = rp.hasControls(); Object newSelectorSource = null; if (rp.hasProperty(TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE)) { newSelectorSource = rp.getProperty(TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE); } else if (rp.hasProperty(TiC.PROPERTY_BACKGROUND_SELECTED_COLOR)) { newSelectorSource = rp.getProperty(TiC.PROPERTY_BACKGROUND_SELECTED_COLOR); } if (newSelectorSource == null || selectorSource != null && !selectorSource.equals(newSelectorSource)) { selectorDrawable = null; } selectorSource = newSelectorSource; if (selectorSource != null) { rp.getTable().getTableView().getTableView().enableCustomSelector(); } setBackgroundFromProxy(rp); // Handle right image boolean clearRightImage = true; // It's one or the other, check or child. If you set them both, child's gonna win. HashMap<String, Object> props = rp.getProperties(); if (props.containsKey(TiC.PROPERTY_HAS_CHECK)) { if (TiConvert.toBoolean(props, TiC.PROPERTY_HAS_CHECK)) { if (hasCheckDrawable == null) { hasCheckDrawable = createHasCheckDrawable(); } rightImage.setImageDrawable(hasCheckDrawable); rightImage.setVisibility(VISIBLE); clearRightImage = false; } } if (props.containsKey(TiC.PROPERTY_HAS_CHILD)) { if (TiConvert.toBoolean(props, TiC.PROPERTY_HAS_CHILD)) { if (hasChildDrawable == null) { hasChildDrawable = createHasChildDrawable(); } rightImage.setImageDrawable(hasChildDrawable); rightImage.setVisibility(VISIBLE); clearRightImage = false; } } if (props.containsKey(TiC.PROPERTY_RIGHT_IMAGE)) { String path = TiConvert.toString(props, TiC.PROPERTY_RIGHT_IMAGE); String url = rp.resolveUrl(null, path); Drawable d = loadDrawable(url); if (d != null) { rightImage.setImageDrawable(d); rightImage.setVisibility(VISIBLE); clearRightImage = false; } } if (clearRightImage) { rightImage.setImageDrawable(null); rightImage.setVisibility(GONE); } // Handle left image if (props.containsKey(TiC.PROPERTY_LEFT_IMAGE)) { String path = TiConvert.toString(props, TiC.PROPERTY_LEFT_IMAGE); String url = rp.resolveUrl(null, path); Drawable d = loadDrawable(url); if (d != null) { leftImage.setImageDrawable(d); leftImage.setVisibility(VISIBLE); } } else { leftImage.setImageDrawable(null); leftImage.setVisibility(GONE); } if (props.containsKey(TiC.PROPERTY_HEIGHT)) { if (!props.get(TiC.PROPERTY_HEIGHT).equals(TiC.SIZE_AUTO) && !props.get(TiC.PROPERTY_HEIGHT).equals(TiC.LAYOUT_SIZE)) { height = TiConvert.toTiDimension(TiConvert.toString(props, TiC.PROPERTY_HEIGHT), TiDimension.TYPE_HEIGHT); } } if (props.containsKey(TiC.PROPERTY_LAYOUT)) { content.setLayoutArrangement(TiConvert.toString(props, TiC.PROPERTY_LAYOUT)); } if (props.containsKey(TiC.PROPERTY_HORIZONTAL_WRAP)) { content.setEnableHorizontalWrap(TiConvert.toBoolean(props, TiC.PROPERTY_HORIZONTAL_WRAP)); } // hasControls() means that the proxy has children if (rp.hasControls()) { createControls(); } else { // no children means that this is an old-style row refreshOldStyleRow(); } if (ICS_OR_GREATER) { Object accessibilityHiddenVal = rp.getProperty(TiC.PROPERTY_ACCESSIBILITY_HIDDEN); if (accessibilityHiddenVal != null) { boolean hidden = TiConvert.toBoolean(accessibilityHiddenVal); if (hidden) { ViewCompat.setImportantForAccessibility(this, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO); } else { ViewCompat.setImportantForAccessibility(this, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO); } } } } protected boolean hasView(TiUIView view) { if (views == null) return false; for (TiUIView v : views) { if (v == view) { return true; } } return false; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int w = MeasureSpec.getSize(widthMeasureSpec); int wMode = MeasureSpec.getMode(widthMeasureSpec); int h = MeasureSpec.getSize(heightMeasureSpec); int hMode = MeasureSpec.getMode(heightMeasureSpec); int imageHMargin = 0; int leftImageWidth = 0; int leftImageHeight = 0; if (leftImage != null && leftImage.getVisibility() != View.GONE) { measureChild(leftImage, widthMeasureSpec, heightMeasureSpec); leftImageWidth = leftImage.getMeasuredWidth(); leftImageHeight = leftImage.getMeasuredHeight(); imageHMargin += new TiDimension(LEFT_MARGIN, TiDimension.TYPE_LEFT).getAsPixels(this); } int rightImageWidth = 0; int rightImageHeight = 0; if (rightImage != null && rightImage.getVisibility() != View.GONE) { measureChild(rightImage, widthMeasureSpec, heightMeasureSpec); rightImageWidth = rightImage.getMeasuredWidth(); rightImageHeight = rightImage.getMeasuredHeight(); imageHMargin += new TiDimension(RIGHT_MARGIN, TiDimension.TYPE_RIGHT).getAsPixels(this); } int adjustedWidth = w - leftImageWidth - rightImageWidth - imageHMargin; // int adjustedWidth = w; if (content != null) { // If there is a child view, we don't set a minimum height for the row. // Otherwise, we set a minimum height. boolean hasChildView = ((TableViewRowProxy) item.proxy).hasControls(); if (hasChildView) { content.setMinimumHeight(0); } else { content.setMinimumHeight(TiConvert.toTiDimension(MIN_HEIGHT, TiDimension.TYPE_HEIGHT).getAsPixels(this)); } measureChild(content, MeasureSpec.makeMeasureSpec(adjustedWidth, wMode), heightMeasureSpec); if (hMode == MeasureSpec.UNSPECIFIED) { TableViewProxy table = ((TableViewRowProxy) item.proxy).getTable(); int minRowHeight = -1; if (table != null && table.hasProperty(TiC.PROPERTY_MIN_ROW_HEIGHT)) { minRowHeight = TiConvert.toTiDimension( TiConvert.toString(table.getProperty(TiC.PROPERTY_MIN_ROW_HEIGHT)), TiDimension.TYPE_HEIGHT) .getAsPixels(this); } if (height == null) { // If measure spec is not specified, height should behave as Ti.UI.SIZE if (hMode == 0) { h = Math.max(content.getMeasuredHeight(), Math.max(leftImageHeight, rightImageHeight)); } else { h = Math.max(h, Math.max(content.getMeasuredHeight(), Math.max(leftImageHeight, rightImageHeight))); } h = Math.max(h, minRowHeight); } else { h = Math.max(minRowHeight, height.getAsPixels(this)); } // Make sure the height is greater than 1 (not 0 since image views default to 1) if (hasChildView && h > 1) { content.getLayoutParams().height = h; } if (Log.isDebugModeEnabled()) { Log.d(TAG, "Row content measure (" + adjustedWidth + "x" + h + ")", Log.DEBUG_MODE); } measureChild(content, MeasureSpec.makeMeasureSpec(adjustedWidth, wMode), MeasureSpec.makeMeasureSpec(h, hMode)); } } setMeasuredDimension(w, Math.max(h, Math.max(leftImageHeight, rightImageHeight))); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { // Make these associations here to avoid doing them on measurement passes getRowProxy().setTableViewItem(this); int contentLeft = left; int contentRight = right; bottom = bottom - top; top = 0; int height = bottom - top; if (leftImage != null && leftImage.getVisibility() != GONE) { int w = leftImage.getMeasuredWidth(); int h = leftImage.getMeasuredHeight(); int leftMargin = new TiDimension(LEFT_MARGIN, TiDimension.TYPE_LEFT).getAsPixels(this); contentLeft += w + leftMargin; int offset = (height - h) / 2; leftImage.layout(left+leftMargin, top+offset, left+leftMargin+w, top+offset+h); } if (rightImage != null && rightImage.getVisibility() != GONE) { int w = new TiDimension(RIGHT_SIZE, TiDimension.TYPE_RIGHT).getAsPixels(this); int h = new TiDimension(RIGHT_SIZE, TiDimension.TYPE_RIGHT).getAsPixels(this); int rightMargin = new TiDimension(RIGHT_MARGIN, TiDimension.TYPE_RIGHT).getAsPixels(this); contentRight -= w + rightMargin; int offset = (height - h) / 2; rightImage.layout(right-w-rightMargin, top+offset, right-rightMargin, top+offset+h); } // if (hasControls) { // contentLeft = left + new TiDimension(LEFT_MARGIN, TiDimension.TYPE_LEFT).getAsPixels(this); // contentRight = right - new TiDimension(RIGHT_MARGIN, TiDimension.TYPE_RIGHT).getAsPixels(this); // } if (content != null) { content.layout(contentLeft, top, contentRight, bottom); } if (changed) { TiUIHelper.firePostLayoutEvent(getRowProxy()); } } private static String[] filteredProperties = new String[]{ TiC.PROPERTY_BACKGROUND_IMAGE, TiC.PROPERTY_BACKGROUND_COLOR, TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE, TiC.PROPERTY_BACKGROUND_SELECTED_COLOR }; private KrollDict filterProperties(KrollDict d) { if (d == null) return new KrollDict(); KrollDict filtered = new KrollDict(d); for (int i = 0;i < filteredProperties.length; i++) { if (filtered.containsKey(filteredProperties[i])) { filtered.remove(filteredProperties[i]); } } return filtered; } @Override public boolean hasSelector() { TableViewRowProxy rowProxy = getRowProxy(); return rowProxy.hasProperty(TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE) || rowProxy.hasProperty(TiC.PROPERTY_BACKGROUND_SELECTED_COLOR); } @Override public Drawable getSelectorDrawable() { TableViewRowProxy rowProxy = getRowProxy(); if (selectorDrawable == null && selectorSource != null) { if (rowProxy.hasProperty(TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE)) { String path = TiConvert.toString( rowProxy.getProperty(TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE)); String url = rowProxy.resolveUrl(null, path); selectorDrawable = loadDrawable(url); } else if (rowProxy.hasProperty(TiC.PROPERTY_BACKGROUND_SELECTED_COLOR)) { int color = TiConvert.toColor(rowProxy.getProperty(TiC.PROPERTY_BACKGROUND_SELECTED_COLOR).toString()); selectorDrawable = new TiTableViewColorSelector(color); } } return selectorDrawable; } @Override public void release() { super.release(); if (views != null) { for (TiUIView view : views) { view.release(); } views = null; } if (content != null) { content.removeAllViews(); content = null; } if (hasCheckDrawable != null) { hasCheckDrawable.setCallback(null); hasCheckDrawable = null; } if (hasChildDrawable != null) { hasChildDrawable.setCallback(null); hasChildDrawable = null; } } }
[TIMOB-25158] Fix TableView.rightImage size
android/modules/ui/src/java/ti/modules/titanium/ui/widget/tableview/TiTableViewRowProxyItem.java
[TIMOB-25158] Fix TableView.rightImage size
Java
apache-2.0
9b07d64470969b761a32e46d84594a7da31ac8cd
0
akirakw/asakusafw-compiler,ashigeru/asakusafw-compiler,akirakw/asakusafw-compiler,ashigeru/asakusafw-compiler,asakusafw/asakusafw-compiler,asakusafw/asakusafw-compiler,ashigeru/asakusafw-compiler
/** * Copyright 2011-2015 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asakusafw.lang.tool.launcher; /** * Represents an error while launching applications. */ public class LauncherException extends RuntimeException { private static final long serialVersionUID = -5566847104874631897L; /** * Creates a new instance. */ public LauncherException() { super(); } /** * Creates a new instance. * @param message the message */ public LauncherException(String message) { super(message); } /** * Creates a new instance. * @param message the message * @param cause the cause of this exception */ public LauncherException(String message, Throwable cause) { super(message, cause); } }
tool-project/tool-launcher/src/main/java/com/asakusafw/lang/tool/launcher/LauncherException.java
package com.asakusafw.lang.tool.launcher; /** * Represents an error while launching applications. */ public class LauncherException extends RuntimeException { private static final long serialVersionUID = -5566847104874631897L; /** * Creates a new instance. */ public LauncherException() { super(); } /** * Creates a new instance. * @param message the message */ public LauncherException(String message) { super(message); } /** * Creates a new instance. * @param message the message * @param cause the cause of this exception */ public LauncherException(String message, Throwable cause) { super(message, cause); } }
Fix license header.
tool-project/tool-launcher/src/main/java/com/asakusafw/lang/tool/launcher/LauncherException.java
Fix license header.
Java
apache-2.0
d4640340c5a2f9640936eeee9506318305009aca
0
haku/camel,noelo/camel,grange74/camel,dkhanolkar/camel,Thopap/camel,lowwool/camel,driseley/camel,bfitzpat/camel,bgaudaen/camel,haku/camel,snadakuduru/camel,drsquidop/camel,YoshikiHigo/camel,cunningt/camel,royopa/camel,jarst/camel,jarst/camel,engagepoint/camel,bgaudaen/camel,oscerd/camel,lasombra/camel,acartapanis/camel,lburgazzoli/apache-camel,manuelh9r/camel,mohanaraosv/camel,YMartsynkevych/camel,jpav/camel,engagepoint/camel,dpocock/camel,bhaveshdt/camel,haku/camel,YMartsynkevych/camel,davidwilliams1978/camel,sebi-hgdata/camel,lburgazzoli/camel,mgyongyosi/camel,anoordover/camel,onders86/camel,hqstevenson/camel,tkopczynski/camel,ssharma/camel,NickCis/camel,kevinearls/camel,woj-i/camel,pmoerenhout/camel,isavin/camel,mike-kukla/camel,dmvolod/camel,mnki/camel,allancth/camel,woj-i/camel,bgaudaen/camel,gyc567/camel,anton-k11/camel,CandleCandle/camel,nboukhed/camel,stalet/camel,YMartsynkevych/camel,tarilabs/camel,manuelh9r/camel,partis/camel,tarilabs/camel,alvinkwekel/camel,zregvart/camel,mgyongyosi/camel,johnpoth/camel,anton-k11/camel,bdecoste/camel,snadakuduru/camel,brreitme/camel,tadayosi/camel,dsimansk/camel,mnki/camel,sebi-hgdata/camel,isavin/camel,josefkarasek/camel,gautric/camel,veithen/camel,onders86/camel,mcollovati/camel,FingolfinTEK/camel,borcsokj/camel,snurmine/camel,onders86/camel,scranton/camel,edigrid/camel,manuelh9r/camel,nboukhed/camel,w4tson/camel,snurmine/camel,apache/camel,pplatek/camel,snadakuduru/camel,mgyongyosi/camel,grgrzybek/camel,bfitzpat/camel,nicolaferraro/camel,punkhorn/camel-upstream,CodeSmell/camel,tdiesler/camel,jamesnetherton/camel,qst-jdc-labs/camel,christophd/camel,DariusX/camel,kevinearls/camel,igarashitm/camel,tlehoux/camel,pplatek/camel,adessaigne/camel,MrCoder/camel,sabre1041/camel,grange74/camel,sirlatrom/camel,stravag/camel,adessaigne/camel,sirlatrom/camel,brreitme/camel,royopa/camel,edigrid/camel,JYBESSON/camel,scranton/camel,manuelh9r/camel,CandleCandle/camel,grange74/camel,cunningt/camel,gilfernandes/camel,jmandawg/camel,sabre1041/camel,arnaud-deprez/camel,bgaudaen/camel,logzio/camel,snadakuduru/camel,lowwool/camel,yogamaha/camel,gilfernandes/camel,koscejev/camel,dkhanolkar/camel,adessaigne/camel,trohovsky/camel,josefkarasek/camel,dvankleef/camel,borcsokj/camel,cunningt/camel,lburgazzoli/camel,rparree/camel,FingolfinTEK/camel,rparree/camel,FingolfinTEK/camel,prashant2402/camel,tarilabs/camel,oscerd/camel,bhaveshdt/camel,jpav/camel,anoordover/camel,ge0ffrey/camel,partis/camel,nikvaessen/camel,haku/camel,jlpedrosa/camel,DariusX/camel,yuruki/camel,skinzer/camel,snadakuduru/camel,alvinkwekel/camel,isururanawaka/camel,mike-kukla/camel,jonmcewen/camel,prashant2402/camel,bdecoste/camel,kevinearls/camel,isururanawaka/camel,jollygeorge/camel,chirino/camel,pkletsko/camel,gilfernandes/camel,joakibj/camel,yuruki/camel,sebi-hgdata/camel,tlehoux/camel,partis/camel,Thopap/camel,josefkarasek/camel,sverkera/camel,anoordover/camel,lowwool/camel,yury-vashchyla/camel,maschmid/camel,yury-vashchyla/camel,prashant2402/camel,jarst/camel,ekprayas/camel,oalles/camel,nikhilvibhav/camel,MrCoder/camel,adessaigne/camel,satishgummadelli/camel,isavin/camel,ge0ffrey/camel,gyc567/camel,nikvaessen/camel,jameszkw/camel,gnodet/camel,joakibj/camel,objectiser/camel,jamesnetherton/camel,YoshikiHigo/camel,rmarting/camel,nikvaessen/camel,tadayosi/camel,allancth/camel,hqstevenson/camel,acartapanis/camel,logzio/camel,bhaveshdt/camel,jollygeorge/camel,salikjan/camel,CodeSmell/camel,eformat/camel,woj-i/camel,gautric/camel,isururanawaka/camel,dpocock/camel,YMartsynkevych/camel,CandleCandle/camel,joakibj/camel,tkopczynski/camel,YoshikiHigo/camel,edigrid/camel,tkopczynski/camel,JYBESSON/camel,bfitzpat/camel,isururanawaka/camel,jlpedrosa/camel,logzio/camel,askannon/camel,duro1/camel,johnpoth/camel,driseley/camel,FingolfinTEK/camel,lburgazzoli/apache-camel,grgrzybek/camel,chanakaudaya/camel,pplatek/camel,cunningt/camel,cunningt/camel,veithen/camel,dvankleef/camel,pax95/camel,igarashitm/camel,snurmine/camel,johnpoth/camel,lburgazzoli/apache-camel,stravag/camel,JYBESSON/camel,iweiss/camel,bdecoste/camel,CandleCandle/camel,Thopap/camel,sverkera/camel,onders86/camel,MohammedHammam/camel,josefkarasek/camel,yuruki/camel,anton-k11/camel,bdecoste/camel,pmoerenhout/camel,yogamaha/camel,NickCis/camel,lowwool/camel,mohanaraosv/camel,jollygeorge/camel,gnodet/camel,apache/camel,oalles/camel,tkopczynski/camel,dsimansk/camel,pplatek/camel,pkletsko/camel,RohanHart/camel,pkletsko/camel,gyc567/camel,drsquidop/camel,sirlatrom/camel,jamesnetherton/camel,logzio/camel,partis/camel,ramonmaruko/camel,jameszkw/camel,ullgren/camel,jpav/camel,tadayosi/camel,edigrid/camel,arnaud-deprez/camel,objectiser/camel,curso007/camel,manuelh9r/camel,apache/camel,JYBESSON/camel,jkorab/camel,maschmid/camel,dsimansk/camel,lburgazzoli/camel,satishgummadelli/camel,mgyongyosi/camel,woj-i/camel,hqstevenson/camel,jmandawg/camel,maschmid/camel,ramonmaruko/camel,tarilabs/camel,driseley/camel,scranton/camel,bgaudaen/camel,sverkera/camel,neoramon/camel,veithen/camel,chanakaudaya/camel,satishgummadelli/camel,brreitme/camel,grgrzybek/camel,arnaud-deprez/camel,skinzer/camel,jameszkw/camel,RohanHart/camel,RohanHart/camel,noelo/camel,rparree/camel,isavin/camel,veithen/camel,tlehoux/camel,onders86/camel,mcollovati/camel,bgaudaen/camel,anton-k11/camel,ekprayas/camel,allancth/camel,w4tson/camel,koscejev/camel,gyc567/camel,allancth/camel,stalet/camel,curso007/camel,YMartsynkevych/camel,johnpoth/camel,lasombra/camel,isavin/camel,dmvolod/camel,ramonmaruko/camel,trohovsky/camel,YoshikiHigo/camel,objectiser/camel,ssharma/camel,anton-k11/camel,eformat/camel,pplatek/camel,mzapletal/camel,zregvart/camel,stalet/camel,yuruki/camel,hqstevenson/camel,MrCoder/camel,drsquidop/camel,iweiss/camel,ekprayas/camel,koscejev/camel,chanakaudaya/camel,engagepoint/camel,mnki/camel,erwelch/camel,mzapletal/camel,christophd/camel,mohanaraosv/camel,neoramon/camel,tdiesler/camel,sabre1041/camel,Thopap/camel,dpocock/camel,akhettar/camel,jonmcewen/camel,pax95/camel,davidkarlsen/camel,sirlatrom/camel,DariusX/camel,tdiesler/camel,davidwilliams1978/camel,askannon/camel,ssharma/camel,ramonmaruko/camel,pplatek/camel,jkorab/camel,snurmine/camel,partis/camel,brreitme/camel,dkhanolkar/camel,CodeSmell/camel,jameszkw/camel,mike-kukla/camel,allancth/camel,aaronwalker/camel,askannon/camel,NetNow/camel,stravag/camel,nikvaessen/camel,punkhorn/camel-upstream,jonmcewen/camel,bfitzpat/camel,atoulme/camel,nikhilvibhav/camel,noelo/camel,jkorab/camel,akhettar/camel,chirino/camel,mcollovati/camel,jmandawg/camel,royopa/camel,dvankleef/camel,tadayosi/camel,mohanaraosv/camel,MrCoder/camel,josefkarasek/camel,dkhanolkar/camel,manuelh9r/camel,mzapletal/camel,jamesnetherton/camel,oalles/camel,rparree/camel,tarilabs/camel,sirlatrom/camel,scranton/camel,logzio/camel,kevinearls/camel,sebi-hgdata/camel,scranton/camel,mnki/camel,arnaud-deprez/camel,lasombra/camel,trohovsky/camel,anoordover/camel,dpocock/camel,iweiss/camel,tkopczynski/camel,davidwilliams1978/camel,trohovsky/camel,duro1/camel,anton-k11/camel,borcsokj/camel,sabre1041/camel,w4tson/camel,alvinkwekel/camel,qst-jdc-labs/camel,NickCis/camel,tlehoux/camel,bhaveshdt/camel,sebi-hgdata/camel,salikjan/camel,gnodet/camel,lburgazzoli/camel,NickCis/camel,neoramon/camel,koscejev/camel,stravag/camel,davidwilliams1978/camel,w4tson/camel,grgrzybek/camel,duro1/camel,sirlatrom/camel,driseley/camel,dsimansk/camel,askannon/camel,koscejev/camel,CandleCandle/camel,bdecoste/camel,nikvaessen/camel,jkorab/camel,gilfernandes/camel,MohammedHammam/camel,woj-i/camel,mzapletal/camel,johnpoth/camel,acartapanis/camel,tadayosi/camel,joakibj/camel,lburgazzoli/camel,aaronwalker/camel,engagepoint/camel,jonmcewen/camel,atoulme/camel,ramonmaruko/camel,akhettar/camel,acartapanis/camel,dsimansk/camel,jameszkw/camel,jlpedrosa/camel,davidkarlsen/camel,aaronwalker/camel,lburgazzoli/apache-camel,bfitzpat/camel,coderczp/camel,tkopczynski/camel,jkorab/camel,rmarting/camel,dmvolod/camel,apache/camel,atoulme/camel,NickCis/camel,pax95/camel,satishgummadelli/camel,nicolaferraro/camel,ge0ffrey/camel,tdiesler/camel,nboukhed/camel,akhettar/camel,oscerd/camel,mzapletal/camel,dvankleef/camel,mohanaraosv/camel,zregvart/camel,jkorab/camel,tlehoux/camel,sverkera/camel,isururanawaka/camel,jarst/camel,anoordover/camel,acartapanis/camel,CodeSmell/camel,jmandawg/camel,FingolfinTEK/camel,Fabryprog/camel,chirino/camel,oscerd/camel,NetNow/camel,jmandawg/camel,mcollovati/camel,dmvolod/camel,qst-jdc-labs/camel,atoulme/camel,atoulme/camel,lburgazzoli/apache-camel,coderczp/camel,brreitme/camel,hqstevenson/camel,stalet/camel,ssharma/camel,igarashitm/camel,mike-kukla/camel,JYBESSON/camel,tdiesler/camel,MohammedHammam/camel,coderczp/camel,driseley/camel,YMartsynkevych/camel,oscerd/camel,akhettar/camel,allancth/camel,atoulme/camel,eformat/camel,objectiser/camel,apache/camel,jollygeorge/camel,oalles/camel,hqstevenson/camel,iweiss/camel,gyc567/camel,curso007/camel,stravag/camel,pmoerenhout/camel,grange74/camel,yury-vashchyla/camel,igarashitm/camel,lowwool/camel,yury-vashchyla/camel,acartapanis/camel,w4tson/camel,partis/camel,skinzer/camel,mnki/camel,trohovsky/camel,duro1/camel,yuruki/camel,mike-kukla/camel,nikhilvibhav/camel,yury-vashchyla/camel,drsquidop/camel,punkhorn/camel-upstream,curso007/camel,oalles/camel,JYBESSON/camel,veithen/camel,sebi-hgdata/camel,NetNow/camel,chirino/camel,pmoerenhout/camel,eformat/camel,rmarting/camel,nicolaferraro/camel,scranton/camel,davidkarlsen/camel,ekprayas/camel,MrCoder/camel,oalles/camel,stalet/camel,jameszkw/camel,aaronwalker/camel,ssharma/camel,royopa/camel,curso007/camel,noelo/camel,NickCis/camel,prashant2402/camel,chanakaudaya/camel,pax95/camel,edigrid/camel,dsimansk/camel,Fabryprog/camel,joakibj/camel,sverkera/camel,josefkarasek/camel,MohammedHammam/camel,johnpoth/camel,christophd/camel,alvinkwekel/camel,satishgummadelli/camel,askannon/camel,jpav/camel,erwelch/camel,MrCoder/camel,snurmine/camel,borcsokj/camel,erwelch/camel,yogamaha/camel,dkhanolkar/camel,kevinearls/camel,Fabryprog/camel,mohanaraosv/camel,anoordover/camel,apache/camel,ullgren/camel,dmvolod/camel,lasombra/camel,noelo/camel,jlpedrosa/camel,isururanawaka/camel,igarashitm/camel,tarilabs/camel,mike-kukla/camel,Fabryprog/camel,joakibj/camel,jollygeorge/camel,FingolfinTEK/camel,jarst/camel,duro1/camel,adessaigne/camel,bdecoste/camel,gnodet/camel,nikhilvibhav/camel,DariusX/camel,pkletsko/camel,gautric/camel,iweiss/camel,NetNow/camel,ekprayas/camel,pplatek/camel,curso007/camel,gautric/camel,jlpedrosa/camel,brreitme/camel,dvankleef/camel,nicolaferraro/camel,gnodet/camel,NetNow/camel,lburgazzoli/apache-camel,qst-jdc-labs/camel,prashant2402/camel,neoramon/camel,coderczp/camel,bfitzpat/camel,snurmine/camel,skinzer/camel,jmandawg/camel,maschmid/camel,pmoerenhout/camel,grgrzybek/camel,Thopap/camel,eformat/camel,pmoerenhout/camel,pax95/camel,nboukhed/camel,askannon/camel,snadakuduru/camel,jpav/camel,erwelch/camel,ge0ffrey/camel,royopa/camel,oscerd/camel,edigrid/camel,pkletsko/camel,ge0ffrey/camel,kevinearls/camel,jonmcewen/camel,stalet/camel,cunningt/camel,gyc567/camel,grgrzybek/camel,aaronwalker/camel,rmarting/camel,christophd/camel,tdiesler/camel,ramonmaruko/camel,arnaud-deprez/camel,haku/camel,erwelch/camel,zregvart/camel,dkhanolkar/camel,Thopap/camel,jamesnetherton/camel,NetNow/camel,tadayosi/camel,engagepoint/camel,skinzer/camel,jlpedrosa/camel,logzio/camel,chirino/camel,satishgummadelli/camel,dpocock/camel,RohanHart/camel,YoshikiHigo/camel,neoramon/camel,rparree/camel,grange74/camel,bhaveshdt/camel,yuruki/camel,ge0ffrey/camel,mzapletal/camel,isavin/camel,davidwilliams1978/camel,borcsokj/camel,ullgren/camel,onders86/camel,drsquidop/camel,coderczp/camel,jarst/camel,chanakaudaya/camel,koscejev/camel,nikvaessen/camel,aaronwalker/camel,yogamaha/camel,christophd/camel,chanakaudaya/camel,gilfernandes/camel,erwelch/camel,eformat/camel,lburgazzoli/camel,jamesnetherton/camel,noelo/camel,lowwool/camel,stravag/camel,iweiss/camel,pax95/camel,davidkarlsen/camel,sverkera/camel,coderczp/camel,gautric/camel,punkhorn/camel-upstream,dpocock/camel,bhaveshdt/camel,mnki/camel,dvankleef/camel,jpav/camel,jonmcewen/camel,maschmid/camel,pkletsko/camel,haku/camel,rmarting/camel,arnaud-deprez/camel,borcsokj/camel,MohammedHammam/camel,lasombra/camel,royopa/camel,nboukhed/camel,davidwilliams1978/camel,duro1/camel,rmarting/camel,drsquidop/camel,nboukhed/camel,neoramon/camel,gautric/camel,veithen/camel,christophd/camel,maschmid/camel,yogamaha/camel,RohanHart/camel,prashant2402/camel,chirino/camel,MohammedHammam/camel,jollygeorge/camel,qst-jdc-labs/camel,ssharma/camel,yury-vashchyla/camel,mgyongyosi/camel,driseley/camel,rparree/camel,YoshikiHigo/camel,akhettar/camel,mgyongyosi/camel,dmvolod/camel,RohanHart/camel,yogamaha/camel,grange74/camel,skinzer/camel,sabre1041/camel,woj-i/camel,qst-jdc-labs/camel,lasombra/camel,ekprayas/camel,logzio/camel,ullgren/camel,igarashitm/camel,trohovsky/camel,adessaigne/camel,w4tson/camel,tlehoux/camel,sabre1041/camel,gilfernandes/camel,CandleCandle/camel
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.jms.discovery; import java.util.HashMap; import java.util.Map; import javax.jms.ConnectionFactory; import javax.naming.Context; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.camel.CamelContext; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; import static org.apache.camel.component.jms.JmsComponent.jmsComponentClientAcknowledge; /** * @version $Revision$ */ public class JmsDiscoveryTest extends CamelTestSupport { protected MyRegistry registry = new MyRegistry(); @Test public void testDiscovery() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMinimumMessageCount(1); mock.setResultWaitTime(5000); // force shutdown after 5 seconds as otherwise the bean will keep generating a new input context.getShutdownStrategy().setTimeout(5); assertMockEndpointsSatisfied(); // sleep a little Thread.sleep(1000); Map<String, Map> map = new HashMap<String, Map>(registry.getServices()); assertTrue("There should be 1 or more, was: " + map.size(), map.size() >= 1); } protected CamelContext createCamelContext() throws Exception { CamelContext camelContext = super.createCamelContext(); ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false&broker.useJmx=false"); camelContext.addComponent("activemq", jmsComponentClientAcknowledge(connectionFactory)); return camelContext; } @Override protected Context createJndiContext() throws Exception { Context context = super.createJndiContext(); context.bind("service1", new MyService("service1")); context.bind("registry", registry); return context; } protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() throws Exception { // lets setup the heartbeats from("bean:service1?method=status").to("activemq:topic:registry.heartbeats"); from("activemq:topic:registry.heartbeats").to("bean:registry?method=onEvent", "mock:result"); } }; } }
components/camel-jms/src/test/java/org/apache/camel/component/jms/discovery/JmsDiscoveryTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.jms.discovery; import java.util.HashMap; import java.util.Map; import javax.jms.ConnectionFactory; import javax.naming.Context; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.camel.CamelContext; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; import static org.apache.camel.component.jms.JmsComponent.jmsComponentClientAcknowledge; /** * @version $Revision$ */ public class JmsDiscoveryTest extends CamelTestSupport { protected MyRegistry registry = new MyRegistry(); @Test public void testDiscovery() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMinimumMessageCount(1); assertMockEndpointsSatisfied(); // sleep a little Thread.sleep(1000); Map<String, Map> map = new HashMap<String, Map>(registry.getServices()); assertTrue("There should be 1 or more, was: " + map.size(), map.size() >= 1); } protected CamelContext createCamelContext() throws Exception { CamelContext camelContext = super.createCamelContext(); ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false&broker.useJmx=false"); camelContext.addComponent("activemq", jmsComponentClientAcknowledge(connectionFactory)); return camelContext; } @Override protected Context createJndiContext() throws Exception { Context context = super.createJndiContext(); context.bind("service1", new MyService("service1")); context.bind("registry", registry); return context; } protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() throws Exception { // lets setup the heartbeats from("bean:service1?method=status").to("activemq:topic:registry.heartbeats"); from("activemq:topic:registry.heartbeats").to("bean:registry?method=onEvent", "mock:result"); } }; } }
CAMEL-1483: Stop unit test quicker due graceful shutdown wanting to be too gentle git-svn-id: 11f3c9e1d08a13a4be44fe98a6d63a9c00f6ab23@893123 13f79535-47bb-0310-9956-ffa450edef68
components/camel-jms/src/test/java/org/apache/camel/component/jms/discovery/JmsDiscoveryTest.java
CAMEL-1483: Stop unit test quicker due graceful shutdown wanting to be too gentle
Java
apache-2.0
94d3bb60caf6ac1fe251ec5de2e04ae46cc9e169
0
webfirmframework/wff,webfirmframework/wff
/* * Copyright 2014-2017 Web Firm Framework * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.webfirmframework.wffweb.server.page; import java.io.UnsupportedEncodingException; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Collection; import java.util.Deque; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.webfirmframework.wffweb.InvalidTagException; import com.webfirmframework.wffweb.tag.html.AbstractHtml; import com.webfirmframework.wffweb.tag.html.html5.attribute.global.DataWffId; import com.webfirmframework.wffweb.tag.html.listener.ChildTagAppendListener; import com.webfirmframework.wffweb.util.data.NameValue; class ChildTagAppendListenerImpl implements ChildTagAppendListener { private static final long serialVersionUID = 1L; public static final Logger LOGGER = Logger .getLogger(ChildTagRemoveListenerImpl.class.getName()); private Object accessObject; private BrowserPage browserPage; private Map<String, AbstractHtml> tagByWffId; @SuppressWarnings("unused") private ChildTagAppendListenerImpl() { throw new AssertionError(); } ChildTagAppendListenerImpl(final BrowserPage browserPage, final Object accessObject, final Map<String, AbstractHtml> tagByWffId) { this.browserPage = browserPage; this.accessObject = accessObject; this.tagByWffId = tagByWffId; } @Override public void childAppended(final Event event) { try { final AbstractHtml parentTag = event.getParentTag(); final AbstractHtml appendedChildTag = event.getAppendedChildTag(); // add data-wff-id to all tags including nested tags final Deque<Set<AbstractHtml>> childrenStack = new ArrayDeque<Set<AbstractHtml>>(); childrenStack.push(new LinkedHashSet<AbstractHtml>( Arrays.asList(appendedChildTag))); while (childrenStack.size() > 0) { final Set<AbstractHtml> children = childrenStack.pop(); for (final AbstractHtml child : children) { if (child.getDataWffId() == null) { child.setDataWffId(browserPage.getNewDataWffId()); } tagByWffId.put(child.getDataWffId().getValue(), child); final Set<AbstractHtml> subChildren = child .getChildren(accessObject); if (subChildren != null && subChildren.size() > 0) { childrenStack.push(subChildren); } } } final DataWffId dataWffId = parentTag.getDataWffId(); if (dataWffId == null && LOGGER.isLoggable(Level.WARNING)) { LOGGER.warning( "Could not find data-wff-id from direct parent tag"); } //@formatter:off // appended child task format :- // { "name": task_byte, "values" : [invoke_method_byte_from_Task_enum]}, { "name": data-wff-id, "values" : [ parent_tag_name, html_string ]} // { "name": 2, "values" : [[3]]}, { "name":"C55", "values" : ["body", "<div><div></div></div>"]} //@formatter:on final NameValue task = Task.APPENDED_CHILD_TAG.getTaskNameValue(); final NameValue nameValue = new NameValue(); final byte[][] tagNameAndWffId = DataWffIdUtil .getTagNameAndWffId(parentTag); final byte[] parentWffIdBytes = tagNameAndWffId[1]; nameValue.setName(parentWffIdBytes); final byte[] parentTagName = tagNameAndWffId[0]; nameValue.setValues(parentTagName, appendedChildTag.toWffBMBytes("UTF-8")); browserPage.push(task, nameValue); } catch (final InvalidTagException e) { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.log(Level.WARNING, "Do not append/add an empty NoTag as child tag, eg: new NoTag(null, \"\").\n" .concat("To make a tag's children as empty then invoke removeAllChildren() method in it."), e); } } catch (final UnsupportedEncodingException e) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } } @Override public void childrenAppended(final Event event) { try { final AbstractHtml parentTag = event.getParentTag(); final Collection<? extends AbstractHtml> appendedChildTags = event .getAppendedChildrenTags(); // add data-wff-id to all tags including nested tags final Deque<Set<AbstractHtml>> childrenStack = new ArrayDeque<Set<AbstractHtml>>(); childrenStack .push(new LinkedHashSet<AbstractHtml>(appendedChildTags)); while (childrenStack.size() > 0) { final Set<AbstractHtml> children = childrenStack.pop(); for (final AbstractHtml child : children) { if (child.getDataWffId() == null) { child.setDataWffId(browserPage.getNewDataWffId()); } tagByWffId.put(child.getDataWffId().getValue(), child); final Set<AbstractHtml> subChildren = child .getChildren(accessObject); if (subChildren != null && subChildren.size() > 0) { childrenStack.push(subChildren); } } } final DataWffId dataWffId = parentTag.getDataWffId(); if (dataWffId == null && LOGGER.isLoggable(Level.WARNING)) { LOGGER.warning( "Could not find data-wff-id from direct parent tag"); } //@formatter:off // appended child task format :- // { "name": task_byte, "values" : [invoke_method_byte_from_Task_enum]}, { "name": data-wff-id, "values" : [ parent_tag_name, html_string ]} // { "name": 2, "values" : [[3]]}, { "name":"C55", "values" : ["body", "<div><div></div></div>"]} //@formatter:on final NameValue task = Task.APPENDED_CHILDREN_TAGS .getTaskNameValue(); final Deque<NameValue> nameValues = new ArrayDeque<NameValue>(); nameValues.add(task); for (final AbstractHtml appendedChildTag : appendedChildTags) { final NameValue nameValue = new NameValue(); final byte[][] tagNameAndWffId = DataWffIdUtil .getTagNameAndWffId(parentTag); final byte[] parentWffIdBytes = tagNameAndWffId[1]; nameValue.setName(parentWffIdBytes); final byte[] parentTagName = tagNameAndWffId[0]; try { nameValue.setValues(parentTagName, appendedChildTag.toWffBMBytes("UTF-8")); } catch (final InvalidTagException e) { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.log(Level.WARNING, "Do not append/add an empty NoTag as child tag, eg: new NoTag(null, \"\").\n" .concat("To make a tag's children as empty then invoke removeAllChildren() method in it."), e); } continue; } nameValues.add(nameValue); } browserPage .push(nameValues.toArray(new NameValue[nameValues.size()])); } catch (final UnsupportedEncodingException e) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } } /** * adds to wffid map * * @param tag * @since 2.0.0 * @author WFF */ private void addInWffIdMap(final AbstractHtml tag) { final Deque<Set<AbstractHtml>> childrenStack = new ArrayDeque<Set<AbstractHtml>>(); childrenStack.push(new HashSet<AbstractHtml>(Arrays.asList(tag))); while (childrenStack.size() > 0) { final Set<AbstractHtml> children = childrenStack.pop(); for (final AbstractHtml child : children) { final DataWffId wffIdAttr = child.getDataWffId(); if (wffIdAttr != null) { tagByWffId.put(wffIdAttr.getValue(), child); } final Set<AbstractHtml> subChildren = child .getChildren(accessObject); if (subChildren != null && subChildren.size() > 0) { childrenStack.push(subChildren); } } } } @Override public void childMoved(final ChildMovedEvent event) { //@formatter:off // moved children tags from some parents to another task format (in this method moving only one child) :- // { "name": task_byte, "values" : [MOVED_CHILDREN_TAGS_byte_from_Task_enum]}, { "name": new_parent_data-wff-id, "values" : [ new_parent_tag_name, child_data-wff-id, child_tag_name ]} // { "name": 2, "values" : [[3]]}, { "name":"C55", "values" : ["div", "S255", "span"]} //@formatter:on try { final AbstractHtml currentParentTag = event.getCurrentParentTag(); final AbstractHtml movedChildTag = event.getMovedChildTag(); final NameValue task = Task.MOVED_CHILDREN_TAGS.getTaskNameValue(); final DataWffId currentParentDataWffIdAttr = currentParentTag .getDataWffId(); if (currentParentDataWffIdAttr != null) { final NameValue nameValue = new NameValue(); final byte[][] currentParentTagNameAndWffId = DataWffIdUtil .getTagNameAndWffId(currentParentTag); final byte[] parentWffIdBytes = currentParentTagNameAndWffId[1]; nameValue.setName(parentWffIdBytes); final byte[] currentTagName = currentParentTagNameAndWffId[0]; final byte[][] movedChildTagNameAndWffId = DataWffIdUtil .getTagNameAndWffId(movedChildTag); final byte[] movedChildWffIdBytes = movedChildTagNameAndWffId[1]; final byte[] movedChildTagName = movedChildTagNameAndWffId[0]; nameValue.setValues(currentTagName, movedChildWffIdBytes, movedChildTagName); browserPage.push(task, nameValue); addInWffIdMap(movedChildTag); } else { LOGGER.severe( "Could not find data-wff-id from previousParentTag"); } } catch (final UnsupportedEncodingException e) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } } @Override public void childrendAppendedOrMoved(final List<ChildMovedEvent> events) { //@formatter:off // moved children tags from some parents to another task format (in this method moving only one child) :- // { "name": task_byte, "values" : [MOVED_CHILDREN_TAGS_byte_from_Task_enum]}, { "name": new_parent_data-wff-id, "values" : [ new_parent_tag_name, child_data-wff-id, child_tag_name ]} // { "name": 2, "values" : [[3]]}, { "name":"C55", "values" : ["div", "S255", "span"]} //@formatter:on try { final NameValue task = Task.MOVED_CHILDREN_TAGS.getTaskNameValue(); final Deque<NameValue> nameValues = new ArrayDeque<NameValue>(); nameValues.add(task); for (final ChildMovedEvent event : events) { // if previousParentTag == null it means it's appending a new // child tag // this checking is done at client side final AbstractHtml previousParentTag = event .getPreviousParentTag(); final AbstractHtml currentParentTag = event .getCurrentParentTag(); final AbstractHtml movedChildTag = event.getMovedChildTag(); final DataWffId currentParentDataWffIdAttr = currentParentTag .getDataWffId(); if (currentParentDataWffIdAttr != null) { final NameValue nameValue = new NameValue(); final byte[][] currentParentTagNameAndWffId = DataWffIdUtil .getTagNameAndWffId(currentParentTag); final byte[] parentWffIdBytes = currentParentTagNameAndWffId[1]; nameValue.setName(parentWffIdBytes); final byte[] currentTagName = currentParentTagNameAndWffId[0]; final boolean noTag = movedChildTag.getTagName() == null; final byte[][] movedChildTagNameAndWffId = noTag ? DataWffIdUtil.getTagNameAndWffIdForNoTag() : DataWffIdUtil.getTagNameAndWffId(movedChildTag); final byte[] movedChildWffIdBytes = movedChildTagNameAndWffId[1]; final byte[] movedChildTagName = movedChildTagNameAndWffId[0]; if (previousParentTag == null) { try { // if the previousParentTag is null it means it's a // new // tag nameValue.setValues(currentTagName, movedChildWffIdBytes, movedChildTagName, movedChildTag.toWffBMBytes("UTF-8")); } catch (final InvalidTagException e) { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.log(Level.WARNING, "Do not append/add an empty NoTag as child tag, eg: new NoTag(null, \"\").\n" .concat("To make a tag's children as empty then invoke removeAllChildren() method in it."), e); } continue; } } else { nameValue.setValues(currentTagName, movedChildWffIdBytes, movedChildTagName); } nameValues.add(nameValue); addInWffIdMap(movedChildTag); } else { LOGGER.severe( "Could not find data-wff-id from previousParentTag"); } } browserPage .push(nameValues.toArray(new NameValue[nameValues.size()])); } catch (final NoSuchElementException e) { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.log(Level.WARNING, "Do not append/add an empty NoTag as child tag, eg: new NoTag(null, \"\").\n" .concat("To make a tag's children as empty then invoke removeAllChildren() method in it."), e); } } catch (final UnsupportedEncodingException e) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } } }
wffweb/src/main/java/com/webfirmframework/wffweb/server/page/ChildTagAppendListenerImpl.java
/* * Copyright 2014-2017 Web Firm Framework * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.webfirmframework.wffweb.server.page; import java.io.UnsupportedEncodingException; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Collection; import java.util.Deque; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.webfirmframework.wffweb.InvalidTagException; import com.webfirmframework.wffweb.tag.html.AbstractHtml; import com.webfirmframework.wffweb.tag.html.html5.attribute.global.DataWffId; import com.webfirmframework.wffweb.tag.html.listener.ChildTagAppendListener; import com.webfirmframework.wffweb.util.data.NameValue; class ChildTagAppendListenerImpl implements ChildTagAppendListener { private static final long serialVersionUID = 1L; public static final Logger LOGGER = Logger .getLogger(ChildTagRemoveListenerImpl.class.getName()); private Object accessObject; private BrowserPage browserPage; private Map<String, AbstractHtml> tagByWffId; @SuppressWarnings("unused") private ChildTagAppendListenerImpl() { throw new AssertionError(); } ChildTagAppendListenerImpl(final BrowserPage browserPage, final Object accessObject, final Map<String, AbstractHtml> tagByWffId) { this.browserPage = browserPage; this.accessObject = accessObject; this.tagByWffId = tagByWffId; } @Override public void childAppended(final Event event) { try { final AbstractHtml parentTag = event.getParentTag(); final AbstractHtml appendedChildTag = event.getAppendedChildTag(); // add data-wff-id to all tags including nested tags final Deque<Set<AbstractHtml>> childrenStack = new ArrayDeque<Set<AbstractHtml>>(); childrenStack.push(new LinkedHashSet<AbstractHtml>( Arrays.asList(appendedChildTag))); while (childrenStack.size() > 0) { final Set<AbstractHtml> children = childrenStack.pop(); for (final AbstractHtml child : children) { if (child.getDataWffId() == null) { child.setDataWffId(browserPage.getNewDataWffId()); } tagByWffId.put(child.getDataWffId().getValue(), child); final Set<AbstractHtml> subChildren = child .getChildren(accessObject); if (subChildren != null && subChildren.size() > 0) { childrenStack.push(subChildren); } } } final DataWffId dataWffId = parentTag.getDataWffId(); if (dataWffId == null) { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.warning( "Could not find data-wff-id from direct parent tag"); } } //@formatter:off // appended child task format :- // { "name": task_byte, "values" : [invoke_method_byte_from_Task_enum]}, { "name": data-wff-id, "values" : [ parent_tag_name, html_string ]} // { "name": 2, "values" : [[3]]}, { "name":"C55", "values" : ["body", "<div><div></div></div>"]} //@formatter:on final NameValue task = Task.APPENDED_CHILD_TAG.getTaskNameValue(); final NameValue nameValue = new NameValue(); final byte[][] tagNameAndWffId = DataWffIdUtil .getTagNameAndWffId(parentTag); final byte[] parentWffIdBytes = tagNameAndWffId[1]; nameValue.setName(parentWffIdBytes); final byte[] parentTagName = tagNameAndWffId[0]; nameValue.setValues(parentTagName, appendedChildTag.toWffBMBytes("UTF-8")); browserPage.push(task, nameValue); } catch (final InvalidTagException e) { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.log(Level.WARNING, "Do not append/add an empty NoTag as child tag, eg: new NoTag(null, \"\").\n" .concat("To make a tag's children as empty then invoke removeAllChildren() method in it."), e); } } catch (final UnsupportedEncodingException e) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } } @Override public void childrenAppended(final Event event) { try { final AbstractHtml parentTag = event.getParentTag(); final Collection<? extends AbstractHtml> appendedChildTags = event .getAppendedChildrenTags(); // add data-wff-id to all tags including nested tags final Deque<Set<AbstractHtml>> childrenStack = new ArrayDeque<Set<AbstractHtml>>(); childrenStack .push(new LinkedHashSet<AbstractHtml>(appendedChildTags)); while (childrenStack.size() > 0) { final Set<AbstractHtml> children = childrenStack.pop(); for (final AbstractHtml child : children) { if (child.getDataWffId() == null) { child.setDataWffId(browserPage.getNewDataWffId()); } tagByWffId.put(child.getDataWffId().getValue(), child); final Set<AbstractHtml> subChildren = child .getChildren(accessObject); if (subChildren != null && subChildren.size() > 0) { childrenStack.push(subChildren); } } } final DataWffId dataWffId = parentTag.getDataWffId(); if (dataWffId == null && LOGGER.isLoggable(Level.WARNING)) { LOGGER.warning( "Could not find data-wff-id from direct parent tag"); } //@formatter:off // appended child task format :- // { "name": task_byte, "values" : [invoke_method_byte_from_Task_enum]}, { "name": data-wff-id, "values" : [ parent_tag_name, html_string ]} // { "name": 2, "values" : [[3]]}, { "name":"C55", "values" : ["body", "<div><div></div></div>"]} //@formatter:on final NameValue task = Task.APPENDED_CHILDREN_TAGS .getTaskNameValue(); final Deque<NameValue> nameValues = new ArrayDeque<NameValue>(); nameValues.add(task); for (final AbstractHtml appendedChildTag : appendedChildTags) { final NameValue nameValue = new NameValue(); final byte[][] tagNameAndWffId = DataWffIdUtil .getTagNameAndWffId(parentTag); final byte[] parentWffIdBytes = tagNameAndWffId[1]; nameValue.setName(parentWffIdBytes); final byte[] parentTagName = tagNameAndWffId[0]; try { nameValue.setValues(parentTagName, appendedChildTag.toWffBMBytes("UTF-8")); } catch (final InvalidTagException e) { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.log(Level.WARNING, "Do not append/add an empty NoTag as child tag, eg: new NoTag(null, \"\").\n" .concat("To make a tag's children as empty then invoke removeAllChildren() method in it."), e); } continue; } nameValues.add(nameValue); } browserPage .push(nameValues.toArray(new NameValue[nameValues.size()])); } catch (final UnsupportedEncodingException e) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } } /** * adds to wffid map * * @param tag * @since 2.0.0 * @author WFF */ private void addInWffIdMap(final AbstractHtml tag) { final Deque<Set<AbstractHtml>> childrenStack = new ArrayDeque<Set<AbstractHtml>>(); childrenStack.push(new HashSet<AbstractHtml>(Arrays.asList(tag))); while (childrenStack.size() > 0) { final Set<AbstractHtml> children = childrenStack.pop(); for (final AbstractHtml child : children) { final DataWffId wffIdAttr = child.getDataWffId(); if (wffIdAttr != null) { tagByWffId.put(wffIdAttr.getValue(), child); } final Set<AbstractHtml> subChildren = child .getChildren(accessObject); if (subChildren != null && subChildren.size() > 0) { childrenStack.push(subChildren); } } } } @Override public void childMoved(final ChildMovedEvent event) { //@formatter:off // moved children tags from some parents to another task format (in this method moving only one child) :- // { "name": task_byte, "values" : [MOVED_CHILDREN_TAGS_byte_from_Task_enum]}, { "name": new_parent_data-wff-id, "values" : [ new_parent_tag_name, child_data-wff-id, child_tag_name ]} // { "name": 2, "values" : [[3]]}, { "name":"C55", "values" : ["div", "S255", "span"]} //@formatter:on try { final AbstractHtml currentParentTag = event.getCurrentParentTag(); final AbstractHtml movedChildTag = event.getMovedChildTag(); final NameValue task = Task.MOVED_CHILDREN_TAGS.getTaskNameValue(); final DataWffId currentParentDataWffIdAttr = currentParentTag .getDataWffId(); if (currentParentDataWffIdAttr != null) { final NameValue nameValue = new NameValue(); final byte[][] currentParentTagNameAndWffId = DataWffIdUtil .getTagNameAndWffId(currentParentTag); final byte[] parentWffIdBytes = currentParentTagNameAndWffId[1]; nameValue.setName(parentWffIdBytes); final byte[] currentTagName = currentParentTagNameAndWffId[0]; final byte[][] movedChildTagNameAndWffId = DataWffIdUtil .getTagNameAndWffId(movedChildTag); final byte[] movedChildWffIdBytes = movedChildTagNameAndWffId[1]; final byte[] movedChildTagName = movedChildTagNameAndWffId[0]; nameValue.setValues(currentTagName, movedChildWffIdBytes, movedChildTagName); browserPage.push(task, nameValue); addInWffIdMap(movedChildTag); } else { LOGGER.severe( "Could not find data-wff-id from previousParentTag"); } } catch (final UnsupportedEncodingException e) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } } @Override public void childrendAppendedOrMoved(final List<ChildMovedEvent> events) { //@formatter:off // moved children tags from some parents to another task format (in this method moving only one child) :- // { "name": task_byte, "values" : [MOVED_CHILDREN_TAGS_byte_from_Task_enum]}, { "name": new_parent_data-wff-id, "values" : [ new_parent_tag_name, child_data-wff-id, child_tag_name ]} // { "name": 2, "values" : [[3]]}, { "name":"C55", "values" : ["div", "S255", "span"]} //@formatter:on try { final NameValue task = Task.MOVED_CHILDREN_TAGS.getTaskNameValue(); final Deque<NameValue> nameValues = new ArrayDeque<NameValue>(); nameValues.add(task); for (final ChildMovedEvent event : events) { // if previousParentTag == null it means it's appending a new // child tag // this checking is done at client side final AbstractHtml previousParentTag = event .getPreviousParentTag(); final AbstractHtml currentParentTag = event .getCurrentParentTag(); final AbstractHtml movedChildTag = event.getMovedChildTag(); final DataWffId currentParentDataWffIdAttr = currentParentTag .getDataWffId(); if (currentParentDataWffIdAttr != null) { final NameValue nameValue = new NameValue(); final byte[][] currentParentTagNameAndWffId = DataWffIdUtil .getTagNameAndWffId(currentParentTag); final byte[] parentWffIdBytes = currentParentTagNameAndWffId[1]; nameValue.setName(parentWffIdBytes); final byte[] currentTagName = currentParentTagNameAndWffId[0]; final boolean noTag = movedChildTag.getTagName() == null; final byte[][] movedChildTagNameAndWffId = noTag ? DataWffIdUtil.getTagNameAndWffIdForNoTag() : DataWffIdUtil.getTagNameAndWffId(movedChildTag); final byte[] movedChildWffIdBytes = movedChildTagNameAndWffId[1]; final byte[] movedChildTagName = movedChildTagNameAndWffId[0]; if (previousParentTag == null) { try { // if the previousParentTag is null it means it's a // new // tag nameValue.setValues(currentTagName, movedChildWffIdBytes, movedChildTagName, movedChildTag.toWffBMBytes("UTF-8")); } catch (final InvalidTagException e) { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.log(Level.WARNING, "Do not append/add an empty NoTag as child tag, eg: new NoTag(null, \"\").\n" .concat("To make a tag's children as empty then invoke removeAllChildren() method in it."), e); } continue; } } else { nameValue.setValues(currentTagName, movedChildWffIdBytes, movedChildTagName); } nameValues.add(nameValue); addInWffIdMap(movedChildTag); } else { LOGGER.severe( "Could not find data-wff-id from previousParentTag"); } } browserPage .push(nameValues.toArray(new NameValue[nameValues.size()])); } catch (final NoSuchElementException e) { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.log(Level.WARNING, "Do not append/add an empty NoTag as child tag, eg: new NoTag(null, \"\").\n" .concat("To make a tag's children as empty then invoke removeAllChildren() method in it."), e); } } catch (final UnsupportedEncodingException e) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } } }
Minor improvement -- nano optimization
wffweb/src/main/java/com/webfirmframework/wffweb/server/page/ChildTagAppendListenerImpl.java
Minor improvement
Java
apache-2.0
1e3a1c7f7177ca22df9e5ffa1d24d331aabd506e
0
freeVM/freeVM,freeVM/freeVM,freeVM/freeVM,freeVM/freeVM,freeVM/freeVM
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Evgeniya G. Maenkova * @version $Revision$ */ package javax.swing.plaf.basic; import java.awt.AWTKeyStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Insets; import java.awt.KeyboardFocusManager; import java.awt.Point; import java.awt.Rectangle; import java.awt.Shape; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.LinkedHashSet; import java.util.Set; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.InputMap; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.KeyStroke; import javax.swing.LookAndFeel; import javax.swing.SwingUtilities; import javax.swing.TransferHandler; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.MouseInputAdapter; import javax.swing.plaf.ActionMapUIResource; import javax.swing.plaf.ComponentInputMapUIResource; import javax.swing.plaf.InputMapUIResource; import javax.swing.plaf.TextUI; import javax.swing.plaf.UIResource; import javax.swing.text.AbstractDocument; import javax.swing.text.BadLocationException; import javax.swing.text.Caret; import javax.swing.text.DefaultCaret; import javax.swing.text.DefaultEditorKit; import javax.swing.text.DefaultHighlighter; import javax.swing.text.Document; import javax.swing.text.EditorKit; import javax.swing.text.Element; import javax.swing.text.Highlighter; import javax.swing.text.JTextComponent; import javax.swing.text.Keymap; import javax.swing.text.Position; import javax.swing.text.TextAction; import javax.swing.text.View; import javax.swing.text.ViewFactory; import org.apache.harmony.awt.text.RootViewContext; import org.apache.harmony.awt.text.TextFactory; import org.apache.harmony.awt.text.TextUtils; import org.apache.harmony.x.swing.StringConstants; import org.apache.harmony.x.swing.Utilities; import org.apache.harmony.x.swing.internal.nls.Messages; public abstract class BasicTextUI extends TextUI implements ViewFactory { public static class BasicCaret extends DefaultCaret implements UIResource { public BasicCaret() { super(); } } public static class BasicHighlighter extends DefaultHighlighter implements UIResource { public BasicHighlighter() { super(); } } // Text Component, concerned with this BasicTextUI private JTextComponent component; // Editor Kit for all components excluding JTextPane and JEditorPane private static final EditorKit EDITOR_KIT = new DefaultEditorKit(); // The Parent of all view Hierarchy. In never changes. When document // changes, // a child of rootView will be replaced only. private RootViewContext rootViewContext; // PropertyChangeListener, DocumentListener private Listener listener = new Listener(); // Document, concerned with this BasicTextUI (component.getDocument) private Document document; // Simple TransferHandler to support cut, copy, paste operations private static TransferHandler transferHandler; // This flag is used in paintSafely, modelToView, viewToModel methods. private boolean isActive = false; // This flag is used in Listener.InsertUpdate method. It need not to lock // document in DocumentListener. Then modelChanged method defines, it need // to lock document or not private boolean needLock = true; // if document i18n property changes, then ViewHierarchy must be rebuild. private boolean i18nProperty = false; // Action to request focus on Text Component (support FocusAcceleratorKey //on JTextComponent). private final Action focusAction = new RequestFocusAction(); // Key for FOCUS_ACTION in ActionMap private static final String FOCUS_ACTION_NAME = "request-focus"; // Flag is used in UpdateFocus AcceleratorKey method private char lastFocusAccelerator = '\0'; //Listener for drop target private DropListener dropListener; //Initiator for DnD private GestureRecognizer gestureRecognizer; private final RootViewContext.ViewFactoryGetter viewFactoryGetter = new RootViewContext.ViewFactoryGetter() { public ViewFactory getViewFactory() { ViewFactory viewFactory = getEditorKit(component).getViewFactory(); return (viewFactory == null) ? BasicTextUI.this : viewFactory; } }; /** * Action to request focus on Text Component, concerned with this * BasicTextUI */ private class RequestFocusAction extends TextAction { public RequestFocusAction() { super(FOCUS_ACTION_NAME); } public void actionPerformed(final ActionEvent e) { JTextComponent jtc = null; if (e != null && e.getSource() != null) { jtc = (JTextComponent)e.getSource(); } if (jtc != null) { jtc.requestFocusInWindow(); } } } /** * Transfer Handler to support basic transfer operation. It need to redefine * javax.swing.TransferHandler because it doesn't support required * operations. See java.beans (Introspector, BeanInfo,...) */ private static class TextTransferHandler extends TransferHandler implements UIResource { boolean isDrag = false; public boolean canImport(final JComponent comp, final DataFlavor[] dataFlavor) { //Note: temporary solution return true; //super.canImport(arg0, arg1); } public void exportToClipboard(final JComponent c, final Clipboard clip, final int action) { TextUtils.exportToClipboard(TextUtils.getTextKit(c), clip, action); } public boolean importData(final JComponent c, final Transferable t) { if (isDrag || !(c instanceof JTextComponent)) { return false; } return TextUtils.importData(TextUtils.getTextKit(c), t); } protected void exportDone(final JComponent c, final Transferable data, final int action) { isDrag = false; TextUtils.exportDone(TextUtils.getTextKit(c), data, action); } protected Transferable createTransferable(final JComponent c) { return TextUtils.createTransferable(TextUtils.getTextKit(c)); } public int getSourceActions(final JComponent c) { return TextUtils.getSourceActions(TextUtils.getTextKit(c)); } public void exportAsDrag(final JComponent comp, final InputEvent ie, final int action) { isDrag = true; super.exportAsDrag(comp, ie, action); } } private class Listener implements DocumentListener, PropertyChangeListener { /** * Call rootView.changeUpdate */ public void changedUpdate(final DocumentEvent e) { getRootView().changedUpdate(e, getVisibleEditorRect(), getRootView().getViewFactory()); } /** * If "i18n" property of document is changed call modelChanged. * Otherwise, call rooView.insertUpdate */ public void insertUpdate(final DocumentEvent e) { boolean currentI18nProperty = ((Boolean)document .getProperty(StringConstants.BIDI_PROPERTY)).booleanValue(); if (currentI18nProperty && !i18nProperty) { needLock = false; modelChanged(); needLock = true; i18nProperty = true; } else { getRootView().insertUpdate(e, getVisibleEditorRect(), getRootView().getViewFactory()); } } /** * Call rootView.removeUpdate */ public void removeUpdate(final DocumentEvent e) { getRootView().removeUpdate(e, getVisibleEditorRect(), getRootView() .getViewFactory()); } /** * If document is changed on Text Component, handle this event. In * particular remove DocumentListener from old document, add Document * Listener to new document, Rebuild view hierarchy. If * "componentOrientaion" property is changes, call modelChanged. If * JTextComponent.FOCUS_ACCELERATOR_KEY property is changes, call * private method UpdateFocusAcceleratorBinding (to reflect changes on * InputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)). Call propertyChange * method. */ public void propertyChange(final PropertyChangeEvent e) { String name = e.getPropertyName(); if (StringConstants.TEXT_COMPONENT_DOCUMENT_PROPERTY.equals(name)) { if (document != null) { document.removeDocumentListener(listener); } Object doc = e.getNewValue(); if (doc != null) { setDocument((Document)doc); document.addDocumentListener(listener); modelChanged(); } } else if (StringConstants.COMPONENT_ORIENTATION.equals(name)) { modelChanged(); } else if (JTextComponent.FOCUS_ACCELERATOR_KEY.equals(name)) { lastFocusAccelerator = ((Character)e.getOldValue()).charValue(); updateFocusAcceleratorBinding(true); } propertyChangeImpl(e); BasicTextUI.this.propertyChange(e); } } /* * Performs drop, instances of this class are added to * component.getDropTarget() */ final class DropListener implements DropTargetListener { String str = null; int start = 0; int end = 0; JTextComponent textComponent; public void dragEnter(final DropTargetDragEvent e) { } public void dragExit(final DropTargetEvent e) { } public void dragOver(final DropTargetDragEvent e) { /* * Component comp = e.getDropTargetContext().getComponent(); if * (comp == null || ! (comp instanceof JTextComponent)) return; * textComponent = (JTextComponent)comp; Transferable t = * e.getTransferable(); start = textComponent.getSelectionStart(); * end = textComponent.getSelectionEnd(); try { str = (String) t * .getTransferData(DataFlavor.stringFlavor); } catch (final * UnsupportedFlavorException ufe) { } catch (final IOException * ioe) {} */ } public void dropActionChanged(final DropTargetDragEvent arg0) { } public void drop(final DropTargetDropEvent e) { int length = end - start; int insertPosition = textComponent.viewToModel(e.getLocation()); try { textComponent.getDocument().remove(start, length); if (insertPosition > end) { insertPosition -= length; } else { if (insertPosition >= start) { insertPosition = start; } } textComponent.getDocument().insertString(insertPosition, str, null); textComponent.replaceSelection(""); textComponent.setCaretPosition(insertPosition + length); } catch (final BadLocationException ex) { } e.dropComplete(true); } } /* * Initiates DnD, instances of this class are added to current component */ final class GestureRecognizer extends MouseInputAdapter { boolean wasMousePressed = false; public void mousePressed(final MouseEvent arg0) { String selectedText = component.getSelectedText(); if (selectedText != null && selectedText != "" && component.getDragEnabled()) { wasMousePressed = true; } } public void mouseDragged(final MouseEvent me) { if (wasMousePressed) { wasMousePressed = false; component.getTransferHandler() .exportAsDrag(component, me, TransferHandler.MOVE); } } } /** * Creates parent of all view hierarchy. */ public BasicTextUI() { initRootViewContext(null); dropListener = new DropListener(); gestureRecognizer = new GestureRecognizer(); } public View create(final Element elem) { return null; } public View create(final Element elem, final int p0, final int p1) { return null; } protected Caret createCaret() { return new BasicCaret(); } protected Highlighter createHighlighter() { return new BasicHighlighter(); } protected Keymap createKeymap() { String name = getKeymapName(); Keymap keymap = JTextComponent.getKeymap(name); if (keymap == null) { keymap = JTextComponent.addKeymap(name, JTextComponent .getKeymap(JTextComponent.DEFAULT_KEYMAP)); } Object bindings = UIManager.get(addPrefix(".keyBindings")); if (bindings != null) { JTextComponent.loadKeymap(keymap, (JTextComponent.KeyBinding[])bindings, component.getActions()); } return keymap; } public void damageRange(final JTextComponent c, final int p0, final int p1) { damageRange(c, p0, p1, Position.Bias.Forward, Position.Bias.Forward); } /** * Calculates rectangle(r, for example), corresponding these position and * biases. Then call component.repaint(r.x, r.y, r.width, r.height) */ public void damageRange(final JTextComponent c, final int p0, final int p1, final Position.Bias b1, final Position.Bias b2) { Shape shape = null; try { shape = getRootView() .modelToView(p0, b1, p1, b2, getVisibleEditorRect()); } catch (final BadLocationException e) { } Rectangle rect; if (shape != null) { rect = shape.getBounds(); component.repaint(rect.x, rect.y, rect.width, rect.height); } } protected final JTextComponent getComponent() { return component; } /** * Always returns DefaultEditorKit */ public EditorKit getEditorKit(final JTextComponent comp) { return EDITOR_KIT; } protected String getKeymapName() { String className = getClass().getName(); final int lastDot = className.lastIndexOf('.'); return className.substring(lastDot + 1); } public Dimension getMaximumSize(final JComponent c) { //See description for getRootView().getMaximumSpan return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); } /** * Uses getMinimumSpan of View Hierarchy and getInsets of TextComponent */ public Dimension getMinimumSize(final JComponent c) { Insets insets = c.getInsets(); int minX = TextUtils.getHrzInsets(insets) + (int)getRootView().getMinimumSpan(View.X_AXIS); int minY = TextUtils.getVrtInsets(insets) + (int)getRootView().getMinimumSpan(View.Y_AXIS); return new Dimension(minX, minY); } /** * Calls getNextVisualPosition on root view. If root view returns -1, then * this method will return p0 and biasRet[0] will be the same as bias */ public int getNextVisualPositionFrom(final JTextComponent c, final int p0, final Position.Bias bias, final int p1, final Position.Bias[] biasRet) throws BadLocationException { int pos = getRootView().getNextVisualPositionFrom(p0, bias, getVisibleEditorRect(), p1, biasRet); if (pos == -1) { pos = p0; biasRet[0] = bias; } return pos; } /** * Uses getPrefferedSpan of View Hierarchy and getInsets of TextComponent */ public Dimension getPreferredSize(final JComponent c) { Insets insets = c.getInsets(); int prefX = TextUtils.getHrzInsets(insets) + (int)getRootView().getPreferredSpan(View.X_AXIS); int prefY = TextUtils.getVrtInsets(insets) + (int)getRootView().getPreferredSpan(View.Y_AXIS); return new Dimension(prefX, prefY); } protected abstract String getPropertyPrefix(); public View getRootView(final JTextComponent c) { return getRootView(); } public String getToolTipText(final JTextComponent c, final Point p) { Rectangle r = getVisibleEditorRect(); return (r != null) ? getRootView().getToolTipText(p.x, p.y, r) : null; } private TransferHandler getTransferHandler() { if (transferHandler == null) { transferHandler = new TextTransferHandler(); } return transferHandler; } /** * Returns, component getSize, excluding insets. */ protected Rectangle getVisibleEditorRect() { return TextUtils.getEditorRect(component); } final String addPrefix(final String property) { return getPropertyPrefix() + property; } protected void installDefaults() { LookAndFeel.installColorsAndFont(component, addPrefix(".background"), addPrefix(".foreground"), addPrefix(".font")); if (Utilities.isUIResource(component.getBorder())) { component.setBorder(UIManager.getBorder(addPrefix(".border"))); } if (Utilities.isUIResource(component.getMargin())) { component.setMargin(UIManager.getInsets(addPrefix(".margin"))); } //RI 6251901. Documentation error if (Utilities.isUIResource(component.getCaretColor())) { component.setCaretColor(UIManager.getColor(addPrefix( ".caretForeground"))); } if (Utilities.isUIResource(component.getSelectionColor())) { component.setSelectionColor(UIManager.getColor(addPrefix( ".selectionBackground"))); } if (Utilities.isUIResource(component.getSelectedTextColor())) { component.setSelectedTextColor(UIManager .getColor(addPrefix(".selectionForeground"))); } if (Utilities.isUIResource(component.getDisabledTextColor())) { component.setDisabledTextColor(UIManager.getColor(addPrefix( ".inactiveForeground"))); } } final Set<AWTKeyStroke> getDefaultFocusTraversalKeys(final int mode) { Set<AWTKeyStroke> result = component.getFocusTraversalKeys(mode); if (result == null) { result = new LinkedHashSet<AWTKeyStroke>(); if (mode == KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS) { result.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.CTRL_DOWN_MASK)); } else { result.add(KeyStroke .getKeyStroke(KeyEvent.VK_TAB, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK)); } } else { result = new LinkedHashSet<AWTKeyStroke>(result); } return result; } void updateFocusTraversalKeys() { if (component == null) { return; } Set<AWTKeyStroke> forwardFocusTraversalKeys = getDefaultFocusTraversalKeys(KeyboardFocusManager .FORWARD_TRAVERSAL_KEYS); Set<AWTKeyStroke> backwardFocusTraversalKeys = getDefaultFocusTraversalKeys(KeyboardFocusManager .BACKWARD_TRAVERSAL_KEYS); KeyStroke tabPressed = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0); KeyStroke shiftTabPressed = KeyStroke .getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_DOWN_MASK); if (component.isEditable()) { forwardFocusTraversalKeys.remove(tabPressed); backwardFocusTraversalKeys.remove(shiftTabPressed); } else { if (!forwardFocusTraversalKeys.contains(tabPressed)) { forwardFocusTraversalKeys.add(tabPressed); } if (!forwardFocusTraversalKeys.contains(shiftTabPressed)) { backwardFocusTraversalKeys.add(shiftTabPressed); } } component.setFocusTraversalKeys(KeyboardFocusManager .FORWARD_TRAVERSAL_KEYS, forwardFocusTraversalKeys); component.setFocusTraversalKeys(KeyboardFocusManager .BACKWARD_TRAVERSAL_KEYS, backwardFocusTraversalKeys); } final void installUIInputMap() { String propertyName = addPrefix(".focusInputMap"); InputMapUIResource inputMap1 = new InputMapUIResource(); InputMapUIResource inputMap2 = (InputMapUIResource)UIManager .get(propertyName); inputMap1.setParent(inputMap2); SwingUtilities.replaceUIInputMap(component, JComponent.WHEN_FOCUSED, inputMap1); } final void putActionToActionMap(final Action a, final ActionMap map) { Object name = a.getValue(Action.NAME); map.put(name, a); } final void installUIActionMap() { UIDefaults uiDefaults = UIManager.getLookAndFeelDefaults(); String propertyName = getPropertyPrefix() + ".actionMap"; ActionMap actionMap1 = new ActionMapUIResource(); putActionToActionMap(focusAction, actionMap1); Object actionMap2 = uiDefaults.get(propertyName); if (actionMap2 == null) { ActionMapUIResource map = new ActionMapUIResource(); Action[] actions = component.getActions(); for (int i = 0; i < actions.length; i++) { putActionToActionMap(actions[i], map); } putActionToActionMap(TransferHandler.getPasteAction(), map); putActionToActionMap(TransferHandler.getCutAction(), map); putActionToActionMap(TransferHandler.getCopyAction(), map); actionMap2 = map; if (!(component instanceof JEditorPane)) { uiDefaults.put(propertyName, map); } } actionMap1.setParent((ActionMap)actionMap2); SwingUtilities.replaceUIActionMap(component, actionMap1); } /** * Sets InputMap(JComponent.WHEN_FOCUSED), ActionMap, Keymap on * TextComponent. * */ protected void installKeyboardActions() { installUIActionMap(); installUIInputMap(); Keymap keymap = createKeymap(); component.setKeymap(keymap); } protected void installListeners() { } public void installUI(final JComponent c) { if (!(c instanceof JTextComponent)) { throw new Error(Messages.getString("swing.B1")); //$NON-NLS-1$ } super.installUI(c); setComponent((JTextComponent)c); installDefaults(); LookAndFeel.installProperty(component, StringConstants.OPAQUE_PROPERTY, Boolean.TRUE); if (Utilities.isUIResource(component.getCaret())) { Caret caret = createCaret(); component.setCaret(caret); caret.setBlinkRate(UIManager.getInt(getPropertyPrefix() + ".caretBlinkRate")); } if (Utilities.isUIResource(component.getHighlighter())) { component.setHighlighter(createHighlighter()); } if (Utilities.isUIResource(component.getTransferHandler())) { component.setTransferHandler(getTransferHandler()); } if (component.getDocument() == null) { setDocument(getEditorKit(component).createDefaultDocument()); component.setDocument(document); } else { setDocument(component.getDocument()); } modelChanged(); ((AbstractDocument)component.getDocument()) .addDocumentListener(listener); component.addPropertyChangeListener(listener); JTextComponent.addKeymap(getKeymapName(), JTextComponent .getKeymap(JTextComponent.DEFAULT_KEYMAP)); installListeners(); installKeyboardActions(); isActive = true; component.setAutoscrolls(true); updateFocusAcceleratorBinding(true); //DnD support // java.awt.Component doesn't support DnD /* * try { component.getDropTarget().addDropTargetListener(dropListener); * } catch (final TooManyListenersException e){} */ component.addMouseListener(gestureRecognizer); component.addMouseMotionListener(gestureRecognizer); updateFocusTraversalKeys(); } /** * Rebuilts view hierarchy. * */ protected void modelChanged() { final Document doc = document; if (needLock) { readLock(doc); } try { setDocument(document); View view = getRootView().getViewFactory() .create(document.getDefaultRootElement()); setView(view); setViewSize(); } finally { if (needLock) { readUnlock(doc); } } if (component != null) { component.repaint(); } } public Rectangle modelToView(final JTextComponent c, final int p) throws BadLocationException { return modelToView(c, p, Position.Bias.Forward); } public Rectangle modelToView(final JTextComponent comp, final int p, final Position.Bias b) throws BadLocationException { final Document doc = document; readLock(doc); try { Rectangle r = null; if (isActive) { Rectangle rect = getVisibleEditorRect(); if (rect != null) { getRootView().setSize(rect.width, rect.height); Shape shape = getRootView().modelToView(p, rect, b); if (shape != null) { r = shape.getBounds(); } } } return r; } finally { readUnlock(doc); } } public final void paint(final Graphics g, final JComponent c) { //super.paint(g, c);//??? paintSafely(g); } protected void paintBackground(final Graphics g) { Color color = component.getBackground(); if (color != null) { g.setColor(color); } Rectangle rect = getVisibleEditorRect(); if (rect != null) { g.fillRect(rect.x, rect.y, rect.width, rect.height); } } protected void paintSafely(final Graphics g) { if (!isActive) { return; } final Document doc = document; readLock(doc); try { Highlighter highlighter = component.getHighlighter(); Caret caret = component.getCaret(); if (component.isOpaque()) { paintBackground(g); } if (highlighter != null) { highlighter.paint(g); } Rectangle visibleRect = getVisibleEditorRect(); if (visibleRect != null) { getRootView().setSize(visibleRect.width, visibleRect.height); getRootView().paint(g, visibleRect); } caret.paint(g); } finally { readUnlock(doc); } } void propertyChangeImpl(final PropertyChangeEvent e) { if (org.apache.harmony.x.swing.StringConstants.EDITABLE_PROPERTY_CHANGED .equals(e.getPropertyName()) && !e.getOldValue().equals(e.getNewValue())) { updateFocusTraversalKeys(); } } protected void propertyChange(final PropertyChangeEvent e) { } /** * Replaces child of the root view */ protected final void setView(final View v) { component.removeAll(); if (v != null) { getRootView().append(v); } if (component != null) { component.invalidate(); } } protected void uninstallDefaults() { if (Utilities.isUIResource(component.getForeground())) { component.setForeground(null); } if (Utilities.isUIResource(component.getBackground())) { component.setBackground(null); } if (Utilities.isUIResource(component.getFont())) { component.setFont(null); } if (Utilities.isUIResource(component.getBorder())) { component.setBorder(null); } if (Utilities.isUIResource(component.getMargin())) { component.setMargin(null); } if (Utilities.isUIResource(component.getCaretColor())) { component.setCaretColor(null); } if (Utilities.isUIResource(component.getSelectionColor())) { component.setSelectionColor(null); } if (Utilities.isUIResource(component.getSelectedTextColor())) { component.setSelectedTextColor(null); } if (Utilities.isUIResource(component.getDisabledTextColor())) { component.setDisabledTextColor(null); } } /** * Sets ActionMap and Keymap of TextComponent to null. * */ protected void uninstallKeyboardActions() { component.setKeymap(null); SwingUtilities.replaceUIActionMap(component, null); } protected void uninstallListeners() { } public void uninstallUI(final JComponent c) { if (component != c) { return; } isActive = false; super.uninstallUI(c); if (Utilities.isUIResource(component.getCaret())) { component.setCaret(null); } if (Utilities.isUIResource(component.getHighlighter())) { component.setHighlighter(null); } uninstallDefaults(); uninstallKeyboardActions(); uninstallListeners(); ((AbstractDocument) component.getDocument()) .removeDocumentListener(listener); component.removePropertyChangeListener(listener); //DnD support //java.awt.Component doesn't support DnD /* * component.getDropTarget().removeDropTargetListener(dropListener); */ component.removeMouseListener(gestureRecognizer); component.removeMouseMotionListener(gestureRecognizer); setComponent(null); } public void update(final Graphics g, final JComponent c) { super.update(g, c); } final void updateFocusAcceleratorBinding(final boolean changed) { if (!changed) { return; } char accelerator = component.getFocusAccelerator(); InputMap im = SwingUtilities.getUIInputMap(component, JComponent.WHEN_IN_FOCUSED_WINDOW); boolean wasInputMap = (im != null); boolean needToRemove = (lastFocusAccelerator != '\0'); boolean needToAdd = (accelerator != '\0'); if (needToAdd) { if (needToRemove && wasInputMap) { im.remove(KeyStroke.getKeyStroke(lastFocusAccelerator, InputEvent.ALT_DOWN_MASK)); } else if (!wasInputMap) { im = new ComponentInputMapUIResource(component); im.put(KeyStroke.getKeyStroke(accelerator, InputEvent.ALT_DOWN_MASK), FOCUS_ACTION_NAME); if (!wasInputMap) { SwingUtilities.replaceUIInputMap(component, JComponent.WHEN_IN_FOCUSED_WINDOW, im); } } else if (wasInputMap) { im.remove(KeyStroke.getKeyStroke(lastFocusAccelerator, InputEvent.ALT_DOWN_MASK)); } } } public int viewToModel(final JTextComponent c, final Point p) { return viewToModel(c, p, new Position.Bias[1]); } public int viewToModel(final JTextComponent c, final Point p, final Position.Bias[] b) { return getRootView().viewToModel(p.x, p.y, getVisibleEditorRect(), b); } private void setViewSize() { Rectangle rect = getVisibleEditorRect(); if (rect != null) { getRootView().setSize(rect.width, rect.height); } } private void readLock(final Document doc) { if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readLock(); } } private void readUnlock(final Document doc) { if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readUnlock(); } } final boolean getI18nProperty() { return document == null ? false : ((Boolean)document.getProperty(StringConstants.BIDI_PROPERTY)) .booleanValue(); } private View getRootView() { return rootViewContext.getView(); } private void setDocument(final Document document) { this.document = document; rootViewContext.setDocument(document); } private void setComponent(final JTextComponent component) { this.component = component; rootViewContext.setComponent(component); } private void initRootViewContext(final Element elem) { rootViewContext = TextFactory.getTextFactory().createRootView(elem); rootViewContext.setViewFactoryGetter(viewFactoryGetter); setComponent(component); setDocument(document); } }
enhanced/classlib/trunk/modules/swing/src/main/java/common/javax/swing/plaf/basic/BasicTextUI.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Evgeniya G. Maenkova * @version $Revision$ */ package javax.swing.plaf.basic; import java.awt.AWTKeyStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Insets; import java.awt.KeyboardFocusManager; import java.awt.Point; import java.awt.Rectangle; import java.awt.Shape; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.LinkedHashSet; import java.util.Set; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.InputMap; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.KeyStroke; import javax.swing.LookAndFeel; import javax.swing.SwingUtilities; import javax.swing.TransferHandler; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.MouseInputAdapter; import javax.swing.plaf.ActionMapUIResource; import javax.swing.plaf.ComponentInputMapUIResource; import javax.swing.plaf.InputMapUIResource; import javax.swing.plaf.TextUI; import javax.swing.plaf.UIResource; import javax.swing.text.AbstractDocument; import javax.swing.text.BadLocationException; import javax.swing.text.Caret; import javax.swing.text.DefaultCaret; import javax.swing.text.DefaultEditorKit; import javax.swing.text.DefaultHighlighter; import javax.swing.text.Document; import javax.swing.text.EditorKit; import javax.swing.text.Element; import javax.swing.text.Highlighter; import javax.swing.text.JTextComponent; import javax.swing.text.Keymap; import javax.swing.text.Position; import javax.swing.text.TextAction; import javax.swing.text.View; import javax.swing.text.ViewFactory; import org.apache.harmony.awt.text.RootViewContext; import org.apache.harmony.awt.text.TextFactory; import org.apache.harmony.awt.text.TextUtils; import org.apache.harmony.x.swing.StringConstants; import org.apache.harmony.x.swing.Utilities; import org.apache.harmony.x.swing.internal.nls.Messages; public abstract class BasicTextUI extends TextUI implements ViewFactory { public static class BasicCaret extends DefaultCaret implements UIResource { public BasicCaret() { super(); } } public static class BasicHighlighter extends DefaultHighlighter implements UIResource { public BasicHighlighter() { super(); } } // Text Component, concerned with this BasicTextUI private JTextComponent component; // Editor Kit for all components excluding JTextPane and JEditorPane private static final EditorKit EDITOR_KIT = new DefaultEditorKit(); // The Parent of all view Hierarchy. In never changes. When document // changes, // a child of rootView will be replaced only. private RootViewContext rootViewContext; // PropertyChangeListener, DocumentListener private Listener listener = new Listener(); // Document, concerned with this BasicTextUI (component.getDocument) private Document document; // Simple TransferHandler to support cut, copy, paste operations private static TransferHandler transferHandler; // This flag is used in paintSafely, modelToView, viewToModel methods. private boolean isActive = false; // Defined, whether document is instance of AbstractDocument or not. // This flag is calculated only when document is replaced by other. private boolean isAbstractDocument = false; // This flag is used in Listener.InsertUpdate method. It need not to lock // document in DocumentListener. Then modelChanged method defines, it need // to lock document or not private boolean needLock = true; // if document i18n property changes, then ViewHierarchy must be rebuild. private boolean i18nProperty = false; // Action to request focus on Text Component (support FocusAcceleratorKey //on JTextComponent). private final Action focusAction = new RequestFocusAction(); // Key for FOCUS_ACTION in ActionMap private static final String FOCUS_ACTION_NAME = "request-focus"; // Flag is used in UpdateFocus AcceleratorKey method private char lastFocusAccelerator = '\0'; //Listener for drop target private DropListener dropListener; //Initiator for DnD private GestureRecognizer gestureRecognizer; private final RootViewContext.ViewFactoryGetter viewFactoryGetter = new RootViewContext.ViewFactoryGetter() { public ViewFactory getViewFactory() { ViewFactory viewFactory = getEditorKit(component).getViewFactory(); return (viewFactory == null) ? BasicTextUI.this : viewFactory; } }; /** * Action to request focus on Text Component, concerned with this * BasicTextUI */ private class RequestFocusAction extends TextAction { public RequestFocusAction() { super(FOCUS_ACTION_NAME); } public void actionPerformed(final ActionEvent e) { JTextComponent jtc = null; if (e != null && e.getSource() != null) { jtc = (JTextComponent)e.getSource(); } if (jtc != null) { jtc.requestFocusInWindow(); } } } /** * Transfer Handler to support basic transfer operation. It need to redefine * javax.swing.TransferHandler because it doesn't support required * operations. See java.beans (Introspector, BeanInfo,...) */ private static class TextTransferHandler extends TransferHandler implements UIResource { boolean isDrag = false; public boolean canImport(final JComponent comp, final DataFlavor[] dataFlavor) { //Note: temporary solution return true; //super.canImport(arg0, arg1); } public void exportToClipboard(final JComponent c, final Clipboard clip, final int action) { TextUtils.exportToClipboard(TextUtils.getTextKit(c), clip, action); } public boolean importData(final JComponent c, final Transferable t) { if (isDrag || !(c instanceof JTextComponent)) { return false; } return TextUtils.importData(TextUtils.getTextKit(c), t); } protected void exportDone(final JComponent c, final Transferable data, final int action) { isDrag = false; TextUtils.exportDone(TextUtils.getTextKit(c), data, action); } protected Transferable createTransferable(final JComponent c) { return TextUtils.createTransferable(TextUtils.getTextKit(c)); } public int getSourceActions(final JComponent c) { return TextUtils.getSourceActions(TextUtils.getTextKit(c)); } public void exportAsDrag(final JComponent comp, final InputEvent ie, final int action) { isDrag = true; super.exportAsDrag(comp, ie, action); } } private class Listener implements DocumentListener, PropertyChangeListener { /** * Call rootView.changeUpdate */ public void changedUpdate(final DocumentEvent e) { getRootView().changedUpdate(e, getVisibleEditorRect(), getRootView().getViewFactory()); } /** * If "i18n" property of document is changed call modelChanged. * Otherwise, call rooView.insertUpdate */ public void insertUpdate(final DocumentEvent e) { boolean currentI18nProperty = ((Boolean)document .getProperty(StringConstants.BIDI_PROPERTY)).booleanValue(); if (currentI18nProperty && !i18nProperty) { needLock = false; modelChanged(); needLock = true; i18nProperty = true; } else { getRootView().insertUpdate(e, getVisibleEditorRect(), getRootView().getViewFactory()); } } /** * Call rootView.removeUpdate */ public void removeUpdate(final DocumentEvent e) { getRootView().removeUpdate(e, getVisibleEditorRect(), getRootView() .getViewFactory()); } /** * If document is changed on Text Component, handle this event. In * particular remove DocumentListener from old document, add Document * Listener to new document, Rebuild view hierarchy. If * "componentOrientaion" property is changes, call modelChanged. If * JTextComponent.FOCUS_ACCELERATOR_KEY property is changes, call * private method UpdateFocusAcceleratorBinding (to reflect changes on * InputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)). Call propertyChange * method. */ public void propertyChange(final PropertyChangeEvent e) { String name = e.getPropertyName(); if (StringConstants.TEXT_COMPONENT_DOCUMENT_PROPERTY.equals(name)) { if (document != null) { document.removeDocumentListener(listener); isAbstractDocument = false; } Object doc = e.getNewValue(); if (doc != null) { setDocument((Document)doc); document.addDocumentListener(listener); isAbstractDocument = (document instanceof AbstractDocument); modelChanged(); } } else if (StringConstants.COMPONENT_ORIENTATION.equals(name)) { modelChanged(); } else if (JTextComponent.FOCUS_ACCELERATOR_KEY.equals(name)) { lastFocusAccelerator = ((Character)e.getOldValue()).charValue(); updateFocusAcceleratorBinding(true); } propertyChangeImpl(e); BasicTextUI.this.propertyChange(e); } } /* * Performs drop, instances of this class are added to * component.getDropTarget() */ final class DropListener implements DropTargetListener { String str = null; int start = 0; int end = 0; JTextComponent textComponent; public void dragEnter(final DropTargetDragEvent e) { } public void dragExit(final DropTargetEvent e) { } public void dragOver(final DropTargetDragEvent e) { /* * Component comp = e.getDropTargetContext().getComponent(); if * (comp == null || ! (comp instanceof JTextComponent)) return; * textComponent = (JTextComponent)comp; Transferable t = * e.getTransferable(); start = textComponent.getSelectionStart(); * end = textComponent.getSelectionEnd(); try { str = (String) t * .getTransferData(DataFlavor.stringFlavor); } catch (final * UnsupportedFlavorException ufe) { } catch (final IOException * ioe) {} */ } public void dropActionChanged(final DropTargetDragEvent arg0) { } public void drop(final DropTargetDropEvent e) { int length = end - start; int insertPosition = textComponent.viewToModel(e.getLocation()); try { textComponent.getDocument().remove(start, length); if (insertPosition > end) { insertPosition -= length; } else { if (insertPosition >= start) { insertPosition = start; } } textComponent.getDocument().insertString(insertPosition, str, null); textComponent.replaceSelection(""); textComponent.setCaretPosition(insertPosition + length); } catch (final BadLocationException ex) { } e.dropComplete(true); } } /* * Initiates DnD, instances of this class are added to current component */ final class GestureRecognizer extends MouseInputAdapter { boolean wasMousePressed = false; public void mousePressed(final MouseEvent arg0) { String selectedText = component.getSelectedText(); if (selectedText != null && selectedText != "" && component.getDragEnabled()) { wasMousePressed = true; } } public void mouseDragged(final MouseEvent me) { if (wasMousePressed) { wasMousePressed = false; component.getTransferHandler() .exportAsDrag(component, me, TransferHandler.MOVE); } } } /** * Creates parent of all view hierarchy. */ public BasicTextUI() { initRootViewContext(null); dropListener = new DropListener(); gestureRecognizer = new GestureRecognizer(); } public View create(final Element elem) { return null; } public View create(final Element elem, final int p0, final int p1) { return null; } protected Caret createCaret() { return new BasicCaret(); } protected Highlighter createHighlighter() { return new BasicHighlighter(); } protected Keymap createKeymap() { String name = getKeymapName(); Keymap keymap = JTextComponent.getKeymap(name); if (keymap == null) { keymap = JTextComponent.addKeymap(name, JTextComponent .getKeymap(JTextComponent.DEFAULT_KEYMAP)); } Object bindings = UIManager.get(addPrefix(".keyBindings")); if (bindings != null) { JTextComponent.loadKeymap(keymap, (JTextComponent.KeyBinding[])bindings, component.getActions()); } return keymap; } public void damageRange(final JTextComponent c, final int p0, final int p1) { damageRange(c, p0, p1, Position.Bias.Forward, Position.Bias.Forward); } /** * Calculates rectangle(r, for example), corresponding these position and * biases. Then call component.repaint(r.x, r.y, r.width, r.height) */ public void damageRange(final JTextComponent c, final int p0, final int p1, final Position.Bias b1, final Position.Bias b2) { Shape shape = null; try { shape = getRootView() .modelToView(p0, b1, p1, b2, getVisibleEditorRect()); } catch (final BadLocationException e) { } Rectangle rect; if (shape != null) { rect = shape.getBounds(); component.repaint(rect.x, rect.y, rect.width, rect.height); } } protected final JTextComponent getComponent() { return component; } /** * Always returns DefaultEditorKit */ public EditorKit getEditorKit(final JTextComponent comp) { return EDITOR_KIT; } protected String getKeymapName() { String className = getClass().getName(); final int lastDot = className.lastIndexOf('.'); return className.substring(lastDot + 1); } public Dimension getMaximumSize(final JComponent c) { //See description for getRootView().getMaximumSpan return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); } /** * Uses getMinimumSpan of View Hierarchy and getInsets of TextComponent */ public Dimension getMinimumSize(final JComponent c) { Insets insets = c.getInsets(); int minX = TextUtils.getHrzInsets(insets) + (int)getRootView().getMinimumSpan(View.X_AXIS); int minY = TextUtils.getVrtInsets(insets) + (int)getRootView().getMinimumSpan(View.Y_AXIS); return new Dimension(minX, minY); } /** * Calls getNextVisualPosition on root view. If root view returns -1, then * this method will return p0 and biasRet[0] will be the same as bias */ public int getNextVisualPositionFrom(final JTextComponent c, final int p0, final Position.Bias bias, final int p1, final Position.Bias[] biasRet) throws BadLocationException { int pos = getRootView().getNextVisualPositionFrom(p0, bias, getVisibleEditorRect(), p1, biasRet); if (pos == -1) { pos = p0; biasRet[0] = bias; } return pos; } /** * Uses getPrefferedSpan of View Hierarchy and getInsets of TextComponent */ public Dimension getPreferredSize(final JComponent c) { Insets insets = c.getInsets(); int prefX = TextUtils.getHrzInsets(insets) + (int)getRootView().getPreferredSpan(View.X_AXIS); int prefY = TextUtils.getVrtInsets(insets) + (int)getRootView().getPreferredSpan(View.Y_AXIS); return new Dimension(prefX, prefY); } protected abstract String getPropertyPrefix(); public View getRootView(final JTextComponent c) { return getRootView(); } public String getToolTipText(final JTextComponent c, final Point p) { Rectangle r = getVisibleEditorRect(); return (r != null) ? getRootView().getToolTipText(p.x, p.y, r) : null; } private TransferHandler getTransferHandler() { if (transferHandler == null) { transferHandler = new TextTransferHandler(); } return transferHandler; } /** * Returns, component getSize, excluding insets. */ protected Rectangle getVisibleEditorRect() { return TextUtils.getEditorRect(component); } final String addPrefix(final String property) { return getPropertyPrefix() + property; } protected void installDefaults() { LookAndFeel.installColorsAndFont(component, addPrefix(".background"), addPrefix(".foreground"), addPrefix(".font")); if (Utilities.isUIResource(component.getBorder())) { component.setBorder(UIManager.getBorder(addPrefix(".border"))); } if (Utilities.isUIResource(component.getMargin())) { component.setMargin(UIManager.getInsets(addPrefix(".margin"))); } //RI 6251901. Documentation error if (Utilities.isUIResource(component.getCaretColor())) { component.setCaretColor(UIManager.getColor(addPrefix( ".caretForeground"))); } if (Utilities.isUIResource(component.getSelectionColor())) { component.setSelectionColor(UIManager.getColor(addPrefix( ".selectionBackground"))); } if (Utilities.isUIResource(component.getSelectedTextColor())) { component.setSelectedTextColor(UIManager .getColor(addPrefix(".selectionForeground"))); } if (Utilities.isUIResource(component.getDisabledTextColor())) { component.setDisabledTextColor(UIManager.getColor(addPrefix( ".inactiveForeground"))); } } final Set<AWTKeyStroke> getDefaultFocusTraversalKeys(final int mode) { Set<AWTKeyStroke> result = component.getFocusTraversalKeys(mode); if (result == null) { result = new LinkedHashSet<AWTKeyStroke>(); if (mode == KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS) { result.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.CTRL_DOWN_MASK)); } else { result.add(KeyStroke .getKeyStroke(KeyEvent.VK_TAB, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK)); } } else { result = new LinkedHashSet<AWTKeyStroke>(result); } return result; } void updateFocusTraversalKeys() { if (component == null) { return; } Set<AWTKeyStroke> forwardFocusTraversalKeys = getDefaultFocusTraversalKeys(KeyboardFocusManager .FORWARD_TRAVERSAL_KEYS); Set<AWTKeyStroke> backwardFocusTraversalKeys = getDefaultFocusTraversalKeys(KeyboardFocusManager .BACKWARD_TRAVERSAL_KEYS); KeyStroke tabPressed = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0); KeyStroke shiftTabPressed = KeyStroke .getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_DOWN_MASK); if (component.isEditable()) { forwardFocusTraversalKeys.remove(tabPressed); backwardFocusTraversalKeys.remove(shiftTabPressed); } else { if (!forwardFocusTraversalKeys.contains(tabPressed)) { forwardFocusTraversalKeys.add(tabPressed); } if (!forwardFocusTraversalKeys.contains(shiftTabPressed)) { backwardFocusTraversalKeys.add(shiftTabPressed); } } component.setFocusTraversalKeys(KeyboardFocusManager .FORWARD_TRAVERSAL_KEYS, forwardFocusTraversalKeys); component.setFocusTraversalKeys(KeyboardFocusManager .BACKWARD_TRAVERSAL_KEYS, backwardFocusTraversalKeys); } final void installUIInputMap() { String propertyName = addPrefix(".focusInputMap"); InputMapUIResource inputMap1 = new InputMapUIResource(); InputMapUIResource inputMap2 = (InputMapUIResource)UIManager .get(propertyName); inputMap1.setParent(inputMap2); SwingUtilities.replaceUIInputMap(component, JComponent.WHEN_FOCUSED, inputMap1); } final void putActionToActionMap(final Action a, final ActionMap map) { Object name = a.getValue(Action.NAME); map.put(name, a); } final void installUIActionMap() { UIDefaults uiDefaults = UIManager.getLookAndFeelDefaults(); String propertyName = getPropertyPrefix() + ".actionMap"; ActionMap actionMap1 = new ActionMapUIResource(); putActionToActionMap(focusAction, actionMap1); Object actionMap2 = uiDefaults.get(propertyName); if (actionMap2 == null) { ActionMapUIResource map = new ActionMapUIResource(); Action[] actions = component.getActions(); for (int i = 0; i < actions.length; i++) { putActionToActionMap(actions[i], map); } putActionToActionMap(TransferHandler.getPasteAction(), map); putActionToActionMap(TransferHandler.getCutAction(), map); putActionToActionMap(TransferHandler.getCopyAction(), map); actionMap2 = map; if (!(component instanceof JEditorPane)) { uiDefaults.put(propertyName, map); } } actionMap1.setParent((ActionMap)actionMap2); SwingUtilities.replaceUIActionMap(component, actionMap1); } /** * Sets InputMap(JComponent.WHEN_FOCUSED), ActionMap, Keymap on * TextComponent. * */ protected void installKeyboardActions() { installUIActionMap(); installUIInputMap(); Keymap keymap = createKeymap(); component.setKeymap(keymap); } protected void installListeners() { } public void installUI(final JComponent c) { if (!(c instanceof JTextComponent)) { throw new Error(Messages.getString("swing.B1")); //$NON-NLS-1$ } super.installUI(c); setComponent((JTextComponent)c); installDefaults(); LookAndFeel.installProperty(component, StringConstants.OPAQUE_PROPERTY, Boolean.TRUE); if (Utilities.isUIResource(component.getCaret())) { Caret caret = createCaret(); component.setCaret(caret); caret.setBlinkRate(UIManager.getInt(getPropertyPrefix() + ".caretBlinkRate")); } if (Utilities.isUIResource(component.getHighlighter())) { component.setHighlighter(createHighlighter()); } if (Utilities.isUIResource(component.getTransferHandler())) { component.setTransferHandler(getTransferHandler()); } if (component.getDocument() == null) { setDocument(getEditorKit(component).createDefaultDocument()); component.setDocument(document); } else { setDocument(component.getDocument()); } isAbstractDocument = (document instanceof AbstractDocument); modelChanged(); ((AbstractDocument)component.getDocument()) .addDocumentListener(listener); component.addPropertyChangeListener(listener); JTextComponent.addKeymap(getKeymapName(), JTextComponent .getKeymap(JTextComponent.DEFAULT_KEYMAP)); installListeners(); installKeyboardActions(); isActive = true; component.setAutoscrolls(true); updateFocusAcceleratorBinding(true); //DnD support // java.awt.Component doesn't support DnD /* * try { component.getDropTarget().addDropTargetListener(dropListener); * } catch (final TooManyListenersException e){} */ component.addMouseListener(gestureRecognizer); component.addMouseMotionListener(gestureRecognizer); updateFocusTraversalKeys(); } /** * Rebuilts view hierarchy. * */ protected void modelChanged() { if (needLock) { readLock(); } try { setDocument(document); View view = getRootView().getViewFactory() .create(document.getDefaultRootElement()); setView(view); setViewSize(); } finally { if (needLock) { readUnlock(); } } if (component != null) { component.repaint(); } } public Rectangle modelToView(final JTextComponent c, final int p) throws BadLocationException { return modelToView(c, p, Position.Bias.Forward); } public Rectangle modelToView(final JTextComponent comp, final int p, final Position.Bias b) throws BadLocationException { readLock(); try { Rectangle r = null; if (isActive) { Rectangle rect = getVisibleEditorRect(); if (rect != null) { getRootView().setSize(rect.width, rect.height); Shape shape = getRootView().modelToView(p, rect, b); if (shape != null) { r = shape.getBounds(); } } } return r; } finally { readUnlock(); } } public final void paint(final Graphics g, final JComponent c) { //super.paint(g, c);//??? paintSafely(g); } protected void paintBackground(final Graphics g) { Color color = component.getBackground(); if (color != null) { g.setColor(color); } Rectangle rect = getVisibleEditorRect(); if (rect != null) { g.fillRect(rect.x, rect.y, rect.width, rect.height); } } protected void paintSafely(final Graphics g) { if (!isActive) { return; } readLock(); try { Highlighter highlighter = component.getHighlighter(); Caret caret = component.getCaret(); if (component.isOpaque()) { paintBackground(g); } if (highlighter != null) { highlighter.paint(g); } Rectangle visibleRect = getVisibleEditorRect(); if (visibleRect != null) { getRootView().setSize(visibleRect.width, visibleRect.height); getRootView().paint(g, visibleRect); } caret.paint(g); } finally { readUnlock(); } } void propertyChangeImpl(final PropertyChangeEvent e) { if (org.apache.harmony.x.swing.StringConstants.EDITABLE_PROPERTY_CHANGED .equals(e.getPropertyName()) && !e.getOldValue().equals(e.getNewValue())) { updateFocusTraversalKeys(); } } protected void propertyChange(final PropertyChangeEvent e) { } /** * Replaces child of the root view */ protected final void setView(final View v) { component.removeAll(); if (v != null) { getRootView().append(v); } if (component != null) { component.invalidate(); } } protected void uninstallDefaults() { if (Utilities.isUIResource(component.getForeground())) { component.setForeground(null); } if (Utilities.isUIResource(component.getBackground())) { component.setBackground(null); } if (Utilities.isUIResource(component.getFont())) { component.setFont(null); } if (Utilities.isUIResource(component.getBorder())) { component.setBorder(null); } if (Utilities.isUIResource(component.getMargin())) { component.setMargin(null); } if (Utilities.isUIResource(component.getCaretColor())) { component.setCaretColor(null); } if (Utilities.isUIResource(component.getSelectionColor())) { component.setSelectionColor(null); } if (Utilities.isUIResource(component.getSelectedTextColor())) { component.setSelectedTextColor(null); } if (Utilities.isUIResource(component.getDisabledTextColor())) { component.setDisabledTextColor(null); } } /** * Sets ActionMap and Keymap of TextComponent to null. * */ protected void uninstallKeyboardActions() { component.setKeymap(null); SwingUtilities.replaceUIActionMap(component, null); } protected void uninstallListeners() { } public void uninstallUI(final JComponent c) { if (component != c) { return; } isActive = false; super.uninstallUI(c); if (Utilities.isUIResource(component.getCaret())) { component.setCaret(null); } if (Utilities.isUIResource(component.getHighlighter())) { component.setHighlighter(null); } uninstallDefaults(); uninstallKeyboardActions(); uninstallListeners(); ((AbstractDocument) component.getDocument()) .removeDocumentListener(listener); component.removePropertyChangeListener(listener); //DnD support //java.awt.Component doesn't support DnD /* * component.getDropTarget().removeDropTargetListener(dropListener); */ component.removeMouseListener(gestureRecognizer); component.removeMouseMotionListener(gestureRecognizer); setComponent(null); } public void update(final Graphics g, final JComponent c) { super.update(g, c); } final void updateFocusAcceleratorBinding(final boolean changed) { if (!changed) { return; } char accelerator = component.getFocusAccelerator(); InputMap im = SwingUtilities.getUIInputMap(component, JComponent.WHEN_IN_FOCUSED_WINDOW); boolean wasInputMap = (im != null); boolean needToRemove = (lastFocusAccelerator != '\0'); boolean needToAdd = (accelerator != '\0'); if (needToAdd) { if (needToRemove && wasInputMap) { im.remove(KeyStroke.getKeyStroke(lastFocusAccelerator, InputEvent.ALT_DOWN_MASK)); } else if (!wasInputMap) { im = new ComponentInputMapUIResource(component); im.put(KeyStroke.getKeyStroke(accelerator, InputEvent.ALT_DOWN_MASK), FOCUS_ACTION_NAME); if (!wasInputMap) { SwingUtilities.replaceUIInputMap(component, JComponent.WHEN_IN_FOCUSED_WINDOW, im); } } else if (wasInputMap) { im.remove(KeyStroke.getKeyStroke(lastFocusAccelerator, InputEvent.ALT_DOWN_MASK)); } } } public int viewToModel(final JTextComponent c, final Point p) { return viewToModel(c, p, new Position.Bias[1]); } public int viewToModel(final JTextComponent c, final Point p, final Position.Bias[] b) { return getRootView().viewToModel(p.x, p.y, getVisibleEditorRect(), b); } private void setViewSize() { Rectangle rect = getVisibleEditorRect(); if (rect != null) { getRootView().setSize(rect.width, rect.height); } } private void readLock() { if (isAbstractDocument) { ((AbstractDocument)document).readLock(); } } private void readUnlock() { if (isAbstractDocument) { ((AbstractDocument)document).readUnlock(); } } final boolean getI18nProperty() { return document == null ? false : ((Boolean)document.getProperty(StringConstants.BIDI_PROPERTY)) .booleanValue(); } private View getRootView() { return rootViewContext.getView(); } private void setDocument(final Document document) { this.document = document; rootViewContext.setDocument(document); } private void setComponent(final JTextComponent component) { this.component = component; rootViewContext.setComponent(component); } private void initRootViewContext(final Element elem) { rootViewContext = TextFactory.getTextFactory().createRootView(elem); rootViewContext.setViewFactoryGetter(viewFactoryGetter); setComponent(component); setDocument(document); } }
Applying patch from HARMONY-4762 ([classlib][swing][html] Flaw in thread synchronization in BasicTextUI) svn path=/harmony/; revision=584810
enhanced/classlib/trunk/modules/swing/src/main/java/common/javax/swing/plaf/basic/BasicTextUI.java
Applying patch from HARMONY-4762 ([classlib][swing][html] Flaw in thread synchronization in BasicTextUI)
Java
apache-2.0
fd7a62b6d82315ed4a2e098a983831d1146df40a
0
egonw/pathvisio,egonw/pathvisio,egonw/pathvisio,egonw/pathvisio,egonw/pathvisio
//package components; /* * SimpleTableDemo.java requires no other files. */ import javax.swing.AbstractButton; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import org.apache.xmlrpc.XmlRpcException; import org.pathvisio.data.DataException; import org.pathvisio.model.ConverterException; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; public class showMenuGUI extends JPanel { public static void main(String[] args) { /** * in the String[] args, 2 arguments are given: * in example: * "C:\\databases\\" * "C:\pathways" * * The first one is the directory that contains the databases. * The second one is the directory that contains the pathway cache. */ final String[] arguments=args; final String dbDir; final File pwDir; final String outfile; try { dbDir = new String(args[0]+"Rn_39_34i.pgdb"); pwDir = new File(args[1]+"\\Rattus_norvegicus"); outfile=args[2]; javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowMenuGUI(arguments); } }); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("String[] args not given!"); System.exit(0); } } public static void createAndShowMenuGUI(String[] arguments){ // create a new frame JFrame frame = new JFrame("Main Menu"); // When click on exit, exit the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // set the size of the frame frame.setSize(400,300); // create a new panel JPanel canvasTop=new JPanel(); JPanel canvasButtons=canvasButtons(arguments); JPanel canvasCloseButton=canvasCloseButton(); JLabel label = new JLabel("Main Menu"); canvasTop.add(label); // add the canvas to the frame frame.add(canvasTop, BorderLayout.NORTH); frame.add(canvasButtons, BorderLayout.CENTER); frame.add(canvasCloseButton, BorderLayout.SOUTH); // Show the frame frame.setVisible(true); } public static JPanel canvasButtons(final String[] arguments){ final String dbDirRn = new String(arguments[0]+"Rn_39_34i.pgdb"); final File pwDirRn = new File(arguments[1]+"\\Rattus_norvegicus"); // create a new panel JPanel canvasButtons = new JPanel(); // create two new buttons, using the makeButton method JButton PomButton = makeBigButton("Pathway overlap Matrix"); JButton LCButton = makeBigButton("Link Checker"); JButton PugButton = makeBigButton("Percentage used genes"); JButton GtdButton = makeBigButton("Go Term Distribution"); // add the functionality to the Pathway overlap Matrix button PomButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent ae){ System.out.println("Go to Pathway overlap Matrix"); showOverlapGUI.createAndShowOverlapGUI(dbDirRn,pwDirRn,arguments); } } ); // add the functionality to the Link Checker button LCButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent ae){ System.out.println("Go to Link Checker"); /*String[] arguments={"C:\\databases\\", "C:\\pathways", "C:\\result.html"};*/ try { LinkChecker.main(arguments); } catch (ConverterException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (DataException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (XmlRpcException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ); // add the functionality to the Go Term Distribution button PugButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent ae){ System.out.println("Go to Percentage of used genes at WikiPathways"); ShowPercentageGUI.createAndShowPercentageGUI(dbDirRn,pwDirRn,arguments); } } ); // add the functionality to the Go Term Distribution button GtdButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent ae){ System.out.println("The Go Term Distribution function is not available"); } } ); // add the buttons to the canvas canvasButtons.add(LCButton); canvasButtons.add(PomButton); canvasButtons.add(PugButton); canvasButtons.add(GtdButton); return canvasButtons; } public static JPanel canvasCloseButton(){ // create a new panel JPanel canvasCloseButton = new JPanel(); // create two new buttons, using the makeButton method JButton closeButton = TestFrames.makeButton("Close"); // add the functionality to the close button closeButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent ae){ System.exit(0); } } ); // add the buttons to the canvas canvasCloseButton.add(closeButton); return canvasCloseButton; } /** * create a new JButton of a preferred size, and with the text centered. */ public static JButton makeBigButton(String name){ // create a new button JButton button = new JButton(name); // set the size of the button Dimension sizeButton = new Dimension(180,30); button.setPreferredSize(sizeButton); // center the text (horizontally and vertically) in the button button.setVerticalTextPosition(AbstractButton.CENTER); button.setHorizontalTextPosition(AbstractButton.CENTER); // return the button return button; } }
tools/project2008/showMenuGUI.java
//package components; /* * SimpleTableDemo.java requires no other files. */ import javax.swing.AbstractButton; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import org.apache.xmlrpc.XmlRpcException; import org.pathvisio.data.DataException; import org.pathvisio.model.ConverterException; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; public class showMenuGUI extends JPanel { public static void main(String[] args) { /** * in the String[] args, 2 arguments are given: * in example: * "C:\\databases\\" * "C:\pathways" * * The first one is the directory that contains the databases. * The second one is the directory that contains the pathway cache. */ final String[] arguments=args; final String dbDir; final File pwDir; try { dbDir = new String(args[0]+"Rn_39_34i.pgdb"); pwDir = new File(args[1]+"\\Rattus_norvegicus"); javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowMenuGUI(dbDir,pwDir); } }); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("String[] args not given!"); System.exit(0); } } public static void createAndShowMenuGUI(final String dbDir,final File pwDir){ // create a new frame JFrame frame = new JFrame("Main Menu"); // When click on exit, exit the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // set the size of the frame frame.setSize(400,300); // create a new panel JPanel canvasTop=new JPanel(); JPanel canvasButtons=canvasButtons(dbDir,pwDir); JPanel canvasCloseButton=canvasCloseButton(); JLabel label = new JLabel("Main Menu"); canvasTop.add(label); // add the canvas to the frame frame.add(canvasTop, BorderLayout.NORTH); frame.add(canvasButtons, BorderLayout.CENTER); frame.add(canvasCloseButton, BorderLayout.SOUTH); // Show the frame frame.setVisible(true); } public static JPanel canvasButtons(final String dbDir,final File pwDir){ // create a new panel JPanel canvasButtons = new JPanel(); // create two new buttons, using the makeButton method JButton PomButton = makeBigButton("Pathway overlap Matrix"); JButton LCButton = makeBigButton("Link Checker"); JButton PugButton = makeBigButton("Percentage used genes"); JButton GtdButton = makeBigButton("Go Term Distribution"); // add the functionality to the Pathway overlap Matrix button PomButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent ae){ System.out.println("Go to Pathway overlap Matrix"); showOverlapGUI.createAndShowOverlapGUI(dbDir,pwDir); } } ); // add the functionality to the Link Checker button LCButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent ae){ System.out.println("Go to Link Checker"); String[] arguments={"C:\\databases\\", "C:\\pathways", "C:\\result.html"}; try { LinkChecker.main(arguments); } catch (ConverterException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (DataException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (XmlRpcException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ); // add the functionality to the Go Term Distribution button PugButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent ae){ ShowPercentageGUI.createAndShowPercentageGUI(dbDir,pwDir); } } ); // add the functionality to the Go Term Distribution button GtdButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent ae){ System.out.println("The Go Term Distribution function is not available"); } } ); // add the buttons to the canvas canvasButtons.add(LCButton); canvasButtons.add(PomButton); canvasButtons.add(PugButton); canvasButtons.add(GtdButton); return canvasButtons; } public static JPanel canvasCloseButton(){ // create a new panel JPanel canvasCloseButton = new JPanel(); // create two new buttons, using the makeButton method JButton closeButton = TestFrames.makeButton("Close"); // add the functionality to the close button closeButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent ae){ System.exit(0); } } ); // add the buttons to the canvas canvasCloseButton.add(closeButton); return canvasCloseButton; } /** * create a new JButton of a preferred size, and with the text centered. */ public static JButton makeBigButton(String name){ // create a new button JButton button = new JButton(name); // set the size of the button Dimension sizeButton = new Dimension(180,30); button.setPreferredSize(sizeButton); // center the text (horizontally and vertically) in the button button.setVerticalTextPosition(AbstractButton.CENTER); button.setHorizontalTextPosition(AbstractButton.CENTER); // return the button return button; } }
git-svn-id: http://svn.bigcat.unimaas.nl/pathvisio/trunk@1705 4f21837e-9f06-0410-ae49-bac5c3a7b9b6
tools/project2008/showMenuGUI.java
Java
apache-2.0
40374fd825553e7570a049f86d63a5934009fa5c
0
semonte/intellij-community,hurricup/intellij-community,retomerz/intellij-community,da1z/intellij-community,signed/intellij-community,allotria/intellij-community,da1z/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,retomerz/intellij-community,semonte/intellij-community,fitermay/intellij-community,allotria/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,apixandru/intellij-community,FHannes/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,apixandru/intellij-community,FHannes/intellij-community,semonte/intellij-community,allotria/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,retomerz/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,apixandru/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,ibinti/intellij-community,xfournet/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,signed/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,hurricup/intellij-community,signed/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,hurricup/intellij-community,FHannes/intellij-community,signed/intellij-community,da1z/intellij-community,da1z/intellij-community,xfournet/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,ibinti/intellij-community,apixandru/intellij-community,fitermay/intellij-community,asedunov/intellij-community,ibinti/intellij-community,asedunov/intellij-community,fitermay/intellij-community,signed/intellij-community,apixandru/intellij-community,FHannes/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,allotria/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,retomerz/intellij-community,semonte/intellij-community,semonte/intellij-community,semonte/intellij-community,asedunov/intellij-community,da1z/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,da1z/intellij-community,FHannes/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,da1z/intellij-community,asedunov/intellij-community,ibinti/intellij-community,FHannes/intellij-community,retomerz/intellij-community,allotria/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,semonte/intellij-community,FHannes/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,FHannes/intellij-community,semonte/intellij-community,xfournet/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,allotria/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,hurricup/intellij-community,retomerz/intellij-community,apixandru/intellij-community,da1z/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,signed/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,semonte/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,da1z/intellij-community,hurricup/intellij-community,semonte/intellij-community,xfournet/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,xfournet/intellij-community,da1z/intellij-community
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.psi; import com.google.common.collect.Collections2; import com.google.common.collect.Maps; import com.intellij.codeInsight.FileModificationService; import com.intellij.codeInsight.completion.PrioritizedLookupElement; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.ide.fileTemplates.FileTemplate; import com.intellij.ide.fileTemplates.FileTemplateManager; import com.intellij.ide.scratch.ScratchFileService; import com.intellij.injected.editor.VirtualFileWindow; import com.intellij.lang.ASTFactory; import com.intellij.lang.ASTNode; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.highlighter.EditorHighlighter; import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.WindowManager; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtilCore; import com.intellij.psi.util.QualifiedName; import com.intellij.ui.awt.RelativePoint; import com.intellij.util.*; import com.intellij.util.containers.ContainerUtil; import com.jetbrains.NotNullPredicate; import com.jetbrains.python.PyBundle; import com.jetbrains.python.PyNames; import com.jetbrains.python.PyTokenTypes; import com.jetbrains.python.codeInsight.completion.OverwriteEqualsInsertHandler; import com.jetbrains.python.codeInsight.controlflow.ScopeOwner; import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil; import com.jetbrains.python.codeInsight.stdlib.PyNamedTupleType; import com.jetbrains.python.formatter.PyCodeStyleSettings; import com.jetbrains.python.magicLiteral.PyMagicLiteralTools; import com.jetbrains.python.psi.impl.PyBuiltinCache; import com.jetbrains.python.psi.impl.PyPsiUtils; import com.jetbrains.python.psi.impl.PyStringLiteralExpressionImpl; import com.jetbrains.python.psi.impl.PythonLanguageLevelPusher; import com.jetbrains.python.psi.resolve.PyResolveContext; import com.jetbrains.python.psi.resolve.QualifiedNameFinder; import com.jetbrains.python.psi.resolve.RatedResolveResult; import com.jetbrains.python.psi.stubs.PySetuptoolsNamespaceIndex; import com.jetbrains.python.psi.types.*; import com.jetbrains.python.refactoring.classes.PyDependenciesComparator; import com.jetbrains.python.refactoring.classes.extractSuperclass.PyExtractSuperclassHelper; import com.jetbrains.python.refactoring.classes.membersManager.PyMemberInfo; import com.jetbrains.python.sdk.PythonSdkType; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.*; import java.util.List; import static com.jetbrains.python.psi.PyFunction.Modifier.CLASSMETHOD; import static com.jetbrains.python.psi.PyFunction.Modifier.STATICMETHOD; public class PyUtil { private PyUtil() { } @NotNull public static <T extends PyElement> T[] getAllChildrenOfType(@NotNull PsiElement element, @NotNull Class<T> aClass) { List<T> result = new SmartList<T>(); for (PsiElement child : element.getChildren()) { if (instanceOf(child, aClass)) { //noinspection unchecked result.add((T)child); } else { ContainerUtil.addAll(result, getAllChildrenOfType(child, aClass)); } } return ArrayUtil.toObjectArray(result, aClass); } /** * @see PyUtil#flattenedParensAndTuples */ protected static List<PyExpression> unfoldParentheses(PyExpression[] targets, List<PyExpression> receiver, boolean unfoldListLiterals, boolean unfoldStarExpressions) { // NOTE: this proliferation of instanceofs is not very beautiful. Maybe rewrite using a visitor. for (PyExpression exp : targets) { if (exp instanceof PyParenthesizedExpression) { final PyParenthesizedExpression parenExpr = (PyParenthesizedExpression)exp; unfoldParentheses(new PyExpression[]{parenExpr.getContainedExpression()}, receiver, unfoldListLiterals, unfoldStarExpressions); } else if (exp instanceof PyTupleExpression) { final PyTupleExpression tupleExpr = (PyTupleExpression)exp; unfoldParentheses(tupleExpr.getElements(), receiver, unfoldListLiterals, unfoldStarExpressions); } else if (exp instanceof PyListLiteralExpression && unfoldListLiterals) { final PyListLiteralExpression listLiteral = (PyListLiteralExpression)exp; unfoldParentheses(listLiteral.getElements(), receiver, true, unfoldStarExpressions); } else if (exp instanceof PyStarExpression && unfoldStarExpressions) { unfoldParentheses(new PyExpression[]{((PyStarExpression)exp).getExpression()}, receiver, unfoldListLiterals, true); } else if (exp != null) { receiver.add(exp); } } return receiver; } /** * Flattens the representation of every element in targets, and puts all results together. * Elements of every tuple nested in target item are brought to the top level: (a, (b, (c, d))) -> (a, b, c, d) * Typical usage: <code>flattenedParensAndTuples(some_tuple.getExpressions())</code>. * * @param targets target elements. * @return the list of flattened expressions. */ @NotNull public static List<PyExpression> flattenedParensAndTuples(PyExpression... targets) { return unfoldParentheses(targets, new ArrayList<PyExpression>(targets.length), false, false); } @NotNull public static List<PyExpression> flattenedParensAndLists(PyExpression... targets) { return unfoldParentheses(targets, new ArrayList<PyExpression>(targets.length), true, true); } @NotNull public static List<PyExpression> flattenedParensAndStars(PyExpression... targets) { return unfoldParentheses(targets, new ArrayList<PyExpression>(targets.length), false, true); } // Poor man's filter // TODO: move to a saner place public static boolean instanceOf(Object obj, Class... possibleClasses) { if (obj == null || possibleClasses == null) return false; for (Class cls : possibleClasses) { if (cls.isInstance(obj)) return true; } return false; } /** * Produce a reasonable representation of a PSI element, good for debugging. * * @param elt element to represent; nulls and invalid nodes are ok. * @param cutAtEOL if true, representation stops at nearest EOL inside the element. * @return the representation. */ @NotNull @NonNls public static String getReadableRepr(PsiElement elt, final boolean cutAtEOL) { if (elt == null) return "null!"; ASTNode node = elt.getNode(); if (node == null) { return "null"; } else { String s = node.getText(); int cut_pos; if (cutAtEOL) { cut_pos = s.indexOf('\n'); } else { cut_pos = -1; } if (cut_pos < 0) cut_pos = s.length(); return s.substring(0, Math.min(cut_pos, s.length())); } } @Nullable public static PyClass getContainingClassOrSelf(final PsiElement element) { PsiElement current = element; while (current != null && !(current instanceof PyClass)) { current = current.getParent(); } return (PyClass)current; } /** * @param element for which to obtain the file * @return PyFile, or null, if there's no containing file, or it is not a PyFile. */ @Nullable public static PyFile getContainingPyFile(PyElement element) { final PsiFile containingFile = element.getContainingFile(); return containingFile instanceof PyFile ? (PyFile)containingFile : null; } /** * Shows an information balloon in a reasonable place at the top right of the window. * * @param project our project * @param message the text, HTML markup allowed * @param messageType message type, changes the icon and the background. */ // TODO: move to a better place public static void showBalloon(Project project, String message, MessageType messageType) { // ripped from com.intellij.openapi.vcs.changes.ui.ChangesViewBalloonProblemNotifier final JFrame frame = WindowManager.getInstance().getFrame(project.isDefault() ? null : project); if (frame == null) return; final JComponent component = frame.getRootPane(); if (component == null) return; final Rectangle rect = component.getVisibleRect(); final Point p = new Point(rect.x + rect.width - 10, rect.y + 10); final RelativePoint point = new RelativePoint(component, p); JBPopupFactory.getInstance().createHtmlTextBalloonBuilder(message, messageType.getDefaultIcon(), messageType.getPopupBackground(), null) .setShowCallout(false).setCloseButtonEnabled(true) .createBalloon().show(point, Balloon.Position.atLeft); } @NonNls /** * Returns a quoted string representation, or "null". */ public static String nvl(Object s) { if (s != null) { return "'" + s.toString() + "'"; } else { return "null"; } } /** * Adds an item into a comma-separated list in a PSI tree. E.g. can turn "foo, bar" into "foo, bar, baz", adding commas as needed. * * @param parent the element to represent the list; we're adding a child to it. * @param newItem the element we're inserting (the "baz" in the example). * @param beforeThis node to mark the insertion point inside the list; must belong to a child of target. Set to null to add first element. * @param isFirst true if we don't need a comma before the element we're adding. * @param isLast true if we don't need a comma after the element we're adding. */ public static void addListNode(PsiElement parent, PsiElement newItem, ASTNode beforeThis, boolean isFirst, boolean isLast, boolean addWhitespace) { if (!FileModificationService.getInstance().preparePsiElementForWrite(parent)) { return; } ASTNode node = parent.getNode(); assert node != null; ASTNode itemNode = newItem.getNode(); assert itemNode != null; Project project = parent.getProject(); PyElementGenerator gen = PyElementGenerator.getInstance(project); if (!isFirst) node.addChild(gen.createComma(), beforeThis); node.addChild(itemNode, beforeThis); if (!isLast) node.addChild(gen.createComma(), beforeThis); if (addWhitespace) node.addChild(ASTFactory.whitespace(" "), beforeThis); } /** * Collects superclasses of a class all the way up the inheritance chain. The order is <i>not</i> necessarily the MRO. */ @NotNull public static List<PyClass> getAllSuperClasses(@NotNull PyClass pyClass) { List<PyClass> superClasses = new ArrayList<PyClass>(); for (PyClass ancestor : pyClass.getAncestorClasses(null)) { if (!PyNames.FAKE_OLD_BASE.equals(ancestor.getName())) { superClasses.add(ancestor); } } return superClasses; } // TODO: move to a more proper place? /** * Determine the type of a special attribute. Currently supported: {@code __class__} and {@code __dict__}. * * @param ref reference to a possible attribute; only qualified references make sense. * @return type, or null (if type cannot be determined, reference is not to a known attribute, etc.) */ @Nullable public static PyType getSpecialAttributeType(@Nullable PyReferenceExpression ref, TypeEvalContext context) { if (ref != null) { PyExpression qualifier = ref.getQualifier(); if (qualifier != null) { String attr_name = ref.getReferencedName(); if (PyNames.__CLASS__.equals(attr_name)) { PyType qualifierType = context.getType(qualifier); if (qualifierType instanceof PyClassType) { return new PyClassTypeImpl(((PyClassType)qualifierType).getPyClass(), true); // always as class, never instance } } else if (PyNames.DICT.equals(attr_name)) { PyType qualifierType = context.getType(qualifier); if (qualifierType instanceof PyClassType && ((PyClassType)qualifierType).isDefinition()) { return PyBuiltinCache.getInstance(ref).getDictType(); } } } } return null; } /** * Makes sure that 'thing' is not null; else throws an {@link IncorrectOperationException}. * * @param thing what we check. * @return thing, if not null. */ @NotNull public static <T> T sure(T thing) { if (thing == null) throw new IncorrectOperationException(); return thing; } /** * Makes sure that the 'thing' is true; else throws an {@link IncorrectOperationException}. * * @param thing what we check. */ public static void sure(boolean thing) { if (!thing) throw new IncorrectOperationException(); } public static boolean isAttribute(PyTargetExpression ex) { return isInstanceAttribute(ex) || isClassAttribute(ex); } public static boolean isInstanceAttribute(PyExpression target) { if (!(target instanceof PyTargetExpression)) { return false; } final ScopeOwner owner = ScopeUtil.getScopeOwner(target); if (owner instanceof PyFunction) { final PyFunction method = (PyFunction)owner; if (method.getContainingClass() != null) { if (method.getStub() != null) { return true; } final PyParameter[] params = method.getParameterList().getParameters(); if (params.length > 0) { final PyTargetExpression targetExpr = (PyTargetExpression)target; final PyExpression qualifier = targetExpr.getQualifier(); return qualifier != null && qualifier.getText().equals(params[0].getName()); } } } return false; } public static boolean isClassAttribute(PsiElement element) { return element instanceof PyTargetExpression && ScopeUtil.getScopeOwner(element) instanceof PyClass; } public static boolean isIfNameEqualsMain(PyIfStatement ifStatement) { final PyExpression condition = ifStatement.getIfPart().getCondition(); return isNameEqualsMain(condition); } private static boolean isNameEqualsMain(PyExpression condition) { if (condition instanceof PyParenthesizedExpression) { return isNameEqualsMain(((PyParenthesizedExpression)condition).getContainedExpression()); } if (condition instanceof PyBinaryExpression) { PyBinaryExpression binaryExpression = (PyBinaryExpression)condition; if (binaryExpression.getOperator() == PyTokenTypes.OR_KEYWORD) { return isNameEqualsMain(binaryExpression.getLeftExpression()) || isNameEqualsMain(binaryExpression.getRightExpression()); } final PyExpression rhs = binaryExpression.getRightExpression(); return binaryExpression.getOperator() == PyTokenTypes.EQEQ && binaryExpression.getLeftExpression().getText().equals(PyNames.NAME) && rhs != null && rhs.getText().contains("__main__"); } return false; } /** * Searches for a method wrapping given element. * * @param start element presumably inside a method * @param deep if true, allow 'start' to be inside functions nested in a method; else, 'start' must be directly inside a method. * @return if not 'deep', [0] is the method and [1] is the class; if 'deep', first several elements may be the nested functions, * the last but one is the method, and the last is the class. */ @Nullable public static List<PsiElement> searchForWrappingMethod(PsiElement start, boolean deep) { PsiElement seeker = start; List<PsiElement> ret = new ArrayList<PsiElement>(2); while (seeker != null) { PyFunction func = PsiTreeUtil.getParentOfType(seeker, PyFunction.class, true, PyClass.class); if (func != null) { PyClass cls = func.getContainingClass(); if (cls != null) { ret.add(func); ret.add(cls); return ret; } else if (deep) { ret.add(func); seeker = func; } else { return null; // no immediate class } } else { return null; // no function } } return null; } public static boolean inSameFile(@NotNull PsiElement e1, @NotNull PsiElement e2) { final PsiFile f1 = e1.getContainingFile(); final PsiFile f2 = e2.getContainingFile(); if (f1 == null || f2 == null) { return false; } return f1 == f2; } public static boolean onSameLine(@NotNull PsiElement e1, @NotNull PsiElement e2) { final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(e1.getProject()); final Document document = documentManager.getDocument(e1.getContainingFile()); if (document == null || document != documentManager.getDocument(e2.getContainingFile())) { return false; } return document.getLineNumber(e1.getTextOffset()) == document.getLineNumber(e2.getTextOffset()); } public static boolean isTopLevel(@NotNull PsiElement element) { if (element instanceof StubBasedPsiElement) { final StubElement stub = ((StubBasedPsiElement)element).getStub(); if (stub != null) { final StubElement parentStub = stub.getParentStub(); if (parentStub != null) { return parentStub.getPsi() instanceof PsiFile; } } } return ScopeUtil.getScopeOwner(element) instanceof PsiFile; } public static void deletePycFiles(String pyFilePath) { if (pyFilePath.endsWith(PyNames.DOT_PY)) { List<File> filesToDelete = new ArrayList<File>(); File pyc = new File(pyFilePath + "c"); if (pyc.exists()) { filesToDelete.add(pyc); } File pyo = new File(pyFilePath + "o"); if (pyo.exists()) { filesToDelete.add(pyo); } final File file = new File(pyFilePath); File pycache = new File(file.getParentFile(), PyNames.PYCACHE); if (pycache.isDirectory()) { final String shortName = FileUtil.getNameWithoutExtension(file); Collections.addAll(filesToDelete, pycache.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { if (!FileUtilRt.extensionEquals(pathname.getName(), "pyc")) return false; String nameWithMagic = FileUtil.getNameWithoutExtension(pathname); return FileUtil.getNameWithoutExtension(nameWithMagic).equals(shortName); } })); } FileUtil.asyncDelete(filesToDelete); } } public static String getElementNameWithoutExtension(PsiNamedElement psiNamedElement) { return psiNamedElement instanceof PyFile ? FileUtil.getNameWithoutExtension(((PyFile)psiNamedElement).getName()) : psiNamedElement.getName(); } public static boolean hasUnresolvedAncestors(@NotNull PyClass cls, @NotNull TypeEvalContext context) { for (PyClassLikeType type : cls.getAncestorTypes(context)) { if (type == null) { return true; } } return false; } @NotNull public static AccessDirection getPropertyAccessDirection(@NotNull PyFunction function) { final Property property = function.getProperty(); if (property != null) { if (property.getGetter().valueOrNull() == function) { return AccessDirection.READ; } if (property.getSetter().valueOrNull() == function) { return AccessDirection.WRITE; } else if (property.getDeleter().valueOrNull() == function) { return AccessDirection.DELETE; } } return AccessDirection.READ; } public static void removeQualifier(@NotNull final PyReferenceExpression element) { final PyExpression qualifier = element.getQualifier(); if (qualifier == null) return; if (qualifier instanceof PyCallExpression) { final PyExpression callee = ((PyCallExpression)qualifier).getCallee(); if (callee instanceof PyReferenceExpression) { final PyExpression calleeQualifier = ((PyReferenceExpression)callee).getQualifier(); if (calleeQualifier != null) { qualifier.replace(calleeQualifier); return; } } } final PsiElement dot = PyPsiUtils.getNextNonWhitespaceSibling(qualifier); if (dot != null) dot.delete(); qualifier.delete(); } /** * Returns string that represents element in string search. * * @param element element to search * @return string that represents element */ @NotNull public static String computeElementNameForStringSearch(@NotNull final PsiElement element) { if (element instanceof PyFile) { return FileUtil.getNameWithoutExtension(((PyFile)element).getName()); } if (element instanceof PsiDirectory) { return ((PsiDirectory)element).getName(); } // Magic literals are always represented by their string values if ((element instanceof PyStringLiteralExpression) && PyMagicLiteralTools.isMagicLiteral(element)) { final String name = ((StringLiteralExpression)element).getStringValue(); if (name != null) { return name; } } if (element instanceof PyElement) { final String name = ((PyElement)element).getName(); if (name != null) { return name; } } return element.getNode().getText(); } public static boolean isOwnScopeComprehension(@NotNull PyComprehensionElement comprehension) { final boolean isAtLeast30 = LanguageLevel.forElement(comprehension).isAtLeast(LanguageLevel.PYTHON30); final boolean isListComprehension = comprehension instanceof PyListCompExpression; return !isListComprehension || isAtLeast30; } public static boolean hasCustomDecorators(@NotNull PyDecoratable decoratable) { return PyKnownDecoratorUtil.hasNonBuiltinDecorator(decoratable, TypeEvalContext.codeInsightFallback(null)); } public static boolean isDecoratedAsAbstract(@NotNull final PyDecoratable decoratable) { return PyKnownDecoratorUtil.hasAbstractDecorator(decoratable, TypeEvalContext.codeInsightFallback(null)); } public static ASTNode createNewName(PyElement element, String name) { return PyElementGenerator.getInstance(element.getProject()).createNameIdentifier(name, LanguageLevel.forElement(element)); } /** * Finds element declaration by resolving its references top the top but not further than file (to prevent un-stubbing) * * @param elementToResolve element to resolve * @return its declaration */ @NotNull public static PsiElement resolveToTheTop(@NotNull final PsiElement elementToResolve) { PsiElement currentElement = elementToResolve; while (true) { final PsiReference reference = currentElement.getReference(); if (reference == null) { break; } final PsiElement resolve = reference.resolve(); if ((resolve == null) || resolve.equals(currentElement) || !inSameFile(resolve, currentElement)) { break; } currentElement = resolve; } return currentElement; } /** * Note that returned list may contain {@code null} items, e.g. for unresolved import elements, originally wrapped * in {@link com.jetbrains.python.psi.resolve.ImportedResolveResult}. */ @NotNull public static List<PsiElement> multiResolveTopPriority(@NotNull PsiElement element, @NotNull PyResolveContext resolveContext) { if (element instanceof PyReferenceOwner) { final PsiPolyVariantReference ref = ((PyReferenceOwner)element).getReference(resolveContext); return filterTopPriorityResults(ref.multiResolve(false)); } else { final PsiReference reference = element.getReference(); return reference != null ? Collections.singletonList(reference.resolve()) : Collections.<PsiElement>emptyList(); } } @NotNull public static List<PsiElement> multiResolveTopPriority(@NotNull PsiPolyVariantReference reference) { return filterTopPriorityResults(reference.multiResolve(false)); } @NotNull private static List<PsiElement> filterTopPriorityResults(@NotNull ResolveResult[] resolveResults) { if (resolveResults.length == 0) { return Collections.emptyList(); } final List<PsiElement> filtered = new ArrayList<PsiElement>(); final int maxRate = getMaxRate(resolveResults); for (ResolveResult resolveResult : resolveResults) { final int rate = resolveResult instanceof RatedResolveResult ? ((RatedResolveResult)resolveResult).getRate() : 0; if (rate >= maxRate) { filtered.add(resolveResult.getElement()); } } return filtered; } private static int getMaxRate(@NotNull ResolveResult[] resolveResults) { int maxRate = Integer.MIN_VALUE; for (ResolveResult resolveResult : resolveResults) { if (resolveResult instanceof RatedResolveResult) { final int rate = ((RatedResolveResult)resolveResult).getRate(); if (rate > maxRate) { maxRate = rate; } } } return maxRate; } /** * Gets class init method * * @param pyClass class where to find init * @return class init method if any */ @Nullable public static PyFunction getInitMethod(@NotNull final PyClass pyClass) { return pyClass.findMethodByName(PyNames.INIT, false, null); } /** * Returns Python language level for a virtual file. * * @see {@link LanguageLevel#forElement} */ @NotNull public static LanguageLevel getLanguageLevelForVirtualFile(@NotNull Project project, @NotNull VirtualFile virtualFile) { if (virtualFile instanceof VirtualFileWindow) { virtualFile = ((VirtualFileWindow)virtualFile).getDelegate(); } // Most of the cases should be handled by this one, PyLanguageLevelPusher pushes folders only final VirtualFile folder = virtualFile.getParent(); if (folder != null) { final LanguageLevel folderLevel = folder.getUserData(LanguageLevel.KEY); if (folderLevel != null) { return folderLevel; } final LanguageLevel fileLevel = PythonLanguageLevelPusher.getFileLanguageLevel(project, virtualFile); if (fileLevel != null) { return fileLevel; } } else { // However this allows us to setup language level per file manually // in case when it is LightVirtualFile final LanguageLevel level = virtualFile.getUserData(LanguageLevel.KEY); if (level != null) return level; if (ApplicationManager.getApplication().isUnitTestMode()) { final LanguageLevel languageLevel = LanguageLevel.FORCE_LANGUAGE_LEVEL; if (languageLevel != null) { return languageLevel; } } } return guessLanguageLevelWithCaching(project); } public static void invalidateLanguageLevelCache(@NotNull Project project) { project.putUserData(PythonLanguageLevelPusher.PYTHON_LANGUAGE_LEVEL, null); } @NotNull public static LanguageLevel guessLanguageLevelWithCaching(@NotNull Project project) { LanguageLevel languageLevel = project.getUserData(PythonLanguageLevelPusher.PYTHON_LANGUAGE_LEVEL); if (languageLevel == null) { languageLevel = guessLanguageLevel(project); project.putUserData(PythonLanguageLevelPusher.PYTHON_LANGUAGE_LEVEL, languageLevel); } return languageLevel; } @NotNull public static LanguageLevel guessLanguageLevel(@NotNull Project project) { final ModuleManager moduleManager = ModuleManager.getInstance(project); if (moduleManager != null) { LanguageLevel maxLevel = null; for (Module projectModule : moduleManager.getModules()) { final Sdk sdk = PythonSdkType.findPythonSdk(projectModule); if (sdk != null) { final LanguageLevel level = PythonSdkType.getLanguageLevelForSdk(sdk); if (maxLevel == null || maxLevel.isOlderThan(level)) { maxLevel = level; } } } if (maxLevel != null) { return maxLevel; } } return LanguageLevel.getDefault(); } /** * Clone of C# "as" operator. * Checks if expression has correct type and casts it if it has. Returns null otherwise. * It saves coder from "instanceof / cast" chains. * * @param expression expression to check * @param clazz class to cast * @param <T> class to cast * @return expression casted to appropriate type (if could be casted). Null otherwise. */ @Nullable @SuppressWarnings("unchecked") public static <T> T as(@Nullable final Object expression, @NotNull final Class<T> clazz) { return ObjectUtils.tryCast(expression, clazz); } // TODO: Move to PsiElement? /** * Searches for references injected to element with certain type * * @param element element to search injected references for * @param expectedClass expected type of element reference resolved to * @param <T> expected type of element reference resolved to * @return resolved element if found or null if not found */ @Nullable public static <T extends PsiElement> T findReference(@NotNull final PsiElement element, @NotNull final Class<T> expectedClass) { for (final PsiReference reference : element.getReferences()) { final T result = as(reference.resolve(), expectedClass); if (result != null) { return result; } } return null; } /** * Converts collection to list of certain type * * @param expression expression of collection type * @param elementClass expected element type * @param <T> expected element type * @return list of elements of expected element type */ @NotNull public static <T> List<T> asList(@Nullable final Collection<?> expression, @NotNull final Class<T> elementClass) { if ((expression == null) || expression.isEmpty()) { return Collections.emptyList(); } final List<T> result = new ArrayList<T>(); for (final Object element : expression) { final T toAdd = as(element, elementClass); if (toAdd != null) { result.add(toAdd); } } return result; } /** * Force re-highlighting in all open editors that belong to specified project. */ public static void rehighlightOpenEditors(final @NotNull Project project) { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { for (Editor editor : EditorFactory.getInstance().getAllEditors()) { if (editor instanceof EditorEx && editor.getProject() == project) { final VirtualFile vFile = ((EditorEx)editor).getVirtualFile(); if (vFile != null) { final EditorHighlighter highlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter(project, vFile); ((EditorEx)editor).setHighlighter(highlighter); } } } } }); } public static class KnownDecoratorProviderHolder { public static PyKnownDecoratorProvider[] KNOWN_DECORATOR_PROVIDERS = Extensions.getExtensions(PyKnownDecoratorProvider.EP_NAME); private KnownDecoratorProviderHolder() { } } /** * If argument is a PsiDirectory, turn it into a PsiFile that points to __init__.py in that directory. * If there's no __init__.py there, null is returned, there's no point to resolve to a dir which is not a package. * Alas, resolve() and multiResolve() can't return anything but a PyFile or PsiFileImpl.isPsiUpToDate() would fail. * This is because isPsiUpToDate() relies on identity of objects returned by FileViewProvider.getPsi(). * If we ever need to exactly tell a dir from __init__.py, that logic has to change. * * @param target a resolve candidate. * @return a PsiFile if target was a PsiDirectory, or null, or target unchanged. */ @Nullable public static PsiElement turnDirIntoInit(@Nullable PsiElement target) { if (target instanceof PsiDirectory) { final PsiDirectory dir = (PsiDirectory)target; final PsiFile file = dir.findFile(PyNames.INIT_DOT_PY); if (file != null) { return file; // ResolveImportUtil will extract directory part as needed, everyone else are better off with a file. } else { return null; } // dir without __init__.py does not resolve } else { return target; } // don't touch non-dirs } /** * If directory is a PsiDirectory, that is also a valid Python package, return PsiFile that points to __init__.py, * if such file exists, or directory itself (i.e. namespace package). Otherwise, return {@code null}. * Unlike {@link #turnDirIntoInit(PsiElement)} this function handles namespace packages and * accepts only PsiDirectories as target. * * @param directory directory to check * @param anchor optional PSI element to determine language level as for {@link #isPackage(PsiDirectory, PsiElement)} * @return PsiFile or PsiDirectory, if target is a Python package and {@code null} null otherwise */ @Nullable public static PsiElement getPackageElement(@NotNull PsiDirectory directory, @Nullable PsiElement anchor) { if (isPackage(directory, anchor)) { final PsiElement init = turnDirIntoInit(directory); if (init != null) { return init; } return directory; } return null; } /** * If target is a Python module named __init__.py file, return its directory. Otherwise return target unchanged. * @param target PSI element to check * @return PsiDirectory or target unchanged */ @Contract("null -> null; !null -> !null") @Nullable public static PsiElement turnInitIntoDir(@Nullable PsiElement target) { if (target instanceof PyFile && isPackage((PsiFile)target)) { return ((PsiFile)target).getContainingDirectory(); } return target; } /** * @see #isPackage(PsiDirectory, boolean, PsiElement) */ public static boolean isPackage(@NotNull PsiDirectory directory, @Nullable PsiElement anchor) { return isPackage(directory, true, anchor); } /** * Checks that given PsiDirectory can be treated as Python package, i.e. it's either contains __init__.py or it's a namespace package * (effectively any directory in Python 3.3 and above). Setuptools namespace packages can be checked as well, but it requires access to * {@link PySetuptoolsNamespaceIndex} and may slow things down during update of project indexes. * Also note that this method does not check that directory itself and its parents have valid importable names, * use {@link PyNames#isIdentifier(String)} for this purpose. * * @param directory PSI directory to check * @param checkSetupToolsPackages whether setuptools namespace packages should be considered as well * @param anchor optional anchor element to determine language level * @return whether given directory is Python package * * @see PyNames#isIdentifier(String) */ public static boolean isPackage(@NotNull PsiDirectory directory, boolean checkSetupToolsPackages, @Nullable PsiElement anchor) { if (directory.findFile(PyNames.INIT_DOT_PY) != null) { return true; } final LanguageLevel level = anchor != null ? LanguageLevel.forElement(anchor) : getLanguageLevelForVirtualFile(directory.getProject(), directory.getVirtualFile()); if (level.isAtLeast(LanguageLevel.PYTHON33)) { return true; } return checkSetupToolsPackages && isSetuptoolsNamespacePackage(directory); } public static boolean isPackage(@NotNull PsiFile file) { return PyNames.INIT_DOT_PY.equals(file.getName()); } private static boolean isSetuptoolsNamespacePackage(@NotNull PsiDirectory directory) { final String packagePath = getPackagePath(directory); return packagePath != null && !PySetuptoolsNamespaceIndex.find(packagePath, directory.getProject()).isEmpty(); } @Nullable private static String getPackagePath(@NotNull PsiDirectory directory) { final QualifiedName name = QualifiedNameFinder.findShortestImportableQName(directory); return name != null ? name.toString() : null; } /** * Counts initial underscores of an identifier. * * @param name identifier * @return 0 if no initial underscores found, 1 if there's only one underscore, 2 if there's two or more initial underscores. */ public static int getInitialUnderscores(String name) { if (name == null) { return 0; } int underscores = 0; if (name.startsWith("__")) { underscores = 2; } else if (name.startsWith("_")) underscores = 1; return underscores; } /** * @param name * @return true iff the name looks like a class-private one, starting with two underscores but not ending with two underscores. */ public static boolean isClassPrivateName(@NotNull String name) { return name.startsWith("__") && !name.endsWith("__"); } public static boolean isSpecialName(@NotNull String name) { return name.length() > 4 && name.startsWith("__") && name.endsWith("__"); } /** * Constructs new lookup element for completion of keyword argument with equals sign appended. * * @param name name of the parameter * @param project project instance to check code style settings and surround equals sign with spaces if necessary * @return lookup element */ @NotNull public static LookupElement createNamedParameterLookup(@NotNull String name, @Nullable Project project) { final String suffix; if (CodeStyleSettingsManager.getSettings(project).getCustomSettings(PyCodeStyleSettings.class).SPACE_AROUND_EQ_IN_KEYWORD_ARGUMENT) { suffix = " = "; } else { suffix = "="; } LookupElementBuilder lookupElementBuilder = LookupElementBuilder.create(name + suffix).withIcon(PlatformIcons.PARAMETER_ICON); lookupElementBuilder = lookupElementBuilder.withInsertHandler(OverwriteEqualsInsertHandler.INSTANCE); return PrioritizedLookupElement.withGrouping(lookupElementBuilder, 1); } /** * Peels argument expression of parentheses and of keyword argument wrapper * * @param expr an item of getArguments() array * @return expression actually passed as argument */ @Nullable public static PyExpression peelArgument(PyExpression expr) { while (expr instanceof PyParenthesizedExpression) expr = ((PyParenthesizedExpression)expr).getContainedExpression(); if (expr instanceof PyKeywordArgument) expr = ((PyKeywordArgument)expr).getValueExpression(); return expr; } public static String getFirstParameterName(PyFunction container) { String selfName = PyNames.CANONICAL_SELF; if (container != null) { final PyParameter[] params = container.getParameterList().getParameters(); if (params.length > 0) { final PyNamedParameter named = params[0].getAsNamed(); if (named != null) { selfName = named.getName(); } } } return selfName; } /** * @return Source roots <strong>and</strong> content roots for element's project */ @NotNull public static Collection<VirtualFile> getSourceRoots(@NotNull PsiElement foothold) { final Module module = ModuleUtilCore.findModuleForPsiElement(foothold); if (module != null) { return getSourceRoots(module); } return Collections.emptyList(); } /** * @return Source roots <strong>and</strong> content roots for module */ @NotNull public static Collection<VirtualFile> getSourceRoots(@NotNull Module module) { final Set<VirtualFile> result = new LinkedHashSet<VirtualFile>(); final ModuleRootManager manager = ModuleRootManager.getInstance(module); Collections.addAll(result, manager.getSourceRoots()); Collections.addAll(result, manager.getContentRoots()); return result; } @Nullable public static VirtualFile findInRoots(Module module, String path) { if (module != null) { for (VirtualFile root : getSourceRoots(module)) { VirtualFile file = root.findFileByRelativePath(path); if (file != null) { return file; } } } return null; } @Nullable public static List<String> getStringListFromTargetExpression(PyTargetExpression attr) { return strListValue(attr.findAssignedValue()); } @Nullable public static List<String> strListValue(PyExpression value) { while (value instanceof PyParenthesizedExpression) { value = ((PyParenthesizedExpression)value).getContainedExpression(); } if (value instanceof PySequenceExpression) { final PyExpression[] elements = ((PySequenceExpression)value).getElements(); List<String> result = new ArrayList<String>(elements.length); for (PyExpression element : elements) { if (!(element instanceof PyStringLiteralExpression)) { return null; } result.add(((PyStringLiteralExpression)element).getStringValue()); } return result; } return null; } @NotNull public static Map<String, PyExpression> dictValue(@NotNull PyDictLiteralExpression dict) { Map<String, PyExpression> result = Maps.newLinkedHashMap(); for (PyKeyValueExpression keyValue : dict.getElements()) { PyExpression key = keyValue.getKey(); PyExpression value = keyValue.getValue(); if (key instanceof PyStringLiteralExpression) { result.put(((PyStringLiteralExpression)key).getStringValue(), value); } } return result; } /** * @param what thing to search for * @param variants things to search among * @return true iff what.equals() one of the variants. */ public static <T> boolean among(@NotNull T what, T... variants) { for (T s : variants) { if (what.equals(s)) return true; } return false; } @Nullable public static String getKeywordArgumentString(PyCallExpression expr, String keyword) { return PyPsiUtils.strValue(expr.getKeywordArgument(keyword)); } public static boolean isExceptionClass(PyClass pyClass) { if (isBaseException(pyClass.getQualifiedName())) { return true; } for (PyClassLikeType type : pyClass.getAncestorTypes(TypeEvalContext.codeInsightFallback(pyClass.getProject()))) { if (type != null && isBaseException(type.getClassQName())) { return true; } } return false; } private static boolean isBaseException(String name) { return name != null && (name.contains("BaseException") || name.startsWith("exceptions.")); } public static class MethodFlags { private final boolean myIsStaticMethod; private final boolean myIsMetaclassMethod; private final boolean myIsSpecialMetaclassMethod; private final boolean myIsClassMethod; /** * @return true iff the method belongs to a metaclass (an ancestor of 'type'). */ public boolean isMetaclassMethod() { return myIsMetaclassMethod; } /** * @return iff isMetaclassMethod and the method is either __init__ or __call__. */ public boolean isSpecialMetaclassMethod() { return myIsSpecialMetaclassMethod; } public boolean isStaticMethod() { return myIsStaticMethod; } public boolean isClassMethod() { return myIsClassMethod; } private MethodFlags(boolean isClassMethod, boolean isStaticMethod, boolean isMetaclassMethod, boolean isSpecialMetaclassMethod) { myIsClassMethod = isClassMethod; myIsStaticMethod = isStaticMethod; myIsMetaclassMethod = isMetaclassMethod; myIsSpecialMetaclassMethod = isSpecialMetaclassMethod; } /** * @param node a function * @return a new flags object, or null if the function is not a method */ @Nullable public static MethodFlags of(@NotNull PyFunction node) { PyClass cls = node.getContainingClass(); if (cls != null) { PyFunction.Modifier modifier = node.getModifier(); boolean isMetaclassMethod = false; PyClass type_cls = PyBuiltinCache.getInstance(node).getClass("type"); for (PyClass ancestor_cls : cls.getAncestorClasses(null)) { if (ancestor_cls == type_cls) { isMetaclassMethod = true; break; } } final String method_name = node.getName(); boolean isSpecialMetaclassMethod = isMetaclassMethod && method_name != null && among(method_name, PyNames.INIT, "__call__"); return new MethodFlags(modifier == CLASSMETHOD, modifier == STATICMETHOD, isMetaclassMethod, isSpecialMetaclassMethod); } return null; } //TODO: Doc public boolean isInstanceMethod() { return !(myIsClassMethod || myIsStaticMethod); } } public static boolean isSuperCall(@NotNull PyCallExpression node) { PyClass klass = PsiTreeUtil.getParentOfType(node, PyClass.class); if (klass == null) return false; PyExpression callee = node.getCallee(); if (callee == null) return false; String name = callee.getName(); if (PyNames.SUPER.equals(name)) { PsiReference reference = callee.getReference(); if (reference == null) return false; PsiElement resolved = reference.resolve(); PyBuiltinCache cache = PyBuiltinCache.getInstance(node); if (resolved != null && cache.isBuiltin(resolved)) { PyExpression[] args = node.getArguments(); if (args.length > 0) { String firstArg = args[0].getText(); if (firstArg.equals(klass.getName()) || firstArg.equals(PyNames.CANONICAL_SELF + "." + PyNames.__CLASS__)) { return true; } for (PyClass s : klass.getAncestorClasses(null)) { if (firstArg.equals(s.getName())) { return true; } } } else { return true; } } } return false; } @NotNull public static PyFile getOrCreateFile(String path, Project project) { final VirtualFile vfile = LocalFileSystem.getInstance().findFileByIoFile(new File(path)); final PsiFile psi; if (vfile == null) { final File file = new File(path); try { final VirtualFile baseDir = project.getBaseDir(); final FileTemplateManager fileTemplateManager = FileTemplateManager.getInstance(project); final FileTemplate template = fileTemplateManager.getInternalTemplate("Python Script"); final Properties properties = fileTemplateManager.getDefaultProperties(); properties.setProperty("NAME", FileUtil.getNameWithoutExtension(file.getName())); final String content = (template != null) ? template.getText(properties) : null; psi = PyExtractSuperclassHelper.placeFile(project, StringUtil.notNullize( file.getParent(), baseDir != null ? baseDir .getPath() : "." ), file.getName(), content ); } catch (IOException e) { throw new IncorrectOperationException(String.format("Cannot create file '%s'", path), (Throwable)e); } } else { psi = PsiManager.getInstance(project).findFile(vfile); } if (!(psi instanceof PyFile)) { throw new IncorrectOperationException(PyBundle.message( "refactoring.move.module.members.error.cannot.place.elements.into.nonpython.file")); } return (PyFile)psi; } /** * counts elements in iterable * * @param expression to count containing elements (iterable) * @return element count */ public static int getElementsCount(PyExpression expression, TypeEvalContext evalContext) { int valuesLength = -1; PyType type = evalContext.getType(expression); if (type instanceof PyTupleType) { valuesLength = ((PyTupleType)type).getElementCount(); } else if (type instanceof PyNamedTupleType) { valuesLength = ((PyNamedTupleType)type).getElementCount(); } else if (expression instanceof PySequenceExpression) { valuesLength = ((PySequenceExpression)expression).getElements().length; } else if (expression instanceof PyStringLiteralExpression) { valuesLength = ((PyStringLiteralExpression)expression).getStringValue().length(); } else if (expression instanceof PyNumericLiteralExpression) { valuesLength = 1; } else if (expression instanceof PyCallExpression) { PyCallExpression call = (PyCallExpression)expression; if (call.isCalleeText("dict")) { valuesLength = call.getArguments().length; } else if (call.isCalleeText("tuple")) { PyExpression[] arguments = call.getArguments(); if (arguments.length > 0 && arguments[0] instanceof PySequenceExpression) { valuesLength = ((PySequenceExpression)arguments[0]).getElements().length; } } } return valuesLength; } @Nullable public static PsiElement findPrevAtOffset(PsiFile psiFile, int caretOffset, Class... toSkip) { PsiElement element; if (caretOffset < 0) { return null; } int lineStartOffset = 0; final Document document = PsiDocumentManager.getInstance(psiFile.getProject()).getDocument(psiFile); if (document != null) { int lineNumber = document.getLineNumber(caretOffset); lineStartOffset = document.getLineStartOffset(lineNumber); } do { caretOffset--; element = psiFile.findElementAt(caretOffset); } while (caretOffset >= lineStartOffset && instanceOf(element, toSkip)); return instanceOf(element, toSkip) ? null : element; } @Nullable public static PsiElement findNonWhitespaceAtOffset(PsiFile psiFile, int caretOffset) { PsiElement element = findNextAtOffset(psiFile, caretOffset, PsiWhiteSpace.class); if (element == null) { element = findPrevAtOffset(psiFile, caretOffset - 1, PsiWhiteSpace.class); } return element; } @Nullable public static PsiElement findElementAtOffset(PsiFile psiFile, int caretOffset) { PsiElement element = findPrevAtOffset(psiFile, caretOffset); if (element == null) { element = findNextAtOffset(psiFile, caretOffset); } return element; } @Nullable public static PsiElement findNextAtOffset(@NotNull final PsiFile psiFile, int caretOffset, Class... toSkip) { PsiElement element = psiFile.findElementAt(caretOffset); if (element == null) { return null; } final Document document = PsiDocumentManager.getInstance(psiFile.getProject()).getDocument(psiFile); int lineEndOffset = 0; if (document != null) { int lineNumber = document.getLineNumber(caretOffset); lineEndOffset = document.getLineEndOffset(lineNumber); } while (caretOffset < lineEndOffset && instanceOf(element, toSkip)) { caretOffset++; element = psiFile.findElementAt(caretOffset); } return instanceOf(element, toSkip) ? null : element; } /** * Adds element to statement list to the correct place according to its dependencies. * * @param element to insert * @param statementList where element should be inserted * @return inserted element */ public static <T extends PyElement> T addElementToStatementList(@NotNull final T element, @NotNull final PyStatementList statementList) { PsiElement before = null; PsiElement after = null; for (final PyStatement statement : statementList.getStatements()) { if (PyDependenciesComparator.depends(element, statement)) { after = statement; } else if (PyDependenciesComparator.depends(statement, element)) { before = statement; } } final PsiElement result; if (after != null) { result = statementList.addAfter(element, after); } else if (before != null) { result = statementList.addBefore(element, before); } else { result = addElementToStatementList(element, statementList, true); } @SuppressWarnings("unchecked") // Inserted element can't have different type final T resultCasted = (T)result; return resultCasted; } /** * Inserts specified element into the statement list either at the beginning or at its end. If new element is going to be * inserted at the beginning, any preceding docstrings and/or calls to super methods will be skipped. * Moreover if statement list previously didn't contain any statements, explicit new line and indentation will be inserted in * front of it. * * @param element element to insert * @param statementList statement list * @param toTheBeginning whether to insert element at the beginning or at the end of the statement list * @return actually inserted element as for {@link PsiElement#add(PsiElement)} */ @NotNull public static PsiElement addElementToStatementList(@NotNull PsiElement element, @NotNull PyStatementList statementList, boolean toTheBeginning) { final PsiElement prevElem = PyPsiUtils.getPrevNonWhitespaceSibling(statementList); // If statement list is on the same line as previous element (supposedly colon), move its only statement on the next line if (prevElem != null && onSameLine(statementList, prevElem)) { final PsiDocumentManager manager = PsiDocumentManager.getInstance(statementList.getProject()); final Document document = manager.getDocument(statementList.getContainingFile()); if (document != null) { final PyStatementListContainer container = (PyStatementListContainer)statementList.getParent(); manager.doPostponedOperationsAndUnblockDocument(document); final String indentation = "\n" + PyIndentUtil.getElementIndent(statementList); // If statement list was empty initially, we need to add some anchor statement ("pass"), so that preceding new line was not // parsed as following entire StatementListContainer (e.g. function). It's going to be replaced anyway. final String text = statementList.getStatements().length == 0 ? indentation + PyNames.PASS : indentation; document.insertString(statementList.getTextRange().getStartOffset(), text); manager.commitDocument(document); statementList = container.getStatementList(); } } final PsiElement firstChild = statementList.getFirstChild(); if (firstChild == statementList.getLastChild() && firstChild instanceof PyPassStatement) { element = firstChild.replace(element); } else { final PyStatement[] statements = statementList.getStatements(); if (toTheBeginning && statements.length > 0) { final PyDocStringOwner docStringOwner = PsiTreeUtil.getParentOfType(statementList, PyDocStringOwner.class); PyStatement anchor = statements[0]; if (docStringOwner != null && anchor instanceof PyExpressionStatement && ((PyExpressionStatement)anchor).getExpression() == docStringOwner.getDocStringExpression()) { final PyStatement next = PsiTreeUtil.getNextSiblingOfType(anchor, PyStatement.class); if (next == null) { return statementList.addAfter(element, anchor); } anchor = next; } while (anchor instanceof PyExpressionStatement) { final PyExpression expression = ((PyExpressionStatement)anchor).getExpression(); if (expression instanceof PyCallExpression) { final PyExpression callee = ((PyCallExpression)expression).getCallee(); if ((isSuperCall((PyCallExpression)expression) || (callee != null && PyNames.INIT.equals(callee.getName())))) { final PyStatement next = PsiTreeUtil.getNextSiblingOfType(anchor, PyStatement.class); if (next == null) { return statementList.addAfter(element, anchor); } anchor = next; continue; } } break; } element = statementList.addBefore(element, anchor); } else { element = statementList.add(element); } } return element; } @NotNull public static List<List<PyParameter>> getOverloadedParametersSet(@NotNull PyCallable callable, @NotNull TypeEvalContext context) { final List<List<PyParameter>> parametersSet = getOverloadedParametersSet(context.getType(callable), context); return parametersSet != null ? parametersSet : Collections.singletonList(Arrays.asList(callable.getParameterList().getParameters())); } @Nullable private static List<PyParameter> getParametersOfCallableType(@NotNull PyCallableType type, @NotNull TypeEvalContext context) { final List<PyCallableParameter> callableTypeParameters = type.getParameters(context); if (callableTypeParameters != null) { boolean allParametersDefined = true; final List<PyParameter> parameters = new ArrayList<PyParameter>(); for (PyCallableParameter callableParameter : callableTypeParameters) { final PyParameter parameter = callableParameter.getParameter(); if (parameter == null) { allParametersDefined = false; break; } parameters.add(parameter); } if (allParametersDefined) { return parameters; } } return null; } @Nullable private static List<List<PyParameter>> getOverloadedParametersSet(@Nullable PyType type, @NotNull TypeEvalContext context) { if (type instanceof PyUnionType) { type = ((PyUnionType)type).excludeNull(context); } if (type instanceof PyCallableType) { final List<PyParameter> results = getParametersOfCallableType((PyCallableType)type, context); if (results != null) { return Collections.singletonList(results); } } else if (type instanceof PyUnionType) { final List<List<PyParameter>> results = new ArrayList<List<PyParameter>>(); final Collection<PyType> members = ((PyUnionType)type).getMembers(); for (PyType member : members) { if (member instanceof PyCallableType) { final List<PyParameter> parameters = getParametersOfCallableType((PyCallableType)member, context); if (parameters != null) { results.add(parameters); } } } if (!results.isEmpty()) { return results; } } return null; } @NotNull public static List<PyParameter> getParameters(@NotNull PyCallable callable, @NotNull TypeEvalContext context) { final List<List<PyParameter>> parametersSet = getOverloadedParametersSet(callable, context); assert !parametersSet.isEmpty(); return parametersSet.get(0); } public static boolean isSignatureCompatibleTo(@NotNull PyCallable callable, @NotNull PyCallable otherCallable, @NotNull TypeEvalContext context) { final List<PyParameter> parameters = getParameters(callable, context); final List<PyParameter> otherParameters = getParameters(otherCallable, context); final int optionalCount = optionalParametersCount(parameters); final int otherOptionalCount = optionalParametersCount(otherParameters); final int requiredCount = requiredParametersCount(callable, parameters); final int otherRequiredCount = requiredParametersCount(otherCallable, otherParameters); if (hasPositionalContainer(otherParameters) || hasKeywordContainer(otherParameters)) { if (otherParameters.size() == specialParametersCount(otherCallable, otherParameters)) { return true; } } if (hasPositionalContainer(parameters) || hasKeywordContainer(parameters)) { return requiredCount <= otherRequiredCount; } return requiredCount <= otherRequiredCount && parameters.size() >= otherParameters.size() && optionalCount >= otherOptionalCount; } private static int optionalParametersCount(@NotNull List<PyParameter> parameters) { int n = 0; for (PyParameter parameter : parameters) { if (parameter.hasDefaultValue()) { n++; } } return n; } private static int requiredParametersCount(@NotNull PyCallable callable, @NotNull List<PyParameter> parameters) { return parameters.size() - optionalParametersCount(parameters) - specialParametersCount(callable, parameters); } private static int specialParametersCount(@NotNull PyCallable callable, @NotNull List<PyParameter> parameters) { int n = 0; if (hasPositionalContainer(parameters)) { n++; } if (hasKeywordContainer(parameters)) { n++; } if (callable.asMethod() != null) { n++; } else { if (parameters.size() > 0) { final PyParameter first = parameters.get(0); if (PyNames.CANONICAL_SELF.equals(first.getName())) { n++; } } } return n; } private static boolean hasPositionalContainer(@NotNull List<PyParameter> parameters) { for (PyParameter parameter : parameters) { if (parameter instanceof PyNamedParameter && ((PyNamedParameter)parameter).isPositionalContainer()) { return true; } } return false; } private static boolean hasKeywordContainer(@NotNull List<PyParameter> parameters) { for (PyParameter parameter : parameters) { if (parameter instanceof PyNamedParameter && ((PyNamedParameter)parameter).isKeywordContainer()) { return true; } } return false; } public static boolean isInit(@NotNull final PyFunction function) { return PyNames.INIT.equals(function.getName()); } /** * Filters out {@link PyMemberInfo} * that should not be displayed in this refactoring (like object) * * @param pyMemberInfos collection to sort * @return sorted collection */ @NotNull public static Collection<PyMemberInfo<PyElement>> filterOutObject(@NotNull final Collection<PyMemberInfo<PyElement>> pyMemberInfos) { return Collections2.filter(pyMemberInfos, new ObjectPredicate(false)); } public static boolean isStarImportableFrom(@NotNull String name, @NotNull PyFile file) { final List<String> dunderAll = file.getDunderAll(); return dunderAll != null ? dunderAll.contains(name) : !name.startsWith("_"); } /** * Filters only PyClass object (new class) */ public static class ObjectPredicate extends NotNullPredicate<PyMemberInfo<PyElement>> { private final boolean myAllowObjects; /** * @param allowObjects allows only objects if true. Allows all but objects otherwise. */ public ObjectPredicate(final boolean allowObjects) { myAllowObjects = allowObjects; } @Override public boolean applyNotNull(@NotNull final PyMemberInfo<PyElement> input) { return myAllowObjects == isObject(input); } private static boolean isObject(@NotNull final PyMemberInfo<PyElement> classMemberInfo) { final PyElement element = classMemberInfo.getMember(); return (element instanceof PyClass) && PyNames.OBJECT.equals(element.getName()); } } /** * Sometimes you do not know real FQN of some class, but you know class name and its package. * I.e. <code>django.apps.conf.AppConfig</code> is not documented, but you know * <code>AppConfig</code> and <code>django</code> package. * * @param symbol element to check (class or function) * @param expectedPackage package like "django" * @param expectedName expected name (i.e. AppConfig) * @return true if element in package */ public static boolean isSymbolInPackage(@NotNull final PyQualifiedNameOwner symbol, @NotNull final String expectedPackage, @NotNull final String expectedName) { final String qualifiedNameString = symbol.getQualifiedName(); if (qualifiedNameString == null) { return false; } final QualifiedName qualifiedName = QualifiedName.fromDottedString(qualifiedNameString); final String aPackage = qualifiedName.getFirstComponent(); if (!(expectedPackage.equals(aPackage))) { return false; } final String symbolName = qualifiedName.getLastComponent(); return expectedName.equals(symbolName); } /** * Checks that given class is the root of class hierarchy, i.e. it's either {@code object} or * special {@link PyNames#FAKE_OLD_BASE} class for old-style classes. * * @param cls Python class to check * @see PyBuiltinCache * @see PyNames#FAKE_OLD_BASE */ public static boolean isObjectClass(@NotNull PyClass cls) { final PyBuiltinCache builtinCache = PyBuiltinCache.getInstance(cls); return cls == builtinCache.getClass(PyNames.OBJECT) || cls == builtinCache.getClass(PyNames.FAKE_OLD_BASE); } public static boolean isInScratchFile(@NotNull PsiElement element) { return ScratchFileService.isInScratchRoot(PsiUtilCore.getVirtualFile(element)); } /** * This helper class allows to collect various information about AST nodes composing {@link PyStringLiteralExpression}. */ public static final class StringNodeInfo { private final ASTNode myNode; private final String myPrefix; private final String myQuote; private final TextRange myContentRange; public StringNodeInfo(@NotNull ASTNode node) { if (!PyTokenTypes.STRING_NODES.contains(node.getElementType())) { throw new IllegalArgumentException("Node must be valid Python string literal token, but " + node.getElementType() + " was given"); } myNode = node; final String nodeText = node.getText(); final int prefixLength = PyStringLiteralExpressionImpl.getPrefixLength(nodeText); myPrefix = nodeText.substring(0, prefixLength); myContentRange = PyStringLiteralExpressionImpl.getNodeTextRange(nodeText); myQuote = nodeText.substring(prefixLength, myContentRange.getStartOffset()); } public StringNodeInfo(@NotNull PsiElement element) { this(element.getNode()); } @NotNull public ASTNode getNode() { return myNode; } /** * @return string prefix, e.g. "UR", "b" etc. */ @NotNull public String getPrefix() { return myPrefix; } /** * @return content of the string node between quotes */ @NotNull public String getContent() { return myContentRange.substring(myNode.getText()); } /** * @return <em>relative</em> range of the content (excluding prefix and quotes) * @see #getAbsoluteContentRange() */ @NotNull public TextRange getContentRange() { return myContentRange; } /** * @return <em>absolute</em> content range that accounts offset of the {@link #getNode() node} in the document */ @NotNull public TextRange getAbsoluteContentRange() { return getContentRange().shiftRight(myNode.getStartOffset()); } /** * @return the first character of {@link #getQuote()} */ public char getSingleQuote() { return myQuote.charAt(0); } @NotNull public String getQuote() { return myQuote; } public boolean isTripleQuoted() { return myQuote.length() == 3; } /** * @return true if string literal ends with starting quote */ public boolean isTerminated() { final String text = myNode.getText(); return text.length() - myPrefix.length() >= myQuote.length() * 2 && text.endsWith(myQuote); } /** * @return true if given string node contains "u" or "U" prefix */ public boolean isUnicode() { return StringUtil.containsIgnoreCase(myPrefix, "u"); } /** * @return true if given string node contains "r" or "R" prefix */ public boolean isRaw() { return StringUtil.containsIgnoreCase(myPrefix, "r"); } /** * @return true if given string node contains "b" or "B" prefix */ public boolean isBytes() { return StringUtil.containsIgnoreCase(myPrefix, "b"); } /** * @return true if other string node has the same decorations, i.e. quotes and prefix */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StringNodeInfo info = (StringNodeInfo)o; return getQuote().equals(info.getQuote()) && isRaw() == info.isRaw() && isUnicode() == info.isUnicode() && isBytes() == info.isBytes(); } } public static class IterHelper { // TODO: rename sanely private IterHelper() {} @Nullable public static PyElement findName(Iterable<PyElement> it, String name) { PyElement ret = null; for (PyElement elt : it) { if (elt != null) { // qualified refs don't match by last name, and we're not checking FQNs here if (elt instanceof PyQualifiedExpression && ((PyQualifiedExpression)elt).isQualified()) continue; if (name.equals(elt.getName())) { // plain name matches ret = elt; break; } } } return ret; } } }
python/src/com/jetbrains/python/psi/PyUtil.java
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.psi; import com.google.common.collect.Collections2; import com.google.common.collect.Maps; import com.intellij.codeInsight.FileModificationService; import com.intellij.codeInsight.completion.PrioritizedLookupElement; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.ide.fileTemplates.FileTemplate; import com.intellij.ide.fileTemplates.FileTemplateManager; import com.intellij.ide.scratch.ScratchFileService; import com.intellij.injected.editor.VirtualFileWindow; import com.intellij.lang.ASTFactory; import com.intellij.lang.ASTNode; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.highlighter.EditorHighlighter; import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.WindowManager; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtilCore; import com.intellij.psi.util.QualifiedName; import com.intellij.ui.awt.RelativePoint; import com.intellij.util.*; import com.intellij.util.containers.ContainerUtil; import com.jetbrains.NotNullPredicate; import com.jetbrains.python.PyBundle; import com.jetbrains.python.PyNames; import com.jetbrains.python.PyTokenTypes; import com.jetbrains.python.codeInsight.completion.OverwriteEqualsInsertHandler; import com.jetbrains.python.codeInsight.controlflow.ScopeOwner; import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil; import com.jetbrains.python.codeInsight.stdlib.PyNamedTupleType; import com.jetbrains.python.formatter.PyCodeStyleSettings; import com.jetbrains.python.magicLiteral.PyMagicLiteralTools; import com.jetbrains.python.psi.impl.PyBuiltinCache; import com.jetbrains.python.psi.impl.PyPsiUtils; import com.jetbrains.python.psi.impl.PyStringLiteralExpressionImpl; import com.jetbrains.python.psi.impl.PythonLanguageLevelPusher; import com.jetbrains.python.psi.resolve.PyResolveContext; import com.jetbrains.python.psi.resolve.QualifiedNameFinder; import com.jetbrains.python.psi.resolve.RatedResolveResult; import com.jetbrains.python.psi.stubs.PySetuptoolsNamespaceIndex; import com.jetbrains.python.psi.types.*; import com.jetbrains.python.refactoring.classes.PyDependenciesComparator; import com.jetbrains.python.refactoring.classes.extractSuperclass.PyExtractSuperclassHelper; import com.jetbrains.python.refactoring.classes.membersManager.PyMemberInfo; import com.jetbrains.python.sdk.PythonSdkType; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.*; import java.util.List; import static com.jetbrains.python.psi.PyFunction.Modifier.CLASSMETHOD; import static com.jetbrains.python.psi.PyFunction.Modifier.STATICMETHOD; public class PyUtil { public static final String PY_EXTENSION = ".py"; private PyUtil() { } @NotNull public static <T extends PyElement> T[] getAllChildrenOfType(@NotNull PsiElement element, @NotNull Class<T> aClass) { List<T> result = new SmartList<T>(); for (PsiElement child : element.getChildren()) { if (instanceOf(child, aClass)) { //noinspection unchecked result.add((T)child); } else { ContainerUtil.addAll(result, getAllChildrenOfType(child, aClass)); } } return ArrayUtil.toObjectArray(result, aClass); } /** * @see PyUtil#flattenedParensAndTuples */ protected static List<PyExpression> unfoldParentheses(PyExpression[] targets, List<PyExpression> receiver, boolean unfoldListLiterals, boolean unfoldStarExpressions) { // NOTE: this proliferation of instanceofs is not very beautiful. Maybe rewrite using a visitor. for (PyExpression exp : targets) { if (exp instanceof PyParenthesizedExpression) { final PyParenthesizedExpression parenExpr = (PyParenthesizedExpression)exp; unfoldParentheses(new PyExpression[]{parenExpr.getContainedExpression()}, receiver, unfoldListLiterals, unfoldStarExpressions); } else if (exp instanceof PyTupleExpression) { final PyTupleExpression tupleExpr = (PyTupleExpression)exp; unfoldParentheses(tupleExpr.getElements(), receiver, unfoldListLiterals, unfoldStarExpressions); } else if (exp instanceof PyListLiteralExpression && unfoldListLiterals) { final PyListLiteralExpression listLiteral = (PyListLiteralExpression)exp; unfoldParentheses(listLiteral.getElements(), receiver, true, unfoldStarExpressions); } else if (exp instanceof PyStarExpression && unfoldStarExpressions) { unfoldParentheses(new PyExpression[]{((PyStarExpression)exp).getExpression()}, receiver, unfoldListLiterals, true); } else if (exp != null) { receiver.add(exp); } } return receiver; } /** * Flattens the representation of every element in targets, and puts all results together. * Elements of every tuple nested in target item are brought to the top level: (a, (b, (c, d))) -> (a, b, c, d) * Typical usage: <code>flattenedParensAndTuples(some_tuple.getExpressions())</code>. * * @param targets target elements. * @return the list of flattened expressions. */ @NotNull public static List<PyExpression> flattenedParensAndTuples(PyExpression... targets) { return unfoldParentheses(targets, new ArrayList<PyExpression>(targets.length), false, false); } @NotNull public static List<PyExpression> flattenedParensAndLists(PyExpression... targets) { return unfoldParentheses(targets, new ArrayList<PyExpression>(targets.length), true, true); } @NotNull public static List<PyExpression> flattenedParensAndStars(PyExpression... targets) { return unfoldParentheses(targets, new ArrayList<PyExpression>(targets.length), false, true); } // Poor man's filter // TODO: move to a saner place public static boolean instanceOf(Object obj, Class... possibleClasses) { if (obj == null || possibleClasses == null) return false; for (Class cls : possibleClasses) { if (cls.isInstance(obj)) return true; } return false; } /** * Produce a reasonable representation of a PSI element, good for debugging. * * @param elt element to represent; nulls and invalid nodes are ok. * @param cutAtEOL if true, representation stops at nearest EOL inside the element. * @return the representation. */ @NotNull @NonNls public static String getReadableRepr(PsiElement elt, final boolean cutAtEOL) { if (elt == null) return "null!"; ASTNode node = elt.getNode(); if (node == null) { return "null"; } else { String s = node.getText(); int cut_pos; if (cutAtEOL) { cut_pos = s.indexOf('\n'); } else { cut_pos = -1; } if (cut_pos < 0) cut_pos = s.length(); return s.substring(0, Math.min(cut_pos, s.length())); } } @Nullable public static PyClass getContainingClassOrSelf(final PsiElement element) { PsiElement current = element; while (current != null && !(current instanceof PyClass)) { current = current.getParent(); } return (PyClass)current; } /** * @param element for which to obtain the file * @return PyFile, or null, if there's no containing file, or it is not a PyFile. */ @Nullable public static PyFile getContainingPyFile(PyElement element) { final PsiFile containingFile = element.getContainingFile(); return containingFile instanceof PyFile ? (PyFile)containingFile : null; } /** * Shows an information balloon in a reasonable place at the top right of the window. * * @param project our project * @param message the text, HTML markup allowed * @param messageType message type, changes the icon and the background. */ // TODO: move to a better place public static void showBalloon(Project project, String message, MessageType messageType) { // ripped from com.intellij.openapi.vcs.changes.ui.ChangesViewBalloonProblemNotifier final JFrame frame = WindowManager.getInstance().getFrame(project.isDefault() ? null : project); if (frame == null) return; final JComponent component = frame.getRootPane(); if (component == null) return; final Rectangle rect = component.getVisibleRect(); final Point p = new Point(rect.x + rect.width - 10, rect.y + 10); final RelativePoint point = new RelativePoint(component, p); JBPopupFactory.getInstance().createHtmlTextBalloonBuilder(message, messageType.getDefaultIcon(), messageType.getPopupBackground(), null) .setShowCallout(false).setCloseButtonEnabled(true) .createBalloon().show(point, Balloon.Position.atLeft); } @NonNls /** * Returns a quoted string representation, or "null". */ public static String nvl(Object s) { if (s != null) { return "'" + s.toString() + "'"; } else { return "null"; } } /** * Adds an item into a comma-separated list in a PSI tree. E.g. can turn "foo, bar" into "foo, bar, baz", adding commas as needed. * * @param parent the element to represent the list; we're adding a child to it. * @param newItem the element we're inserting (the "baz" in the example). * @param beforeThis node to mark the insertion point inside the list; must belong to a child of target. Set to null to add first element. * @param isFirst true if we don't need a comma before the element we're adding. * @param isLast true if we don't need a comma after the element we're adding. */ public static void addListNode(PsiElement parent, PsiElement newItem, ASTNode beforeThis, boolean isFirst, boolean isLast, boolean addWhitespace) { if (!FileModificationService.getInstance().preparePsiElementForWrite(parent)) { return; } ASTNode node = parent.getNode(); assert node != null; ASTNode itemNode = newItem.getNode(); assert itemNode != null; Project project = parent.getProject(); PyElementGenerator gen = PyElementGenerator.getInstance(project); if (!isFirst) node.addChild(gen.createComma(), beforeThis); node.addChild(itemNode, beforeThis); if (!isLast) node.addChild(gen.createComma(), beforeThis); if (addWhitespace) node.addChild(ASTFactory.whitespace(" "), beforeThis); } /** * Collects superclasses of a class all the way up the inheritance chain. The order is <i>not</i> necessarily the MRO. */ @NotNull public static List<PyClass> getAllSuperClasses(@NotNull PyClass pyClass) { List<PyClass> superClasses = new ArrayList<PyClass>(); for (PyClass ancestor : pyClass.getAncestorClasses(null)) { if (!PyNames.FAKE_OLD_BASE.equals(ancestor.getName())) { superClasses.add(ancestor); } } return superClasses; } // TODO: move to a more proper place? /** * Determine the type of a special attribute. Currently supported: {@code __class__} and {@code __dict__}. * * @param ref reference to a possible attribute; only qualified references make sense. * @return type, or null (if type cannot be determined, reference is not to a known attribute, etc.) */ @Nullable public static PyType getSpecialAttributeType(@Nullable PyReferenceExpression ref, TypeEvalContext context) { if (ref != null) { PyExpression qualifier = ref.getQualifier(); if (qualifier != null) { String attr_name = ref.getReferencedName(); if (PyNames.__CLASS__.equals(attr_name)) { PyType qualifierType = context.getType(qualifier); if (qualifierType instanceof PyClassType) { return new PyClassTypeImpl(((PyClassType)qualifierType).getPyClass(), true); // always as class, never instance } } else if (PyNames.DICT.equals(attr_name)) { PyType qualifierType = context.getType(qualifier); if (qualifierType instanceof PyClassType && ((PyClassType)qualifierType).isDefinition()) { return PyBuiltinCache.getInstance(ref).getDictType(); } } } } return null; } /** * Makes sure that 'thing' is not null; else throws an {@link IncorrectOperationException}. * * @param thing what we check. * @return thing, if not null. */ @NotNull public static <T> T sure(T thing) { if (thing == null) throw new IncorrectOperationException(); return thing; } /** * Makes sure that the 'thing' is true; else throws an {@link IncorrectOperationException}. * * @param thing what we check. */ public static void sure(boolean thing) { if (!thing) throw new IncorrectOperationException(); } public static boolean isAttribute(PyTargetExpression ex) { return isInstanceAttribute(ex) || isClassAttribute(ex); } public static boolean isInstanceAttribute(PyExpression target) { if (!(target instanceof PyTargetExpression)) { return false; } final ScopeOwner owner = ScopeUtil.getScopeOwner(target); if (owner instanceof PyFunction) { final PyFunction method = (PyFunction)owner; if (method.getContainingClass() != null) { if (method.getStub() != null) { return true; } final PyParameter[] params = method.getParameterList().getParameters(); if (params.length > 0) { final PyTargetExpression targetExpr = (PyTargetExpression)target; final PyExpression qualifier = targetExpr.getQualifier(); return qualifier != null && qualifier.getText().equals(params[0].getName()); } } } return false; } public static boolean isClassAttribute(PsiElement element) { return element instanceof PyTargetExpression && ScopeUtil.getScopeOwner(element) instanceof PyClass; } public static boolean isIfNameEqualsMain(PyIfStatement ifStatement) { final PyExpression condition = ifStatement.getIfPart().getCondition(); return isNameEqualsMain(condition); } private static boolean isNameEqualsMain(PyExpression condition) { if (condition instanceof PyParenthesizedExpression) { return isNameEqualsMain(((PyParenthesizedExpression)condition).getContainedExpression()); } if (condition instanceof PyBinaryExpression) { PyBinaryExpression binaryExpression = (PyBinaryExpression)condition; if (binaryExpression.getOperator() == PyTokenTypes.OR_KEYWORD) { return isNameEqualsMain(binaryExpression.getLeftExpression()) || isNameEqualsMain(binaryExpression.getRightExpression()); } final PyExpression rhs = binaryExpression.getRightExpression(); return binaryExpression.getOperator() == PyTokenTypes.EQEQ && binaryExpression.getLeftExpression().getText().equals(PyNames.NAME) && rhs != null && rhs.getText().contains("__main__"); } return false; } /** * Searches for a method wrapping given element. * * @param start element presumably inside a method * @param deep if true, allow 'start' to be inside functions nested in a method; else, 'start' must be directly inside a method. * @return if not 'deep', [0] is the method and [1] is the class; if 'deep', first several elements may be the nested functions, * the last but one is the method, and the last is the class. */ @Nullable public static List<PsiElement> searchForWrappingMethod(PsiElement start, boolean deep) { PsiElement seeker = start; List<PsiElement> ret = new ArrayList<PsiElement>(2); while (seeker != null) { PyFunction func = PsiTreeUtil.getParentOfType(seeker, PyFunction.class, true, PyClass.class); if (func != null) { PyClass cls = func.getContainingClass(); if (cls != null) { ret.add(func); ret.add(cls); return ret; } else if (deep) { ret.add(func); seeker = func; } else { return null; // no immediate class } } else { return null; // no function } } return null; } public static boolean inSameFile(@NotNull PsiElement e1, @NotNull PsiElement e2) { final PsiFile f1 = e1.getContainingFile(); final PsiFile f2 = e2.getContainingFile(); if (f1 == null || f2 == null) { return false; } return f1 == f2; } public static boolean onSameLine(@NotNull PsiElement e1, @NotNull PsiElement e2) { final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(e1.getProject()); final Document document = documentManager.getDocument(e1.getContainingFile()); if (document == null || document != documentManager.getDocument(e2.getContainingFile())) { return false; } return document.getLineNumber(e1.getTextOffset()) == document.getLineNumber(e2.getTextOffset()); } public static boolean isTopLevel(@NotNull PsiElement element) { if (element instanceof StubBasedPsiElement) { final StubElement stub = ((StubBasedPsiElement)element).getStub(); if (stub != null) { final StubElement parentStub = stub.getParentStub(); if (parentStub != null) { return parentStub.getPsi() instanceof PsiFile; } } } return ScopeUtil.getScopeOwner(element) instanceof PsiFile; } public static void deletePycFiles(String pyFilePath) { if (pyFilePath.endsWith(PY_EXTENSION)) { List<File> filesToDelete = new ArrayList<File>(); File pyc = new File(pyFilePath + "c"); if (pyc.exists()) { filesToDelete.add(pyc); } File pyo = new File(pyFilePath + "o"); if (pyo.exists()) { filesToDelete.add(pyo); } final File file = new File(pyFilePath); File pycache = new File(file.getParentFile(), PyNames.PYCACHE); if (pycache.isDirectory()) { final String shortName = FileUtil.getNameWithoutExtension(file); Collections.addAll(filesToDelete, pycache.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { if (!FileUtilRt.extensionEquals(pathname.getName(), "pyc")) return false; String nameWithMagic = FileUtil.getNameWithoutExtension(pathname); return FileUtil.getNameWithoutExtension(nameWithMagic).equals(shortName); } })); } FileUtil.asyncDelete(filesToDelete); } } public static String getElementNameWithoutExtension(PsiNamedElement psiNamedElement) { return psiNamedElement instanceof PyFile ? FileUtil.getNameWithoutExtension(((PyFile)psiNamedElement).getName()) : psiNamedElement.getName(); } public static boolean hasUnresolvedAncestors(@NotNull PyClass cls, @NotNull TypeEvalContext context) { for (PyClassLikeType type : cls.getAncestorTypes(context)) { if (type == null) { return true; } } return false; } @NotNull public static AccessDirection getPropertyAccessDirection(@NotNull PyFunction function) { final Property property = function.getProperty(); if (property != null) { if (property.getGetter().valueOrNull() == function) { return AccessDirection.READ; } if (property.getSetter().valueOrNull() == function) { return AccessDirection.WRITE; } else if (property.getDeleter().valueOrNull() == function) { return AccessDirection.DELETE; } } return AccessDirection.READ; } public static void removeQualifier(@NotNull final PyReferenceExpression element) { final PyExpression qualifier = element.getQualifier(); if (qualifier == null) return; if (qualifier instanceof PyCallExpression) { final PyExpression callee = ((PyCallExpression)qualifier).getCallee(); if (callee instanceof PyReferenceExpression) { final PyExpression calleeQualifier = ((PyReferenceExpression)callee).getQualifier(); if (calleeQualifier != null) { qualifier.replace(calleeQualifier); return; } } } final PsiElement dot = PyPsiUtils.getNextNonWhitespaceSibling(qualifier); if (dot != null) dot.delete(); qualifier.delete(); } /** * Returns string that represents element in string search. * * @param element element to search * @return string that represents element */ @NotNull public static String computeElementNameForStringSearch(@NotNull final PsiElement element) { if (element instanceof PyFile) { return FileUtil.getNameWithoutExtension(((PyFile)element).getName()); } if (element instanceof PsiDirectory) { return ((PsiDirectory)element).getName(); } // Magic literals are always represented by their string values if ((element instanceof PyStringLiteralExpression) && PyMagicLiteralTools.isMagicLiteral(element)) { final String name = ((StringLiteralExpression)element).getStringValue(); if (name != null) { return name; } } if (element instanceof PyElement) { final String name = ((PyElement)element).getName(); if (name != null) { return name; } } return element.getNode().getText(); } public static boolean isOwnScopeComprehension(@NotNull PyComprehensionElement comprehension) { final boolean isAtLeast30 = LanguageLevel.forElement(comprehension).isAtLeast(LanguageLevel.PYTHON30); final boolean isListComprehension = comprehension instanceof PyListCompExpression; return !isListComprehension || isAtLeast30; } public static boolean hasCustomDecorators(@NotNull PyDecoratable decoratable) { return PyKnownDecoratorUtil.hasNonBuiltinDecorator(decoratable, TypeEvalContext.codeInsightFallback(null)); } public static boolean isDecoratedAsAbstract(@NotNull final PyDecoratable decoratable) { return PyKnownDecoratorUtil.hasAbstractDecorator(decoratable, TypeEvalContext.codeInsightFallback(null)); } public static ASTNode createNewName(PyElement element, String name) { return PyElementGenerator.getInstance(element.getProject()).createNameIdentifier(name, LanguageLevel.forElement(element)); } /** * Finds element declaration by resolving its references top the top but not further than file (to prevent un-stubbing) * * @param elementToResolve element to resolve * @return its declaration */ @NotNull public static PsiElement resolveToTheTop(@NotNull final PsiElement elementToResolve) { PsiElement currentElement = elementToResolve; while (true) { final PsiReference reference = currentElement.getReference(); if (reference == null) { break; } final PsiElement resolve = reference.resolve(); if ((resolve == null) || resolve.equals(currentElement) || !inSameFile(resolve, currentElement)) { break; } currentElement = resolve; } return currentElement; } /** * Note that returned list may contain {@code null} items, e.g. for unresolved import elements, originally wrapped * in {@link com.jetbrains.python.psi.resolve.ImportedResolveResult}. */ @NotNull public static List<PsiElement> multiResolveTopPriority(@NotNull PsiElement element, @NotNull PyResolveContext resolveContext) { if (element instanceof PyReferenceOwner) { final PsiPolyVariantReference ref = ((PyReferenceOwner)element).getReference(resolveContext); return filterTopPriorityResults(ref.multiResolve(false)); } else { final PsiReference reference = element.getReference(); return reference != null ? Collections.singletonList(reference.resolve()) : Collections.<PsiElement>emptyList(); } } @NotNull public static List<PsiElement> multiResolveTopPriority(@NotNull PsiPolyVariantReference reference) { return filterTopPriorityResults(reference.multiResolve(false)); } @NotNull private static List<PsiElement> filterTopPriorityResults(@NotNull ResolveResult[] resolveResults) { if (resolveResults.length == 0) { return Collections.emptyList(); } final List<PsiElement> filtered = new ArrayList<PsiElement>(); final int maxRate = getMaxRate(resolveResults); for (ResolveResult resolveResult : resolveResults) { final int rate = resolveResult instanceof RatedResolveResult ? ((RatedResolveResult)resolveResult).getRate() : 0; if (rate >= maxRate) { filtered.add(resolveResult.getElement()); } } return filtered; } private static int getMaxRate(@NotNull ResolveResult[] resolveResults) { int maxRate = Integer.MIN_VALUE; for (ResolveResult resolveResult : resolveResults) { if (resolveResult instanceof RatedResolveResult) { final int rate = ((RatedResolveResult)resolveResult).getRate(); if (rate > maxRate) { maxRate = rate; } } } return maxRate; } /** * Gets class init method * * @param pyClass class where to find init * @return class init method if any */ @Nullable public static PyFunction getInitMethod(@NotNull final PyClass pyClass) { return pyClass.findMethodByName(PyNames.INIT, false, null); } /** * Returns Python language level for a virtual file. * * @see {@link LanguageLevel#forElement} */ @NotNull public static LanguageLevel getLanguageLevelForVirtualFile(@NotNull Project project, @NotNull VirtualFile virtualFile) { if (virtualFile instanceof VirtualFileWindow) { virtualFile = ((VirtualFileWindow)virtualFile).getDelegate(); } // Most of the cases should be handled by this one, PyLanguageLevelPusher pushes folders only final VirtualFile folder = virtualFile.getParent(); if (folder != null) { final LanguageLevel folderLevel = folder.getUserData(LanguageLevel.KEY); if (folderLevel != null) { return folderLevel; } final LanguageLevel fileLevel = PythonLanguageLevelPusher.getFileLanguageLevel(project, virtualFile); if (fileLevel != null) { return fileLevel; } } else { // However this allows us to setup language level per file manually // in case when it is LightVirtualFile final LanguageLevel level = virtualFile.getUserData(LanguageLevel.KEY); if (level != null) return level; if (ApplicationManager.getApplication().isUnitTestMode()) { final LanguageLevel languageLevel = LanguageLevel.FORCE_LANGUAGE_LEVEL; if (languageLevel != null) { return languageLevel; } } } return guessLanguageLevelWithCaching(project); } public static void invalidateLanguageLevelCache(@NotNull Project project) { project.putUserData(PythonLanguageLevelPusher.PYTHON_LANGUAGE_LEVEL, null); } @NotNull public static LanguageLevel guessLanguageLevelWithCaching(@NotNull Project project) { LanguageLevel languageLevel = project.getUserData(PythonLanguageLevelPusher.PYTHON_LANGUAGE_LEVEL); if (languageLevel == null) { languageLevel = guessLanguageLevel(project); project.putUserData(PythonLanguageLevelPusher.PYTHON_LANGUAGE_LEVEL, languageLevel); } return languageLevel; } @NotNull public static LanguageLevel guessLanguageLevel(@NotNull Project project) { final ModuleManager moduleManager = ModuleManager.getInstance(project); if (moduleManager != null) { LanguageLevel maxLevel = null; for (Module projectModule : moduleManager.getModules()) { final Sdk sdk = PythonSdkType.findPythonSdk(projectModule); if (sdk != null) { final LanguageLevel level = PythonSdkType.getLanguageLevelForSdk(sdk); if (maxLevel == null || maxLevel.isOlderThan(level)) { maxLevel = level; } } } if (maxLevel != null) { return maxLevel; } } return LanguageLevel.getDefault(); } /** * Clone of C# "as" operator. * Checks if expression has correct type and casts it if it has. Returns null otherwise. * It saves coder from "instanceof / cast" chains. * * @param expression expression to check * @param clazz class to cast * @param <T> class to cast * @return expression casted to appropriate type (if could be casted). Null otherwise. */ @Nullable @SuppressWarnings("unchecked") public static <T> T as(@Nullable final Object expression, @NotNull final Class<T> clazz) { return ObjectUtils.tryCast(expression, clazz); } // TODO: Move to PsiElement? /** * Searches for references injected to element with certain type * * @param element element to search injected references for * @param expectedClass expected type of element reference resolved to * @param <T> expected type of element reference resolved to * @return resolved element if found or null if not found */ @Nullable public static <T extends PsiElement> T findReference(@NotNull final PsiElement element, @NotNull final Class<T> expectedClass) { for (final PsiReference reference : element.getReferences()) { final T result = as(reference.resolve(), expectedClass); if (result != null) { return result; } } return null; } /** * Converts collection to list of certain type * * @param expression expression of collection type * @param elementClass expected element type * @param <T> expected element type * @return list of elements of expected element type */ @NotNull public static <T> List<T> asList(@Nullable final Collection<?> expression, @NotNull final Class<T> elementClass) { if ((expression == null) || expression.isEmpty()) { return Collections.emptyList(); } final List<T> result = new ArrayList<T>(); for (final Object element : expression) { final T toAdd = as(element, elementClass); if (toAdd != null) { result.add(toAdd); } } return result; } /** * Force re-highlighting in all open editors that belong to specified project. */ public static void rehighlightOpenEditors(final @NotNull Project project) { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { for (Editor editor : EditorFactory.getInstance().getAllEditors()) { if (editor instanceof EditorEx && editor.getProject() == project) { final VirtualFile vFile = ((EditorEx)editor).getVirtualFile(); if (vFile != null) { final EditorHighlighter highlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter(project, vFile); ((EditorEx)editor).setHighlighter(highlighter); } } } } }); } public static class KnownDecoratorProviderHolder { public static PyKnownDecoratorProvider[] KNOWN_DECORATOR_PROVIDERS = Extensions.getExtensions(PyKnownDecoratorProvider.EP_NAME); private KnownDecoratorProviderHolder() { } } /** * If argument is a PsiDirectory, turn it into a PsiFile that points to __init__.py in that directory. * If there's no __init__.py there, null is returned, there's no point to resolve to a dir which is not a package. * Alas, resolve() and multiResolve() can't return anything but a PyFile or PsiFileImpl.isPsiUpToDate() would fail. * This is because isPsiUpToDate() relies on identity of objects returned by FileViewProvider.getPsi(). * If we ever need to exactly tell a dir from __init__.py, that logic has to change. * * @param target a resolve candidate. * @return a PsiFile if target was a PsiDirectory, or null, or target unchanged. */ @Nullable public static PsiElement turnDirIntoInit(@Nullable PsiElement target) { if (target instanceof PsiDirectory) { final PsiDirectory dir = (PsiDirectory)target; final PsiFile file = dir.findFile(PyNames.INIT_DOT_PY); if (file != null) { return file; // ResolveImportUtil will extract directory part as needed, everyone else are better off with a file. } else { return null; } // dir without __init__.py does not resolve } else { return target; } // don't touch non-dirs } /** * If directory is a PsiDirectory, that is also a valid Python package, return PsiFile that points to __init__.py, * if such file exists, or directory itself (i.e. namespace package). Otherwise, return {@code null}. * Unlike {@link #turnDirIntoInit(PsiElement)} this function handles namespace packages and * accepts only PsiDirectories as target. * * @param directory directory to check * @param anchor optional PSI element to determine language level as for {@link #isPackage(PsiDirectory, PsiElement)} * @return PsiFile or PsiDirectory, if target is a Python package and {@code null} null otherwise */ @Nullable public static PsiElement getPackageElement(@NotNull PsiDirectory directory, @Nullable PsiElement anchor) { if (isPackage(directory, anchor)) { final PsiElement init = turnDirIntoInit(directory); if (init != null) { return init; } return directory; } return null; } /** * If target is a Python module named __init__.py file, return its directory. Otherwise return target unchanged. * @param target PSI element to check * @return PsiDirectory or target unchanged */ @Contract("null -> null; !null -> !null") @Nullable public static PsiElement turnInitIntoDir(@Nullable PsiElement target) { if (target instanceof PyFile && isPackage((PsiFile)target)) { return ((PsiFile)target).getContainingDirectory(); } return target; } /** * @see #isPackage(PsiDirectory, boolean, PsiElement) */ public static boolean isPackage(@NotNull PsiDirectory directory, @Nullable PsiElement anchor) { return isPackage(directory, true, anchor); } /** * Checks that given PsiDirectory can be treated as Python package, i.e. it's either contains __init__.py or it's a namespace package * (effectively any directory in Python 3.3 and above). Setuptools namespace packages can be checked as well, but it requires access to * {@link PySetuptoolsNamespaceIndex} and may slow things down during update of project indexes. * Also note that this method does not check that directory itself and its parents have valid importable names, * use {@link PyNames#isIdentifier(String)} for this purpose. * * @param directory PSI directory to check * @param checkSetupToolsPackages whether setuptools namespace packages should be considered as well * @param anchor optional anchor element to determine language level * @return whether given directory is Python package * * @see PyNames#isIdentifier(String) */ public static boolean isPackage(@NotNull PsiDirectory directory, boolean checkSetupToolsPackages, @Nullable PsiElement anchor) { if (directory.findFile(PyNames.INIT_DOT_PY) != null) { return true; } final LanguageLevel level = anchor != null ? LanguageLevel.forElement(anchor) : getLanguageLevelForVirtualFile(directory.getProject(), directory.getVirtualFile()); if (level.isAtLeast(LanguageLevel.PYTHON33)) { return true; } return checkSetupToolsPackages && isSetuptoolsNamespacePackage(directory); } public static boolean isPackage(@NotNull PsiFile file) { return PyNames.INIT_DOT_PY.equals(file.getName()); } private static boolean isSetuptoolsNamespacePackage(@NotNull PsiDirectory directory) { final String packagePath = getPackagePath(directory); return packagePath != null && !PySetuptoolsNamespaceIndex.find(packagePath, directory.getProject()).isEmpty(); } @Nullable private static String getPackagePath(@NotNull PsiDirectory directory) { final QualifiedName name = QualifiedNameFinder.findShortestImportableQName(directory); return name != null ? name.toString() : null; } /** * Counts initial underscores of an identifier. * * @param name identifier * @return 0 if no initial underscores found, 1 if there's only one underscore, 2 if there's two or more initial underscores. */ public static int getInitialUnderscores(String name) { if (name == null) { return 0; } int underscores = 0; if (name.startsWith("__")) { underscores = 2; } else if (name.startsWith("_")) underscores = 1; return underscores; } /** * @param name * @return true iff the name looks like a class-private one, starting with two underscores but not ending with two underscores. */ public static boolean isClassPrivateName(@NotNull String name) { return name.startsWith("__") && !name.endsWith("__"); } public static boolean isSpecialName(@NotNull String name) { return name.length() > 4 && name.startsWith("__") && name.endsWith("__"); } /** * Constructs new lookup element for completion of keyword argument with equals sign appended. * * @param name name of the parameter * @param project project instance to check code style settings and surround equals sign with spaces if necessary * @return lookup element */ @NotNull public static LookupElement createNamedParameterLookup(@NotNull String name, @Nullable Project project) { final String suffix; if (CodeStyleSettingsManager.getSettings(project).getCustomSettings(PyCodeStyleSettings.class).SPACE_AROUND_EQ_IN_KEYWORD_ARGUMENT) { suffix = " = "; } else { suffix = "="; } LookupElementBuilder lookupElementBuilder = LookupElementBuilder.create(name + suffix).withIcon(PlatformIcons.PARAMETER_ICON); lookupElementBuilder = lookupElementBuilder.withInsertHandler(OverwriteEqualsInsertHandler.INSTANCE); return PrioritizedLookupElement.withGrouping(lookupElementBuilder, 1); } /** * Peels argument expression of parentheses and of keyword argument wrapper * * @param expr an item of getArguments() array * @return expression actually passed as argument */ @Nullable public static PyExpression peelArgument(PyExpression expr) { while (expr instanceof PyParenthesizedExpression) expr = ((PyParenthesizedExpression)expr).getContainedExpression(); if (expr instanceof PyKeywordArgument) expr = ((PyKeywordArgument)expr).getValueExpression(); return expr; } public static String getFirstParameterName(PyFunction container) { String selfName = PyNames.CANONICAL_SELF; if (container != null) { final PyParameter[] params = container.getParameterList().getParameters(); if (params.length > 0) { final PyNamedParameter named = params[0].getAsNamed(); if (named != null) { selfName = named.getName(); } } } return selfName; } /** * @return Source roots <strong>and</strong> content roots for element's project */ @NotNull public static Collection<VirtualFile> getSourceRoots(@NotNull PsiElement foothold) { final Module module = ModuleUtilCore.findModuleForPsiElement(foothold); if (module != null) { return getSourceRoots(module); } return Collections.emptyList(); } /** * @return Source roots <strong>and</strong> content roots for module */ @NotNull public static Collection<VirtualFile> getSourceRoots(@NotNull Module module) { final Set<VirtualFile> result = new LinkedHashSet<VirtualFile>(); final ModuleRootManager manager = ModuleRootManager.getInstance(module); Collections.addAll(result, manager.getSourceRoots()); Collections.addAll(result, manager.getContentRoots()); return result; } @Nullable public static VirtualFile findInRoots(Module module, String path) { if (module != null) { for (VirtualFile root : getSourceRoots(module)) { VirtualFile file = root.findFileByRelativePath(path); if (file != null) { return file; } } } return null; } @Nullable public static List<String> getStringListFromTargetExpression(PyTargetExpression attr) { return strListValue(attr.findAssignedValue()); } @Nullable public static List<String> strListValue(PyExpression value) { while (value instanceof PyParenthesizedExpression) { value = ((PyParenthesizedExpression)value).getContainedExpression(); } if (value instanceof PySequenceExpression) { final PyExpression[] elements = ((PySequenceExpression)value).getElements(); List<String> result = new ArrayList<String>(elements.length); for (PyExpression element : elements) { if (!(element instanceof PyStringLiteralExpression)) { return null; } result.add(((PyStringLiteralExpression)element).getStringValue()); } return result; } return null; } @NotNull public static Map<String, PyExpression> dictValue(@NotNull PyDictLiteralExpression dict) { Map<String, PyExpression> result = Maps.newLinkedHashMap(); for (PyKeyValueExpression keyValue : dict.getElements()) { PyExpression key = keyValue.getKey(); PyExpression value = keyValue.getValue(); if (key instanceof PyStringLiteralExpression) { result.put(((PyStringLiteralExpression)key).getStringValue(), value); } } return result; } /** * @param what thing to search for * @param variants things to search among * @return true iff what.equals() one of the variants. */ public static <T> boolean among(@NotNull T what, T... variants) { for (T s : variants) { if (what.equals(s)) return true; } return false; } @Nullable public static String getKeywordArgumentString(PyCallExpression expr, String keyword) { return PyPsiUtils.strValue(expr.getKeywordArgument(keyword)); } public static boolean isExceptionClass(PyClass pyClass) { if (isBaseException(pyClass.getQualifiedName())) { return true; } for (PyClassLikeType type : pyClass.getAncestorTypes(TypeEvalContext.codeInsightFallback(pyClass.getProject()))) { if (type != null && isBaseException(type.getClassQName())) { return true; } } return false; } private static boolean isBaseException(String name) { return name != null && (name.contains("BaseException") || name.startsWith("exceptions.")); } public static class MethodFlags { private final boolean myIsStaticMethod; private final boolean myIsMetaclassMethod; private final boolean myIsSpecialMetaclassMethod; private final boolean myIsClassMethod; /** * @return true iff the method belongs to a metaclass (an ancestor of 'type'). */ public boolean isMetaclassMethod() { return myIsMetaclassMethod; } /** * @return iff isMetaclassMethod and the method is either __init__ or __call__. */ public boolean isSpecialMetaclassMethod() { return myIsSpecialMetaclassMethod; } public boolean isStaticMethod() { return myIsStaticMethod; } public boolean isClassMethod() { return myIsClassMethod; } private MethodFlags(boolean isClassMethod, boolean isStaticMethod, boolean isMetaclassMethod, boolean isSpecialMetaclassMethod) { myIsClassMethod = isClassMethod; myIsStaticMethod = isStaticMethod; myIsMetaclassMethod = isMetaclassMethod; myIsSpecialMetaclassMethod = isSpecialMetaclassMethod; } /** * @param node a function * @return a new flags object, or null if the function is not a method */ @Nullable public static MethodFlags of(@NotNull PyFunction node) { PyClass cls = node.getContainingClass(); if (cls != null) { PyFunction.Modifier modifier = node.getModifier(); boolean isMetaclassMethod = false; PyClass type_cls = PyBuiltinCache.getInstance(node).getClass("type"); for (PyClass ancestor_cls : cls.getAncestorClasses(null)) { if (ancestor_cls == type_cls) { isMetaclassMethod = true; break; } } final String method_name = node.getName(); boolean isSpecialMetaclassMethod = isMetaclassMethod && method_name != null && among(method_name, PyNames.INIT, "__call__"); return new MethodFlags(modifier == CLASSMETHOD, modifier == STATICMETHOD, isMetaclassMethod, isSpecialMetaclassMethod); } return null; } //TODO: Doc public boolean isInstanceMethod() { return !(myIsClassMethod || myIsStaticMethod); } } public static boolean isSuperCall(@NotNull PyCallExpression node) { PyClass klass = PsiTreeUtil.getParentOfType(node, PyClass.class); if (klass == null) return false; PyExpression callee = node.getCallee(); if (callee == null) return false; String name = callee.getName(); if (PyNames.SUPER.equals(name)) { PsiReference reference = callee.getReference(); if (reference == null) return false; PsiElement resolved = reference.resolve(); PyBuiltinCache cache = PyBuiltinCache.getInstance(node); if (resolved != null && cache.isBuiltin(resolved)) { PyExpression[] args = node.getArguments(); if (args.length > 0) { String firstArg = args[0].getText(); if (firstArg.equals(klass.getName()) || firstArg.equals(PyNames.CANONICAL_SELF + "." + PyNames.__CLASS__)) { return true; } for (PyClass s : klass.getAncestorClasses(null)) { if (firstArg.equals(s.getName())) { return true; } } } else { return true; } } } return false; } @NotNull public static PyFile getOrCreateFile(String path, Project project) { final VirtualFile vfile = LocalFileSystem.getInstance().findFileByIoFile(new File(path)); final PsiFile psi; if (vfile == null) { final File file = new File(path); try { final VirtualFile baseDir = project.getBaseDir(); final FileTemplateManager fileTemplateManager = FileTemplateManager.getInstance(project); final FileTemplate template = fileTemplateManager.getInternalTemplate("Python Script"); final Properties properties = fileTemplateManager.getDefaultProperties(); properties.setProperty("NAME", FileUtil.getNameWithoutExtension(file.getName())); final String content = (template != null) ? template.getText(properties) : null; psi = PyExtractSuperclassHelper.placeFile(project, StringUtil.notNullize( file.getParent(), baseDir != null ? baseDir .getPath() : "." ), file.getName(), content ); } catch (IOException e) { throw new IncorrectOperationException(String.format("Cannot create file '%s'", path), (Throwable)e); } } else { psi = PsiManager.getInstance(project).findFile(vfile); } if (!(psi instanceof PyFile)) { throw new IncorrectOperationException(PyBundle.message( "refactoring.move.module.members.error.cannot.place.elements.into.nonpython.file")); } return (PyFile)psi; } /** * counts elements in iterable * * @param expression to count containing elements (iterable) * @return element count */ public static int getElementsCount(PyExpression expression, TypeEvalContext evalContext) { int valuesLength = -1; PyType type = evalContext.getType(expression); if (type instanceof PyTupleType) { valuesLength = ((PyTupleType)type).getElementCount(); } else if (type instanceof PyNamedTupleType) { valuesLength = ((PyNamedTupleType)type).getElementCount(); } else if (expression instanceof PySequenceExpression) { valuesLength = ((PySequenceExpression)expression).getElements().length; } else if (expression instanceof PyStringLiteralExpression) { valuesLength = ((PyStringLiteralExpression)expression).getStringValue().length(); } else if (expression instanceof PyNumericLiteralExpression) { valuesLength = 1; } else if (expression instanceof PyCallExpression) { PyCallExpression call = (PyCallExpression)expression; if (call.isCalleeText("dict")) { valuesLength = call.getArguments().length; } else if (call.isCalleeText("tuple")) { PyExpression[] arguments = call.getArguments(); if (arguments.length > 0 && arguments[0] instanceof PySequenceExpression) { valuesLength = ((PySequenceExpression)arguments[0]).getElements().length; } } } return valuesLength; } @Nullable public static PsiElement findPrevAtOffset(PsiFile psiFile, int caretOffset, Class... toSkip) { PsiElement element; if (caretOffset < 0) { return null; } int lineStartOffset = 0; final Document document = PsiDocumentManager.getInstance(psiFile.getProject()).getDocument(psiFile); if (document != null) { int lineNumber = document.getLineNumber(caretOffset); lineStartOffset = document.getLineStartOffset(lineNumber); } do { caretOffset--; element = psiFile.findElementAt(caretOffset); } while (caretOffset >= lineStartOffset && instanceOf(element, toSkip)); return instanceOf(element, toSkip) ? null : element; } @Nullable public static PsiElement findNonWhitespaceAtOffset(PsiFile psiFile, int caretOffset) { PsiElement element = findNextAtOffset(psiFile, caretOffset, PsiWhiteSpace.class); if (element == null) { element = findPrevAtOffset(psiFile, caretOffset - 1, PsiWhiteSpace.class); } return element; } @Nullable public static PsiElement findElementAtOffset(PsiFile psiFile, int caretOffset) { PsiElement element = findPrevAtOffset(psiFile, caretOffset); if (element == null) { element = findNextAtOffset(psiFile, caretOffset); } return element; } @Nullable public static PsiElement findNextAtOffset(@NotNull final PsiFile psiFile, int caretOffset, Class... toSkip) { PsiElement element = psiFile.findElementAt(caretOffset); if (element == null) { return null; } final Document document = PsiDocumentManager.getInstance(psiFile.getProject()).getDocument(psiFile); int lineEndOffset = 0; if (document != null) { int lineNumber = document.getLineNumber(caretOffset); lineEndOffset = document.getLineEndOffset(lineNumber); } while (caretOffset < lineEndOffset && instanceOf(element, toSkip)) { caretOffset++; element = psiFile.findElementAt(caretOffset); } return instanceOf(element, toSkip) ? null : element; } /** * Adds element to statement list to the correct place according to its dependencies. * * @param element to insert * @param statementList where element should be inserted * @return inserted element */ public static <T extends PyElement> T addElementToStatementList(@NotNull final T element, @NotNull final PyStatementList statementList) { PsiElement before = null; PsiElement after = null; for (final PyStatement statement : statementList.getStatements()) { if (PyDependenciesComparator.depends(element, statement)) { after = statement; } else if (PyDependenciesComparator.depends(statement, element)) { before = statement; } } final PsiElement result; if (after != null) { result = statementList.addAfter(element, after); } else if (before != null) { result = statementList.addBefore(element, before); } else { result = addElementToStatementList(element, statementList, true); } @SuppressWarnings("unchecked") // Inserted element can't have different type final T resultCasted = (T)result; return resultCasted; } /** * Inserts specified element into the statement list either at the beginning or at its end. If new element is going to be * inserted at the beginning, any preceding docstrings and/or calls to super methods will be skipped. * Moreover if statement list previously didn't contain any statements, explicit new line and indentation will be inserted in * front of it. * * @param element element to insert * @param statementList statement list * @param toTheBeginning whether to insert element at the beginning or at the end of the statement list * @return actually inserted element as for {@link PsiElement#add(PsiElement)} */ @NotNull public static PsiElement addElementToStatementList(@NotNull PsiElement element, @NotNull PyStatementList statementList, boolean toTheBeginning) { final PsiElement prevElem = PyPsiUtils.getPrevNonWhitespaceSibling(statementList); // If statement list is on the same line as previous element (supposedly colon), move its only statement on the next line if (prevElem != null && onSameLine(statementList, prevElem)) { final PsiDocumentManager manager = PsiDocumentManager.getInstance(statementList.getProject()); final Document document = manager.getDocument(statementList.getContainingFile()); if (document != null) { final PyStatementListContainer container = (PyStatementListContainer)statementList.getParent(); manager.doPostponedOperationsAndUnblockDocument(document); final String indentation = "\n" + PyIndentUtil.getElementIndent(statementList); // If statement list was empty initially, we need to add some anchor statement ("pass"), so that preceding new line was not // parsed as following entire StatementListContainer (e.g. function). It's going to be replaced anyway. final String text = statementList.getStatements().length == 0 ? indentation + PyNames.PASS : indentation; document.insertString(statementList.getTextRange().getStartOffset(), text); manager.commitDocument(document); statementList = container.getStatementList(); } } final PsiElement firstChild = statementList.getFirstChild(); if (firstChild == statementList.getLastChild() && firstChild instanceof PyPassStatement) { element = firstChild.replace(element); } else { final PyStatement[] statements = statementList.getStatements(); if (toTheBeginning && statements.length > 0) { final PyDocStringOwner docStringOwner = PsiTreeUtil.getParentOfType(statementList, PyDocStringOwner.class); PyStatement anchor = statements[0]; if (docStringOwner != null && anchor instanceof PyExpressionStatement && ((PyExpressionStatement)anchor).getExpression() == docStringOwner.getDocStringExpression()) { final PyStatement next = PsiTreeUtil.getNextSiblingOfType(anchor, PyStatement.class); if (next == null) { return statementList.addAfter(element, anchor); } anchor = next; } while (anchor instanceof PyExpressionStatement) { final PyExpression expression = ((PyExpressionStatement)anchor).getExpression(); if (expression instanceof PyCallExpression) { final PyExpression callee = ((PyCallExpression)expression).getCallee(); if ((isSuperCall((PyCallExpression)expression) || (callee != null && PyNames.INIT.equals(callee.getName())))) { final PyStatement next = PsiTreeUtil.getNextSiblingOfType(anchor, PyStatement.class); if (next == null) { return statementList.addAfter(element, anchor); } anchor = next; continue; } } break; } element = statementList.addBefore(element, anchor); } else { element = statementList.add(element); } } return element; } @NotNull public static List<List<PyParameter>> getOverloadedParametersSet(@NotNull PyCallable callable, @NotNull TypeEvalContext context) { final List<List<PyParameter>> parametersSet = getOverloadedParametersSet(context.getType(callable), context); return parametersSet != null ? parametersSet : Collections.singletonList(Arrays.asList(callable.getParameterList().getParameters())); } @Nullable private static List<PyParameter> getParametersOfCallableType(@NotNull PyCallableType type, @NotNull TypeEvalContext context) { final List<PyCallableParameter> callableTypeParameters = type.getParameters(context); if (callableTypeParameters != null) { boolean allParametersDefined = true; final List<PyParameter> parameters = new ArrayList<PyParameter>(); for (PyCallableParameter callableParameter : callableTypeParameters) { final PyParameter parameter = callableParameter.getParameter(); if (parameter == null) { allParametersDefined = false; break; } parameters.add(parameter); } if (allParametersDefined) { return parameters; } } return null; } @Nullable private static List<List<PyParameter>> getOverloadedParametersSet(@Nullable PyType type, @NotNull TypeEvalContext context) { if (type instanceof PyUnionType) { type = ((PyUnionType)type).excludeNull(context); } if (type instanceof PyCallableType) { final List<PyParameter> results = getParametersOfCallableType((PyCallableType)type, context); if (results != null) { return Collections.singletonList(results); } } else if (type instanceof PyUnionType) { final List<List<PyParameter>> results = new ArrayList<List<PyParameter>>(); final Collection<PyType> members = ((PyUnionType)type).getMembers(); for (PyType member : members) { if (member instanceof PyCallableType) { final List<PyParameter> parameters = getParametersOfCallableType((PyCallableType)member, context); if (parameters != null) { results.add(parameters); } } } if (!results.isEmpty()) { return results; } } return null; } @NotNull public static List<PyParameter> getParameters(@NotNull PyCallable callable, @NotNull TypeEvalContext context) { final List<List<PyParameter>> parametersSet = getOverloadedParametersSet(callable, context); assert !parametersSet.isEmpty(); return parametersSet.get(0); } public static boolean isSignatureCompatibleTo(@NotNull PyCallable callable, @NotNull PyCallable otherCallable, @NotNull TypeEvalContext context) { final List<PyParameter> parameters = getParameters(callable, context); final List<PyParameter> otherParameters = getParameters(otherCallable, context); final int optionalCount = optionalParametersCount(parameters); final int otherOptionalCount = optionalParametersCount(otherParameters); final int requiredCount = requiredParametersCount(callable, parameters); final int otherRequiredCount = requiredParametersCount(otherCallable, otherParameters); if (hasPositionalContainer(otherParameters) || hasKeywordContainer(otherParameters)) { if (otherParameters.size() == specialParametersCount(otherCallable, otherParameters)) { return true; } } if (hasPositionalContainer(parameters) || hasKeywordContainer(parameters)) { return requiredCount <= otherRequiredCount; } return requiredCount <= otherRequiredCount && parameters.size() >= otherParameters.size() && optionalCount >= otherOptionalCount; } private static int optionalParametersCount(@NotNull List<PyParameter> parameters) { int n = 0; for (PyParameter parameter : parameters) { if (parameter.hasDefaultValue()) { n++; } } return n; } private static int requiredParametersCount(@NotNull PyCallable callable, @NotNull List<PyParameter> parameters) { return parameters.size() - optionalParametersCount(parameters) - specialParametersCount(callable, parameters); } private static int specialParametersCount(@NotNull PyCallable callable, @NotNull List<PyParameter> parameters) { int n = 0; if (hasPositionalContainer(parameters)) { n++; } if (hasKeywordContainer(parameters)) { n++; } if (callable.asMethod() != null) { n++; } else { if (parameters.size() > 0) { final PyParameter first = parameters.get(0); if (PyNames.CANONICAL_SELF.equals(first.getName())) { n++; } } } return n; } private static boolean hasPositionalContainer(@NotNull List<PyParameter> parameters) { for (PyParameter parameter : parameters) { if (parameter instanceof PyNamedParameter && ((PyNamedParameter)parameter).isPositionalContainer()) { return true; } } return false; } private static boolean hasKeywordContainer(@NotNull List<PyParameter> parameters) { for (PyParameter parameter : parameters) { if (parameter instanceof PyNamedParameter && ((PyNamedParameter)parameter).isKeywordContainer()) { return true; } } return false; } public static boolean isInit(@NotNull final PyFunction function) { return PyNames.INIT.equals(function.getName()); } /** * Filters out {@link PyMemberInfo} * that should not be displayed in this refactoring (like object) * * @param pyMemberInfos collection to sort * @return sorted collection */ @NotNull public static Collection<PyMemberInfo<PyElement>> filterOutObject(@NotNull final Collection<PyMemberInfo<PyElement>> pyMemberInfos) { return Collections2.filter(pyMemberInfos, new ObjectPredicate(false)); } public static boolean isStarImportableFrom(@NotNull String name, @NotNull PyFile file) { final List<String> dunderAll = file.getDunderAll(); return dunderAll != null ? dunderAll.contains(name) : !name.startsWith("_"); } /** * Filters only PyClass object (new class) */ public static class ObjectPredicate extends NotNullPredicate<PyMemberInfo<PyElement>> { private final boolean myAllowObjects; /** * @param allowObjects allows only objects if true. Allows all but objects otherwise. */ public ObjectPredicate(final boolean allowObjects) { myAllowObjects = allowObjects; } @Override public boolean applyNotNull(@NotNull final PyMemberInfo<PyElement> input) { return myAllowObjects == isObject(input); } private static boolean isObject(@NotNull final PyMemberInfo<PyElement> classMemberInfo) { final PyElement element = classMemberInfo.getMember(); return (element instanceof PyClass) && PyNames.OBJECT.equals(element.getName()); } } /** * Sometimes you do not know real FQN of some class, but you know class name and its package. * I.e. <code>django.apps.conf.AppConfig</code> is not documented, but you know * <code>AppConfig</code> and <code>django</code> package. * * @param symbol element to check (class or function) * @param expectedPackage package like "django" * @param expectedName expected name (i.e. AppConfig) * @return true if element in package */ public static boolean isSymbolInPackage(@NotNull final PyQualifiedNameOwner symbol, @NotNull final String expectedPackage, @NotNull final String expectedName) { final String qualifiedNameString = symbol.getQualifiedName(); if (qualifiedNameString == null) { return false; } final QualifiedName qualifiedName = QualifiedName.fromDottedString(qualifiedNameString); final String aPackage = qualifiedName.getFirstComponent(); if (!(expectedPackage.equals(aPackage))) { return false; } final String symbolName = qualifiedName.getLastComponent(); return expectedName.equals(symbolName); } /** * Checks that given class is the root of class hierarchy, i.e. it's either {@code object} or * special {@link PyNames#FAKE_OLD_BASE} class for old-style classes. * * @param cls Python class to check * @see PyBuiltinCache * @see PyNames#FAKE_OLD_BASE */ public static boolean isObjectClass(@NotNull PyClass cls) { final PyBuiltinCache builtinCache = PyBuiltinCache.getInstance(cls); return cls == builtinCache.getClass(PyNames.OBJECT) || cls == builtinCache.getClass(PyNames.FAKE_OLD_BASE); } public static boolean isInScratchFile(@NotNull PsiElement element) { return ScratchFileService.isInScratchRoot(PsiUtilCore.getVirtualFile(element)); } /** * This helper class allows to collect various information about AST nodes composing {@link PyStringLiteralExpression}. */ public static final class StringNodeInfo { private final ASTNode myNode; private final String myPrefix; private final String myQuote; private final TextRange myContentRange; public StringNodeInfo(@NotNull ASTNode node) { if (!PyTokenTypes.STRING_NODES.contains(node.getElementType())) { throw new IllegalArgumentException("Node must be valid Python string literal token, but " + node.getElementType() + " was given"); } myNode = node; final String nodeText = node.getText(); final int prefixLength = PyStringLiteralExpressionImpl.getPrefixLength(nodeText); myPrefix = nodeText.substring(0, prefixLength); myContentRange = PyStringLiteralExpressionImpl.getNodeTextRange(nodeText); myQuote = nodeText.substring(prefixLength, myContentRange.getStartOffset()); } public StringNodeInfo(@NotNull PsiElement element) { this(element.getNode()); } @NotNull public ASTNode getNode() { return myNode; } /** * @return string prefix, e.g. "UR", "b" etc. */ @NotNull public String getPrefix() { return myPrefix; } /** * @return content of the string node between quotes */ @NotNull public String getContent() { return myContentRange.substring(myNode.getText()); } /** * @return <em>relative</em> range of the content (excluding prefix and quotes) * @see #getAbsoluteContentRange() */ @NotNull public TextRange getContentRange() { return myContentRange; } /** * @return <em>absolute</em> content range that accounts offset of the {@link #getNode() node} in the document */ @NotNull public TextRange getAbsoluteContentRange() { return getContentRange().shiftRight(myNode.getStartOffset()); } /** * @return the first character of {@link #getQuote()} */ public char getSingleQuote() { return myQuote.charAt(0); } @NotNull public String getQuote() { return myQuote; } public boolean isTripleQuoted() { return myQuote.length() == 3; } /** * @return true if string literal ends with starting quote */ public boolean isTerminated() { final String text = myNode.getText(); return text.length() - myPrefix.length() >= myQuote.length() * 2 && text.endsWith(myQuote); } /** * @return true if given string node contains "u" or "U" prefix */ public boolean isUnicode() { return StringUtil.containsIgnoreCase(myPrefix, "u"); } /** * @return true if given string node contains "r" or "R" prefix */ public boolean isRaw() { return StringUtil.containsIgnoreCase(myPrefix, "r"); } /** * @return true if given string node contains "b" or "B" prefix */ public boolean isBytes() { return StringUtil.containsIgnoreCase(myPrefix, "b"); } /** * @return true if other string node has the same decorations, i.e. quotes and prefix */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StringNodeInfo info = (StringNodeInfo)o; return getQuote().equals(info.getQuote()) && isRaw() == info.isRaw() && isUnicode() == info.isUnicode() && isBytes() == info.isBytes(); } } public static class IterHelper { // TODO: rename sanely private IterHelper() {} @Nullable public static PyElement findName(Iterable<PyElement> it, String name) { PyElement ret = null; for (PyElement elt : it) { if (elt != null) { // qualified refs don't match by last name, and we're not checking FQNs here if (elt instanceof PyQualifiedExpression && ((PyQualifiedExpression)elt).isQualified()) continue; if (name.equals(elt.getName())) { // plain name matches ret = elt; break; } } } return ret; } } }
Reused PyNames.DOT_PY
python/src/com/jetbrains/python/psi/PyUtil.java
Reused PyNames.DOT_PY
Java
apache-2.0
4800e76ad2beccd7951ff7ef8541fc9909a251bd
0
hbs/warp10-platform,hbs/warp10-platform,hbs/warp10-platform,hbs/warp10-platform
// // Copyright 2018 SenX S.A.S. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package io.warp10.script.functions; import io.warp10.script.NamedWarpScriptFunction; import io.warp10.script.WarpScriptException; import io.warp10.script.WarpScriptStack; import io.warp10.script.WarpScriptStackFunction; import java.util.ArrayList; import java.util.List; /** * Create a new list with the elements whose indices are in the parameter list. * If the parameter list contains two indices [a,b] then SUBLIST * returns the list of elements from the lesser index to the bigger index (included). * If the parameter list contains more than two indices, the result of SUBLIST * contains all the elements at the specified indices, with possible duplicates. * If, instead of the parameter list, there are number, they are considered to define * a range. From top to bottom: step (optional), end(optional), start */ public class SUBLIST extends NamedWarpScriptFunction implements WarpScriptStackFunction { public SUBLIST(String name) { super(name); } @Override public Object apply(WarpScriptStack stack) throws WarpScriptException { Object o; List indices = null; List elements = null; ArrayList<Long> longParams = new ArrayList<Long>(); // Get the 4 elements on top of the stack or until a list is found. // After this, either indices is null or longParams contains at least one long. for (int i = 0; i < 4; i++) { o = stack.pop(); if (o instanceof List) { if (0 == i) { // No range defined as numbers indices = (List) o; o = stack.pop(); if (o instanceof List) { elements = (List) o; } else { throw new WarpScriptException(getName() + " expects a list of indices on top of the stack and will operate on the list below it."); } } else { elements = (List) o; } break; } else if (o instanceof Number) { longParams.add(0, ((Number) o).longValue()); // Prepend the clamped int parameter } else { throw new WarpScriptException(getName() + " expects a list of indices on top of the stack or a start end step and will operate on the list below it."); } } // elements can be null if the 4 elements on top of the stack were numbers. if (null == elements) { throw new WarpScriptException(getName() + " expects a list of indices on top of the stack or a start end step and will operate on the list below it."); } int size = elements.size(); List<Object> sublist = new ArrayList<Object>(); if (null == indices) { // Range definition with longParams // If indices is null, there is at least one parameter in longParams: start. long start = longParams.get(0); // Get end if defined long end; if (longParams.size() > 1) { end = longParams.get(1); } else { // End is not defined, neither is step. So step will default to 1. // Thus end defaults to the end of the list or start, if start is greater than end. end = Math.max(size - 1, start); } // Add the size of the list to defined negative indexes. They can still be negative afterward. // No risk of overflow because start/end is strictly negative and size is positive if (start < 0) { start += size; } if (end < 0) { end += size; } // Only if the defined range intersects the valid indexes, else the sublist is empty. if (!(start < 0 && end < 0 || start >= size && end >= size)) { // Get step if defined long step = 1L; if (longParams.size() > 2) { step = longParams.get(2); } else { if (start > end) { step = -1L; // Reverse order } // else step is already 1 } // Check start/end/step coherency if (0 == step) { throw new WarpScriptException(getName() + " expects the step parameter to be a strictly positive or negative number."); } else if (step > 0) { if (start > end) { throw new WarpScriptException(getName() + " expects start to be before end when step is positive."); } } else { if (end > start) { throw new WarpScriptException(getName() + " expects start to be after end when step is negative."); } } // Jump step by step start to nearest valid index in elements start = nearestValidBound(start, step, size); // Fill the sublist try { if (step > 0) { end = Math.min(end, size - 1); for (long i = start; i <= end; i = Math.addExact(i, step)) { sublist.add(elements.get(Math.toIntExact(i))); } } else { end = Math.max(end, 0L); for (long i = start; i >= end; i = Math.addExact(i, step)) { sublist.add(elements.get(Math.toIntExact(i))); } } } catch (ArithmeticException ae) { // Do nothing, that means i + step overflowed int and thus is not a valid index anymore. // This is most probably the case of a step near to or greater than max integer. } } } else if (2 == indices.size()) { // Range definition with indices Object a = indices.get(0); Object b = indices.get(1); if (!(a instanceof Long) || !(b instanceof Long)) { throw new WarpScriptException(getName() + " expects a list of indices which are numeric integers."); } int la = ((Long) a).intValue(); int lb = ((Long) b).intValue(); if (la < 0) { la = size + la; } if (lb < 0) { lb = size + lb; } if (la < 0 && lb < 0) { la = size; lb = size; } else { la = Math.max(0, la); lb = Math.max(0, lb); } // // If at least one of the bounds is included in the list indices, // fix the other one // if (la < size || lb < size) { if (la >= size) { la = size - 1; } else if (la < -1 * size) { la = -1 * size; } if (lb >= size) { lb = size - 1; } else if (lb < -1 * size) { lb = -1 * size; } } if (la < lb) { if (la < size) { lb = Math.min(size - 1, lb); for (int i = la; i <= lb; i++) { sublist.add(elements.get(i)); } } } else { if (lb < size) { la = Math.min(size - 1, la); for (int i = lb; i <= la; i++) { sublist.add(elements.get(i)); } } } } else { // Individual elements selection for (Object index: indices) { if (!(index instanceof Long)) { throw new WarpScriptException(getName() + " expects a list of indices which are numeric integers."); } int idx = ((Long) index).intValue(); if (idx >= size || (idx < -1 * size)) { throw new WarpScriptException(getName() + " reported an out of bound index."); } if (idx >= 0) { sublist.add(elements.get(idx)); } else { sublist.add(elements.get(size + idx)); } } } stack.push(sublist); return stack; } /** * Moves a bound to the closer valid index by "jumping" by step. * * Example table for a step of 3 and a size of 8, list given for visualization: * Input bound: [ -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10 11 ] * Nearest valid: [ 1 2 0 1 2 0 1 2 3 4 5 6 7 5 6 7 5 ] * List: [ a b c d e f g h ] * * @param bound start or end. * @param step Amount to add or subtract to the bound. May be positive or negative. * @param size Size of the list. * @return A valid index if it exists, else an invalid index. */ private static long nearestValidBound(long bound, long step, int size) { if (bound >= size) { return ((bound - size) % step) - Math.abs(step) + size; } else if (bound < 0) { return ((bound + 1) % step) + Math.abs(step) - 1; } else { return bound; } } }
warp10/src/main/java/io/warp10/script/functions/SUBLIST.java
// // Copyright 2018 SenX S.A.S. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package io.warp10.script.functions; import io.warp10.script.NamedWarpScriptFunction; import io.warp10.script.WarpScriptException; import io.warp10.script.WarpScriptStack; import io.warp10.script.WarpScriptStackFunction; import java.util.ArrayList; import java.util.List; /** * Create a new list with the elements whose indices are in the parameter list. * If the parameter list contains two indices [a,b] then SUBLIST * returns the list of elements from the lesser index to the bigger index (included). * If the parameter list contains more than two indices, the result of SUBLIST * contains all the elements at the specified indices, with possible duplicates. * If, instead of the parameter list, there are number, they are considered to define * a range. From top to bottom: step (optional), end(optional), start */ public class SUBLIST extends NamedWarpScriptFunction implements WarpScriptStackFunction { public SUBLIST(String name) { super(name); } @Override public Object apply(WarpScriptStack stack) throws WarpScriptException { Object o; List indices = null; List elements = null; ArrayList<Integer> intParams = new ArrayList<Integer>(); // Get the 4 elements on top of the stack or until a list is found. // After this, either indices is null or longParams contains at least one long. for (int i = 0; i < 4; i++) { o = stack.pop(); if (o instanceof List) { if (0 == i) { // No range defined as numbers indices = (List) o; o = stack.pop(); if (o instanceof List) { elements = (List) o; } else { throw new WarpScriptException(getName() + " expects a list of indices on top of the stack and will operate on the list below it."); } } else { elements = (List) o; } break; } else if (o instanceof Number) { try { intParams.add(0, Math.toIntExact(((Number) o).longValue())); // Prepend the int parameter } catch (ArithmeticException ae) { throw new WarpScriptException(getName() + " expects number parameters to be ints.", ae); } } else { throw new WarpScriptException(getName() + " expects a list of indices on top of the stack or a start end step and will operate on the list below it."); } } // elements can be null if the 4 elements on top of the stack were numbers. if (null == elements) { throw new WarpScriptException(getName() + " expects a list of indices on top of the stack or a start end step and will operate on the list below it."); } List<Object> sublist = new ArrayList<Object>(); if (null == indices) { // Range definition with intParams // If indices is null, there is at least one parameter in longParams: start. int start = intParams.get(0); int end = intParams.size() > 1 ? intParams.get(1) : -1; // Defaults to end of the list if (start < 0) { start += elements.size(); } if (end < 0) { end += elements.size(); } start = Math.max(0, Math.min(elements.size() - 1, start)); end = Math.max(0, Math.min(elements.size() - 1, end)); int step = 1; if (intParams.size() > 2) { step = intParams.get(2); } else { if (start > end) { step = -1; } // else step is already 1 } if (0 == step) { throw new WarpScriptException(getName() + " expects the step parameter to be a strictly positive or negative integer."); } else if (step > 0) { if (start > end) { throw new WarpScriptException(getName() + " expects start to be before end when step is positive."); } } else { if (end > start) { throw new WarpScriptException(getName() + " expects start to be after end when step is negative."); } } if (step > 0) { for (int i = start; i <= end; i += step) { sublist.add(elements.get(i)); } } else { for (int i = start; i >= end; i += step) { sublist.add(elements.get(i)); } } } else if (2 == indices.size()) { // Range definition with indices Object a = indices.get(0); Object b = indices.get(1); if (!(a instanceof Long) || !(b instanceof Long)) { throw new WarpScriptException(getName() + " expects a list of indices which are numeric integers."); } int la = ((Long) a).intValue(); int lb = ((Long) b).intValue(); if (la < 0) { la = elements.size() + la; } if (lb < 0) { lb = elements.size() + lb; } if (la < 0 && lb < 0) { la = elements.size(); lb = elements.size(); } else { la = Math.max(0, la); lb = Math.max(0, lb); } // // If at least one of the bounds is included in the list indices, // fix the other one // if (la < elements.size() || lb < elements.size()) { if (la >= elements.size()) { la = elements.size() - 1; } else if (la < -1 * elements.size()) { la = -1 * elements.size(); } if (lb >= elements.size()) { lb = elements.size() - 1; } else if (lb < -1 * elements.size()) { lb = -1 * elements.size(); } } if (la < lb) { if (la < elements.size()) { lb = Math.min(elements.size() - 1, lb); for (int i = la; i <= lb; i++) { sublist.add(elements.get(i)); } } } else { if (lb < elements.size()) { la = Math.min(elements.size() - 1, la); for (int i = lb; i <= la; i++) { sublist.add(elements.get(i)); } } } } else { // Individual elements selection for (Object index: indices) { if (!(index instanceof Long)) { throw new WarpScriptException(getName() + " expects a list of indices which are numeric integers."); } int idx = ((Long) index).intValue(); if (idx >= elements.size() || (idx < -1 * elements.size())) { throw new WarpScriptException(getName() + " reported an out of bound index."); } if (idx >= 0) { sublist.add(elements.get(idx)); } else { sublist.add(elements.get(elements.size() + idx)); } } } stack.push(sublist); return stack; } }
Fix new SUBLIST signature and align start using step
warp10/src/main/java/io/warp10/script/functions/SUBLIST.java
Fix new SUBLIST signature and align start using step
Java
apache-2.0
370cccfb118ce370f758411f3bc0fbc261806041
0
UnknownStudio/UDPLib,UnknownStudio/UDPLib
package team.unstudio.udpl.area; import java.util.HashMap; import java.util.Map; import javax.annotation.Nonnull; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.configuration.serialization.ConfigurationSerializable; public class Area implements ConfigurationSerializable{ private final Location minLocation,maxLocation; private AreaDataContainer data; public Area(@Nonnull Location point1,@Nonnull Location point2) { if(!point1.getWorld().equals(point2.getWorld())) throw new IllegalArgumentException("Different world."); //Location1 < Location2 double x1=point1.getX(),x2=point2.getX(),y1=point1.getY(),y2=point2.getY(),z1=point1.getZ(),z2=point2.getZ(),t; if(x1>x2){t=x1;x1=x2;x2=t;} if(y1>y2){t=y1;y1=y2;y2=t;} if(z1>z2){t=z1;z1=z2;z2=t;} this.minLocation = new Location(point1.getWorld(), x1, y1, z1); this.maxLocation = new Location(point2.getWorld(), x2, y2, z2); } public final World getWorld(){ return minLocation.getWorld(); } public final Location getMinLocation() { return minLocation; } public final Location getMaxLocation() { return maxLocation; } public final AreaDataContainer getData() { if(data == null) data = new AreaDataContainer(); return data; } /** * 判断坐标是否含于该区域 * @param location * @return */ public boolean contain(final Location location){ if(location==null) return false; if(!getMinLocation().getWorld().equals(location.getWorld())) return false; if(getMinLocation().getX()>location.getX()) return false; if(getMinLocation().getY()>location.getY()) return false; if(getMinLocation().getZ()>location.getZ()) return false; if(getMaxLocation().getX()<location.getX()) return false; if(getMaxLocation().getY()<location.getY()) return false; if(getMaxLocation().getZ()<location.getZ()) return false; return true; } /** * 判断区域是否含于该区域 * @param area * @return */ public boolean contain(final Area area){ if(area==null) return false; if(!getMinLocation().getWorld().equals(area.getMinLocation().getWorld())) return false; if(getMinLocation().getX()>area.getMinLocation().getX()) return false; if(getMinLocation().getY()>area.getMinLocation().getY()) return false; if(getMinLocation().getZ()>area.getMinLocation().getZ()) return false; if(getMaxLocation().getX()<area.getMaxLocation().getX()) return false; if(getMaxLocation().getY()<area.getMaxLocation().getY()) return false; if(getMaxLocation().getZ()<area.getMaxLocation().getZ()) return false; return true; } /** * 判断区域是否与该区域相交 * @param area * @return */ public boolean intersect(final Area area){ if(area==null) return false; if(contain(area.getMinLocation())) return true; if(contain(area.getMaxLocation())) return true; if(area.contain(getMinLocation())) return true; if(area.contain(getMaxLocation())) return true; return false; } @Override public Map<String, Object> serialize() { Map<String, Object> map = new HashMap<>(); map.put("==", getClass().getName()); map.put("point1", getMinLocation()); map.put("point2", getMaxLocation()); if(data != null) map.put("data", data); return map; } public static Area deserialize(Map<String, Object> args) { Area area = new Area((Location)args.get("point1"),(Location)args.get("point2")); if(args.containsKey("data")) area.data = (AreaDataContainer) args.get("data"); return area; } @Override public boolean equals(Object obj) { if(obj == null) return false; if(!(obj instanceof Area)) return false; Area other = (Area) obj; if(!getMinLocation().equals(other.getMinLocation())) return false; if(!getMaxLocation().equals(other.getMaxLocation())) return false; return true; } @Override public int hashCode() { return getMinLocation().hashCode()*37+getMaxLocation().hashCode(); } @Override public String toString() { return "Area: {MaxLocation: "+getMinLocation().toString()+", MinLocation: "+getMaxLocation().toString()+", Data: "+data.toString()+" }"; } }
src/main/java/team/unstudio/udpl/area/Area.java
package team.unstudio.udpl.area; import java.util.HashMap; import java.util.Map; import javax.annotation.Nonnull; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.configuration.serialization.ConfigurationSerializable; public class Area implements ConfigurationSerializable{ private final Location minLocation,maxLocation; private AreaDataContainer data; public Area(Map<String, Object> map) { this((Location)map.get("point1"),(Location)map.get("point2")); if(map.containsKey("data")) data = (AreaDataContainer) map.get("data"); } public Area(@Nonnull Location point1,@Nonnull Location point2) { if(!point1.getWorld().equals(point2.getWorld())) throw new IllegalArgumentException("Different world."); //Location1 < Location2 double x1=point1.getX(),x2=point2.getX(),y1=point1.getY(),y2=point2.getY(),z1=point1.getZ(),z2=point2.getZ(),t; if(x1>x2){t=x1;x1=x2;x2=t;} if(y1>y2){t=y1;y1=y2;y2=t;} if(z1>z2){t=z1;z1=z2;z2=t;} this.minLocation = new Location(point1.getWorld(), x1, y1, z1); this.maxLocation = new Location(point2.getWorld(), x2, y2, z2); } public final World getWorld(){ return minLocation.getWorld(); } public final Location getMinLocation() { return minLocation; } public final Location getMaxLocation() { return maxLocation; } public final AreaDataContainer getData() { if(data == null) data = new AreaDataContainer(); return data; } /** * 判断坐标是否含于该区域 * @param location * @return */ public boolean contain(final Location location){ if(location==null) return false; if(!getMinLocation().getWorld().equals(location.getWorld())) return false; if(getMinLocation().getX()>location.getX()) return false; if(getMinLocation().getY()>location.getY()) return false; if(getMinLocation().getZ()>location.getZ()) return false; if(getMaxLocation().getX()<location.getX()) return false; if(getMaxLocation().getY()<location.getY()) return false; if(getMaxLocation().getZ()<location.getZ()) return false; return true; } /** * 判断区域是否含于该区域 * @param area * @return */ public boolean contain(final Area area){ if(area==null) return false; if(!getMinLocation().getWorld().equals(area.getMinLocation().getWorld())) return false; if(getMinLocation().getX()>area.getMinLocation().getX()) return false; if(getMinLocation().getY()>area.getMinLocation().getY()) return false; if(getMinLocation().getZ()>area.getMinLocation().getZ()) return false; if(getMaxLocation().getX()<area.getMaxLocation().getX()) return false; if(getMaxLocation().getY()<area.getMaxLocation().getY()) return false; if(getMaxLocation().getZ()<area.getMaxLocation().getZ()) return false; return true; } /** * 判断区域是否与该区域相交 * @param area * @return */ public boolean intersect(final Area area){ if(area==null) return false; if(contain(area.getMinLocation())) return true; if(contain(area.getMaxLocation())) return true; if(area.contain(getMinLocation())) return true; if(area.contain(getMaxLocation())) return true; return false; } @Override public Map<String, Object> serialize() { Map<String, Object> map = new HashMap<>(); map.put("==", getClass().getName()); map.put("point1", getMinLocation()); map.put("point2", getMaxLocation()); if(data != null) map.put("data", data); return map; } @Override public boolean equals(Object obj) { if(obj == null) return false; if(!(obj instanceof Area)) return false; Area other = (Area) obj; if(!getMinLocation().equals(other.getMinLocation())) return false; if(!getMaxLocation().equals(other.getMaxLocation())) return false; return true; } @Override public int hashCode() { return getMinLocation().hashCode()*37+getMaxLocation().hashCode(); } @Override public String toString() { return "Area: {MaxLocation: "+getMinLocation().toString()+", MinLocation: "+getMaxLocation().toString()+", Data: "+data.toString()+" }"; } }
Update Area
src/main/java/team/unstudio/udpl/area/Area.java
Update Area
Java
apache-2.0
6b2c49226e91e11487a90889731c55220a7ea9e4
0
holmes/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,ernestp/consulo,joewalnes/idea-community,diorcety/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,adedayo/intellij-community,samthor/intellij-community,caot/intellij-community,Lekanich/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,holmes/intellij-community,clumsy/intellij-community,samthor/intellij-community,holmes/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,signed/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,xfournet/intellij-community,jagguli/intellij-community,joewalnes/idea-community,FHannes/intellij-community,hurricup/intellij-community,caot/intellij-community,jexp/idea2,ryano144/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,petteyg/intellij-community,diorcety/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,signed/intellij-community,asedunov/intellij-community,jexp/idea2,suncycheng/intellij-community,apixandru/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,gnuhub/intellij-community,joewalnes/idea-community,dslomov/intellij-community,supersven/intellij-community,ibinti/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,ibinti/intellij-community,holmes/intellij-community,caot/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,slisson/intellij-community,clumsy/intellij-community,dslomov/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,caot/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,petteyg/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,slisson/intellij-community,asedunov/intellij-community,ibinti/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,hurricup/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,ernestp/consulo,alphafoobar/intellij-community,SerCeMan/intellij-community,caot/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,semonte/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,signed/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,allotria/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,joewalnes/idea-community,joewalnes/idea-community,holmes/intellij-community,ryano144/intellij-community,joewalnes/idea-community,youdonghai/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,signed/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,signed/intellij-community,retomerz/intellij-community,consulo/consulo,kool79/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,retomerz/intellij-community,blademainer/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,signed/intellij-community,ernestp/consulo,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,ryano144/intellij-community,caot/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,kool79/intellij-community,ernestp/consulo,ahb0327/intellij-community,allotria/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,consulo/consulo,clumsy/intellij-community,fitermay/intellij-community,dslomov/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,signed/intellij-community,hurricup/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,amith01994/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,FHannes/intellij-community,da1z/intellij-community,retomerz/intellij-community,fnouama/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,jagguli/intellij-community,jexp/idea2,adedayo/intellij-community,dslomov/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,retomerz/intellij-community,signed/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,da1z/intellij-community,FHannes/intellij-community,kdwink/intellij-community,samthor/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,asedunov/intellij-community,hurricup/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,consulo/consulo,idea4bsd/idea4bsd,suncycheng/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,kool79/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,adedayo/intellij-community,jagguli/intellij-community,retomerz/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,joewalnes/idea-community,allotria/intellij-community,ernestp/consulo,da1z/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,signed/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,supersven/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,joewalnes/idea-community,semonte/intellij-community,apixandru/intellij-community,blademainer/intellij-community,amith01994/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,caot/intellij-community,allotria/intellij-community,izonder/intellij-community,izonder/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,ryano144/intellij-community,izonder/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,jexp/idea2,kool79/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,petteyg/intellij-community,diorcety/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,xfournet/intellij-community,robovm/robovm-studio,samthor/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,ahb0327/intellij-community,samthor/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,ahb0327/intellij-community,semonte/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,kool79/intellij-community,diorcety/intellij-community,amith01994/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,vladmm/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,semonte/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,samthor/intellij-community,clumsy/intellij-community,fitermay/intellij-community,holmes/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,caot/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,clumsy/intellij-community,vladmm/intellij-community,fnouama/intellij-community,hurricup/intellij-community,da1z/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,izonder/intellij-community,slisson/intellij-community,asedunov/intellij-community,consulo/consulo,vvv1559/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,slisson/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,consulo/consulo,robovm/robovm-studio,FHannes/intellij-community,jagguli/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,allotria/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,ryano144/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,diorcety/intellij-community,fnouama/intellij-community,diorcety/intellij-community,izonder/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,apixandru/intellij-community,dslomov/intellij-community,robovm/robovm-studio,consulo/consulo,gnuhub/intellij-community,kool79/intellij-community,supersven/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,signed/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,ryano144/intellij-community,xfournet/intellij-community,caot/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,signed/intellij-community,jexp/idea2,youdonghai/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,ernestp/consulo,blademainer/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,fitermay/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,kool79/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,jexp/idea2,kdwink/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,izonder/intellij-community,jexp/idea2,amith01994/intellij-community,tmpgit/intellij-community,supersven/intellij-community,FHannes/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,da1z/intellij-community,ibinti/intellij-community,clumsy/intellij-community,da1z/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,signed/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,kool79/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,allotria/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,kdwink/intellij-community,blademainer/intellij-community,allotria/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,da1z/intellij-community,vladmm/intellij-community,vladmm/intellij-community,blademainer/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,jexp/idea2,jagguli/intellij-community,ivan-fedorov/intellij-community,joewalnes/idea-community,robovm/robovm-studio,FHannes/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,kdwink/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,da1z/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,kdwink/intellij-community,semonte/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,allotria/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,slisson/intellij-community,vladmm/intellij-community,supersven/intellij-community
package com.intellij.find.impl; import com.intellij.find.*; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.actionSystem.DataConstants; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ContentIterator; import com.intellij.openapi.roots.FileIndex; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Factory; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.impl.PsiManagerImpl; import com.intellij.psi.impl.cache.CacheManager; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.UsageSearchContext; import com.intellij.psi.search.PsiSearchScopeUtil; import com.intellij.psi.search.SearchScope; import com.intellij.usageView.AsyncFindUsagesProcessListener; import com.intellij.usageView.UsageInfo; import com.intellij.usages.*; import com.intellij.util.PatternUtil; import com.intellij.util.Processor; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.io.File; import java.util.*; import java.util.regex.Pattern; public class FindInProjectUtil { private static final int USAGES_LIMIT = 1000; private static final int FILES_SIZE_LIMIT = 70 * 1024 * 1024; // megabytes. private static final int SINGLE_FILE_SIZE_LIMIT = 5 * 1024 * 1024; // megabytes. private static final int SKIP = 0; private static final int PROCESS_FILE = 1; private static final int SKIP_ALL = 2; private static final int PROCESS_ALL = 3; private FindInProjectUtil() {} public static void setDirectoryName(FindModel model, DataContext dataContext) { PsiElement psiElement = (PsiElement)dataContext.getData(DataConstants.PSI_ELEMENT); String directoryName = null; if (psiElement instanceof PsiDirectory) { directoryName = ((PsiDirectory)psiElement).getVirtualFile().getPresentableUrl(); } else { final PsiFile psiFile = (PsiFile)dataContext.getData(DataConstants.PSI_FILE); if (psiFile != null) { PsiDirectory psiDirectory = psiFile.getContainingDirectory(); if (psiDirectory != null) { directoryName = psiDirectory.getVirtualFile().getPresentableUrl(); } } } if (directoryName == null && psiElement instanceof PsiPackage) { final PsiDirectory[] directories = ((PsiPackage)psiElement).getDirectories(); directoryName = directories.length == 1 ? directories[0].getVirtualFile().getPresentableUrl():null; } Module module = (Module)dataContext.getData(DataConstants.MODULE_CONTEXT); if (module != null) { model.setModuleName(module.getName()); } if (model.getModuleName() == null || dataContext.getData(DataConstants.EDITOR) == null) { model.setDirectoryName(directoryName); model.setProjectScope(directoryName == null && module == null && model.getCustomScopeName() == null || dataContext.getData(DataConstants.EDITOR) != null); } } @Nullable public static PsiDirectory getPsiDirectory(final FindModel findModel, Project project) { String directoryName = findModel.getDirectoryName(); if (findModel.isProjectScope() || directoryName == null) { return null; } final PsiManager psiManager = PsiManager.getInstance(project); String path = directoryName.replace(File.separatorChar, '/'); VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(path); if (virtualFile == null || !virtualFile.isDirectory()) { if (!path.contains(JarFileSystem.JAR_SEPARATOR)) { path += JarFileSystem.JAR_SEPARATOR; } virtualFile = JarFileSystem.getInstance().findFileByPath(path); } if (virtualFile != null) { return psiManager.findDirectory(virtualFile); } else { return null; } } private static void addFilesUnderDirectory(PsiDirectory directory, Collection<PsiFile> fileList, boolean isRecursive, Pattern fileMaskRegExp) { final PsiElement[] children = directory.getChildren(); for (PsiElement child : children) { if (child instanceof PsiFile && (fileMaskRegExp == null || fileMaskRegExp.matcher(((PsiFile)child).getName()).matches() ) ) { PsiFile file = (PsiFile)child; PsiFile sourceFile = (PsiFile)file.getNavigationElement(); if (sourceFile != null) file = sourceFile; fileList.add(file); } else if (isRecursive && child instanceof PsiDirectory) { addFilesUnderDirectory((PsiDirectory)child, fileList, isRecursive, fileMaskRegExp); } } } @NotNull public static List<UsageInfo> findUsages(final FindModel findModel, final PsiDirectory psiDirectory, final Project project) { class MyAsyncUsageConsumer implements AsyncFindUsagesProcessListener { final ArrayList<UsageInfo> usages = new ArrayList<UsageInfo>(); public void foundUsage(UsageInfo info) { usages.add(info); } public int getCount() { return usages.size(); } public void findUsagesCompleted() { } } MyAsyncUsageConsumer consumer = new MyAsyncUsageConsumer(); findUsages(findModel, psiDirectory, project, consumer); return consumer.usages; } @Nullable private static Pattern createFileMaskRegExp(FindModel findModel) { if (findModel.getFileFilter() != null) { return Pattern.compile(PatternUtil.convertToRegex(findModel.getFileFilter()), Pattern.CASE_INSENSITIVE); } else { return null; } } public static void findUsages(final FindModel findModel, final PsiDirectory psiDirectory, final Project project, final AsyncFindUsagesProcessListener consumer) { final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); final Collection<PsiFile> psiFiles = getFilesToSearchIn(findModel, project, psiDirectory); final FileDocumentManager manager = FileDocumentManager.getInstance(); try { final SearchScope customScope = findModel.getCustomScope(); findModel.setCustomScope(null); //avoid mem leak int i = 0; long totalFilesSize = 0; final int[] count = new int[]{0}; boolean warningShown = false; boolean skipAllLarge = false; boolean processAllLarge = false; for (final PsiFile psiFile : psiFiles) { ProgressManager.getInstance().checkCanceled(); if (customScope != null && !ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() { public Boolean compute() { return PsiSearchScopeUtil.isInScope(customScope, psiFile); } })) { continue; } final VirtualFile virtualFile = psiFile.getVirtualFile(); final int index = i++; if (virtualFile == null) continue; long fileLength = getFileLength(virtualFile); if (fileLength == -1) continue; // Binary or invalid if (fileLength > SINGLE_FILE_SIZE_LIMIT) { if (skipAllLarge) continue; if (!processAllLarge) { int retCode = showMessage(project, FindBundle.message("find.skip.large.file.prompt", ApplicationNamesInfo.getInstance().getProductName(), getPresentablePath(virtualFile), presentableSize(fileLength)), FindBundle.message("find.skip.large.file.title"), new String[] { FindBundle.message("find.skip.large.file.skip.file"), FindBundle.message("find.skip.large.file.scan.file"), FindBundle.message("find.skip.large.file.skip.all"), FindBundle.message("find.skip.large.file.scan.all") }); if (retCode == SKIP_ALL) { skipAllLarge = true; continue; } else if (retCode == SKIP) { continue; } else if (retCode == PROCESS_ALL) { processAllLarge = true; } else { assert retCode == PROCESS_FILE : retCode; } } } int countBefore = count[0]; ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { if (virtualFile.isValid()) { // Check once more if valid and text since we're in new read action and things might have been changed. if (FileTypeManager.getInstance().getFileTypeByFile(virtualFile).isBinary()) return; // do not decompile .class files final Document document = manager.getDocument(virtualFile); if (document != null) { addToUsages(project, document, consumer, findModel, psiFile, count); if (progress != null) { progress.setFraction((double)index / psiFiles.size()); String text = FindBundle.message("find.searching.for.string.in.file.progress", findModel.getStringToFind(), virtualFile.getPresentableUrl()); progress.setText(text); int size = consumer.getCount(); progress.setText2(FindBundle.message("find.searching.for.string.in.file.occurrences.progress", size)); } } } } }); if (countBefore < count[0]) { totalFilesSize += fileLength; if (totalFilesSize > FILES_SIZE_LIMIT && !warningShown) { showTooManyUsagesWaring(project, FindBundle.message("find.excessive.total.size.prompt", presentableSize(totalFilesSize), ApplicationNamesInfo.getInstance().getProductName())); warningShown = true; } } if (count[0] > USAGES_LIMIT && !warningShown) { showTooManyUsagesWaring(project, FindBundle.message("find.excessive.usage.count.prompt", count[0])); warningShown = true; } } } catch (ProcessCanceledException e) { // fine } if (progress != null) { progress.setText(FindBundle.message("find.progress.search.completed")); } consumer.findUsagesCompleted(); } private static String getPresentablePath(final VirtualFile virtualFile) { return ApplicationManager.getApplication().runReadAction(new Computable<String>() { public String compute() { return virtualFile.getPresentableUrl(); } }); } private static String presentableSize(long bytes) { long megabytes = bytes / (1024 * 1024); return FindBundle.message("find.file.size.megabytes", Long.toString(megabytes)); } private static long getFileLength(final VirtualFile virtualFile) { final long[] length = new long[] {-1L}; ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { if (!virtualFile.isValid()) return; if (FileTypeManager.getInstance().getFileTypeByFile(virtualFile).isBinary()) return; length[0] = virtualFile.getLength(); } }); return length[0]; } private static void showTooManyUsagesWaring(final Project project, final String message) { int retCode = invokeAndWait(new Computable<Integer>() { public Integer compute() { return Messages.showYesNoDialog(project, message, FindBundle.message("find.excessive.usages.title"), Messages.getWarningIcon()); } }); if (retCode != DialogWrapper.OK_EXIT_CODE) { throw new ProcessCanceledException(); } } private static int invokeAndWait(final Computable<Integer> f) { final int[] answer = new int[1]; try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { answer[0] = f.compute(); } }); } catch (Exception e) { answer[0] = 0; } return answer[0]; } private static int showMessage(final Project project, final String message, final String title, final String[] buttons) { return invokeAndWait(new Computable<Integer>() { public Integer compute() { return Messages.showDialog(project, message, title, buttons, 0, Messages.getWarningIcon()); } }); } private static Collection<PsiFile> getFilesToSearchIn(final FindModel findModel, final Project project, final PsiDirectory psiDirectory) { return ApplicationManager.getApplication().runReadAction(new Computable<Collection<PsiFile>>() { public Collection<PsiFile> compute() { return getFilesToSearchInReadAction(findModel, project, psiDirectory); } }); } private static Collection<PsiFile> getFilesToSearchInReadAction(final FindModel findModel, final Project project, final PsiDirectory psiDirectory) { String moduleName = findModel.getModuleName(); Module module = moduleName == null ? null : ModuleManager.getInstance(project).findModuleByName(moduleName); final FileIndex fileIndex = module == null ? ProjectRootManager.getInstance(project).getFileIndex() : ModuleRootManager.getInstance(module).getFileIndex(); if (psiDirectory == null || findModel.isWithSubdirectories() && fileIndex.isInContent(psiDirectory.getVirtualFile())) { final Pattern fileMaskRegExp = createFileMaskRegExp(findModel); // optimization final Collection<PsiFile> filesForFastWordSearch = getFilesForFastWordSearch(findModel, project, psiDirectory, fileMaskRegExp, module); if (filesForFastWordSearch != null && canOptimizeForFastWordSearch(findModel)) return filesForFastWordSearch; class EnumContentIterator implements ContentIterator { List<PsiFile> myFiles = new ArrayList<PsiFile>(filesForFastWordSearch == null ? Collections.<PsiFile>emptyList() : filesForFastWordSearch); final PsiManager psiManager = PsiManager.getInstance(project); public boolean processFile(VirtualFile virtualFile) { if (!virtualFile.isDirectory() && (fileMaskRegExp == null || fileMaskRegExp.matcher(virtualFile.getName()).matches()) ) { final PsiFile psiFile = psiManager.findFile(virtualFile); if (psiFile != null && (filesForFastWordSearch == null || !filesForFastWordSearch.contains(psiFile))) { myFiles.add(psiFile); } } return true; } private Collection<PsiFile> getFiles() { return myFiles; } } final EnumContentIterator iterator = new EnumContentIterator(); if (psiDirectory == null) { fileIndex.iterateContent(iterator); } else { fileIndex.iterateContentUnderDirectory(psiDirectory.getVirtualFile(), iterator); } return iterator.getFiles(); } else { Collection<PsiFile> fileList = new THashSet<PsiFile>(); addFilesUnderDirectory(psiDirectory, fileList, findModel.isWithSubdirectories(), createFileMaskRegExp(findModel)); return fileList; } } @Nullable private static Collection<PsiFile> getFilesForFastWordSearch(final FindModel findModel, final Project project, final PsiDirectory psiDirectory, final Pattern fileMaskRegExp, final Module module) { CacheManager cacheManager = ((PsiManagerImpl)PsiManager.getInstance(project)).getCacheManager(); GlobalSearchScope scope = psiDirectory == null ? module == null ? GlobalSearchScope.projectScope(project) : moduleContentScope(module) : GlobalSearchScope.directoryScope(psiDirectory, true); List<String> words = StringUtil.getWordsIn(findModel.getStringToFind()); // if no words specified in search box, fallback to brute force search if (words.isEmpty()) return null; // hope long words are rare Collections.sort(words, new Comparator<String>() { public int compare(final String o1, final String o2) { return o2.length() - o1.length(); } }); Set<PsiFile> resultFiles = new THashSet<PsiFile>(); for (int i = 0; i < words.size(); i++) { String word = words.get(i); PsiFile[] files = cacheManager.getFilesWithWord(word, UsageSearchContext.ANY, scope, findModel.isCaseSensitive()); if (files.length == 0) { resultFiles.clear(); break; } final List<PsiFile> psiFiles = Arrays.asList(files); if (i == 0) { resultFiles.addAll(psiFiles); } else { resultFiles.retainAll(psiFiles); } filterMaskedFiles(resultFiles, fileMaskRegExp); if (resultFiles.isEmpty()) break; } // in case our word splitting is incorrect PsiFile[] allWordsFiles = cacheManager.getFilesWithWord(findModel.getStringToFind(), UsageSearchContext.ANY, scope, findModel.isCaseSensitive()); resultFiles.addAll(Arrays.asList(allWordsFiles)); filterMaskedFiles(resultFiles, fileMaskRegExp); return resultFiles; } private static GlobalSearchScope moduleContentScope(final Module module) { VirtualFile[] contentRoots = ModuleRootManager.getInstance(module).getContentRoots(); GlobalSearchScope result = null; PsiManager psiManager = PsiManager.getInstance(module.getProject()); for (VirtualFile root : contentRoots) { PsiDirectory directory = psiManager.findDirectory(root); GlobalSearchScope moduleContent = GlobalSearchScope.directoryScope(directory, true); if (result == null) { result = moduleContent; } else { result = result.uniteWith(moduleContent); } } return result; } private static void filterMaskedFiles(final Set<PsiFile> resultFiles, final Pattern fileMaskRegExp) { if (fileMaskRegExp != null) { for (Iterator<PsiFile> iterator = resultFiles.iterator(); iterator.hasNext();) { PsiFile file = iterator.next(); if (!fileMaskRegExp.matcher(file.getName()).matches()) { iterator.remove(); } } } } private static boolean canOptimizeForFastWordSearch(final FindModel findModel) { // $ is used to separate words when indexing plain-text files but not when indexing // Java identifiers, so we can't consistently break a string containing $ characters // into words return findModel.isWholeWordsOnly() && !findModel.isRegularExpressions() && findModel.getStringToFind().indexOf('$') < 0; } private static void addToUsages(@NotNull Project project, @NotNull Document document, @NotNull AsyncFindUsagesProcessListener consumer, @NotNull FindModel findModel, @NotNull final PsiFile psiFile, @NotNull final int[] count) { CharSequence text = document.getCharsSequence(); int textLength = document.getTextLength(); if (text != null) { int offset = 0; FindManager findManager = FindManager.getInstance(project); while (offset < textLength) { FindResult result = findManager.findString(text, offset, findModel); if (!result.isStringFound()) break; UsageInfo info = new UsageInfo(psiFile, result.getStartOffset(), result.getEndOffset()); consumer.foundUsage(info); count[0]++; final int prevOffset = offset; offset = result.getEndOffset(); if (prevOffset == offset) { // for regular expr the size of the match could be zero -> could be infinite loop in finding usages! ++offset; } } } } private static String getTitleForScope(final FindModel findModel) { String result; if (findModel.isProjectScope()) { result = FindBundle.message("find.scope.project.title"); } else if (findModel.getModuleName() != null) { result = FindBundle.message("find.scope.module.title", findModel.getModuleName()); } else if(findModel.getCustomScopeName() != null) { result = findModel.getCustomScopeName(); } else { result = FindBundle.message("find.scope.directory.title", findModel.getDirectoryName()); } if (findModel.getFileFilter() != null) { result = FindBundle.message("find.scope.files.with.mask", result, findModel.getFileFilter()); } return result; } public static UsageViewPresentation setupViewPresentation(final boolean toOpenInNewTab, final FindModel findModelCopy) { final UsageViewPresentation presentation = new UsageViewPresentation(); final String scope = getTitleForScope(findModelCopy); final String stringToFind = findModelCopy.getStringToFind(); presentation.setScopeText(scope); presentation.setTabText(FindBundle.message("find.usage.view.tab.text", stringToFind)); presentation.setToolwindowTitle(FindBundle.message("find.usage.view.toolwindow.title", stringToFind, scope)); presentation.setUsagesString(FindBundle.message("find.usage.view.usages.text", stringToFind)); presentation.setOpenInNewTab(toOpenInNewTab); presentation.setCodeUsages(false); return presentation; } public static boolean hasReadOnlyUsages(final Collection<Usage> usages) { for (Usage usage : usages) { if (usage.isReadOnly()) return true; } return false; } public static FindUsagesProcessPresentation setupProcessPresentation(final Project project, final boolean showPanelIfOnlyOneUsage, final UsageViewPresentation presentation) { FindUsagesProcessPresentation processPresentation = new FindUsagesProcessPresentation(); processPresentation.setShowNotFoundMessage(true); processPresentation.setShowPanelIfOnlyOneUsage(showPanelIfOnlyOneUsage); processPresentation.setProgressIndicatorFactory( new Factory<ProgressIndicator>() { public ProgressIndicator create() { return new FindProgressIndicator(project, presentation.getScopeText()); } } ); return processPresentation; } public static class StringUsageTarget implements UsageTarget { private String myStringToFind; private ItemPresentation myItemPresentation = new ItemPresentation() { public String getPresentableText() { return FindBundle.message("find.usage.target.string.text", myStringToFind); } public String getLocationString() { return myStringToFind + "!!"; } public Icon getIcon(boolean open) { return null; } public TextAttributesKey getTextAttributesKey() { return null; } }; public StringUsageTarget(String _stringToFind) { myStringToFind = _stringToFind; } public void findUsages() {} public void findUsagesInEditor(FileEditor editor) {} public boolean isValid() { return true; } public boolean isReadOnly() { return true; } @Nullable public VirtualFile[] getFiles() { return null; } public void update() { } public String getName() { return myStringToFind; } public ItemPresentation getPresentation() { return myItemPresentation; } public FileStatus getFileStatus() { return FileStatus.NOT_CHANGED; } public void navigate(boolean requestFocus) { throw new UnsupportedOperationException(); } public boolean canNavigate() { return false; } public boolean canNavigateToSource() { return false; } } public static class AsyncFindUsagesProcessListener2ProcessorAdapter implements AsyncFindUsagesProcessListener { private final Processor<Usage> processor; private int count; public AsyncFindUsagesProcessListener2ProcessorAdapter(Processor<Usage> _processor) { processor = _processor; } public void foundUsage(UsageInfo info) { ++count; processor.process(new UsageInfo2UsageAdapter(info)); } public void findUsagesCompleted() { } public int getCount() { return count; } } }
source/com/intellij/find/impl/FindInProjectUtil.java
package com.intellij.find.impl; import com.intellij.find.*; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.actionSystem.DataConstants; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ContentIterator; import com.intellij.openapi.roots.FileIndex; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Factory; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.impl.PsiManagerImpl; import com.intellij.psi.impl.cache.CacheManager; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.UsageSearchContext; import com.intellij.psi.search.PsiSearchScopeUtil; import com.intellij.psi.search.SearchScope; import com.intellij.usageView.AsyncFindUsagesProcessListener; import com.intellij.usageView.UsageInfo; import com.intellij.usages.*; import com.intellij.util.PatternUtil; import com.intellij.util.Processor; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.io.File; import java.util.*; import java.util.regex.Pattern; public class FindInProjectUtil { private static final int USAGES_LIMIT = 1000; private static final int FILES_SIZE_LIMIT = 70 * 1024 * 1024; // megabytes. private static final int SINGLE_FILE_SIZE_LIMIT = 5 * 1024 * 1024; // megabytes. private static final int SKIP = 0; private static final int PROCESS_FILE = 1; private static final int SKIP_ALL = 2; private static final int PROCESS_ALL = 3; private FindInProjectUtil() {} public static void setDirectoryName(FindModel model, DataContext dataContext) { PsiElement psiElement = (PsiElement)dataContext.getData(DataConstants.PSI_ELEMENT); String directoryName = null; if (psiElement instanceof PsiDirectory) { directoryName = ((PsiDirectory)psiElement).getVirtualFile().getPresentableUrl(); } else { final PsiFile psiFile = (PsiFile)dataContext.getData(DataConstants.PSI_FILE); if (psiFile != null) { PsiDirectory psiDirectory = psiFile.getContainingDirectory(); if (psiDirectory != null) { directoryName = psiDirectory.getVirtualFile().getPresentableUrl(); } } } if (directoryName == null && psiElement instanceof PsiPackage) { final PsiDirectory[] directories = ((PsiPackage)psiElement).getDirectories(); directoryName = directories.length == 1 ? directories[0].getVirtualFile().getPresentableUrl():null; } Module module = (Module)dataContext.getData(DataConstants.MODULE_CONTEXT); if (module != null) { model.setModuleName(module.getName()); } if (model.getModuleName() == null || dataContext.getData(DataConstants.EDITOR) == null) { model.setDirectoryName(directoryName); model.setProjectScope(directoryName == null && module == null && model.getCustomScopeName() == null || dataContext.getData(DataConstants.EDITOR) != null); } } @Nullable public static PsiDirectory getPsiDirectory(final FindModel findModel, Project project) { String directoryName = findModel.getDirectoryName(); if (findModel.isProjectScope() || directoryName == null) { return null; } final PsiManager psiManager = PsiManager.getInstance(project); String path = directoryName.replace(File.separatorChar, '/'); VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(path); if (virtualFile == null || !virtualFile.isDirectory()) { if (!path.contains(JarFileSystem.JAR_SEPARATOR)) { path += JarFileSystem.JAR_SEPARATOR; } virtualFile = JarFileSystem.getInstance().findFileByPath(path); } if (virtualFile != null) { return psiManager.findDirectory(virtualFile); } else { return null; } } private static void addFilesUnderDirectory(PsiDirectory directory, Collection<PsiFile> fileList, boolean isRecursive, Pattern fileMaskRegExp) { final PsiElement[] children = directory.getChildren(); for (PsiElement child : children) { if (child instanceof PsiFile && (fileMaskRegExp == null || fileMaskRegExp.matcher(((PsiFile)child).getName()).matches() ) ) { PsiFile file = (PsiFile)child; PsiFile sourceFile = (PsiFile)file.getNavigationElement(); if (sourceFile != null) file = sourceFile; fileList.add(file); } else if (isRecursive && child instanceof PsiDirectory) { addFilesUnderDirectory((PsiDirectory)child, fileList, isRecursive, fileMaskRegExp); } } } @NotNull public static List<UsageInfo> findUsages(final FindModel findModel, final PsiDirectory psiDirectory, final Project project) { class MyAsyncUsageConsumer implements AsyncFindUsagesProcessListener { final ArrayList<UsageInfo> usages = new ArrayList<UsageInfo>(); public void foundUsage(UsageInfo info) { usages.add(info); } public int getCount() { return usages.size(); } public void findUsagesCompleted() { } } MyAsyncUsageConsumer consumer = new MyAsyncUsageConsumer(); findUsages(findModel, psiDirectory, project, consumer); return consumer.usages; } @Nullable private static Pattern createFileMaskRegExp(FindModel findModel) { if (findModel.getFileFilter() != null) { return Pattern.compile(PatternUtil.convertToRegex(findModel.getFileFilter()), Pattern.CASE_INSENSITIVE); } else { return null; } } public static void findUsages(final FindModel findModel, final PsiDirectory psiDirectory, final Project project, final AsyncFindUsagesProcessListener consumer) { final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); final Collection<PsiFile> psiFiles = getFilesToSearchIn(findModel, project, psiDirectory); final FileDocumentManager manager = FileDocumentManager.getInstance(); try { final SearchScope customScope = findModel.getCustomScope(); findModel.setCustomScope(null); //avoid mem leak int i = 0; long totalFilesSize = 0; final int[] count = new int[]{0}; boolean warningShown = false; boolean skipAllLarge = false; boolean processAllLarge = false; for (final PsiFile psiFile : psiFiles) { ProgressManager.getInstance().checkCanceled(); if (customScope != null && !ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() { public Boolean compute() { return PsiSearchScopeUtil.isInScope(customScope, psiFile); } })) { continue; } final VirtualFile virtualFile = psiFile.getVirtualFile(); final int index = i++; if (virtualFile == null) continue; long fileLength = getFileLength(virtualFile); if (fileLength == -1) continue; // Binary or invalid if (fileLength > SINGLE_FILE_SIZE_LIMIT) { if (skipAllLarge) continue; if (!processAllLarge) { int retCode = showMessage(project, FindBundle.message("find.skip.large.file.prompt", ApplicationNamesInfo.getInstance().getProductName(), getPresentablePath(virtualFile), presentableSize(fileLength)), FindBundle.message("find.skip.large.file.title"), new String[] { FindBundle.message("find.skip.large.file.skip.file"), FindBundle.message("find.skip.large.file.scan.file"), FindBundle.message("find.skip.large.file.skip.all"), FindBundle.message("find.skip.large.file.scan.all") }); if (retCode == SKIP_ALL) { skipAllLarge = true; continue; } else if (retCode == SKIP) { continue; } else if (retCode == PROCESS_ALL) { processAllLarge = true; } else { assert retCode == PROCESS_FILE : retCode; } } } int countBefore = count[0]; ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { if (virtualFile.isValid()) { // Check once more if valid and text since we're in new read action and things might have been changed. if (FileTypeManager.getInstance().getFileTypeByFile(virtualFile).isBinary()) return; // do not decompile .class files final Document document = manager.getDocument(virtualFile); if (document != null) { addToUsages(project, document, consumer, findModel, psiFile, count); if (progress != null) { progress.setFraction((double)index / psiFiles.size()); String text = FindBundle.message("find.searching.for.string.in.file.progress", findModel.getStringToFind(), virtualFile.getPresentableUrl()); progress.setText(text); int size = consumer.getCount(); progress.setText2(FindBundle.message("find.searching.for.string.in.file.occurrences.progress", size)); } } } } }); if (countBefore < count[0]) { totalFilesSize += fileLength; if (totalFilesSize > FILES_SIZE_LIMIT && !warningShown) { showTooManyUsagesWaring(project, FindBundle.message("find.excessive.total.size.prompt", presentableSize(totalFilesSize), ApplicationNamesInfo.getInstance().getProductName())); warningShown = true; } } if (count[0] > USAGES_LIMIT && !warningShown) { showTooManyUsagesWaring(project, FindBundle.message("find.excessive.usage.count.prompt", count[0])); warningShown = true; } } } catch (ProcessCanceledException e) { // fine } if (progress != null) { progress.setText(FindBundle.message("find.progress.search.completed")); } consumer.findUsagesCompleted(); } private static String getPresentablePath(final VirtualFile virtualFile) { return ApplicationManager.getApplication().runReadAction(new Computable<String>() { public String compute() { return virtualFile.getPresentableUrl(); } }); } private static String presentableSize(long bytes) { long megabytes = bytes / (1024 * 1024); return FindBundle.message("find.file.size.megabytes", Long.toString(megabytes)); } private static long getFileLength(final VirtualFile virtualFile) { final long[] length = new long[] {-1L}; ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { if (!virtualFile.isValid()) return; if (FileTypeManager.getInstance().getFileTypeByFile(virtualFile).isBinary()) return; length[0] = virtualFile.getLength(); } }); return length[0]; } private static void showTooManyUsagesWaring(final Project project, final String message) { int retCode = invokeAndWait(new Computable<Integer>() { public Integer compute() { return Messages.showYesNoDialog(project, message, FindBundle.message("find.excessive.usages.title"), Messages.getWarningIcon()); } }); if (retCode != DialogWrapper.OK_EXIT_CODE) { throw new ProcessCanceledException(); } } private static int invokeAndWait(final Computable<Integer> f) { final int[] answer = new int[1]; try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { answer[0] = f.compute(); } }); } catch (Exception e) { answer[0] = 0; } return answer[0]; } private static int showMessage(final Project project, final String message, final String title, final String[] buttons) { return invokeAndWait(new Computable<Integer>() { public Integer compute() { return Messages.showDialog(project, message, title, buttons, 0, Messages.getWarningIcon()); } }); } private static Collection<PsiFile> getFilesToSearchIn(final FindModel findModel, final Project project, final PsiDirectory psiDirectory) { return ApplicationManager.getApplication().runReadAction(new Computable<Collection<PsiFile>>() { public Collection<PsiFile> compute() { return getFilesToSearchInReadAction(findModel, project, psiDirectory); } }); } private static Collection<PsiFile> getFilesToSearchInReadAction(final FindModel findModel, final Project project, final PsiDirectory psiDirectory) { String moduleName = findModel.getModuleName(); Module module = moduleName == null ? null : ModuleManager.getInstance(project).findModuleByName(moduleName); final FileIndex fileIndex = module == null ? ProjectRootManager.getInstance(project).getFileIndex() : ModuleRootManager.getInstance(module).getFileIndex(); if (psiDirectory == null || findModel.isWithSubdirectories() && fileIndex.isInContent(psiDirectory.getVirtualFile())) { final Pattern fileMaskRegExp = createFileMaskRegExp(findModel); // optimization final Collection<PsiFile> filesForFastWordSearch = getFilesForFastWordSearch(findModel, project, psiDirectory, fileMaskRegExp, module); if (filesForFastWordSearch != null && canOptimizeForFastWordSearch(findModel)) return filesForFastWordSearch; class EnumContentIterator implements ContentIterator { List<PsiFile> myFiles = new ArrayList<PsiFile>(filesForFastWordSearch == null ? Collections.<PsiFile>emptyList() : filesForFastWordSearch); final PsiManager psiManager = PsiManager.getInstance(project); public boolean processFile(VirtualFile virtualFile) { if (!virtualFile.isDirectory() && (fileMaskRegExp == null || fileMaskRegExp.matcher(virtualFile.getName()).matches()) ) { final PsiFile psiFile = psiManager.findFile(virtualFile); if (psiFile != null && (filesForFastWordSearch == null || !filesForFastWordSearch.contains(psiFile))) { myFiles.add(psiFile); } } return true; } private Collection<PsiFile> getFiles() { return myFiles; } } final EnumContentIterator iterator = new EnumContentIterator(); if (psiDirectory == null) { fileIndex.iterateContent(iterator); } else { fileIndex.iterateContentUnderDirectory(psiDirectory.getVirtualFile(), iterator); } return iterator.getFiles(); } else { Collection<PsiFile> fileList = new THashSet<PsiFile>(); addFilesUnderDirectory(psiDirectory, fileList, findModel.isWithSubdirectories(), createFileMaskRegExp(findModel)); return fileList; } } @Nullable private static Collection<PsiFile> getFilesForFastWordSearch(final FindModel findModel, final Project project, final PsiDirectory psiDirectory, final Pattern fileMaskRegExp, final Module module) { CacheManager cacheManager = ((PsiManagerImpl)PsiManager.getInstance(project)).getCacheManager(); GlobalSearchScope scope = psiDirectory == null ? module == null ? GlobalSearchScope.projectScope(project) : moduleContentScope(module) : GlobalSearchScope.directoryScope(psiDirectory, true); List<String> words = StringUtil.getWordsIn(findModel.getStringToFind()); // if no words specified in search box, fallback to brute force search if (words.isEmpty()) return null; // hope long words are rare Collections.sort(words, new Comparator<String>() { public int compare(final String o1, final String o2) { return o2.length() - o1.length(); } }); Set<PsiFile> resultFiles = new THashSet<PsiFile>(); for (int i = 0; i < words.size(); i++) { String word = words.get(i); PsiFile[] files = cacheManager.getFilesWithWord(word, UsageSearchContext.ANY, scope, findModel.isCaseSensitive()); if (files.length == 0) { resultFiles.clear(); break; } final List<PsiFile> psiFiles = Arrays.asList(files); if (i == 0) { resultFiles.addAll(psiFiles); } else { resultFiles.retainAll(psiFiles); } filterMaskedFiles(resultFiles, fileMaskRegExp); if (resultFiles.isEmpty()) break; } // in case our word splitting is incorrect PsiFile[] allWordsFiles = cacheManager.getFilesWithWord(findModel.getStringToFind(), UsageSearchContext.ANY, scope, findModel.isCaseSensitive()); resultFiles.addAll(Arrays.asList(allWordsFiles)); filterMaskedFiles(resultFiles, fileMaskRegExp); return resultFiles; } private static GlobalSearchScope moduleContentScope(final Module module) { VirtualFile[] contentRoots = ModuleRootManager.getInstance(module).getContentRoots(); GlobalSearchScope result = null; PsiManager psiManager = PsiManager.getInstance(module.getProject()); for (VirtualFile root : contentRoots) { PsiDirectory directory = psiManager.findDirectory(root); GlobalSearchScope moduleContent = GlobalSearchScope.directoryScope(directory, true); if (result == null) { result = moduleContent; } else { result = result.uniteWith(moduleContent); } } return result; } private static void filterMaskedFiles(final Set<PsiFile> resultFiles, final Pattern fileMaskRegExp) { if (fileMaskRegExp != null) { for (Iterator<PsiFile> iterator = resultFiles.iterator(); iterator.hasNext();) { PsiFile file = iterator.next(); if (!fileMaskRegExp.matcher(file.getName()).matches()) { iterator.remove(); } } } } private static boolean canOptimizeForFastWordSearch(final FindModel findModel) { // $ is used to separate words when indexing plain-text files but not when indexing // Java identifiers, so we can't consistently break a string containing $ characters // into words return findModel.isWholeWordsOnly() && !findModel.isRegularExpressions() && findModel.getStringToFind().indexOf('$') < 0; } private static void addToUsages(@NotNull Project project, @NotNull Document document, @NotNull AsyncFindUsagesProcessListener consumer, @NotNull FindModel findModel, @NotNull final PsiFile psiFile, @NotNull final int[] count) { CharSequence text = document.getCharsSequence(); int textLength = document.getTextLength(); if (text != null) { int offset = 0; FindManager findManager = FindManager.getInstance(project); while (offset < textLength) { FindResult result = findManager.findString(text, offset, findModel); if (!result.isStringFound()) break; UsageInfo info = new UsageInfo(psiFile, result.getStartOffset(), result.getEndOffset()); consumer.foundUsage(info); count[0]++; final int prevOffset = offset; offset = result.getEndOffset(); if (prevOffset == offset) { // for regular expr the size of the match could be zero -> could be infinite loop in finding usages! ++offset; } } } } private static String getTitleForScope(final FindModel findModel) { String result; if (findModel.isProjectScope()) { result = FindBundle.message("find.scope.project.title"); } else if (findModel.getModuleName() != null) { result = FindBundle.message("find.scope.module.title", findModel.getModuleName()); } else { result = FindBundle.message("find.scope.directory.title", findModel.getDirectoryName()); } if (findModel.getFileFilter() != null) { result = FindBundle.message("find.scope.files.with.mask", result, findModel.getFileFilter()); } return result; } public static UsageViewPresentation setupViewPresentation(final boolean toOpenInNewTab, final FindModel findModelCopy) { final UsageViewPresentation presentation = new UsageViewPresentation(); final String scope = getTitleForScope(findModelCopy); final String stringToFind = findModelCopy.getStringToFind(); presentation.setScopeText(scope); presentation.setTabText(FindBundle.message("find.usage.view.tab.text", stringToFind)); presentation.setToolwindowTitle(FindBundle.message("find.usage.view.toolwindow.title", stringToFind, scope)); presentation.setUsagesString(FindBundle.message("find.usage.view.usages.text", stringToFind)); presentation.setOpenInNewTab(toOpenInNewTab); presentation.setCodeUsages(false); return presentation; } public static boolean hasReadOnlyUsages(final Collection<Usage> usages) { for (Usage usage : usages) { if (usage.isReadOnly()) return true; } return false; } public static FindUsagesProcessPresentation setupProcessPresentation(final Project project, final boolean showPanelIfOnlyOneUsage, final UsageViewPresentation presentation) { FindUsagesProcessPresentation processPresentation = new FindUsagesProcessPresentation(); processPresentation.setShowNotFoundMessage(true); processPresentation.setShowPanelIfOnlyOneUsage(showPanelIfOnlyOneUsage); processPresentation.setProgressIndicatorFactory( new Factory<ProgressIndicator>() { public ProgressIndicator create() { return new FindProgressIndicator(project, presentation.getScopeText()); } } ); return processPresentation; } public static class StringUsageTarget implements UsageTarget { private String myStringToFind; private ItemPresentation myItemPresentation = new ItemPresentation() { public String getPresentableText() { return FindBundle.message("find.usage.target.string.text", myStringToFind); } public String getLocationString() { return myStringToFind + "!!"; } public Icon getIcon(boolean open) { return null; } public TextAttributesKey getTextAttributesKey() { return null; } }; public StringUsageTarget(String _stringToFind) { myStringToFind = _stringToFind; } public void findUsages() {} public void findUsagesInEditor(FileEditor editor) {} public boolean isValid() { return true; } public boolean isReadOnly() { return true; } @Nullable public VirtualFile[] getFiles() { return null; } public void update() { } public String getName() { return myStringToFind; } public ItemPresentation getPresentation() { return myItemPresentation; } public FileStatus getFileStatus() { return FileStatus.NOT_CHANGED; } public void navigate(boolean requestFocus) { throw new UnsupportedOperationException(); } public boolean canNavigate() { return false; } public boolean canNavigateToSource() { return false; } } public static class AsyncFindUsagesProcessListener2ProcessorAdapter implements AsyncFindUsagesProcessListener { private final Processor<Usage> processor; private int count; public AsyncFindUsagesProcessListener2ProcessorAdapter(Processor<Usage> _processor) { processor = _processor; } public void foundUsage(UsageInfo info) { ++count; processor.process(new UsageInfo2UsageAdapter(info)); } public void findUsagesCompleted() { } public int getCount() { return count; } } }
message text fixed
source/com/intellij/find/impl/FindInProjectUtil.java
message text fixed
Java
apache-2.0
00d53bb1e9fbc8d33a9118d8a621e3ce6a7151d7
0
obidea/semantika-cli
/* * Copyright (c) 2013-2014 Obidea * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.obidea.semantika.cli; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.List; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.io.FileUtils; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import com.obidea.semantika.app.ApplicationFactory; import com.obidea.semantika.app.ApplicationManager; import com.obidea.semantika.exception.SemantikaException; import com.obidea.semantika.materializer.IMaterializerEngine; import com.obidea.semantika.materializer.MaterializationException; import com.obidea.semantika.materializer.MaterializerEngineException; import com.obidea.semantika.queryanswer.IQueryEngine; import com.obidea.semantika.queryanswer.IQueryEngineExt; import com.obidea.semantika.queryanswer.QueryEngineException; import com.obidea.semantika.queryanswer.result.IQueryResult; import com.obidea.semantika.util.StringUtils; @SuppressWarnings("static-access") public class Main { private static final String VERSION_NUMBER = "1.2"; //$NON-NLS-1$ private static final String SEMANTIKA_CORE_VERSION_NUMBER = "1.6"; //$NON-NLS-1$ private static Options sOptions = new Options(); static { sOptions.addOption(CliEnvironment.HELP, false, "print this message"); //$NON-NLS-1$ sOptions.addOption(CliEnvironment.VERSION, false, "print the version information and exit"); //$NON-NLS-1$ sOptions.addOption(CliEnvironment.SHOW_SQL, false, "show the generated SQL (for 'queryanswer' only)"); //$NON-NLS-1$ sOptions.addOption(CliEnvironment.VERBOSE_SHORTCUT, CliEnvironment.VERBOSE, false, "be extra verbose"); //$NON-NLS-1$ sOptions.addOption(CliEnvironment.QUIET_SHORTCUT, CliEnvironment.QUIET, false, "be extra quiet"); //$NON-NLS-1$ sOptions.addOption( OptionBuilder.withLongOpt(CliEnvironment.CONFIG) .withDescription("path to Semantika configuration file (default=./configuration.xml)") //$NON-NLS-1$ .hasArg() .withArgName("=PATH") //$NON-NLS-1$ .create()); sOptions.addOption( OptionBuilder.withLongOpt(CliEnvironment.QUERY) .withDescription("path to SPARQL query file") //$NON-NLS-1$ .hasArg() .withArgName("=PATH") //$NON-NLS-1$ .create()); sOptions.addOption( OptionBuilder.withLongOpt(CliEnvironment.OUTPUT) .withDescription("path to output file to flush the result") //$NON-NLS-1$ .hasArg() .withArgName("=PATH") //$NON-NLS-1$ .create()); sOptions.addOption( OptionBuilder.withLongOpt(CliEnvironment.FORMAT) .withDescription("flush result in selected format (options: N3,TTL,XML,JSON)") //$NON-NLS-1$ .hasArg() .withArgName("FORMAT") //$NON-NLS-1$ .create(CliEnvironment.FORMAT_SHORTCUT)); sOptions.addOption( OptionBuilder.withLongOpt(CliEnvironment.LIMIT) .withDescription("limit the number of returned query result") //$NON-NLS-1$ .hasArg() .withArgName("SIZE") //$NON-NLS-1$ .create(CliEnvironment.LIMIT_SHORTCUT)); } private static CustomHelpFormatter mFormatter = new CustomHelpFormatter(); public static void main(String[] args) { @SuppressWarnings("unchecked") List<Logger> loggers = Collections.list(LogManager.getCurrentLoggers()); loggers.add(LogManager.getRootLogger()); normal(loggers); try { CommandLineParser parser = new GnuParser(); CommandLine optionLine = parser.parse(sOptions, args); if (optionLine.hasOption(CliEnvironment.VERSION)) { printVersion(); System.exit(0); } if (optionLine.hasOption(CliEnvironment.HELP)) { printUsage(); System.exit(0); } String operation = determineOperation(args); if (StringUtils.isEmpty(operation)) { printUsage(); } else { setupLoggers(optionLine, loggers); executeOperation(operation, optionLine); } } catch (Exception e) { System.err.println("Unexpected exception:" + e.getMessage()); //$NON-NLS-1$ System.exit(1); } } private static void setupLoggers(CommandLine optionLine, List<Logger> loggers) { if (optionLine.hasOption(CliEnvironment.VERBOSE)) { verbose(loggers); } else if (optionLine.hasOption(CliEnvironment.QUIET)) { quiet(loggers); } } private static void executeOperation(String operation, CommandLine optionLine) throws Exception { if (operation.equals(CliEnvironment.QUERYANSWER_OP)) { File config = determineConfigurationFile(optionLine); ApplicationManager manager = new ApplicationFactory().configure(config).createApplicationManager(); File fquery = determineQueryFile(optionLine); int limit = determineResultLimit(optionLine); IQueryEngine engine = createQueryEngine(manager); boolean showSql = determineShowSql(optionLine); queryanswer(engine, fquery, limit, showSql); } else if (operation.equals(CliEnvironment.MATERIALIZE_OP)) { File config = determineConfigurationFile(optionLine); ApplicationManager manager = new ApplicationFactory().configure(config).createApplicationManager(); String format = determineOutputFormat(optionLine); File fout = determineOutputFile(optionLine); IMaterializerEngine engine = createMaterializerEngine(manager, format); materialize(engine, fout); } else { System.err.println("Invalid command"); //$NON-NLS-1$ printUsage(); } } private static void queryanswer(IQueryEngine engine, File fquery, int limit, boolean showSql) throws QueryEngineException, SemantikaException, IOException { String sparql = FileUtils.readFileToString(fquery, "UTF-8"); //$NON-NLS-1$ engine.start(); if (showSql) { printSql(sparql, engine); } else { flushResult(evaluateQuery(sparql, engine, limit)); } engine.stop(); } private static void printSql(String sparql, IQueryEngine engine) throws SemantikaException { String sql = engine.translate(sparql); System.out.println(sql); } private static IQueryResult evaluateQuery(String sparql, IQueryEngine engine, int limit) throws SemantikaException { if (engine instanceof IQueryEngineExt) { return ((IQueryEngineExt) engine).createQuery(sparql).setMaxResults(limit).evaluate(); } return engine.evaluate(sparql); } private static void materialize(IMaterializerEngine engine, File fout) throws MaterializerEngineException, MaterializationException { engine.start(); engine.materialize(fout, new ConsoleProgressBar()); engine.stop(); } private static IQueryEngine createQueryEngine(ApplicationManager manager) { return manager.createQueryEngine(); } private static IMaterializerEngine createMaterializerEngine(ApplicationManager manager, String format) { if (format.equals("N3")) { //$NON-NLS-1$ return manager.createMaterializerEngine().useNTriples(); } else if (format.equals("TTL")) { //$NON-NLS-1$ return manager.createMaterializerEngine().useTurtle(); } else if (format.equals("XML")) { //$NON-NLS-1$ return manager.createMaterializerEngine().useRdfXml(); } else if (format.equals("JSON")) { //$NON-NLS-1$ return manager.createMaterializerEngine().useRdfJson(); } return null; // should never goes here } /** * Flush the query result to stdout. */ private static void flushResult(IQueryResult result) throws IOException { while (result.next()) { System.out.println(result.getValueList().toString()); } } /** * Determines the file to use for reading the SPARQL query. * * @param optionLine * The command-line arguments passed in. * @return The path of the query file on disk. */ private static File determineQueryFile(CommandLine optionLine) { String query = optionLine.getOptionValue(CliEnvironment.QUERY); //$NON-NLS-1$ if (StringUtils.isEmpty(query)) { System.err.println("Query file is missing"); //$NON-NLS-1$ System.exit(1); } return new File(query); } /** * Determines the file to use for loading the configuration. * * @param optionLine * The command-line arguments passed in. * @return The path of the configuration file on disk. */ private static File determineConfigurationFile(CommandLine optionLine) { String config = optionLine.getOptionValue(CliEnvironment.CONFIG); //$NON-NLS-1$ if (StringUtils.isEmpty(config)) { return new File(ApplicationFactory.DEFAULT_CONFIGURATION_FILENAME); //$NON-NLS-1$ } return new File(config); } /** * Determines the writer format for flushing the output. * * @param args * The command-line arguments passed in. * @return The selected writer format. */ private static String determineOutputFormat(CommandLine optionLine) { String format = optionLine.getOptionValue(CliEnvironment.FORMAT); if (StringUtils.isEmpty(format)) { format = "TTL"; //$NON-NLS-1$ - by default } return format; } /** * Determines the limit of the query result to be fetched. * * @param optionLine * The command-line arguments passed in. * @return The limit amount. */ private static int determineResultLimit(CommandLine optionLine) { String limit = optionLine.getOptionValue(CliEnvironment.LIMIT); if (StringUtils.isEmpty(limit)) { return -1; } return Integer.parseInt(limit); } /** * Determines if the generated SQL should be printed instead of executing it. * * @param optionLine * The command-line arguments passed in. */ private static boolean determineShowSql(CommandLine optionLine) { return optionLine.hasOption(CliEnvironment.SHOW_SQL); } /** * Determines the command operation Semantika CLI should execute. * * @param args * The command-line arguments passed in. * @return The operation string or <code>null</code> if it could not be * determined. */ private static String determineOperation(String[] args) { for (String arg : args) { if (!arg.startsWith("-")) { //$NON-NLS-1$ return arg; } } return null; } /** * Determines the file to use to flush out the result. * * @param args * The command-line arguments passed in. * @return The path of the output file on disk. */ private static File determineOutputFile(CommandLine optionLine) { String output = optionLine.getOptionValue(CliEnvironment.OUTPUT); if (!StringUtils.isEmpty(output)) { return new File(output); } System.err.println("Output file is missing"); //$NON-NLS-1$ System.exit(1); return null; } /** * Print tool version. */ private static void printVersion() { StringBuilder sb = new StringBuilder(); sb.append("semantika version "); //$NON-NLS-1$ sb.append("\"").append(VERSION_NUMBER).append("\""); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("\n"); //$NON-NLS-1$ sb.append("Semantika Core Runtime "); //$NON-NLS-1$ sb.append("(build ").append(SEMANTIKA_CORE_VERSION_NUMBER).append(")"); //$NON-NLS-1$ //$NON-NLS-2$ System.out.println(sb.toString()); } /** * Set all loggers in INFO level. */ private static void normal(List<Logger> loggers) { for ( Logger logger : loggers ) { logger.setLevel(Level.INFO); } } /** * Set all loggers in DEBUG level. */ private static void verbose(List<Logger> loggers) { for ( Logger logger : loggers ) { logger.setLevel(Level.DEBUG); } } /** * Disable all loggers. */ private static void quiet(List<Logger> loggers) { for ( Logger logger : loggers ) { logger.setLevel(Level.OFF); } } /** * Prints the usage instructions on the console. */ private static void printUsage() { StringBuilder usage = new StringBuilder(); usage.append(String.format("semantika %s [OPTIONS...]\n", CliEnvironment.QUERYANSWER_OP)); usage.append(" (to execute query answer)\n"); usage.append(String.format(" semantika %s [OPTIONS...]\n", CliEnvironment.MATERIALIZE_OP)); usage.append(" (to execute RDB2RDF export)"); String header = "where OPTIONS include:"; //$NON-NLS-1$ String footer = "\nExample:\n" + //$NON-NLS-1$ " ./semantika queryanswer --config=configuration.xml --query=query.txt -l 100\n" + //$NON-NLS-1$ " ./semantika rdb2rdf --config=configuration.xml --output=output.n3 -f N3"; //$NON-NLS-1$ mFormatter.setOptionComparator(null); mFormatter.printHelp(400, usage.toString(), header, sOptions, footer); } }
src/com/obidea/semantika/cli/Main.java
/* * Copyright (c) 2013-2014 Obidea * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.obidea.semantika.cli; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.List; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.io.FileUtils; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import com.obidea.semantika.app.ApplicationFactory; import com.obidea.semantika.app.ApplicationManager; import com.obidea.semantika.exception.SemantikaException; import com.obidea.semantika.materializer.IMaterializerEngine; import com.obidea.semantika.materializer.MaterializationException; import com.obidea.semantika.materializer.MaterializerEngineException; import com.obidea.semantika.queryanswer.IQueryEngine; import com.obidea.semantika.queryanswer.IQueryEngineExt; import com.obidea.semantika.queryanswer.QueryEngineException; import com.obidea.semantika.queryanswer.result.IQueryResult; import com.obidea.semantika.util.StringUtils; @SuppressWarnings("static-access") public class Main { private static final String VERSION_NUMBER = "1.2"; //$NON-NLS-1$ private static final String SEMANTIKA_CORE_VERSION_NUMBER = "1.4"; //$NON-NLS-1$ private static Options sOptions = new Options(); static { sOptions.addOption(CliEnvironment.HELP, false, "print this message"); //$NON-NLS-1$ sOptions.addOption(CliEnvironment.VERSION, false, "print the version information and exit"); //$NON-NLS-1$ sOptions.addOption(CliEnvironment.SHOW_SQL, false, "show the generated SQL (for 'queryanswer' only)"); //$NON-NLS-1$ sOptions.addOption(CliEnvironment.VERBOSE_SHORTCUT, CliEnvironment.VERBOSE, false, "be extra verbose"); //$NON-NLS-1$ sOptions.addOption(CliEnvironment.QUIET_SHORTCUT, CliEnvironment.QUIET, false, "be extra quiet"); //$NON-NLS-1$ sOptions.addOption( OptionBuilder.withLongOpt(CliEnvironment.CONFIG) .withDescription("path to Semantika configuration file (default=./configuration.xml)") //$NON-NLS-1$ .hasArg() .withArgName("=PATH") //$NON-NLS-1$ .create()); sOptions.addOption( OptionBuilder.withLongOpt(CliEnvironment.QUERY) .withDescription("path to SPARQL query file") //$NON-NLS-1$ .hasArg() .withArgName("=PATH") //$NON-NLS-1$ .create()); sOptions.addOption( OptionBuilder.withLongOpt(CliEnvironment.OUTPUT) .withDescription("path to output file to flush the result") //$NON-NLS-1$ .hasArg() .withArgName("=PATH") //$NON-NLS-1$ .create()); sOptions.addOption( OptionBuilder.withLongOpt(CliEnvironment.FORMAT) .withDescription("flush result in selected format (options: N3,TTL,XML,JSON)") //$NON-NLS-1$ .hasArg() .withArgName("FORMAT") //$NON-NLS-1$ .create(CliEnvironment.FORMAT_SHORTCUT)); sOptions.addOption( OptionBuilder.withLongOpt(CliEnvironment.LIMIT) .withDescription("limit the number of returned query result") //$NON-NLS-1$ .hasArg() .withArgName("SIZE") //$NON-NLS-1$ .create(CliEnvironment.LIMIT_SHORTCUT)); } private static CustomHelpFormatter mFormatter = new CustomHelpFormatter(); public static void main(String[] args) { @SuppressWarnings("unchecked") List<Logger> loggers = Collections.list(LogManager.getCurrentLoggers()); loggers.add(LogManager.getRootLogger()); normal(loggers); try { CommandLineParser parser = new GnuParser(); CommandLine optionLine = parser.parse(sOptions, args); if (optionLine.hasOption(CliEnvironment.VERSION)) { printVersion(); System.exit(0); } if (optionLine.hasOption(CliEnvironment.HELP)) { printUsage(); System.exit(0); } String operation = determineOperation(args); if (StringUtils.isEmpty(operation)) { printUsage(); } else { setupLoggers(optionLine, loggers); executeOperation(operation, optionLine); } } catch (Exception e) { System.err.println("Unexpected exception:" + e.getMessage()); //$NON-NLS-1$ System.exit(1); } } private static void setupLoggers(CommandLine optionLine, List<Logger> loggers) { if (optionLine.hasOption(CliEnvironment.VERBOSE)) { verbose(loggers); } else if (optionLine.hasOption(CliEnvironment.QUIET)) { quiet(loggers); } } private static void executeOperation(String operation, CommandLine optionLine) throws Exception { if (operation.equals(CliEnvironment.QUERYANSWER_OP)) { File config = determineConfigurationFile(optionLine); ApplicationManager manager = new ApplicationFactory().configure(config).createApplicationManager(); File fquery = determineQueryFile(optionLine); int limit = determineResultLimit(optionLine); IQueryEngine engine = createQueryEngine(manager); boolean showSql = determineShowSql(optionLine); queryanswer(engine, fquery, limit, showSql); } else if (operation.equals(CliEnvironment.MATERIALIZE_OP)) { File config = determineConfigurationFile(optionLine); ApplicationManager manager = new ApplicationFactory().configure(config).createApplicationManager(); String format = determineOutputFormat(optionLine); File fout = determineOutputFile(optionLine); IMaterializerEngine engine = createMaterializerEngine(manager, format); materialize(engine, fout); } else { System.err.println("Invalid command"); //$NON-NLS-1$ printUsage(); } } private static void queryanswer(IQueryEngine engine, File fquery, int limit, boolean showSql) throws QueryEngineException, SemantikaException, IOException { String sparql = FileUtils.readFileToString(fquery, "UTF-8"); //$NON-NLS-1$ engine.start(); if (showSql) { printSql(sparql, engine); } else { flushResult(evaluateQuery(sparql, engine, limit)); } engine.stop(); } private static void printSql(String sparql, IQueryEngine engine) throws SemantikaException { String sql = engine.translate(sparql); System.out.println(sql); } private static IQueryResult evaluateQuery(String sparql, IQueryEngine engine, int limit) throws SemantikaException { if (engine instanceof IQueryEngineExt) { return ((IQueryEngineExt) engine).createQuery(sparql).setMaxResults(limit).evaluate(); } return engine.evaluate(sparql); } private static void materialize(IMaterializerEngine engine, File fout) throws MaterializerEngineException, MaterializationException { engine.start(); engine.materialize(fout, new ConsoleProgressBar()); engine.stop(); } private static IQueryEngine createQueryEngine(ApplicationManager manager) { return manager.createQueryEngine(); } private static IMaterializerEngine createMaterializerEngine(ApplicationManager manager, String format) { if (format.equals("N3")) { //$NON-NLS-1$ return manager.createMaterializerEngine().useNTriples(); } else if (format.equals("TTL")) { //$NON-NLS-1$ return manager.createMaterializerEngine().useTurtle(); } else if (format.equals("XML")) { //$NON-NLS-1$ return manager.createMaterializerEngine().useRdfXml(); } else if (format.equals("JSON")) { //$NON-NLS-1$ return manager.createMaterializerEngine().useRdfJson(); } return null; // should never goes here } /** * Flush the query result to stdout. */ private static void flushResult(IQueryResult result) throws IOException { while (result.next()) { System.out.println(result.getValueList().toString()); } } /** * Determines the file to use for reading the SPARQL query. * * @param optionLine * The command-line arguments passed in. * @return The path of the query file on disk. */ private static File determineQueryFile(CommandLine optionLine) { String query = optionLine.getOptionValue(CliEnvironment.QUERY); //$NON-NLS-1$ if (StringUtils.isEmpty(query)) { System.err.println("Query file is missing"); //$NON-NLS-1$ System.exit(1); } return new File(query); } /** * Determines the file to use for loading the configuration. * * @param optionLine * The command-line arguments passed in. * @return The path of the configuration file on disk. */ private static File determineConfigurationFile(CommandLine optionLine) { String config = optionLine.getOptionValue(CliEnvironment.CONFIG); //$NON-NLS-1$ if (StringUtils.isEmpty(config)) { return new File(ApplicationFactory.DEFAULT_CONFIGURATION_FILENAME); //$NON-NLS-1$ } return new File(config); } /** * Determines the writer format for flushing the output. * * @param args * The command-line arguments passed in. * @return The selected writer format. */ private static String determineOutputFormat(CommandLine optionLine) { String format = optionLine.getOptionValue(CliEnvironment.FORMAT); if (StringUtils.isEmpty(format)) { format = "TTL"; //$NON-NLS-1$ - by default } return format; } /** * Determines the limit of the query result to be fetched. * * @param optionLine * The command-line arguments passed in. * @return The limit amount. */ private static int determineResultLimit(CommandLine optionLine) { String limit = optionLine.getOptionValue(CliEnvironment.LIMIT); if (StringUtils.isEmpty(limit)) { return -1; } return Integer.parseInt(limit); } /** * Determines if the generated SQL should be printed instead of executing it. * * @param optionLine * The command-line arguments passed in. */ private static boolean determineShowSql(CommandLine optionLine) { return optionLine.hasOption(CliEnvironment.SHOW_SQL); } /** * Determines the command operation Semantika CLI should execute. * * @param args * The command-line arguments passed in. * @return The operation string or <code>null</code> if it could not be * determined. */ private static String determineOperation(String[] args) { for (String arg : args) { if (!arg.startsWith("-")) { //$NON-NLS-1$ return arg; } } return null; } /** * Determines the file to use to flush out the result. * * @param args * The command-line arguments passed in. * @return The path of the output file on disk. */ private static File determineOutputFile(CommandLine optionLine) { String output = optionLine.getOptionValue(CliEnvironment.OUTPUT); if (!StringUtils.isEmpty(output)) { return new File(output); } System.err.println("Output file is missing"); //$NON-NLS-1$ System.exit(1); return null; } /** * Print tool version. */ private static void printVersion() { StringBuilder sb = new StringBuilder(); sb.append("semantika version "); //$NON-NLS-1$ sb.append("\"").append(VERSION_NUMBER).append("\""); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("\n"); //$NON-NLS-1$ sb.append("Semantika Core Runtime "); //$NON-NLS-1$ sb.append("(build ").append(SEMANTIKA_CORE_VERSION_NUMBER).append(")"); //$NON-NLS-1$ //$NON-NLS-2$ System.out.println(sb.toString()); } /** * Set all loggers in INFO level. */ private static void normal(List<Logger> loggers) { for ( Logger logger : loggers ) { logger.setLevel(Level.INFO); } } /** * Set all loggers in DEBUG level. */ private static void verbose(List<Logger> loggers) { for ( Logger logger : loggers ) { logger.setLevel(Level.DEBUG); } } /** * Disable all loggers. */ private static void quiet(List<Logger> loggers) { for ( Logger logger : loggers ) { logger.setLevel(Level.OFF); } } /** * Prints the usage instructions on the console. */ private static void printUsage() { StringBuilder usage = new StringBuilder(); usage.append(String.format("semantika %s [OPTIONS...]\n", CliEnvironment.QUERYANSWER_OP)); usage.append(" (to execute query answer)\n"); usage.append(String.format(" semantika %s [OPTIONS...]\n", CliEnvironment.MATERIALIZE_OP)); usage.append(" (to execute RDB2RDF export)"); String header = "where OPTIONS include:"; //$NON-NLS-1$ String footer = "\nExample:\n" + //$NON-NLS-1$ " ./semantika queryanswer --config=configuration.xml --query=query.txt -l 100\n" + //$NON-NLS-1$ " ./semantika rdb2rdf --config=configuration.xml --output=output.n3 -f N3"; //$NON-NLS-1$ mFormatter.setOptionComparator(null); mFormatter.printHelp(400, usage.toString(), header, sOptions, footer); } }
Change Semantika version number.
src/com/obidea/semantika/cli/Main.java
Change Semantika version number.
Java
apache-2.0
3855cf94a49a8da2db12ca9159dc22fb71e1d9fb
0
mozafari/verdict,mozafari/verdict,mozafari/verdict,mozafari/verdict,mozafari/verdict
/* * Copyright 2017 University of Michigan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.umich.verdict; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.TreeMap; import edu.umich.verdict.datatypes.SampleParam; import edu.umich.verdict.datatypes.TableUniqueName; import org.apache.commons.lang3.tuple.Pair; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import edu.umich.verdict.util.VerdictLogger; public class VerdictConf { private Map<String, String> configs = new TreeMap<String, String>(); private static Map<TableUniqueName, SampleParam> samplesToUse = null; private final Map<String, String> configKeySynonyms = new ImmutableMap.Builder<String, String>() .put("bypass", "verdict.bypass") .put("loglevel", "verdict.loglevel") .put("user", "verdict.jdbc.user") .put("password", "verdict.jdbc.password") .put("principal", "verdict.jdbc.kerberos_principal") .build(); private final String DEFAULT_CONFIG_FILE = "verdict_default.properties"; private final String USER_CONFIG_FILE = "verdict.properties"; public static void setSamplesToUse(Map<TableUniqueName, SampleParam> samples) { samplesToUse = samples; } public static Map<TableUniqueName, SampleParam> getSamplesToUse() { return samplesToUse; } public VerdictConf() { this(true); } public VerdictConf(boolean resetProperties) { if (resetProperties) { setDefaults(); setUserConfig(); } } public VerdictConf(String propertyFileName) { this(true); updateFromPropertyFile(propertyFileName); } public VerdictConf(Properties properties) { this(true); setProperties(properties); } private void setDefaults() { updateFromPropertyFile(DEFAULT_CONFIG_FILE); } private void setUserConfig() { updateFromPropertyFile(USER_CONFIG_FILE); } public void setProperties(Properties properties) { for (String prop : properties.stringPropertyNames()) { String value = properties.getProperty(prop); set(prop, value); } } private void updateFromPropertyFile(String propertyFileName) { try { InputStream is = this.getClass().getClassLoader().getResourceAsStream(propertyFileName); if (is == null) { return; } Properties p = new Properties(); p.load(is); is.close(); setProperties(p); } catch (IOException e) { e.printStackTrace(); } } public Map<String, String> getConfigs() { return configs; } public int getInt(String key) { return Integer.parseInt(get(key)); } public boolean getBoolean(String key) { String val = get(key); if (val == null) return false; val = val.toLowerCase(); return val.equals("on") || val.equals("yes") || val.equals("true") || val.equals("1"); } public double getDouble(String key) { return Double.parseDouble(get(key)); } public double getPercent(String key) { String val = get(key); if (val.endsWith("%")) return Double.parseDouble(val.substring(0, val.length() - 1)) / 100; return Double.parseDouble(val); } public String get(String key) { if (configKeySynonyms.containsKey(key)) { return get(configKeySynonyms.get(key)); } return configs.get(key); } public String getOr(String key, Object defaultValue) { if (configs.containsKey(key)) { return configs.get(key); } else { return defaultValue.toString(); } } public VerdictConf set(String keyVal) { int equalIndex = keyVal.indexOf('='); if (equalIndex == -1) return this; String key = keyVal.substring(0, equalIndex).trim(); String val = keyVal.substring(equalIndex + 1).trim(); return set(key, val); } public VerdictConf set(String key, String value) { if (value.startsWith("\"") && value.endsWith("\"")) value = value.substring(1, value.length() - 1); if (configKeySynonyms.containsKey(key)) { return set(configKeySynonyms.get(key), value); } if (key.equals("verdict.loglevel")) { VerdictLogger.setLogLevel(value); } configs.put(key, value); return this; } public Properties toProperties() { Properties p = new Properties(); for (String key : configs.keySet()) { p.setProperty(key, configs.get(key)); } return p; } public boolean doesContain(String key) { return configs.containsKey(key); } /* * Helpers */ // data DBMS public void setDbmsSchema(String schema) { configs.put("verdict.jdbc.schema", schema); } public String getDbmsSchema() { return get("verdict.jdbc.schema"); } public void setDbms(String name) { set("verdict.jdbc.dbname", name); } public String getDbms() { return get("verdict.jdbc.dbname"); } public String getDbmsClassName() { return get("verdict.jdbc." + getDbms() + ".class_name"); } public void setHost(String host) { set("verdict.jdbc.host", host); } public String getHost() { return get("verdict.jdbc.host"); } public void setUser(String user) { set("verdict.jdbc.user", user); } public String getUser() { return get("verdict.jdbc.user"); } public void setPassword(String password) { set("verdict.jdbc.password", password); } public String getPassword() { return get("verdict.jdbc.password"); } public boolean ignoreUserCredentials() { return getBoolean("verdict.jdbc.ignore_user_credentials"); } public void setPort(String port) { set("verdict.jdbc.port", port); } public void setLoglevel(String level) { set("loglevel", level); } public String getPort() { String explicitPortNumber = get("verdict.jdbc.port"); if (explicitPortNumber != null && explicitPortNumber.length() != 0) { return explicitPortNumber; } else { return getDefaultPort(); } } public String getDefaultPort() { return get("verdict.jdbc." + getDbms() + ".default_port"); } public double errorBoundConfidenceInPercentage() { return getPercent("verdict.error_bound.confidence_internal_probability"); } public double getRelativeTargetCost() { return getPercent("verdict.relative_target_cost"); } public boolean cacheSparkSamples() { return getBoolean("verdict.spark.cache_samples"); } public String errorBoundMethod() { return get("verdict.error_bound.method"); } public int subsamplingPartitionCount() { return getInt("verdict.error_bound.subsampling.partition_count"); } public String subsamplingPartitionColumn() { return get("verdict.error_bound.subsampling.partition_column"); } public String subsamplingProbabilityColumn() { return get("verdict.error_bound.subsampling.probability_column"); } public String metaNameTableName() { return get("verdict.meta_data.meta_name_table"); } public String metaSizeTableName() { return get("verdict.meta_data.meta_size_table"); } public String metaRefreshPolicy() { return get("verdict.meta_data.refresh_policy"); } public String metaDatabaseSuffix() { return get("verdict.meta_data.meta_database_suffix"); } public String bootstrappingRandomValueColumn() { return get("verdict.error_bound.bootstrapping.random_value_column_name"); } public String bootstrappingMultiplicityColumn() { return get("verdict.error_bound.bootstrapping.bootstrap_multiplicity_colname"); } public boolean bypass() { return getBoolean("verdict.bypass"); } public boolean isJdbcKerberosSet() { return (getJdbcKerberos().equals("n/a")) ? false : true; } public String getJdbcKerberos() { return get("verdict.jdbc.kerberos_principal"); } public boolean areSamplesStoredAsParquet() { if (getDbms().equals("redshift")) { return false; } else { return (getParquetSamples().equals("true")) ? true : false; } } public boolean areHiveSampleStoredAsOrc() { if (getDbms().equalsIgnoreCase("hive") || getDbms().equalsIgnoreCase("hive2")) { return getHiveOrcSamples().equalsIgnoreCase("true"); } return false; } public String getHiveOrcSamples() { return get("verdict.hive.orc_sample"); } public String getParquetSamples() { return get("verdict.parquet_sample"); } /** * These are the probabilities for ensuring at least 10 tuples. */ protected static List<Pair<Integer, Double>> minSamplingProbForStratifiedSamplesMin10 = new ImmutableList.Builder<Pair<Integer, Double>>() .add(Pair.of(100, 0.203759)) .add(Pair.of(50, 0.376508)) .add(Pair.of(40, 0.452739)) .add(Pair.of(30, 0.566406)) .add(Pair.of(20, 0.749565)) .add(Pair.of(15, 0.881575)) .add(Pair.of(14, 0.910660)) .add(Pair.of(13, 0.939528)) .add(Pair.of(12, 0.966718)) .add(Pair.of(11, 0.989236)) .build(); /** * These are the probabilities for ensuring at least 100 tuples. */ protected static List<Pair<Integer, Double>> minSamplingProbForStratifiedSamplesMin100 = new ImmutableList.Builder<Pair<Integer, Double>>() .add(Pair.of(900, 0.140994)) .add(Pair.of(800, 0.158239)) .add(Pair.of(700, 0.180286)) .add(Pair.of(600, 0.209461)) .add(Pair.of(500, 0.249876)) .add(Pair.of(400, 0.309545)) .add(Pair.of(300, 0.406381)) .add(Pair.of(200, 0.589601)) .add(Pair.of(150, 0.756890)) .add(Pair.of(140, 0.801178)) .add(Pair.of(130, 0.849921)) .add(Pair.of(120, 0.902947)) .add(Pair.of(110, 0.958229)) .build(); public List<Pair<Integer, Double>> samplingProbabilitiesForStratifiedSamples() { return minSamplingProbForStratifiedSamplesMin10; } }
core/src/main/java/edu/umich/verdict/VerdictConf.java
/* * Copyright 2017 University of Michigan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.umich.verdict; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.TreeMap; import edu.umich.verdict.datatypes.SampleParam; import edu.umich.verdict.datatypes.TableUniqueName; import org.apache.commons.lang3.tuple.Pair; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import edu.umich.verdict.util.VerdictLogger; public class VerdictConf { private Map<String, String> configs = new TreeMap<String, String>(); private static Map<TableUniqueName, SampleParam> forcedSamples = null; private final Map<String, String> configKeySynonyms = new ImmutableMap.Builder<String, String>() .put("bypass", "verdict.bypass") .put("loglevel", "verdict.loglevel") .put("user", "verdict.jdbc.user") .put("password", "verdict.jdbc.password") .put("principal", "verdict.jdbc.kerberos_principal") .build(); private final String DEFAULT_CONFIG_FILE = "verdict_default.properties"; private final String USER_CONFIG_FILE = "verdict.properties"; private static void setForcedSamples(Map<TableUniqueName, SampleParam> samples) { forcedSamples = samples; } public static Map<TableUniqueName, SampleParam> getForcedSamples() { return forcedSamples; } public VerdictConf() { this(true); } public VerdictConf(boolean resetProperties) { if (resetProperties) { setDefaults(); setUserConfig(); } } public VerdictConf(String propertyFileName) { this(true); updateFromPropertyFile(propertyFileName); } public VerdictConf(Properties properties) { this(true); setProperties(properties); } private void setDefaults() { updateFromPropertyFile(DEFAULT_CONFIG_FILE); } private void setUserConfig() { updateFromPropertyFile(USER_CONFIG_FILE); } public void setProperties(Properties properties) { for (String prop : properties.stringPropertyNames()) { String value = properties.getProperty(prop); set(prop, value); } } private void updateFromPropertyFile(String propertyFileName) { try { InputStream is = this.getClass().getClassLoader().getResourceAsStream(propertyFileName); if (is == null) { return; } Properties p = new Properties(); p.load(is); is.close(); setProperties(p); } catch (IOException e) { e.printStackTrace(); } } public Map<String, String> getConfigs() { return configs; } public int getInt(String key) { return Integer.parseInt(get(key)); } public boolean getBoolean(String key) { String val = get(key); if (val == null) return false; val = val.toLowerCase(); return val.equals("on") || val.equals("yes") || val.equals("true") || val.equals("1"); } public double getDouble(String key) { return Double.parseDouble(get(key)); } public double getPercent(String key) { String val = get(key); if (val.endsWith("%")) return Double.parseDouble(val.substring(0, val.length() - 1)) / 100; return Double.parseDouble(val); } public String get(String key) { if (configKeySynonyms.containsKey(key)) { return get(configKeySynonyms.get(key)); } return configs.get(key); } public String getOr(String key, Object defaultValue) { if (configs.containsKey(key)) { return configs.get(key); } else { return defaultValue.toString(); } } public VerdictConf set(String keyVal) { int equalIndex = keyVal.indexOf('='); if (equalIndex == -1) return this; String key = keyVal.substring(0, equalIndex).trim(); String val = keyVal.substring(equalIndex + 1).trim(); return set(key, val); } public VerdictConf set(String key, String value) { if (value.startsWith("\"") && value.endsWith("\"")) value = value.substring(1, value.length() - 1); if (configKeySynonyms.containsKey(key)) { return set(configKeySynonyms.get(key), value); } if (key.equals("verdict.loglevel")) { VerdictLogger.setLogLevel(value); } configs.put(key, value); return this; } public Properties toProperties() { Properties p = new Properties(); for (String key : configs.keySet()) { p.setProperty(key, configs.get(key)); } return p; } public boolean doesContain(String key) { return configs.containsKey(key); } /* * Helpers */ // data DBMS public void setDbmsSchema(String schema) { configs.put("verdict.jdbc.schema", schema); } public String getDbmsSchema() { return get("verdict.jdbc.schema"); } public void setDbms(String name) { set("verdict.jdbc.dbname", name); } public String getDbms() { return get("verdict.jdbc.dbname"); } public String getDbmsClassName() { return get("verdict.jdbc." + getDbms() + ".class_name"); } public void setHost(String host) { set("verdict.jdbc.host", host); } public String getHost() { return get("verdict.jdbc.host"); } public void setUser(String user) { set("verdict.jdbc.user", user); } public String getUser() { return get("verdict.jdbc.user"); } public void setPassword(String password) { set("verdict.jdbc.password", password); } public String getPassword() { return get("verdict.jdbc.password"); } public boolean ignoreUserCredentials() { return getBoolean("verdict.jdbc.ignore_user_credentials"); } public void setPort(String port) { set("verdict.jdbc.port", port); } public void setLoglevel(String level) { set("loglevel", level); } public String getPort() { String explicitPortNumber = get("verdict.jdbc.port"); if (explicitPortNumber != null && explicitPortNumber.length() != 0) { return explicitPortNumber; } else { return getDefaultPort(); } } public String getDefaultPort() { return get("verdict.jdbc." + getDbms() + ".default_port"); } public double errorBoundConfidenceInPercentage() { return getPercent("verdict.error_bound.confidence_internal_probability"); } public double getRelativeTargetCost() { return getPercent("verdict.relative_target_cost"); } public boolean cacheSparkSamples() { return getBoolean("verdict.spark.cache_samples"); } public String errorBoundMethod() { return get("verdict.error_bound.method"); } public int subsamplingPartitionCount() { return getInt("verdict.error_bound.subsampling.partition_count"); } public String subsamplingPartitionColumn() { return get("verdict.error_bound.subsampling.partition_column"); } public String subsamplingProbabilityColumn() { return get("verdict.error_bound.subsampling.probability_column"); } public String metaNameTableName() { return get("verdict.meta_data.meta_name_table"); } public String metaSizeTableName() { return get("verdict.meta_data.meta_size_table"); } public String metaRefreshPolicy() { return get("verdict.meta_data.refresh_policy"); } public String metaDatabaseSuffix() { return get("verdict.meta_data.meta_database_suffix"); } public String bootstrappingRandomValueColumn() { return get("verdict.error_bound.bootstrapping.random_value_column_name"); } public String bootstrappingMultiplicityColumn() { return get("verdict.error_bound.bootstrapping.bootstrap_multiplicity_colname"); } public boolean bypass() { return getBoolean("verdict.bypass"); } public boolean isJdbcKerberosSet() { return (getJdbcKerberos().equals("n/a")) ? false : true; } public String getJdbcKerberos() { return get("verdict.jdbc.kerberos_principal"); } public boolean areSamplesStoredAsParquet() { if (getDbms().equals("redshift")) { return false; } else { return (getParquetSamples().equals("true")) ? true : false; } } public boolean areHiveSampleStoredAsOrc() { if (getDbms().equalsIgnoreCase("hive") || getDbms().equalsIgnoreCase("hive2")) { return getHiveOrcSamples().equalsIgnoreCase("true"); } return false; } public String getHiveOrcSamples() { return get("verdict.hive.orc_sample"); } public String getParquetSamples() { return get("verdict.parquet_sample"); } /** * These are the probabilities for ensuring at least 10 tuples. */ protected static List<Pair<Integer, Double>> minSamplingProbForStratifiedSamplesMin10 = new ImmutableList.Builder<Pair<Integer, Double>>() .add(Pair.of(100, 0.203759)) .add(Pair.of(50, 0.376508)) .add(Pair.of(40, 0.452739)) .add(Pair.of(30, 0.566406)) .add(Pair.of(20, 0.749565)) .add(Pair.of(15, 0.881575)) .add(Pair.of(14, 0.910660)) .add(Pair.of(13, 0.939528)) .add(Pair.of(12, 0.966718)) .add(Pair.of(11, 0.989236)) .build(); /** * These are the probabilities for ensuring at least 100 tuples. */ protected static List<Pair<Integer, Double>> minSamplingProbForStratifiedSamplesMin100 = new ImmutableList.Builder<Pair<Integer, Double>>() .add(Pair.of(900, 0.140994)) .add(Pair.of(800, 0.158239)) .add(Pair.of(700, 0.180286)) .add(Pair.of(600, 0.209461)) .add(Pair.of(500, 0.249876)) .add(Pair.of(400, 0.309545)) .add(Pair.of(300, 0.406381)) .add(Pair.of(200, 0.589601)) .add(Pair.of(150, 0.756890)) .add(Pair.of(140, 0.801178)) .add(Pair.of(130, 0.849921)) .add(Pair.of(120, 0.902947)) .add(Pair.of(110, 0.958229)) .build(); public List<Pair<Integer, Double>> samplingProbabilitiesForStratifiedSamples() { return minSamplingProbForStratifiedSamplesMin10; } }
adding support for users to select samples to sue
core/src/main/java/edu/umich/verdict/VerdictConf.java
adding support for users to select samples to sue
Java
apache-2.0
099856cc92b67de25e6a8be8bc87e4536618e7a8
0
FireElementalNE/wtg-research,FireElementalNE/wtg-research,FireElementalNE/wtg-research
import soot.*; import soot.jimple.Jimple; import soot.options.Options; import soot.util.Chain; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MainClass { public static void main(String[] args) { // TODO: see list // I need to find all cases of an intent, and link them back the their _Activity_ not just the declaring class // I also have to look for the actual call to intent.startActivityForResult //prefer Android APK files// -src-prec apk Options.v().set_src_prec(Options.src_prec_apk); //output as APK, too//-f J Options.v().set_output_format(Options.output_format_jimple); // resolve the PrintStream and System soot-classes Scene.v().addBasicClass("java.io.PrintStream",SootClass.SIGNATURES); Scene.v().addBasicClass("java.lang.System",SootClass.SIGNATURES); // To remove messy shell scripting file! Options.v().set_force_android_jar("."); Options.v().set_src_prec(Options.src_prec_apk); Options.v().set_allow_phantom_refs(true); Options.v().set_ignore_resolution_errors(true); Options.v().set_whole_program(true); Options.v().set_verbose(Constants.CG_VERBOSE); // Exclude packages String[] excludes = new String[] { "android.annotation", "android.hardware", "android.support", "android.media", "com.android", "android.bluetooth", "android.media", "com.google", "com.yume.android", "com.squareup.okhttp", "com.crashlytics", // "com.nbpcorp.mobilead", // ad // "com.inmobi.androidsdk", //ad // "com.millennialmedia", //ad // "com.admob", //ad // "com.admarvel.android.ads", // ad // "com.mopub.mobileads", //ad // "com.medialets", // ad "com.slidingmenu", "com.amazon.inapp.purchasing", "com.loopj", "com.appbrain", "com.heyzap.sdk", "net.daum.adam.publisher", "twitter4j.", "org.java_websocket", "org.acra", "org.apache" }; List<String> exclude = new ArrayList<String>(Arrays.asList(excludes)); Options.v().set_exclude(exclude); String apk_file = ""; for(int i = 0; i < args.length; i++) { if(args[i].contains("-process-dir")) { apk_file = args[i+1]; } } Options.v().set_whole_program(true); AndroidXMLUtility androidXMLUtility = new AndroidXMLUtility(apk_file); List<String> xml_files = androidXMLUtility.get_xml_names(); for(String s : xml_files) { androidXMLUtility.parse_xml_file(s); } androidXMLUtility.write_elements(); InferenceTransformer infTrans = new InferenceTransformer(); /** * TODO * Maybe use wjtp for whole program analysis so we can get that pesky sootOutput/com.credgenfixed.R$id.jimple * this will allows us to map declared UI elements in the XML to ones found in the program (there is a * unique string) */ PackManager.v().getPack("jtp").add(new Transform("jtp.myInstrumenter1", infTrans)); soot.Main.main(args); // TODO: this is how you can all classes. this will help u get com.credgenfixed.R$id // Chain<SootClass> sootClassChain = Scene.v().getClasses(); infTrans.printAll(); infTrans.print_ui_elements(); } private static Local addTmpRef(Body body) { Local tmpRef = Jimple.v().newLocal("tmpRef", RefType.v("java.io.PrintStream")); body.getLocals().add(tmpRef); return tmpRef; } private static Local addTmpString(Body body) { Local tmpString = Jimple.v().newLocal("tmpString", RefType.v("java.lang.String")); body.getLocals().add(tmpString); return tmpString; } }
src/MainClass.java
import soot.*; import soot.jimple.Jimple; import soot.options.Options; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MainClass { public static void main(String[] args) { // TODO: see list // I need to find all cases of an intent, and link them back the their _Activity_ not just the declaring class // I also have to look for the actual call to intent.startActivityForResult //prefer Android APK files// -src-prec apk Options.v().set_src_prec(Options.src_prec_apk); //output as APK, too//-f J Options.v().set_output_format(Options.output_format_jimple); // resolve the PrintStream and System soot-classes Scene.v().addBasicClass("java.io.PrintStream",SootClass.SIGNATURES); Scene.v().addBasicClass("java.lang.System",SootClass.SIGNATURES); // To remove messy shell scripting file! Options.v().set_force_android_jar("."); Options.v().set_src_prec(Options.src_prec_apk); Options.v().set_allow_phantom_refs(true); Options.v().set_ignore_resolution_errors(true); Options.v().set_whole_program(true); Options.v().set_verbose(Constants.CG_VERBOSE); // Exclude packages String[] excludes = new String[] { "android.annotation", "android.hardware", "android.support", "android.media", "com.android", "android.bluetooth", "android.media", "com.google", "com.yume.android", "com.squareup.okhttp", "com.crashlytics", // "com.nbpcorp.mobilead", // ad // "com.inmobi.androidsdk", //ad // "com.millennialmedia", //ad // "com.admob", //ad // "com.admarvel.android.ads", // ad // "com.mopub.mobileads", //ad // "com.medialets", // ad "com.slidingmenu", "com.amazon.inapp.purchasing", "com.loopj", "com.appbrain", "com.heyzap.sdk", "net.daum.adam.publisher", "twitter4j.", "org.java_websocket", "org.acra", "org.apache" }; List<String> exclude = new ArrayList<String>(Arrays.asList(excludes)); Options.v().set_exclude(exclude); String apk_file = ""; for(int i = 0; i < args.length; i++) { if(args[i].contains("-process-dir")) { apk_file = args[i+1]; } } Options.v().set_whole_program(true); AndroidXMLUtility androidXMLUtility = new AndroidXMLUtility(apk_file); List<String> xml_files = androidXMLUtility.get_xml_names(); for(String s : xml_files) { androidXMLUtility.parse_xml_file(s); } androidXMLUtility.write_elements(); InferenceTransformer infTrans = new InferenceTransformer(); /** * TODO * Maybe use wjtp for whole program analysis so we can get that pesky sootOutput/com.credgenfixed.R$id.jimple * this will allows us to map declared UI elements in the XML to ones found in the program (there is a * unique string) */ PackManager.v().getPack("jtp").add(new Transform("jtp.myInstrumenter1", infTrans)); soot.Main.main(args); infTrans.printAll(); infTrans.print_ui_elements(); } private static Local addTmpRef(Body body) { Local tmpRef = Jimple.v().newLocal("tmpRef", RefType.v("java.io.PrintStream")); body.getLocals().add(tmpRef); return tmpRef; } private static Local addTmpString(Body body) { Local tmpString = Jimple.v().newLocal("tmpString", RefType.v("java.lang.String")); body.getLocals().add(tmpString); return tmpString; } }
added new todo
src/MainClass.java
added new todo
Java
apache-2.0
347a50f42839c164aa8c78c615ccbd280cf6f7fd
0
Rimbit/rimbitj
/** * Copyright 2013 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.bitcoin.core; import com.google.bitcoin.core.TransactionConfidence.ConfidenceType; import com.google.bitcoin.crypto.KeyCrypter; import com.google.bitcoin.crypto.KeyCrypterException; import com.google.bitcoin.crypto.KeyCrypterScrypt; import com.google.bitcoin.script.Script; import com.google.bitcoin.script.ScriptBuilder; import com.google.bitcoin.script.ScriptChunk; import com.google.bitcoin.store.UnreadableWalletException; import com.google.bitcoin.store.WalletProtobufSerializer; import com.google.bitcoin.utils.ListenerRegistration; import com.google.bitcoin.utils.Threading; import com.google.bitcoin.wallet.*; import com.google.bitcoin.wallet.WalletTransaction.Pool; import com.google.common.collect.*; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import org.bitcoinj.wallet.Protos.Wallet.EncryptionType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.crypto.params.KeyParameter; import org.spongycastle.util.encoders.Hex; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import static com.google.bitcoin.core.Utils.bitcoinValueToFriendlyString; import static com.google.bitcoin.core.Utils.bitcoinValueToPlainString; import static com.google.common.base.Preconditions.*; // To do list: // // This whole class has evolved over a period of years and needs a ground-up rewrite. // // - Take all wallet-relevant data out of Transaction and put it into WalletTransaction. Make Transaction immutable. // - Only store relevant transaction outputs, don't bother storing the rest of the data. // - Split block chain and tx output tracking into a superclass that doesn't have any key or spending related code. // - Simplify how transactions are tracked and stored: in particular, have the wallet maintain positioning information // for transactions independent of the transactions themselves, so the timeline can be walked without having to // process and sort every single transaction. // - Decompose the class where possible: break logic out into classes that can be customized/replaced by the user. // - [Auto]saving to a backing store // - Key management // - just generally make Wallet smaller and easier to work with // - Make clearing of transactions able to only rewind the wallet a certain distance instead of all blocks. // - Make it scale: // - eliminate all the algorithms with quadratic complexity (or worse) // - don't require everything to be held in RAM at once // - consider allowing eviction of no longer re-orgable transactions or keys that were used up /** * <p>A Wallet stores keys and a record of transactions that send and receive value from those keys. Using these, * it is able to create new transactions that spend the recorded transactions, and this is the fundamental operation * of the Bitcoin protocol.</p> * * <p>To learn more about this class, read <b><a href="http://code.google.com/p/bitcoinj/wiki/WorkingWithTheWallet"> * working with the wallet.</a></b></p> * * <p>To fill up a Wallet with transactions, you need to use it in combination with a {@link BlockChain} and various * other objects, see the <a href="http://code.google.com/p/bitcoinj/wiki/GettingStarted">Getting started</a> tutorial * on the website to learn more about how to set everything up.</p> * * <p>Wallets can be serialized using either Java serialization - this is not compatible across versions of bitcoinj, * or protocol buffer serialization. You need to save the wallet whenever it changes, there is an auto-save feature * that simplifies this for you although you're still responsible for manually triggering a save when your app is about * to quit because the auto-save feature waits a moment before actually committing to disk to avoid IO thrashing when * the wallet is changing very fast (eg due to a block chain sync). See * {@link Wallet#autosaveToFile(java.io.File, long, java.util.concurrent.TimeUnit, com.google.bitcoin.wallet.WalletFiles.Listener)} * for more information about this.</p> */ public class Wallet implements Serializable, BlockChainListener, PeerFilterProvider { private static final Logger log = LoggerFactory.getLogger(Wallet.class); private static final long serialVersionUID = 2L; private static final int MINIMUM_BLOOM_DATA_LENGTH = 8; protected final ReentrantLock lock = Threading.lock("wallet"); // The various pools below give quick access to wallet-relevant transactions by the state they're in: // // Pending: Transactions that didn't make it into the best chain yet. Pending transactions can be killed if a // double-spend against them appears in the best chain, in which case they move to the dead pool. // If a double-spend appears in the pending state as well, currently we just ignore the second // and wait for the miners to resolve the race. // Unspent: Transactions that appeared in the best chain and have outputs we can spend. Note that we store the // entire transaction in memory even though for spending purposes we only really need the outputs, the // reason being that this simplifies handling of re-orgs. It would be worth fixing this in future. // Spent: Transactions that appeared in the best chain but don't have any spendable outputs. They're stored here // for history browsing/auditing reasons only and in future will probably be flushed out to some other // kind of cold storage or just removed. // Dead: Transactions that we believe will never confirm get moved here, out of pending. Note that the Satoshi // client has no notion of dead-ness: the assumption is that double spends won't happen so there's no // need to notify the user about them. We take a more pessimistic approach and try to track the fact that // transactions have been double spent so applications can do something intelligent (cancel orders, show // to the user in the UI, etc). A transaction can leave dead and move into spent/unspent if there is a // re-org to a chain that doesn't include the double spend. final Map<Sha256Hash, Transaction> pending; final Map<Sha256Hash, Transaction> unspent; final Map<Sha256Hash, Transaction> spent; final Map<Sha256Hash, Transaction> dead; // All transactions together. final Map<Sha256Hash, Transaction> transactions; // A list of public/private EC keys owned by this user. Access it using addKey[s], hasKey[s] and findPubKeyFromHash. private ArrayList<ECKey> keychain; // A list of scripts watched by this wallet. private Set<Script> watchedScripts; private final NetworkParameters params; @Nullable private Sha256Hash lastBlockSeenHash; private int lastBlockSeenHeight; private long lastBlockSeenTimeSecs; private transient CopyOnWriteArrayList<ListenerRegistration<WalletEventListener>> eventListeners; // A listener that relays confidence changes from the transaction confidence object to the wallet event listener, // as a convenience to API users so they don't have to register on every transaction themselves. private transient TransactionConfidence.Listener txConfidenceListener; // If a TX hash appears in this set then notifyNewBestBlock will ignore it, as its confidence was already set up // in receive() via Transaction.setBlockAppearance(). As the BlockChain always calls notifyNewBestBlock even if // it sent transactions to the wallet, without this we'd double count. private transient HashSet<Sha256Hash> ignoreNextNewBlock; // Whether or not to ignore nLockTime > 0 transactions that are received to the mempool. private boolean acceptRiskyTransactions; // Stuff for notifying transaction objects that we changed their confidences. The purpose of this is to avoid // spuriously sending lots of repeated notifications to listeners that API users aren't really interested in as a // side effect of how the code is written (e.g. during re-orgs confidence data gets adjusted multiple times). private int onWalletChangedSuppressions; private boolean insideReorg; private Map<Transaction, TransactionConfidence.Listener.ChangeReason> confidenceChanged; private volatile WalletFiles vFileManager; // Object that is used to send transactions asynchronously when the wallet requires it. private volatile TransactionBroadcaster vTransactionBroadcaster; // UNIX time in seconds. Money controlled by keys created before this time will be automatically respent to a key // that was created after it. Useful when you believe some keys have been compromised. private volatile long vKeyRotationTimestamp; private volatile boolean vKeyRotationEnabled; private transient CoinSelector coinSelector = new DefaultCoinSelector(); // The keyCrypter for the wallet. This specifies the algorithm used for encrypting and decrypting the private keys. private KeyCrypter keyCrypter; // The wallet version. This is an int that can be used to track breaking changes in the wallet format. // You can also use it to detect wallets that come from the future (ie they contain features you // do not know how to deal with). private int version; // User-provided description that may help people keep track of what a wallet is for. private String description; // Stores objects that know how to serialize/unserialize themselves to byte streams and whether they're mandatory // or not. The string key comes from the extension itself. private final HashMap<String, WalletExtension> extensions; // Object that performs risk analysis of received pending transactions. We might reject transactions that seem like // a high risk of being a double spending attack. private RiskAnalysis.Analyzer riskAnalyzer = DefaultRiskAnalysis.FACTORY; /** * Creates a new, empty wallet with no keys and no transactions. If you want to restore a wallet from disk instead, * see loadFromFile. */ public Wallet(NetworkParameters params) { this.params = checkNotNull(params); keychain = new ArrayList<ECKey>(); watchedScripts = Sets.newHashSet(); unspent = new HashMap<Sha256Hash, Transaction>(); spent = new HashMap<Sha256Hash, Transaction>(); pending = new HashMap<Sha256Hash, Transaction>(); dead = new HashMap<Sha256Hash, Transaction>(); transactions = new HashMap<Sha256Hash, Transaction>(); eventListeners = new CopyOnWriteArrayList<ListenerRegistration<WalletEventListener>>(); extensions = new HashMap<String, WalletExtension>(); confidenceChanged = new HashMap<Transaction, TransactionConfidence.Listener.ChangeReason>(); createTransientState(); } /** * Create a wallet with a keyCrypter to use in encrypting and decrypting keys. */ public Wallet(NetworkParameters params, KeyCrypter keyCrypter) { this(params); this.keyCrypter = checkNotNull(keyCrypter); } private void createTransientState() { ignoreNextNewBlock = new HashSet<Sha256Hash>(); txConfidenceListener = new TransactionConfidence.Listener() { @Override public void onConfidenceChanged(Transaction tx, TransactionConfidence.Listener.ChangeReason reason) { // This will run on the user code thread so we shouldn't do anything too complicated here. // We only want to queue a wallet changed event and auto-save if the number of peers announcing // the transaction has changed, as that confidence change is made by the networking code which // doesn't necessarily know at that point which wallets contain which transactions, so it's up // to us to listen for that. Other types of confidence changes (type, etc) are triggered by us, // so we'll queue up a wallet change event in other parts of the code. if (reason == ChangeReason.SEEN_PEERS) { lock.lock(); try { checkBalanceFuturesLocked(null); queueOnTransactionConfidenceChanged(tx); maybeQueueOnWalletChanged(); } finally { lock.unlock(); } } } }; acceptRiskyTransactions = false; } public NetworkParameters getNetworkParameters() { return params; } /** * Returns a snapshot of the keychain. This view is not live. */ public List<ECKey> getKeys() { lock.lock(); try { return new ArrayList<ECKey>(keychain); } finally { lock.unlock(); } } /** * Returns a snapshot of the watched scripts. This view is not live. */ public List<Script> getWatchedScripts() { lock.lock(); try { return new ArrayList<Script>(watchedScripts); } finally { lock.unlock(); } } /** * Removes the given key from the keychain. Be very careful with this - losing a private key <b>destroys the * money associated with it</b>. * @return Whether the key was removed or not. */ public boolean removeKey(ECKey key) { lock.lock(); try { return keychain.remove(key); } finally { lock.unlock(); } } /** * Returns the number of keys in the keychain. */ public int getKeychainSize() { lock.lock(); try { return keychain.size(); } finally { lock.unlock(); } } /** Saves the wallet first to the given temp file, then renames to the dest file. */ public void saveToFile(File temp, File destFile) throws IOException { FileOutputStream stream = null; lock.lock(); try { stream = new FileOutputStream(temp); saveToFileStream(stream); // Attempt to force the bits to hit the disk. In reality the OS or hard disk itself may still decide // to not write through to physical media for at least a few seconds, but this is the best we can do. stream.flush(); stream.getFD().sync(); stream.close(); stream = null; if (Utils.isWindows()) { // Work around an issue on Windows whereby you can't rename over existing files. File canonical = destFile.getCanonicalFile(); if (!canonical.delete()) throw new IOException("Failed to delete canonical wallet file for replacement with autosave"); if (temp.renameTo(canonical)) return; // else fall through. throw new IOException("Failed to rename " + temp + " to " + canonical); } else if (!temp.renameTo(destFile)) { throw new IOException("Failed to rename " + temp + " to " + destFile); } } catch (RuntimeException e) { log.error("Failed whilst saving wallet", e); throw e; } finally { lock.unlock(); if (stream != null) { stream.close(); } if (temp.exists()) { log.warn("Temp file still exists after failed save."); } } } /** * Uses protobuf serialization to save the wallet to the given file. To learn more about this file format, see * {@link WalletProtobufSerializer}. Writes out first to a temporary file in the same directory and then renames * once written. */ public void saveToFile(File f) throws IOException { File directory = f.getAbsoluteFile().getParentFile(); File temp = File.createTempFile("wallet", null, directory); saveToFile(temp, f); } /** * <p>Whether or not the wallet will ignore received pending transactions that fail the selected * {@link RiskAnalysis}. By default, if a transaction is considered risky then it won't enter the wallet * and won't trigger any event listeners. If you set this property to true, then all transactions will * be allowed in regardless of risk. Currently, the {@link DefaultRiskAnalysis} checks for non-finality of * transactions. You should not encounter these outside of special protocols.</p> * * <p>Note that this property is not serialized. You have to set it each time a Wallet object is constructed, * even if it's loaded from a protocol buffer.</p> */ public void setAcceptRiskyTransactions(boolean acceptRiskyTransactions) { lock.lock(); try { this.acceptRiskyTransactions = acceptRiskyTransactions; } finally { lock.unlock(); } } /** * See {@link Wallet#setAcceptRiskyTransactions(boolean)} for an explanation of this property. */ public boolean doesAcceptRiskyTransactions() { lock.lock(); try { return acceptRiskyTransactions; } finally { lock.unlock(); } } /** * Sets the {@link RiskAnalysis} implementation to use for deciding whether received pending transactions are risky * or not. If the analyzer says a transaction is risky, by default it will be dropped. You can customize this * behaviour with {@link #setAcceptRiskyTransactions(boolean)}. */ public void setRiskAnalyzer(RiskAnalysis.Analyzer analyzer) { lock.lock(); try { this.riskAnalyzer = checkNotNull(analyzer); } finally { lock.unlock(); } } /** * Gets the current {@link RiskAnalysis} implementation. The default is {@link DefaultRiskAnalysis}. */ public RiskAnalysis.Analyzer getRiskAnalyzer() { lock.lock(); try { return riskAnalyzer; } finally { lock.unlock(); } } /** * <p>Sets up the wallet to auto-save itself to the given file, using temp files with atomic renames to ensure * consistency. After connecting to a file, you no longer need to save the wallet manually, it will do it * whenever necessary. Protocol buffer serialization will be used.</p> * * <p>If delayTime is set, a background thread will be created and the wallet will only be saved to * disk every so many time units. If no changes have occurred for the given time period, nothing will be written. * In this way disk IO can be rate limited. It's a good idea to set this as otherwise the wallet can change very * frequently, eg if there are a lot of transactions in it or during block sync, and there will be a lot of redundant * writes. Note that when a new key is added, that always results in an immediate save regardless of * delayTime. <b>You should still save the wallet manually when your program is about to shut down as the JVM * will not wait for the background thread.</b></p> * * <p>An event listener can be provided. If a delay >0 was specified, it will be called on a background thread * with the wallet locked when an auto-save occurs. If delay is zero or you do something that always triggers * an immediate save, like adding a key, the event listener will be invoked on the calling threads.</p> * * @param f The destination file to save to. * @param delayTime How many time units to wait until saving the wallet on a background thread. * @param timeUnit the unit of measurement for delayTime. * @param eventListener callback to be informed when the auto-save thread does things, or null */ public WalletFiles autosaveToFile(File f, long delayTime, TimeUnit timeUnit, @Nullable WalletFiles.Listener eventListener) { lock.lock(); try { checkState(vFileManager == null, "Already auto saving this wallet."); WalletFiles manager = new WalletFiles(this, f, delayTime, timeUnit); if (eventListener != null) manager.setListener(eventListener); vFileManager = manager; return manager; } finally { lock.unlock(); } } /** * <p> * Disables auto-saving, after it had been enabled with * {@link Wallet#autosaveToFile(java.io.File, long, java.util.concurrent.TimeUnit, com.google.bitcoin.wallet.WalletFiles.Listener)} * before. This method blocks until finished. * </p> */ public void shutdownAutosaveAndWait() { lock.lock(); try { WalletFiles files = vFileManager; vFileManager = null; checkState(files != null, "Auto saving not enabled."); files.shutdownAndWait(); } finally { lock.unlock(); } } private void saveLater() { WalletFiles files = vFileManager; if (files != null) files.saveLater(); } /** If auto saving is enabled, do an immediate sync write to disk ignoring any delays. */ private void saveNow() { WalletFiles files = vFileManager; if (files != null) { try { files.saveNow(); // This calls back into saveToFile(). } catch (IOException e) { // Can't really do much at this point, just let the API user know. log.error("Failed to save wallet to disk!", e); Thread.UncaughtExceptionHandler handler = Threading.uncaughtExceptionHandler; if (handler != null) handler.uncaughtException(Thread.currentThread(), e); } } } /** * Uses protobuf serialization to save the wallet to the given file stream. To learn more about this file format, see * {@link WalletProtobufSerializer}. */ public void saveToFileStream(OutputStream f) throws IOException { lock.lock(); try { new WalletProtobufSerializer().writeWallet(this, f); } finally { lock.unlock(); } } /** Returns the parameters this wallet was created with. */ public NetworkParameters getParams() { return params; } /** * Returns a wallet deserialized from the given file. */ public static Wallet loadFromFile(File f) throws UnreadableWalletException { try { FileInputStream stream = null; try { stream = new FileInputStream(f); return loadFromFileStream(stream); } finally { if (stream != null) stream.close(); } } catch (IOException e) { throw new UnreadableWalletException("Could not open file", e); } } public boolean isConsistent() { lock.lock(); try { boolean success = true; Set<Transaction> transactions = getTransactions(true); Set<Sha256Hash> hashes = new HashSet<Sha256Hash>(); for (Transaction tx : transactions) { hashes.add(tx.getHash()); } int size1 = transactions.size(); if (size1 != hashes.size()) { log.error("Two transactions with same hash"); success = false; } int size2 = unspent.size() + spent.size() + pending.size() + dead.size(); if (size1 != size2) { log.error("Inconsistent wallet sizes: {} {}", size1, size2); success = false; } for (Transaction tx : unspent.values()) { if (!tx.isConsistent(this, false)) { success = false; log.error("Inconsistent unspent tx {}", tx.getHashAsString()); } } for (Transaction tx : spent.values()) { if (!tx.isConsistent(this, true)) { success = false; log.error("Inconsistent spent tx {}", tx.getHashAsString()); } } if (!success) { try { log.error(toString()); } catch (RuntimeException x) { log.error("Printing inconsistent wallet failed", x); } } return success; } finally { lock.unlock(); } } /** * Returns a wallet deserialized from the given input stream. */ public static Wallet loadFromFileStream(InputStream stream) throws UnreadableWalletException { Wallet wallet = new WalletProtobufSerializer().readWallet(stream); if (!wallet.isConsistent()) { log.error("Loaded an inconsistent wallet"); } return wallet; } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); createTransientState(); } /** * Called by the {@link BlockChain} when we receive a new filtered block that contains a transactions previously * received by a call to @{link receivePending}.<p> * * This is necessary for the internal book-keeping Wallet does. When a transaction is received that sends us * coins it is added to a pool so we can use it later to create spends. When a transaction is received that * consumes outputs they are marked as spent so they won't be used in future.<p> * * A transaction that spends our own coins can be received either because a spend we created was accepted by the * network and thus made it into a block, or because our keys are being shared between multiple instances and * some other node spent the coins instead. We still have to know about that to avoid accidentally trying to * double spend.<p> * * A transaction may be received multiple times if is included into blocks in parallel chains. The blockType * parameter describes whether the containing block is on the main/best chain or whether it's on a presently * inactive side chain. We must still record these transactions and the blocks they appear in because a future * block might change which chain is best causing a reorganize. A re-org can totally change our balance! */ public void notifyTransactionIsInBlock(Sha256Hash txHash, StoredBlock block, BlockChain.NewBlockType blockType, int relativityOffset) throws VerificationException { lock.lock(); try { Transaction tx = transactions.get(txHash); if (tx == null) { log.error("TX {} not found despite being sent to wallet", txHash); return; } receive(tx, block, blockType, relativityOffset); } finally { lock.unlock(); } if (blockType == AbstractBlockChain.NewBlockType.BEST_CHAIN) { // If some keys are considered to be bad, possibly move money assigned to them now. // This has to run outside the wallet lock as it may trigger broadcasting of new transactions. maybeRotateKeys(); } } /** * <p>Called when we have found a transaction (via network broadcast or otherwise) that is relevant to this wallet * and want to record it. Note that we <b>cannot verify these transactions at all</b>, they may spend fictional * coins or be otherwise invalid. They are useful to inform the user about coins they can expect to receive soon, * and if you trust the sender of the transaction you can choose to assume they are in fact valid and will not * be double spent as an optimization.</p> * * <p>This is the same as {@link Wallet#receivePending(Transaction, java.util.List)} but allows you to override the * {@link Wallet#isPendingTransactionRelevant(Transaction)} sanity-check to keep track of transactions that are not * spendable or spend our coins. This can be useful when you want to keep track of transaction confidence on * arbitrary transactions. Note that transactions added in this way will still be relayed to peers and appear in * transaction lists like any other pending transaction (even when not relevant).</p> */ public void receivePending(Transaction tx, @Nullable List<Transaction> dependencies, boolean overrideIsRelevant) throws VerificationException { // Can run in a peer thread. This method will only be called if a prior call to isPendingTransactionRelevant // returned true, so we already know by this point that it sends coins to or from our wallet, or is a double // spend against one of our other pending transactions. lock.lock(); try { tx.verify(); // Ignore it if we already know about this transaction. Receiving a pending transaction never moves it // between pools. EnumSet<Pool> containingPools = getContainingPools(tx); if (!containingPools.equals(EnumSet.noneOf(Pool.class))) { log.debug("Received tx we already saw in a block or created ourselves: " + tx.getHashAsString()); return; } // Repeat the check of relevancy here, even though the caller may have already done so - this is to avoid // race conditions where receivePending may be being called in parallel. if (!overrideIsRelevant && !isPendingTransactionRelevant(tx)) return; if (isTransactionRisky(tx, dependencies) && !acceptRiskyTransactions) return; BigInteger valueSentToMe = tx.getValueSentToMe(this); BigInteger valueSentFromMe = tx.getValueSentFromMe(this); if (log.isInfoEnabled()) { log.info(String.format("Received a pending transaction %s that spends %s BTC from our own wallet," + " and sends us %s BTC", tx.getHashAsString(), Utils.bitcoinValueToFriendlyString(valueSentFromMe), Utils.bitcoinValueToFriendlyString(valueSentToMe))); } if (tx.getConfidence().getSource().equals(TransactionConfidence.Source.UNKNOWN)) { log.warn("Wallet received transaction with an unknown source. Consider tagging it!"); } // If this tx spends any of our unspent outputs, mark them as spent now, then add to the pending pool. This // ensures that if some other client that has our keys broadcasts a spend we stay in sync. Also updates the // timestamp on the transaction and registers/runs event listeners. commitTx(tx); } finally { lock.unlock(); } // maybeRotateKeys() will ignore pending transactions so we don't bother calling it here (see the comments // in that function for an explanation of why). } /** * Given a transaction and an optional list of dependencies (recursive/flattened), returns true if the given * transaction would be rejected by the analyzer, or false otherwise. The result of this call is independent * of the value of {@link #doesAcceptRiskyTransactions()}. Risky transactions yield a logged warning. If you * want to know the reason why a transaction is risky, create an instance of the {@link RiskAnalysis} yourself * using the factory returned by {@link #getRiskAnalyzer()} and use it directly. */ public boolean isTransactionRisky(Transaction tx, @Nullable List<Transaction> dependencies) { lock.lock(); try { if (dependencies == null) dependencies = ImmutableList.of(); RiskAnalysis analysis = riskAnalyzer.create(this, tx, dependencies); RiskAnalysis.Result result = analysis.analyze(); if (result != RiskAnalysis.Result.OK) { log.warn("Pending transaction {} was considered risky: {}", tx.getHashAsString(), analysis); return true; } return false; } finally { lock.unlock(); } } /** * <p>Called when we have found a transaction (via network broadcast or otherwise) that is relevant to this wallet * and want to record it. Note that we <b>cannot verify these transactions at all</b>, they may spend fictional * coins or be otherwise invalid. They are useful to inform the user about coins they can expect to receive soon, * and if you trust the sender of the transaction you can choose to assume they are in fact valid and will not * be double spent as an optimization.</p> * * <p>Before this method is called, {@link Wallet#isPendingTransactionRelevant(Transaction)} should have been * called to decide whether the wallet cares about the transaction - if it does, then this method expects the * transaction and any dependencies it has which are still in the memory pool.</p> */ public void receivePending(Transaction tx, @Nullable List<Transaction> dependencies) throws VerificationException { receivePending(tx, dependencies, false); } /** * This method is used by a {@link Peer} to find out if a transaction that has been announced is interesting, * that is, whether we should bother downloading its dependencies and exploring the transaction to decide how * risky it is. If this method returns true then {@link Wallet#receivePending(Transaction, java.util.List)} * will soon be called with the transactions dependencies as well. */ public boolean isPendingTransactionRelevant(Transaction tx) throws ScriptException { lock.lock(); try { // Ignore it if we already know about this transaction. Receiving a pending transaction never moves it // between pools. EnumSet<Pool> containingPools = getContainingPools(tx); if (!containingPools.equals(EnumSet.noneOf(Pool.class))) { log.debug("Received tx we already saw in a block or created ourselves: " + tx.getHashAsString()); return false; } // We only care about transactions that: // - Send us coins // - Spend our coins if (!isTransactionRelevant(tx)) { log.debug("Received tx that isn't relevant to this wallet, discarding."); return false; } if (isTransactionRisky(tx, null) && !acceptRiskyTransactions) { log.warn("Received transaction {} with a lock time of {}, but not configured to accept these, discarding", tx.getHashAsString(), tx.getLockTime()); return false; } return true; } finally { lock.unlock(); } } /** * <p>Returns true if the given transaction sends coins to any of our keys, or has inputs spending any of our outputs, * and if includeDoubleSpending is true, also returns true if tx has inputs that are spending outputs which are * not ours but which are spent by pending transactions.</p> * * <p>Note that if the tx has inputs containing one of our keys, but the connected transaction is not in the wallet, * it will not be considered relevant.</p> */ public boolean isTransactionRelevant(Transaction tx) throws ScriptException { lock.lock(); try { return tx.getValueSentFromMe(this).compareTo(BigInteger.ZERO) > 0 || tx.getValueSentToMe(this).compareTo(BigInteger.ZERO) > 0 || checkForDoubleSpendAgainstPending(tx, false); } finally { lock.unlock(); } } /** * Checks if "tx" is spending any inputs of pending transactions. Not a general check, but it can work even if * the double spent inputs are not ours. Returns the pending tx that was double spent or null if none found. */ private boolean checkForDoubleSpendAgainstPending(Transaction tx, boolean takeAction) { checkState(lock.isHeldByCurrentThread()); // Compile a set of outpoints that are spent by tx. HashSet<TransactionOutPoint> outpoints = new HashSet<TransactionOutPoint>(); for (TransactionInput input : tx.getInputs()) { outpoints.add(input.getOutpoint()); } // Now for each pending transaction, see if it shares any outpoints with this tx. LinkedList<Transaction> doubleSpentTxns = Lists.newLinkedList(); for (Transaction p : pending.values()) { for (TransactionInput input : p.getInputs()) { // This relies on the fact that TransactionOutPoint equality is defined at the protocol not object // level - outpoints from two different inputs that point to the same output compare the same. TransactionOutPoint outpoint = input.getOutpoint(); if (outpoints.contains(outpoint)) { // It does, it's a double spend against the pending pool, which makes it relevant. if (!doubleSpentTxns.isEmpty() && doubleSpentTxns.getLast() == p) continue; doubleSpentTxns.add(p); } } } if (takeAction && !doubleSpentTxns.isEmpty()) { killTx(tx, doubleSpentTxns); } return !doubleSpentTxns.isEmpty(); } /** * Called by the {@link BlockChain} when we receive a new block that sends coins to one of our addresses or * spends coins from one of our addresses (note that a single transaction can do both).<p> * * This is necessary for the internal book-keeping Wallet does. When a transaction is received that sends us * coins it is added to a pool so we can use it later to create spends. When a transaction is received that * consumes outputs they are marked as spent so they won't be used in future.<p> * * A transaction that spends our own coins can be received either because a spend we created was accepted by the * network and thus made it into a block, or because our keys are being shared between multiple instances and * some other node spent the coins instead. We still have to know about that to avoid accidentally trying to * double spend.<p> * * A transaction may be received multiple times if is included into blocks in parallel chains. The blockType * parameter describes whether the containing block is on the main/best chain or whether it's on a presently * inactive side chain. We must still record these transactions and the blocks they appear in because a future * block might change which chain is best causing a reorganize. A re-org can totally change our balance! */ @Override public void receiveFromBlock(Transaction tx, StoredBlock block, BlockChain.NewBlockType blockType, int relativityOffset) throws VerificationException { lock.lock(); try { receive(tx, block, blockType, relativityOffset); } finally { lock.unlock(); } if (blockType == AbstractBlockChain.NewBlockType.BEST_CHAIN) { // If some keys are considered to be bad, possibly move money assigned to them now. // This has to run outside the wallet lock as it may trigger broadcasting of new transactions. maybeRotateKeys(); } } private void receive(Transaction tx, StoredBlock block, BlockChain.NewBlockType blockType, int relativityOffset) throws VerificationException { // Runs in a peer thread. checkState(lock.isHeldByCurrentThread()); BigInteger prevBalance = getBalance(); Sha256Hash txHash = tx.getHash(); boolean bestChain = blockType == BlockChain.NewBlockType.BEST_CHAIN; boolean sideChain = blockType == BlockChain.NewBlockType.SIDE_CHAIN; BigInteger valueSentFromMe = tx.getValueSentFromMe(this); BigInteger valueSentToMe = tx.getValueSentToMe(this); BigInteger valueDifference = valueSentToMe.subtract(valueSentFromMe); log.info("Received tx{} for {} BTC: {} [{}] in block {}", sideChain ? " on a side chain" : "", bitcoinValueToFriendlyString(valueDifference), tx.getHashAsString(), relativityOffset, block != null ? block.getHeader().getHash() : "(unit test)"); onWalletChangedSuppressions++; // If this transaction is already in the wallet we may need to move it into a different pool. At the very // least we need to ensure we're manipulating the canonical object rather than a duplicate. { Transaction tmp = transactions.get(tx.getHash()); if (tmp != null) tx = tmp; } boolean wasPending = pending.remove(txHash) != null; if (wasPending) log.info(" <-pending"); if (bestChain) { if (wasPending) { // Was pending and is now confirmed. Disconnect the outputs in case we spent any already: they will be // re-connected by processTxFromBestChain below. for (TransactionOutput output : tx.getOutputs()) { final TransactionInput spentBy = output.getSpentBy(); if (spentBy != null) spentBy.disconnect(); } } processTxFromBestChain(tx, wasPending); } else { checkState(sideChain); // Transactions that appear in a side chain will have that appearance recorded below - we assume that // some miners are also trying to include the transaction into the current best chain too, so let's treat // it as pending, except we don't need to do any risk analysis on it. if (wasPending) { // Just put it back in without touching the connections or confidence. addWalletTransaction(Pool.PENDING, tx); log.info(" ->pending"); } else { // Ignore the case where a tx appears on a side chain at the same time as the best chain (this is // quite normal and expected). Sha256Hash hash = tx.getHash(); if (!unspent.containsKey(hash) && !spent.containsKey(hash)) { // Otherwise put it (possibly back) into pending. // Committing it updates the spent flags and inserts into the pool as well. commitTx(tx); } } } if (block != null) { // Mark the tx as appearing in this block so we can find it later after a re-org. This also tells the tx // confidence object about the block and sets its work done/depth appropriately. tx.setBlockAppearance(block, bestChain, relativityOffset); if (bestChain) { // Don't notify this tx of work done in notifyNewBestBlock which will be called immediately after // this method has been called by BlockChain for all relevant transactions. Otherwise we'd double // count. ignoreNextNewBlock.add(txHash); } } onWalletChangedSuppressions--; // Side chains don't affect confidence. if (bestChain) { // notifyNewBestBlock will be invoked next and will then call maybeQueueOnWalletChanged for us. confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.TYPE); } else { maybeQueueOnWalletChanged(); } // Inform anyone interested that we have received or sent coins but only if: // - This is not due to a re-org. // - The coins appeared on the best chain. // - We did in fact receive some new money. // - We have not already informed the user about the coins when we received the tx broadcast, or for our // own spends. If users want to know when a broadcast tx becomes confirmed, they need to use tx confidence // listeners. if (!insideReorg && bestChain) { BigInteger newBalance = getBalance(); // This is slow. log.info("Balance is now: " + bitcoinValueToFriendlyString(newBalance)); if (!wasPending) { int diff = valueDifference.compareTo(BigInteger.ZERO); // We pick one callback based on the value difference, though a tx can of course both send and receive // coins from the wallet. if (diff > 0) { queueOnCoinsReceived(tx, prevBalance, newBalance); } else if (diff < 0) { queueOnCoinsSent(tx, prevBalance, newBalance); } } checkBalanceFuturesLocked(newBalance); } informConfidenceListenersIfNotReorganizing(); checkState(isConsistent()); saveNow(); } private void informConfidenceListenersIfNotReorganizing() { if (insideReorg) return; for (Map.Entry<Transaction, TransactionConfidence.Listener.ChangeReason> entry : confidenceChanged.entrySet()) { final Transaction tx = entry.getKey(); tx.getConfidence().queueListeners(entry.getValue()); queueOnTransactionConfidenceChanged(tx); } confidenceChanged.clear(); } /** * <p>Called by the {@link BlockChain} when a new block on the best chain is seen, AFTER relevant wallet * transactions are extracted and sent to us UNLESS the new block caused a re-org, in which case this will * not be called (the {@link Wallet#reorganize(StoredBlock, java.util.List, java.util.List)} method will * call this one in that case).</p> * <p/> * <p>Used to update confidence data in each transaction and last seen block hash. Triggers auto saving. * Invokes the onWalletChanged event listener if there were any affected transactions.</p> */ public void notifyNewBestBlock(StoredBlock block) throws VerificationException { // Check to see if this block has been seen before. Sha256Hash newBlockHash = block.getHeader().getHash(); if (newBlockHash.equals(getLastBlockSeenHash())) return; lock.lock(); try { // Store the new block hash. setLastBlockSeenHash(newBlockHash); setLastBlockSeenHeight(block.getHeight()); setLastBlockSeenTimeSecs(block.getHeader().getTimeSeconds()); // TODO: Clarify the code below. // Notify all the BUILDING transactions of the new block. // This is so that they can update their work done and depth. Set<Transaction> transactions = getTransactions(true); for (Transaction tx : transactions) { if (ignoreNextNewBlock.contains(tx.getHash())) { // tx was already processed in receive() due to it appearing in this block, so we don't want to // notify the tx confidence of work done twice, it'd result in miscounting. ignoreNextNewBlock.remove(tx.getHash()); } else if (tx.getConfidence().getConfidenceType() == ConfidenceType.BUILDING) { tx.getConfidence().notifyWorkDone(block.getHeader()); confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.DEPTH); } } informConfidenceListenersIfNotReorganizing(); maybeQueueOnWalletChanged(); // Coalesce writes to avoid throttling on disk access when catching up with the chain. saveLater(); } finally { lock.unlock(); } } /** * Handle when a transaction becomes newly active on the best chain, either due to receiving a new block or a * re-org. Places the tx into the right pool, handles coinbase transactions, handles double-spends and so on. */ private void processTxFromBestChain(Transaction tx, boolean forceAddToPool) throws VerificationException { checkState(lock.isHeldByCurrentThread()); checkState(!pending.containsKey(tx.getHash())); // This TX may spend our existing outputs even though it was not pending. This can happen in unit // tests, if keys are moved between wallets, if we're catching up to the chain given only a set of keys, // or if a dead coinbase transaction has moved back onto the main chain. boolean isDeadCoinbase = tx.isCoinBase() && dead.containsKey(tx.getHash()); if (isDeadCoinbase) { // There is a dead coinbase tx being received on the best chain. A coinbase tx is made dead when it moves // to a side chain but it can be switched back on a reorg and 'resurrected' back to spent or unspent. // So take it out of the dead pool. log.info(" coinbase tx {} <-dead: confidence {}", tx.getHashAsString(), tx.getConfidence().getConfidenceType().name()); dead.remove(tx.getHash()); } // Update tx and other unspent/pending transactions by connecting inputs/outputs. updateForSpends(tx, true); // Now make sure it ends up in the right pool. Also, handle the case where this TX is double-spending // against our pending transactions. Note that a tx may double spend our pending transactions and also send // us money/spend our money. boolean hasOutputsToMe = tx.getValueSentToMe(this, true).compareTo(BigInteger.ZERO) > 0; if (hasOutputsToMe) { // Needs to go into either unspent or spent (if the outputs were already spent by a pending tx). if (tx.isEveryOwnedOutputSpent(this)) { log.info(" tx {} ->spent (by pending)", tx.getHashAsString()); addWalletTransaction(Pool.SPENT, tx); } else { log.info(" tx {} ->unspent", tx.getHashAsString()); addWalletTransaction(Pool.UNSPENT, tx); } } else if (tx.getValueSentFromMe(this).compareTo(BigInteger.ZERO) > 0) { // Didn't send us any money, but did spend some. Keep it around for record keeping purposes. log.info(" tx {} ->spent", tx.getHashAsString()); addWalletTransaction(Pool.SPENT, tx); } else if (forceAddToPool) { // Was manually added to pending, so we should keep it to notify the user of confidence information log.info(" tx {} ->spent (manually added)", tx.getHashAsString()); addWalletTransaction(Pool.SPENT, tx); } checkForDoubleSpendAgainstPending(tx, true); } /** * <p>Updates the wallet by checking if this TX spends any of our outputs, and marking them as spent if so. If * fromChain is true, also checks to see if any pending transaction spends outputs of this transaction and marks * the spent flags appropriately.</p> * * <p>It can be called in two contexts. One is when we receive a transaction on the best chain but it wasn't pending, * this most commonly happens when we have a set of keys but the wallet transactions were wiped and we are catching * up with the block chain. It can also happen if a block includes a transaction we never saw at broadcast time. * If this tx double spends, it takes precedence over our pending transactions and the pending tx goes dead.</p> * * <p>The other context it can be called is from {@link Wallet#receivePending(Transaction, java.util.List)}, * ie we saw a tx be broadcast or one was submitted directly that spends our own coins. If this tx double spends * it does NOT take precedence because the winner will be resolved by the miners - we assume that our version will * win, if we are wrong then when a block appears the tx will go dead.</p> * * @param tx The transaction which is being updated. * @param fromChain If true, the tx appeared on the current best chain, if false it was pending. */ private void updateForSpends(Transaction tx, boolean fromChain) throws VerificationException { checkState(lock.isHeldByCurrentThread()); if (fromChain) checkState(!pending.containsKey(tx.getHash())); for (TransactionInput input : tx.getInputs()) { TransactionInput.ConnectionResult result = input.connect(unspent, TransactionInput.ConnectMode.ABORT_ON_CONFLICT); if (result == TransactionInput.ConnectionResult.NO_SUCH_TX) { // Not found in the unspent map. Try again with the spent map. result = input.connect(spent, TransactionInput.ConnectMode.ABORT_ON_CONFLICT); if (result == TransactionInput.ConnectionResult.NO_SUCH_TX) { // Not found in the unspent and spent maps. Try again with the pending map. result = input.connect(pending, TransactionInput.ConnectMode.ABORT_ON_CONFLICT); if (result == TransactionInput.ConnectionResult.NO_SUCH_TX) { // Doesn't spend any of our outputs or is coinbase. continue; } } } if (result == TransactionInput.ConnectionResult.ALREADY_SPENT) { if (fromChain) { // Double spend from chain: this will be handled later by checkForDoubleSpendAgainstPending. log.warn("updateForSpends: saw double spend from chain, handling later."); } else { // We saw two pending transactions that double spend each other. We don't know which will win. // This can happen in the case of bad network nodes that mutate transactions. Do a hex dump // so the exact nature of the mutation can be examined. log.warn("Saw two pending transactions double spend each other"); log.warn(" offending input is input {}", tx.getInputs().indexOf(input)); log.warn("{}: {}", tx.getHash(), new String(Hex.encode(tx.unsafeBitcoinSerialize()))); Transaction other = input.getConnectedOutput().getSpentBy().getParentTransaction(); log.warn("{}: {}", other.getHash(), new String(Hex.encode(tx.unsafeBitcoinSerialize()))); } } else if (result == TransactionInput.ConnectionResult.SUCCESS) { // Otherwise we saw a transaction spend our coins, but we didn't try and spend them ourselves yet. // The outputs are already marked as spent by the connect call above, so check if there are any more for // us to use. Move if not. Transaction connected = checkNotNull(input.getOutpoint().fromTx); log.info(" marked {} as spent", input.getOutpoint()); maybeMovePool(connected, "prevtx"); } } // Now check each output and see if there is a pending transaction which spends it. This shouldn't normally // ever occur because we expect transactions to arrive in temporal order, but this assumption can be violated // when we receive a pending transaction from the mempool that is relevant to us, which spends coins that we // didn't see arrive on the best chain yet. For instance, because of a chain replay or because of our keys were // used by another wallet somewhere else. if (fromChain) { for (Transaction pendingTx : pending.values()) { for (TransactionInput input : pendingTx.getInputs()) { TransactionInput.ConnectionResult result = input.connect(tx, TransactionInput.ConnectMode.ABORT_ON_CONFLICT); // This TX is supposed to have just appeared on the best chain, so its outputs should not be marked // as spent yet. If they are, it means something is happening out of order. checkState(result != TransactionInput.ConnectionResult.ALREADY_SPENT); if (result == TransactionInput.ConnectionResult.SUCCESS) { log.info("Connected pending tx input {}:{}", pendingTx.getHashAsString(), pendingTx.getInputs().indexOf(input)); } } // If the transactions outputs are now all spent, it will be moved into the spent pool by the // processTxFromBestChain method. } } } private void killCoinbase(Transaction coinbase) { log.warn("Coinbase killed by re-org: {}", coinbase.getHashAsString()); coinbase.getConfidence().setOverridingTransaction(null); confidenceChanged.put(coinbase, TransactionConfidence.Listener.ChangeReason.TYPE); final Sha256Hash hash = coinbase.getHash(); pending.remove(hash); unspent.remove(hash); spent.remove(hash); addWalletTransaction(Pool.DEAD, coinbase); // TODO: Properly handle the recursive nature of killing transactions here. } // Updates the wallet when a double spend occurs. overridingTx/overridingInput can be null for the case of coinbases private void killTx(Transaction overridingTx, List<Transaction> killedTx) { for (Transaction tx : killedTx) { log.warn("Saw double spend from chain override pending tx {}", tx.getHashAsString()); log.warn(" <-pending ->dead killed by {}", overridingTx.getHashAsString()); log.warn("Disconnecting each input and moving connected transactions."); pending.remove(tx.getHash()); addWalletTransaction(Pool.DEAD, tx); for (TransactionInput deadInput : tx.getInputs()) { Transaction connected = deadInput.getOutpoint().fromTx; if (connected == null) continue; deadInput.disconnect(); maybeMovePool(connected, "kill"); } tx.getConfidence().setOverridingTransaction(overridingTx); confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.TYPE); } log.warn("Now attempting to connect the inputs of the overriding transaction."); for (TransactionInput input : overridingTx.getInputs()) { TransactionInput.ConnectionResult result = input.connect(unspent, TransactionInput.ConnectMode.DISCONNECT_ON_CONFLICT); if (result == TransactionInput.ConnectionResult.SUCCESS) { maybeMovePool(input.getOutpoint().fromTx, "kill"); } else { result = input.connect(spent, TransactionInput.ConnectMode.DISCONNECT_ON_CONFLICT); if (result == TransactionInput.ConnectionResult.SUCCESS) { maybeMovePool(input.getOutpoint().fromTx, "kill"); } } } // TODO: Recursively kill other transactions that were double spent. } /** * If the transactions outputs are all marked as spent, and it's in the unspent map, move it. * If the owned transactions outputs are not all marked as spent, and it's in the spent map, move it. */ private void maybeMovePool(Transaction tx, String context) { checkState(lock.isHeldByCurrentThread()); if (tx.isEveryOwnedOutputSpent(this)) { // There's nothing left I can spend in this transaction. if (unspent.remove(tx.getHash()) != null) { if (log.isInfoEnabled()) { log.info(" {} {} <-unspent ->spent", tx.getHashAsString(), context); } spent.put(tx.getHash(), tx); } } else { if (spent.remove(tx.getHash()) != null) { if (log.isInfoEnabled()) { log.info(" {} {} <-spent ->unspent", tx.getHashAsString(), context); } unspent.put(tx.getHash(), tx); } } } /** * Adds an event listener object. Methods on this object are called when something interesting happens, * like receiving money. Runs the listener methods in the user thread. */ public void addEventListener(WalletEventListener listener) { addEventListener(listener, Threading.USER_THREAD); } /** * Adds an event listener object. Methods on this object are called when something interesting happens, * like receiving money. The listener is executed by the given executor. */ public void addEventListener(WalletEventListener listener, Executor executor) { eventListeners.add(new ListenerRegistration<WalletEventListener>(listener, executor)); } /** * Removes the given event listener object. Returns true if the listener was removed, false if that listener * was never added. */ public boolean removeEventListener(WalletEventListener listener) { return ListenerRegistration.removeFromList(listener, eventListeners); } /** * Calls {@link Wallet#commitTx} if tx is not already in the pending pool * * @return true if the tx was added to the wallet, or false if it was already in the pending pool */ public boolean maybeCommitTx(Transaction tx) throws VerificationException { tx.verify(); lock.lock(); try { if (pending.containsKey(tx.getHash())) return false; log.info("commitTx of {}", tx.getHashAsString()); BigInteger balance = getBalance(); tx.setUpdateTime(Utils.now()); // Mark the outputs we're spending as spent so we won't try and use them in future creations. This will also // move any transactions that are now fully spent to the spent map so we can skip them when creating future // spends. updateForSpends(tx, false); // Add to the pending pool. It'll be moved out once we receive this transaction on the best chain. // This also registers txConfidenceListener so wallet listeners get informed. log.info("->pending: {}", tx.getHashAsString()); tx.getConfidence().setConfidenceType(ConfidenceType.PENDING); confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.TYPE); addWalletTransaction(Pool.PENDING, tx); try { BigInteger valueSentFromMe = tx.getValueSentFromMe(this); BigInteger valueSentToMe = tx.getValueSentToMe(this); BigInteger newBalance = balance.add(valueSentToMe).subtract(valueSentFromMe); if (valueSentToMe.compareTo(BigInteger.ZERO) > 0) { checkBalanceFuturesLocked(null); queueOnCoinsReceived(tx, balance, newBalance); } if (valueSentFromMe.compareTo(BigInteger.ZERO) > 0) queueOnCoinsSent(tx, balance, newBalance); maybeQueueOnWalletChanged(); } catch (ScriptException e) { // Cannot happen as we just created this transaction ourselves. throw new RuntimeException(e); } checkState(isConsistent()); informConfidenceListenersIfNotReorganizing(); saveNow(); } finally { lock.unlock(); } return true; } /** * <p>Updates the wallet with the given transaction: puts it into the pending pool, sets the spent flags and runs * the onCoinsSent/onCoinsReceived event listener. Used in two situations:</p> * * <ol> * <li>When we have just successfully transmitted the tx we created to the network.</li> * <li>When we receive a pending transaction that didn't appear in the chain yet, and we did not create it.</li> * </ol> * * <p>Triggers an auto save.</p> */ public void commitTx(Transaction tx) throws VerificationException { checkArgument(maybeCommitTx(tx), "commitTx called on the same transaction twice"); } /** * Returns a set of all transactions in the wallet. * @param includeDead If true, transactions that were overridden by a double spend are included. */ public Set<Transaction> getTransactions(boolean includeDead) { lock.lock(); try { Set<Transaction> all = new HashSet<Transaction>(); all.addAll(unspent.values()); all.addAll(spent.values()); all.addAll(pending.values()); if (includeDead) all.addAll(dead.values()); return all; } finally { lock.unlock(); } } /** * Returns a set of all WalletTransactions in the wallet. */ public Iterable<WalletTransaction> getWalletTransactions() { lock.lock(); try { Set<WalletTransaction> all = new HashSet<WalletTransaction>(); addWalletTransactionsToSet(all, Pool.UNSPENT, unspent.values()); addWalletTransactionsToSet(all, Pool.SPENT, spent.values()); addWalletTransactionsToSet(all, Pool.DEAD, dead.values()); addWalletTransactionsToSet(all, Pool.PENDING, pending.values()); return all; } finally { lock.unlock(); } } private static void addWalletTransactionsToSet(Set<WalletTransaction> txs, Pool poolType, Collection<Transaction> pool) { for (Transaction tx : pool) { txs.add(new WalletTransaction(poolType, tx)); } } /** * Adds a transaction that has been associated with a particular wallet pool. This is intended for usage by * deserialization code, such as the {@link WalletProtobufSerializer} class. It isn't normally useful for * applications. It does not trigger auto saving. */ public void addWalletTransaction(WalletTransaction wtx) { lock.lock(); try { addWalletTransaction(wtx.getPool(), wtx.getTransaction()); } finally { lock.unlock(); } } /** * Adds the given transaction to the given pools and registers a confidence change listener on it. */ private void addWalletTransaction(Pool pool, Transaction tx) { checkState(lock.isHeldByCurrentThread()); transactions.put(tx.getHash(), tx); switch (pool) { case UNSPENT: checkState(unspent.put(tx.getHash(), tx) == null); break; case SPENT: checkState(spent.put(tx.getHash(), tx) == null); break; case PENDING: checkState(pending.put(tx.getHash(), tx) == null); break; case DEAD: checkState(dead.put(tx.getHash(), tx) == null); break; default: throw new RuntimeException("Unknown wallet transaction type " + pool); } // This is safe even if the listener has been added before, as TransactionConfidence ignores duplicate // registration requests. That makes the code in the wallet simpler. tx.getConfidence().addEventListener(txConfidenceListener, Threading.SAME_THREAD); } /** * Returns all non-dead, active transactions ordered by recency. */ public List<Transaction> getTransactionsByTime() { return getRecentTransactions(0, false); } /** * Returns an list of N transactions, ordered by increasing age. Transactions on side chains are not included. * Dead transactions (overridden by double spends) are optionally included. <p> * <p/> * Note: the current implementation is O(num transactions in wallet). Regardless of how many transactions are * requested, the cost is always the same. In future, requesting smaller numbers of transactions may be faster * depending on how the wallet is implemented (eg if backed by a database). */ public List<Transaction> getRecentTransactions(int numTransactions, boolean includeDead) { lock.lock(); try { checkArgument(numTransactions >= 0); // Firstly, put all transactions into an array. int size = getPoolSize(Pool.UNSPENT) + getPoolSize(Pool.SPENT) + getPoolSize(Pool.PENDING); if (numTransactions > size || numTransactions == 0) { numTransactions = size; } ArrayList<Transaction> all = new ArrayList<Transaction>(getTransactions(includeDead)); // Order by date. Collections.sort(all, Collections.reverseOrder(new Comparator<Transaction>() { public int compare(Transaction t1, Transaction t2) { return t1.getUpdateTime().compareTo(t2.getUpdateTime()); } })); if (numTransactions == all.size()) { return all; } else { all.subList(numTransactions, all.size()).clear(); return all; } } finally { lock.unlock(); } } /** * Returns a transaction object given its hash, if it exists in this wallet, or null otherwise. */ @Nullable public Transaction getTransaction(Sha256Hash hash) { lock.lock(); try { return transactions.get(hash); } finally { lock.unlock(); } } /** * Deletes transactions which appeared above the given block height from the wallet, but does not touch the keys. * This is useful if you have some keys and wish to replay the block chain into the wallet in order to pick them up. * Triggers auto saving. */ public void clearTransactions(int fromHeight) { lock.lock(); try { if (fromHeight == 0) { unspent.clear(); spent.clear(); pending.clear(); dead.clear(); transactions.clear(); saveLater(); } else { throw new UnsupportedOperationException(); } } finally { lock.unlock(); } } /** * Clean up the wallet. Currently, it only removes risky pending transaction from the wallet and only if their * outputs have not been spent. */ public void cleanup() { lock.lock(); try { boolean dirty = false; for (Iterator<Transaction> i = pending.values().iterator(); i.hasNext();) { Transaction tx = i.next(); if (isTransactionRisky(tx, null) && !acceptRiskyTransactions) { log.debug("Found risky transaction {} in wallet during cleanup.", tx.getHashAsString()); if (!tx.isAnyOutputSpent()) { tx.disconnectInputs(); i.remove(); transactions.remove(tx.getHash()); dirty = true; log.info("Removed transaction {} from pending pool during cleanup.", tx.getHashAsString()); } else { log.info( "Cannot remove transaction {} from pending pool during cleanup, as it's already spent partially.", tx.getHashAsString()); } } } if (dirty) { checkState(isConsistent()); saveLater(); } } finally { lock.unlock(); } } EnumSet<Pool> getContainingPools(Transaction tx) { lock.lock(); try { EnumSet<Pool> result = EnumSet.noneOf(Pool.class); Sha256Hash txHash = tx.getHash(); if (unspent.containsKey(txHash)) { result.add(Pool.UNSPENT); } if (spent.containsKey(txHash)) { result.add(Pool.SPENT); } if (pending.containsKey(txHash)) { result.add(Pool.PENDING); } if (dead.containsKey(txHash)) { result.add(Pool.DEAD); } return result; } finally { lock.unlock(); } } int getPoolSize(WalletTransaction.Pool pool) { lock.lock(); try { switch (pool) { case UNSPENT: return unspent.size(); case SPENT: return spent.size(); case PENDING: return pending.size(); case DEAD: return dead.size(); } throw new RuntimeException("Unreachable"); } finally { lock.unlock(); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // SEND APIS // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** A SendResult is returned to you as part of sending coins to a recipient. */ public static class SendResult { /** The Bitcoin transaction message that moves the money. */ public Transaction tx; /** A future that will complete once the tx message has been successfully broadcast to the network. */ public ListenableFuture<Transaction> broadcastComplete; } /** * A SendRequest gives the wallet information about precisely how to send money to a recipient or set of recipients. * Static methods are provided to help you create SendRequests and there are a few helper methods on the wallet that * just simplify the most common use cases. You may wish to customize a SendRequest if you want to attach a fee or * modify the change address. */ public static class SendRequest { /** * <p>A transaction, probably incomplete, that describes the outline of what you want to do. This typically will * mean it has some outputs to the intended destinations, but no inputs or change address (and therefore no * fees) - the wallet will calculate all that for you and update tx later.</p> * * <p>Be careful when adding outputs that you check the min output value * ({@link TransactionOutput#getMinNonDustValue(BigInteger)}) to avoid the whole transaction being rejected * because one output is dust.</p> * * <p>If there are already inputs to the transaction, make sure their out point has a connected output, * otherwise their value will be added to fee. Also ensure they are either signed or are spendable by a wallet * key, otherwise the behavior of {@link Wallet#completeTx(Wallet.SendRequest)} is undefined (likely * RuntimeException).</p> */ public Transaction tx; /** * When emptyWallet is set, all coins selected by the coin selector are sent to the first output in tx * (its value is ignored and set to {@link com.google.bitcoin.core.Wallet#getBalance()} - the fees required * for the transaction). Any additional outputs are removed. */ public boolean emptyWallet = false; /** * "Change" means the difference between the value gathered by a transactions inputs (the size of which you * don't really control as it depends on who sent you money), and the value being sent somewhere else. The * change address should be selected from this wallet, normally. <b>If null this will be chosen for you.</b> */ public Address changeAddress = null; /** * <p>A transaction can have a fee attached, which is defined as the difference between the input values * and output values. Any value taken in that is not provided to an output can be claimed by a miner. This * is how mining is incentivized in later years of the Bitcoin system when inflation drops. It also provides * a way for people to prioritize their transactions over others and is used as a way to make denial of service * attacks expensive.</p> * * <p>This is a constant fee (in satoshis) which will be added to the transaction. It is recommended that it be * at least {@link Transaction#REFERENCE_DEFAULT_MIN_TX_FEE} if it is set, as default reference clients will * otherwise simply treat the transaction as if there were no fee at all.</p> * * <p>Once {@link Wallet#completeTx(com.google.bitcoin.core.Wallet.SendRequest)} is called, this is set to the * value of the fee that was added.</p> * * <p>You might also consider adding a {@link SendRequest#feePerKb} to set the fee per kb of transaction size * (rounded down to the nearest kb) as that is how transactions are sorted when added to a block by miners.</p> */ public BigInteger fee = null; /** * <p>A transaction can have a fee attached, which is defined as the difference between the input values * and output values. Any value taken in that is not provided to an output can be claimed by a miner. This * is how mining is incentivized in later years of the Bitcoin system when inflation drops. It also provides * a way for people to prioritize their transactions over others and is used as a way to make denial of service * attacks expensive.</p> * * <p>This is a dynamic fee (in satoshis) which will be added to the transaction for each kilobyte in size * including the first. This is useful as as miners usually sort pending transactions by their fee per unit size * when choosing which transactions to add to a block. Note that, to keep this equivalent to the reference * client definition, a kilobyte is defined as 1000 bytes, not 1024.</p> * * <p>You might also consider using a {@link SendRequest#fee} to set the fee added for the first kb of size.</p> */ public BigInteger feePerKb = DEFAULT_FEE_PER_KB; /** * If you want to modify the default fee for your entire app without having to change each SendRequest you make, * you can do it here. This is primarily useful for unit tests. */ public static BigInteger DEFAULT_FEE_PER_KB = Transaction.REFERENCE_DEFAULT_MIN_TX_FEE; /** * <p>Requires that there be enough fee for a default reference client to at least relay the transaction. * (ie ensure the transaction will not be outright rejected by the network). Defaults to true, you should * only set this to false if you know what you're doing.</p> * * <p>Note that this does not enforce certain fee rules that only apply to transactions which are larger than * 26,000 bytes. If you get a transaction which is that large, you should set a fee and feePerKb of at least * {@link Transaction#REFERENCE_DEFAULT_MIN_TX_FEE}.</p> */ public boolean ensureMinRequiredFee = true; /** * The AES key to use to decrypt the private keys before signing. * If null then no decryption will be performed and if decryption is required an exception will be thrown. * You can get this from a password by doing wallet.getKeyCrypter().deriveKey(password). */ public KeyParameter aesKey = null; /** * If not null, the {@link com.google.bitcoin.wallet.CoinSelector} to use instead of the wallets default. Coin selectors are * responsible for choosing which transaction outputs (coins) in a wallet to use given the desired send value * amount. */ public CoinSelector coinSelector = null; // Tracks if this has been passed to wallet.completeTx already: just a safety check. private boolean completed; private SendRequest() {} /** * <p>Creates a new SendRequest to the given address for the given value.</p> * * <p>Be very careful when value is smaller than {@link Transaction#MIN_NONDUST_OUTPUT} as the transaction will * likely be rejected by the network in this case.</p> */ public static SendRequest to(Address destination, BigInteger value) { SendRequest req = new SendRequest(); final NetworkParameters parameters = destination.getParameters(); checkNotNull(parameters, "Address is for an unknown network"); req.tx = new Transaction(parameters); req.tx.addOutput(value, destination); return req; } /** * <p>Creates a new SendRequest to the given pubkey for the given value.</p> * * <p>Be careful to check the output's value is reasonable using * {@link TransactionOutput#getMinNonDustValue(BigInteger)} afterwards or you risk having the transaction * rejected by the network. Note that using {@link SendRequest#to(Address, java.math.BigInteger)} will result * in a smaller output, and thus the ability to use a smaller output value without rejection.</p> */ public static SendRequest to(NetworkParameters params, ECKey destination, BigInteger value) { SendRequest req = new SendRequest(); req.tx = new Transaction(params); req.tx.addOutput(value, destination); return req; } /** Simply wraps a pre-built incomplete transaction provided by you. */ public static SendRequest forTx(Transaction tx) { SendRequest req = new SendRequest(); req.tx = tx; return req; } public static SendRequest emptyWallet(Address destination) { SendRequest req = new SendRequest(); final NetworkParameters parameters = destination.getParameters(); checkNotNull(parameters, "Address is for an unknown network"); req.tx = new Transaction(parameters); req.tx.addOutput(BigInteger.ZERO, destination); req.emptyWallet = true; return req; } } /** * <p>Statelessly creates a transaction that sends the given value to address. The change is sent to * {@link Wallet#getChangeAddress()}, so you must have added at least one key.</p> * * <p>If you just want to send money quickly, you probably want * {@link Wallet#sendCoins(TransactionBroadcaster, Address, java.math.BigInteger)} instead. That will create the sending * transaction, commit to the wallet and broadcast it to the network all in one go. This method is lower level * and lets you see the proposed transaction before anything is done with it.</p> * * <p>This is a helper method that is equivalent to using {@link Wallet.SendRequest#to(Address, java.math.BigInteger)} * followed by {@link Wallet#completeTx(Wallet.SendRequest)} and returning the requests transaction object. * Note that this means a fee may be automatically added if required, if you want more control over the process, * just do those two steps yourself.</p> * * <p>IMPORTANT: This method does NOT update the wallet. If you call createSend again you may get two transactions * that spend the same coins. You have to call {@link Wallet#commitTx(Transaction)} on the created transaction to * prevent this, but that should only occur once the transaction has been accepted by the network. This implies * you cannot have more than one outstanding sending tx at once.</p> * * <p>You MUST ensure that nanocoins is not smaller than {@link Transaction#MIN_NONDUST_OUTPUT} or the transaction * will almost certainly be rejected by the network as dust.</p> * * @param address The Bitcoin address to send the money to. * @param nanocoins How much currency to send, in nanocoins. * @return either the created Transaction or null if there are insufficient coins. * coins as spent until commitTx is called on the result. * @throws InsufficientMoneyException if the request could not be completed due to not enough balance. */ public Transaction createSend(Address address, BigInteger nanocoins) throws InsufficientMoneyException { SendRequest req = SendRequest.to(address, nanocoins); completeTx(req); return req.tx; } /** * Sends coins to the given address but does not broadcast the resulting pending transaction. It is still stored * in the wallet, so when the wallet is added to a {@link PeerGroup} or {@link Peer} the transaction will be * announced to the network. The given {@link SendRequest} is completed first using * {@link Wallet#completeTx(Wallet.SendRequest)} to make it valid. * * @return the Transaction that was created * @throws InsufficientMoneyException if the request could not be completed due to not enough balance. */ public Transaction sendCoinsOffline(SendRequest request) throws InsufficientMoneyException { lock.lock(); try { completeTx(request); commitTx(request.tx); return request.tx; } finally { lock.unlock(); } } /** * <p>Sends coins to the given address, via the given {@link PeerGroup}. Change is returned to * {@link Wallet#getChangeAddress()}. Note that a fee may be automatically added if one may be required for the * transaction to be confirmed.</p> * * <p>The returned object provides both the transaction, and a future that can be used to learn when the broadcast * is complete. Complete means, if the PeerGroup is limited to only one connection, when it was written out to * the socket. Otherwise when the transaction is written out and we heard it back from a different peer.</p> * * <p>Note that the sending transaction is committed to the wallet immediately, not when the transaction is * successfully broadcast. This means that even if the network hasn't heard about your transaction you won't be * able to spend those same coins again.</p> * * <p>You MUST ensure that value is not smaller than {@link Transaction#MIN_NONDUST_OUTPUT} or the transaction will * almost certainly be rejected by the network as dust.</p> * * @param broadcaster a {@link TransactionBroadcaster} to use to send the transactions out. * @param to Which address to send coins to. * @param value How much value to send. You can use Utils.toNanoCoins() to calculate this. * @return An object containing the transaction that was created, and a future for the broadcast of it. * @throws InsufficientMoneyException if the request could not be completed due to not enough balance. */ public SendResult sendCoins(TransactionBroadcaster broadcaster, Address to, BigInteger value) throws InsufficientMoneyException { SendRequest request = SendRequest.to(to, value); return sendCoins(broadcaster, request); } /** * <p>Sends coins according to the given request, via the given {@link TransactionBroadcaster}.</p> * * <p>The returned object provides both the transaction, and a future that can be used to learn when the broadcast * is complete. Complete means, if the PeerGroup is limited to only one connection, when it was written out to * the socket. Otherwise when the transaction is written out and we heard it back from a different peer.</p> * * <p>Note that the sending transaction is committed to the wallet immediately, not when the transaction is * successfully broadcast. This means that even if the network hasn't heard about your transaction you won't be * able to spend those same coins again.</p> * * @param broadcaster the target to use for broadcast. * @param request the SendRequest that describes what to do, get one using static methods on SendRequest itself. * @return An object containing the transaction that was created, and a future for the broadcast of it. * @throws InsufficientMoneyException if the request could not be completed due to not enough balance. */ public SendResult sendCoins(TransactionBroadcaster broadcaster, SendRequest request) throws InsufficientMoneyException { // Should not be locked here, as we're going to call into the broadcaster and that might want to hold its // own lock. sendCoinsOffline handles everything that needs to be locked. checkState(!lock.isHeldByCurrentThread()); // Commit the TX to the wallet immediately so the spent coins won't be reused. // TODO: We should probably allow the request to specify tx commit only after the network has accepted it. Transaction tx = sendCoinsOffline(request); SendResult result = new SendResult(); result.tx = tx; // The tx has been committed to the pending pool by this point (via sendCoinsOffline -> commitTx), so it has // a txConfidenceListener registered. Once the tx is broadcast the peers will update the memory pool with the // count of seen peers, the memory pool will update the transaction confidence object, that will invoke the // txConfidenceListener which will in turn invoke the wallets event listener onTransactionConfidenceChanged // method. result.broadcastComplete = broadcaster.broadcastTransaction(tx); return result; } /** * Satisfies the given {@link SendRequest} using the default transaction broadcaster configured either via * {@link PeerGroup#addWallet(Wallet)} or directly with {@link #setTransactionBroadcaster(TransactionBroadcaster)}. * * @param request the SendRequest that describes what to do, get one using static methods on SendRequest itself. * @return An object containing the transaction that was created, and a future for the broadcast of it. * @throws IllegalStateException if no transaction broadcaster has been configured. * @throws InsufficientMoneyException if the request could not be completed due to not enough balance. */ public SendResult sendCoins(SendRequest request) throws InsufficientMoneyException { TransactionBroadcaster broadcaster = vTransactionBroadcaster; checkState(broadcaster != null, "No transaction broadcaster is configured"); return sendCoins(broadcaster, request); } /** * Sends coins to the given address, via the given {@link Peer}. Change is returned to {@link Wallet#getChangeAddress()}. * If an exception is thrown by {@link Peer#sendMessage(Message)} the transaction is still committed, so the * pending transaction must be broadcast <b>by you</b> at some other time. Note that a fee may be automatically added * if one may be required for the transaction to be confirmed. * * @return The {@link Transaction} that was created or null if there was insufficient balance to send the coins. * @throws InsufficientMoneyException if the request could not be completed due to not enough balance. */ public Transaction sendCoins(Peer peer, SendRequest request) throws InsufficientMoneyException { Transaction tx = sendCoinsOffline(request); peer.sendMessage(tx); return tx; } /** * Given a spend request containing an incomplete transaction, makes it valid by adding outputs and signed inputs * according to the instructions in the request. The transaction in the request is modified by this method, as is * the fee parameter. * * @param req a SendRequest that contains the incomplete transaction and details for how to make it valid. * @throws InsufficientMoneyException if the request could not be completed due to not enough balance. * @throws IllegalArgumentException if you try and complete the same SendRequest twice, or if the given send request * cannot be completed without violating the protocol rules. */ public void completeTx(SendRequest req) throws InsufficientMoneyException { lock.lock(); try { checkArgument(!req.completed, "Given SendRequest has already been completed."); // Calculate the amount of value we need to import. BigInteger value = BigInteger.ZERO; for (TransactionOutput output : req.tx.getOutputs()) { value = value.add(output.getValue()); } BigInteger totalOutput = value; log.info("Completing send tx with {} outputs totalling {} satoshis (not including fees)", req.tx.getOutputs().size(), value); // If any inputs have already been added, we don't need to get their value from wallet BigInteger totalInput = BigInteger.ZERO; for (TransactionInput input : req.tx.getInputs()) if (input.getConnectedOutput() != null) totalInput = totalInput.add(input.getConnectedOutput().getValue()); else log.warn("SendRequest transaction already has inputs but we don't know how much they are worth - they will be added to fee."); value = value.subtract(totalInput); List<TransactionInput> originalInputs = new ArrayList<TransactionInput>(req.tx.getInputs()); // We need to know if we need to add an additional fee because one of our values are smaller than 0.01 BTC boolean needAtLeastReferenceFee = false; if (req.ensureMinRequiredFee && !req.emptyWallet) { // min fee checking is handled later for emptyWallet for (TransactionOutput output : req.tx.getOutputs()) if (output.getValue().compareTo(Utils.CENT) < 0) { if (output.getValue().compareTo(output.getMinNonDustValue()) < 0) throw new IllegalArgumentException("Tried to send dust with ensureMinRequiredFee set - no way to complete this"); needAtLeastReferenceFee = true; break; } } // Calculate a list of ALL potential candidates for spending and then ask a coin selector to provide us // with the actual outputs that'll be used to gather the required amount of value. In this way, users // can customize coin selection policies. // // Note that this code is poorly optimized: the spend candidates only alter when transactions in the wallet // change - it could be pre-calculated and held in RAM, and this is probably an optimization worth doing. // Note that output.isMine(this) needs to test the keychain which is currently an array, so it's // O(candidate outputs ^ keychain.size())! There's lots of low hanging fruit here. LinkedList<TransactionOutput> candidates = calculateAllSpendCandidates(true); CoinSelection bestCoinSelection; TransactionOutput bestChangeOutput = null; if (!req.emptyWallet) { // This can throw InsufficientMoneyException. FeeCalculation feeCalculation; feeCalculation = new FeeCalculation(req, value, originalInputs, needAtLeastReferenceFee, candidates); bestCoinSelection = feeCalculation.bestCoinSelection; bestChangeOutput = feeCalculation.bestChangeOutput; } else { // We're being asked to empty the wallet. What this means is ensuring "tx" has only a single output // of the total value we can currently spend as determined by the selector, and then subtracting the fee. checkState(req.tx.getOutputs().size() == 1, "Empty wallet TX must have a single output only."); CoinSelector selector = req.coinSelector == null ? coinSelector : req.coinSelector; bestCoinSelection = selector.select(NetworkParameters.MAX_MONEY, candidates); req.tx.getOutput(0).setValue(bestCoinSelection.valueGathered); totalOutput = bestCoinSelection.valueGathered; } for (TransactionOutput output : bestCoinSelection.gathered) req.tx.addInput(output); if (req.ensureMinRequiredFee && req.emptyWallet) { final BigInteger baseFee = req.fee == null ? BigInteger.ZERO : req.fee; final BigInteger feePerKb = req.feePerKb == null ? BigInteger.ZERO : req.feePerKb; Transaction tx = req.tx; if (!adjustOutputDownwardsForFee(tx, bestCoinSelection, baseFee, feePerKb)) throw new InsufficientMoneyException.CouldNotAdjustDownwards(); } totalInput = totalInput.add(bestCoinSelection.valueGathered); if (bestChangeOutput != null) { req.tx.addOutput(bestChangeOutput); totalOutput = totalOutput.add(bestChangeOutput.getValue()); log.info(" with {} coins change", bitcoinValueToFriendlyString(bestChangeOutput.getValue())); } final BigInteger calculatedFee = totalInput.subtract(totalOutput); if (calculatedFee.compareTo(BigInteger.ZERO) > 0) { log.info(" with a fee of {}", bitcoinValueToFriendlyString(calculatedFee)); } // Now sign the inputs, thus proving that we are entitled to redeem the connected outputs. req.tx.signInputs(Transaction.SigHash.ALL, this, req.aesKey); // Check size. int size = req.tx.bitcoinSerialize().length; if (size > Transaction.MAX_STANDARD_TX_SIZE) { throw new IllegalArgumentException( String.format("Transaction could not be created without exceeding max size: %d vs %d", size, Transaction.MAX_STANDARD_TX_SIZE)); } // Label the transaction as being self created. We can use this later to spend its change output even before // the transaction is confirmed. We deliberately won't bother notifying listeners here as there's not much // point - the user isn't interested in a confidence transition they made themselves. req.tx.getConfidence().setSource(TransactionConfidence.Source.SELF); // Label the transaction as being a user requested payment. This can be used to render GUI wallet // transaction lists more appropriately, especially when the wallet starts to generate transactions itself // for internal purposes. req.tx.setPurpose(Transaction.Purpose.USER_PAYMENT); req.completed = true; req.fee = calculatedFee; log.info(" completed: {}", req.tx); } finally { lock.unlock(); } } /** Reduce the value of the first output of a transaction to pay the given feePerKb as appropriate for its size. */ private boolean adjustOutputDownwardsForFee(Transaction tx, CoinSelection coinSelection, BigInteger baseFee, BigInteger feePerKb) { TransactionOutput output = tx.getOutput(0); // Check if we need additional fee due to the transaction's size int size = tx.bitcoinSerialize().length; size += estimateBytesForSigning(coinSelection); BigInteger fee = baseFee.add(BigInteger.valueOf((size / 1000) + 1).multiply(feePerKb)); output.setValue(output.getValue().subtract(fee)); // Check if we need additional fee due to the output's value if (output.getValue().compareTo(Utils.CENT) < 0 && fee.compareTo(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE) < 0) output.setValue(output.getValue().subtract(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.subtract(fee))); return output.getMinNonDustValue().compareTo(output.getValue()) <= 0; } /** * Returns a list of all possible outputs we could possibly spend, potentially even including immature coinbases * (which the protocol may forbid us from spending). In other words, return all outputs that this wallet holds * keys for and which are not already marked as spent. */ public LinkedList<TransactionOutput> calculateAllSpendCandidates(boolean excludeImmatureCoinbases) { lock.lock(); try { LinkedList<TransactionOutput> candidates = Lists.newLinkedList(); for (Transaction tx : Iterables.concat(unspent.values(), pending.values())) { // Do not try and spend coinbases that were mined too recently, the protocol forbids it. if (excludeImmatureCoinbases && !tx.isMature()) continue; for (TransactionOutput output : tx.getOutputs()) { if (!output.isAvailableForSpending()) continue; if (!output.isMine(this)) continue; candidates.add(output); } } return candidates; } finally { lock.unlock(); } } /** * Returns all the outputs that match addresses or scripts added via {@link #addWatchedAddress(Address)} or * {@link #addWatchedScripts(java.util.List)}. * @param excludeImmatureCoinbases Whether to ignore outputs that are unspendable due to being immature. */ public LinkedList<TransactionOutput> getWatchedOutputs(boolean excludeImmatureCoinbases) { lock.lock(); try { LinkedList<TransactionOutput> candidates = Lists.newLinkedList(); for (Transaction tx : Iterables.concat(unspent.values(), pending.values())) { if (excludeImmatureCoinbases && !tx.isMature()) continue; for (TransactionOutput output : tx.getOutputs()) { if (!output.isAvailableForSpending()) continue; try { Script scriptPubKey = output.getScriptPubKey(); if (!watchedScripts.contains(scriptPubKey)) continue; candidates.add(output); } catch (ScriptException e) { // Ignore } } } return candidates; } finally { lock.unlock(); } } /** Returns the address used for change outputs. Note: this will probably go away in future. */ public Address getChangeAddress() { lock.lock(); try { // For now let's just pick the first key in our keychain. In future we might want to do something else to // give the user better privacy here, eg in incognito mode. checkState(keychain.size() > 0, "Can't send value without an address to use for receiving change"); ECKey first = keychain.get(0); return first.toAddress(params); } finally { lock.unlock(); } } /** * Adds the given ECKey to the wallet. There is currently no way to delete keys (that would result in coin loss). * If {@link Wallet#autosaveToFile(java.io.File, long, java.util.concurrent.TimeUnit, com.google.bitcoin.wallet.WalletFiles.Listener)} * has been called, triggers an auto save bypassing the normal coalescing delay and event handlers. * If the key already exists in the wallet, does nothing and returns false. */ public boolean addKey(final ECKey key) { return addKeys(Lists.newArrayList(key)) == 1; } /** * Adds the given keys to the wallet. There is currently no way to delete keys (that would result in coin loss). * If {@link Wallet#autosaveToFile(java.io.File, long, java.util.concurrent.TimeUnit, com.google.bitcoin.wallet.WalletFiles.Listener)} * has been called, triggers an auto save bypassing the normal coalescing delay and event handlers. * Returns the number of keys added, after duplicates are ignored. The onKeyAdded event will be called for each key * in the list that was not already present. */ public int addKeys(final List<ECKey> keys) { lock.lock(); try { int added = 0; // TODO: Consider making keys a sorted list or hashset so membership testing is faster. for (final ECKey key : keys) { if (keychain.contains(key)) continue; // If the key has a keyCrypter that does not match the Wallet's then a KeyCrypterException is thrown. // This is done because only one keyCrypter is persisted per Wallet and hence all the keys must be homogenous. if (isEncrypted() && (!key.isEncrypted() || !keyCrypter.equals(key.getKeyCrypter()))) { throw new KeyCrypterException("Cannot add key " + key.toString() + " because the keyCrypter does not match the wallets. Keys must be homogenous."); } else if (key.isEncrypted() && !isEncrypted()) { throw new KeyCrypterException("Cannot add key because it's encrypted and this wallet is not."); } keychain.add(key); added++; } queueOnKeysAdded(keys); // Force an auto-save immediately rather than queueing one, as keys are too important to risk losing. saveNow(); return added; } finally { lock.unlock(); } } /** * Return true if we are watching this address. */ public boolean isAddressWatched(Address address) { Script script = ScriptBuilder.createOutputScript(address); return isWatchedScript(script); } /** * Same as {@link #addWatchedAddress(Address, long)} with the current time as the creation time. */ public boolean addWatchedAddress(final Address address) { long now = Utils.currentTimeMillis() / 1000; return addWatchedAddresses(Lists.newArrayList(address), now) == 1; } /** * Adds the given address to the wallet to be watched. Outputs can be retrieved by {@link #getWatchedOutputs(boolean)}. * * @param creationTime creation time in seconds since the epoch, for scanning the blockchain * @return whether the address was added successfully (not already present) */ public boolean addWatchedAddress(final Address address, long creationTime) { return addWatchedAddresses(Lists.newArrayList(address), creationTime) == 1; } /** * Adds the given address to the wallet to be watched. Outputs can be retrieved * by {@link #getWatchedOutputs(boolean)}. * * @return how many addresses were added successfully */ public int addWatchedAddresses(final List<Address> addresses, long creationTime) { List<Script> scripts = Lists.newArrayList(); for (Address address : addresses) { Script script = ScriptBuilder.createOutputScript(address); script.setCreationTimeSeconds(creationTime); scripts.add(script); } return addWatchedScripts(scripts); } /** * Adds the given output scripts to the wallet to be watched. Outputs can be retrieved * by {@link #getWatchedOutputs(boolean)}. * * @return how many scripts were added successfully */ public int addWatchedScripts(final List<Script> scripts) { lock.lock(); try { int added = 0; for (final Script script : scripts) { if (watchedScripts.contains(script)) continue; watchedScripts.add(script); added++; } queueOnScriptsAdded(scripts); saveNow(); return added; } finally { lock.unlock(); } } /** * Locates a keypair from the keychain given the hash of the public key. This is needed when finding out which * key we need to use to redeem a transaction output. * * @return ECKey object or null if no such key was found. */ @Nullable public ECKey findKeyFromPubHash(byte[] pubkeyHash) { lock.lock(); try { for (ECKey key : keychain) { if (Arrays.equals(key.getPubKeyHash(), pubkeyHash)) return key; } return null; } finally { lock.unlock(); } } /** Returns true if the given key is in the wallet, false otherwise. Currently an O(N) operation. */ public boolean hasKey(ECKey key) { lock.lock(); try { return keychain.contains(key); } finally { lock.unlock(); } } /** * Returns true if this wallet contains a public key which hashes to the given hash. */ public boolean isPubKeyHashMine(byte[] pubkeyHash) { return findKeyFromPubHash(pubkeyHash) != null; } /** Returns true if this wallet is watching transactions for outputs with the script. */ public boolean isWatchedScript(Script script) { lock.lock(); try { return watchedScripts.contains(script); } finally { lock.unlock(); } } /** * Locates a keypair from the keychain given the raw public key bytes. * @return ECKey or null if no such key was found. */ @Nullable public ECKey findKeyFromPubKey(byte[] pubkey) { lock.lock(); try { for (ECKey key : keychain) { if (Arrays.equals(key.getPubKey(), pubkey)) return key; } return null; } finally { lock.unlock(); } } /** * Returns true if this wallet contains a keypair with the given public key. */ public boolean isPubKeyMine(byte[] pubkey) { return findKeyFromPubKey(pubkey) != null; } /** * <p>It's possible to calculate a wallets balance from multiple points of view. This enum selects which * getBalance() should use.</p> * * <p>Consider a real-world example: you buy a snack costing $5 but you only have a $10 bill. At the start you have * $10 viewed from every possible angle. After you order the snack you hand over your $10 bill. From the * perspective of your wallet you have zero dollars (AVAILABLE). But you know in a few seconds the shopkeeper * will give you back $5 change so most people in practice would say they have $5 (ESTIMATED).</p> */ public enum BalanceType { /** * Balance calculated assuming all pending transactions are in fact included into the best chain by miners. * This includes the value of immature coinbase transactions. */ ESTIMATED, /** * Balance that can be safely used to create new spends. This is whatever the default coin selector would * make available, which by default means transaction outputs with at least 1 confirmation and pending * transactions created by our own wallet which have been propagated across the network. */ AVAILABLE } /** * Returns the AVAILABLE balance of this wallet. See {@link BalanceType#AVAILABLE} for details on what this * means. */ public BigInteger getBalance() { return getBalance(BalanceType.AVAILABLE); } /** * Returns the balance of this wallet as calculated by the provided balanceType. */ public BigInteger getBalance(BalanceType balanceType) { lock.lock(); try { if (balanceType == BalanceType.AVAILABLE) { return getBalance(coinSelector); } else if (balanceType == BalanceType.ESTIMATED) { LinkedList<TransactionOutput> all = calculateAllSpendCandidates(false); BigInteger value = BigInteger.ZERO; for (TransactionOutput out : all) value = value.add(out.getValue()); return value; } else { throw new AssertionError("Unknown balance type"); // Unreachable. } } finally { lock.unlock(); } } /** * Returns the balance that would be considered spendable by the given coin selector. Just asks it to select * as many coins as possible and returns the total. */ public BigInteger getBalance(CoinSelector selector) { lock.lock(); try { checkNotNull(selector); LinkedList<TransactionOutput> candidates = calculateAllSpendCandidates(true); CoinSelection selection = selector.select(NetworkParameters.MAX_MONEY, candidates); return selection.valueGathered; } finally { lock.unlock(); } } /** Returns the available balance, including any unspent balance at watched addresses */ public BigInteger getWatchedBalance() { return getWatchedBalance(coinSelector); } /** * Returns the balance that would be considered spendable by the given coin selector, including * any unspent balance at watched addresses. */ public BigInteger getWatchedBalance(CoinSelector selector) { lock.lock(); try { checkNotNull(selector); LinkedList<TransactionOutput> candidates = getWatchedOutputs(true); CoinSelection selection = selector.select(NetworkParameters.MAX_MONEY, candidates); return selection.valueGathered; } finally { lock.unlock(); } } @Override public String toString() { return toString(false, true, true, null); } private static final Comparator<Transaction> SORT_ORDER_BY_UPDATE_TIME = new Comparator<Transaction>() { @Override public int compare(final Transaction tx1, final Transaction tx2) { final long time1 = tx1.getUpdateTime().getTime(); final long time2 = tx2.getUpdateTime().getTime(); return -(Longs.compare(time1, time2)); } }; private static final Comparator<Transaction> SORT_ORDER_BY_HEIGHT = new Comparator<Transaction>() { @Override public int compare(final Transaction tx1, final Transaction tx2) { final int height1 = tx1.getConfidence().getAppearedAtChainHeight(); final int height2 = tx2.getConfidence().getAppearedAtChainHeight(); return -(Ints.compare(height1, height2)); } }; /** * Formats the wallet as a human readable piece of text. Intended for debugging, the format is not meant to be * stable or human readable. * @param includePrivateKeys Whether raw private key data should be included. * @param includeTransactions Whether to print transaction data. * @param includeExtensions Whether to print extension data. * @param chain If set, will be used to estimate lock times for block timelocked transactions. */ public String toString(boolean includePrivateKeys, boolean includeTransactions, boolean includeExtensions, @Nullable AbstractBlockChain chain) { lock.lock(); try { StringBuilder builder = new StringBuilder(); BigInteger estimatedBalance = getBalance(BalanceType.ESTIMATED); BigInteger availableBalance = getBalance(BalanceType.AVAILABLE); builder.append(String.format("Wallet containing %s BTC (available: %s BTC) in:%n", bitcoinValueToPlainString(estimatedBalance), bitcoinValueToPlainString(availableBalance))); builder.append(String.format(" %d pending transactions%n", pending.size())); builder.append(String.format(" %d unspent transactions%n", unspent.size())); builder.append(String.format(" %d spent transactions%n", spent.size())); builder.append(String.format(" %d dead transactions%n", dead.size())); final Date lastBlockSeenTime = getLastBlockSeenTime(); final String lastBlockSeenTimeStr = lastBlockSeenTime == null ? "time unknown" : lastBlockSeenTime.toString(); builder.append(String.format("Last seen best block: %d (%s): %s%n", getLastBlockSeenHeight(), lastBlockSeenTimeStr, getLastBlockSeenHash())); if (this.keyCrypter != null) { builder.append(String.format("Encryption: %s%n", keyCrypter.toString())); } // Do the keys. builder.append("\nKeys:\n"); for (ECKey key : keychain) { final Address address = key.toAddress(params); builder.append(" addr:"); builder.append(address.toString()); builder.append(" hash160:"); builder.append(Utils.bytesToHexString(address.getHash160())); builder.append(" "); builder.append(includePrivateKeys ? key.toStringWithPrivate() : key.toString()); builder.append("\n"); } if (!watchedScripts.isEmpty()) { builder.append("\nWatched scripts:\n"); for (Script script : watchedScripts) { builder.append(" "); builder.append(script.toString()); builder.append("\n"); } } if (includeTransactions) { // Print the transactions themselves if (pending.size() > 0) { builder.append("\n>>> PENDING:\n"); toStringHelper(builder, pending, chain, SORT_ORDER_BY_UPDATE_TIME); } if (unspent.size() > 0) { builder.append("\n>>> UNSPENT:\n"); toStringHelper(builder, unspent, chain, SORT_ORDER_BY_HEIGHT); } if (spent.size() > 0) { builder.append("\n>>> SPENT:\n"); toStringHelper(builder, spent, chain, SORT_ORDER_BY_HEIGHT); } if (dead.size() > 0) { builder.append("\n>>> DEAD:\n"); toStringHelper(builder, dead, chain, SORT_ORDER_BY_HEIGHT); } } if (includeExtensions && extensions.size() > 0) { builder.append("\n>>> EXTENSIONS:\n"); for (WalletExtension extension : extensions.values()) { builder.append(extension).append("\n\n"); } } return builder.toString(); } finally { lock.unlock(); } } private void toStringHelper(StringBuilder builder, Map<Sha256Hash, Transaction> transactionMap, @Nullable AbstractBlockChain chain, @Nullable Comparator<Transaction> sortOrder) { checkState(lock.isHeldByCurrentThread()); final Collection<Transaction> txns; if (sortOrder != null) { txns = new TreeSet<Transaction>(sortOrder); txns.addAll(transactionMap.values()); } else { txns = transactionMap.values(); } for (Transaction tx : txns) { try { builder.append("Sends "); builder.append(Utils.bitcoinValueToFriendlyString(tx.getValueSentFromMe(this))); builder.append(" and receives "); builder.append(Utils.bitcoinValueToFriendlyString(tx.getValueSentToMe(this))); builder.append(", total value "); builder.append(Utils.bitcoinValueToFriendlyString(tx.getValue(this))); builder.append(".\n"); } catch (ScriptException e) { // Ignore and don't print this line. } builder.append(tx.toString(chain)); } } private static class TxOffsetPair implements Comparable<TxOffsetPair> { public final Transaction tx; public final int offset; public TxOffsetPair(Transaction tx, int offset) { this.tx = tx; this.offset = offset; } @Override public int compareTo(TxOffsetPair o) { return Ints.compare(offset, o.offset); } } /** * <p>Don't call this directly. It's not intended for API users.</p> * * <p>Called by the {@link BlockChain} when the best chain (representing total work done) has changed. This can * cause the number of confirmations of a transaction to go higher, lower, drop to zero and can even result in * a transaction going dead (will never confirm) due to a double spend.</p> * * <p>The oldBlocks/newBlocks lists are ordered height-wise from top first to bottom last.</p> */ public void reorganize(StoredBlock splitPoint, List<StoredBlock> oldBlocks, List<StoredBlock> newBlocks) throws VerificationException { lock.lock(); try { // This runs on any peer thread with the block chain locked. // // The reorganize functionality of the wallet is tested in ChainSplitTest.java // // receive() has been called on the block that is triggering the re-org before this is called, with type // of SIDE_CHAIN. // // Note that this code assumes blocks are not invalid - if blocks contain duplicated transactions, // transactions that double spend etc then we can calculate the incorrect result. This could open up // obscure DoS attacks if someone successfully mines a throwaway invalid block and feeds it to us, just // to try and corrupt the internal data structures. We should try harder to avoid this but it's tricky // because there are so many ways the block can be invalid. // Avoid spuriously informing the user of wallet/tx confidence changes whilst we're re-organizing. checkState(confidenceChanged.size() == 0); checkState(!insideReorg); insideReorg = true; checkState(onWalletChangedSuppressions == 0); onWalletChangedSuppressions++; // Map block hash to transactions that appear in it. We ensure that the map values are sorted according // to their relative position within those blocks. ArrayListMultimap<Sha256Hash, TxOffsetPair> mapBlockTx = ArrayListMultimap.create(); for (Transaction tx : getTransactions(true)) { Map<Sha256Hash, Integer> appearsIn = tx.getAppearsInHashes(); if (appearsIn == null) continue; // Pending. for (Map.Entry<Sha256Hash, Integer> block : appearsIn.entrySet()) mapBlockTx.put(block.getKey(), new TxOffsetPair(tx, block.getValue())); } for (Sha256Hash blockHash : mapBlockTx.keySet()) Collections.sort(mapBlockTx.get(blockHash)); List<Sha256Hash> oldBlockHashes = new ArrayList<Sha256Hash>(oldBlocks.size()); log.info("Old part of chain (top to bottom):"); for (StoredBlock b : oldBlocks) { log.info(" {}", b.getHeader().getHashAsString()); oldBlockHashes.add(b.getHeader().getHash()); } log.info("New part of chain (top to bottom):"); for (StoredBlock b : newBlocks) { log.info(" {}", b.getHeader().getHashAsString()); } Collections.reverse(newBlocks); // Need bottom-to-top but we get top-to-bottom. // For each block in the old chain, disconnect the transactions in reverse order. LinkedList<Transaction> oldChainTxns = Lists.newLinkedList(); for (Sha256Hash blockHash : oldBlockHashes) { for (TxOffsetPair pair : mapBlockTx.get(blockHash)) { Transaction tx = pair.tx; final Sha256Hash txHash = tx.getHash(); if (tx.isCoinBase()) { // All the transactions that we have in our wallet which spent this coinbase are now invalid // and will never confirm. Hopefully this should never happen - that's the point of the maturity // rule that forbids spending of coinbase transactions for 100 blocks. // // This could be recursive, although of course because we don't have the full transaction // graph we can never reliably kill all transactions we might have that were rooted in // this coinbase tx. Some can just go pending forever, like the Satoshi client. However we // can do our best. // // TODO: Is it better to try and sometimes fail, or not try at all? killCoinbase(tx); } else { for (TransactionOutput output : tx.getOutputs()) { TransactionInput input = output.getSpentBy(); if (input != null) input.disconnect(); } for (TransactionInput input : tx.getInputs()) { input.disconnect(); } oldChainTxns.add(tx); unspent.remove(txHash); spent.remove(txHash); checkState(!pending.containsKey(txHash)); checkState(!dead.containsKey(txHash)); } } } // Put all the disconnected transactions back into the pending pool and re-connect them. for (Transaction tx : oldChainTxns) { // Coinbase transactions on the old part of the chain are dead for good and won't come back unless // there's another re-org. if (tx.isCoinBase()) continue; log.info(" ->pending {}", tx.getHash()); tx.getConfidence().setConfidenceType(ConfidenceType.PENDING); // Wipe height/depth/work data. confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.TYPE); addWalletTransaction(Pool.PENDING, tx); updateForSpends(tx, false); } // Note that dead transactions stay dead. Consider a chain that Finney attacks T1 and replaces it with // T2, so we move T1 into the dead pool. If there's now a re-org to a chain that doesn't include T2, it // doesn't matter - the miners deleted T1 from their mempool, will resurrect T2 and put that into the // mempool and so T1 is still seen as a losing double spend. // The old blocks have contributed to the depth and work done for all the transactions in the // wallet that are in blocks up to and including the chain split block. // The total depth and work done is calculated here and then subtracted from the appropriate transactions. int depthToSubtract = oldBlocks.size(); BigInteger workDoneToSubtract = BigInteger.ZERO; for (StoredBlock b : oldBlocks) { workDoneToSubtract = workDoneToSubtract.add(b.getHeader().getWork()); } log.info("depthToSubtract = " + depthToSubtract + ", workDoneToSubtract = " + workDoneToSubtract); // Remove depthToSubtract and workDoneToSubtract from all transactions in the wallet except for pending. subtractDepthAndWorkDone(depthToSubtract, workDoneToSubtract, spent.values()); subtractDepthAndWorkDone(depthToSubtract, workDoneToSubtract, unspent.values()); subtractDepthAndWorkDone(depthToSubtract, workDoneToSubtract, dead.values()); // The effective last seen block is now the split point so set the lastSeenBlockHash. setLastBlockSeenHash(splitPoint.getHeader().getHash()); // For each block in the new chain, work forwards calling receive() and notifyNewBestBlock(). // This will pull them back out of the pending pool, or if the tx didn't appear in the old chain and // does appear in the new chain, will treat it as such and possibly kill pending transactions that // conflict. for (StoredBlock block : newBlocks) { log.info("Replaying block {}", block.getHeader().getHashAsString()); for (TxOffsetPair pair : mapBlockTx.get(block.getHeader().getHash())) { log.info(" tx {}", pair.tx.getHash()); try { receive(pair.tx, block, BlockChain.NewBlockType.BEST_CHAIN, pair.offset); } catch (ScriptException e) { throw new RuntimeException(e); // Cannot happen as these blocks were already verified. } } notifyNewBestBlock(block); } checkState(isConsistent()); final BigInteger balance = getBalance(); log.info("post-reorg balance is {}", Utils.bitcoinValueToFriendlyString(balance)); // Inform event listeners that a re-org took place. queueOnReorganize(); insideReorg = false; onWalletChangedSuppressions--; maybeQueueOnWalletChanged(); checkBalanceFuturesLocked(balance); informConfidenceListenersIfNotReorganizing(); saveLater(); } finally { lock.unlock(); } } /** * Subtract the supplied depth and work done from the given transactions. */ private void subtractDepthAndWorkDone(int depthToSubtract, BigInteger workDoneToSubtract, Collection<Transaction> transactions) { for (Transaction tx : transactions) { if (tx.getConfidence().getConfidenceType() == ConfidenceType.BUILDING) { tx.getConfidence().setDepthInBlocks(tx.getConfidence().getDepthInBlocks() - depthToSubtract); tx.getConfidence().setWorkDone(tx.getConfidence().getWorkDone().subtract(workDoneToSubtract)); confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.DEPTH); } } } /** * Returns an immutable view of the transactions currently waiting for network confirmations. */ public Collection<Transaction> getPendingTransactions() { lock.lock(); try { return Collections.unmodifiableCollection(pending.values()); } finally { lock.unlock(); } } /** * Returns the earliest creation time of keys or watched scripts in this wallet, in seconds since the epoch, ie the min * of {@link com.google.bitcoin.core.ECKey#getCreationTimeSeconds()}. This can return zero if at least one key does * not have that data (was created before key timestamping was implemented). <p> * * This method is most often used in conjunction with {@link PeerGroup#setFastCatchupTimeSecs(long)} in order to * optimize chain download for new users of wallet apps. Backwards compatibility notice: if you get zero from this * method, you can instead use the time of the first release of your software, as it's guaranteed no users will * have wallets pre-dating this time. <p> * * If there are no keys in the wallet, the current time is returned. */ @Override public long getEarliestKeyCreationTime() { lock.lock(); try { long earliestTime = Long.MAX_VALUE; for (ECKey key : keychain) earliestTime = Math.min(key.getCreationTimeSeconds(), earliestTime); for (Script script : watchedScripts) earliestTime = Math.min(script.getCreationTimeSeconds(), earliestTime); if (earliestTime == Long.MAX_VALUE) return Utils.currentTimeMillis() / 1000; return earliestTime; } finally { lock.unlock(); } } /** Returns the hash of the last seen best-chain block, or null if the wallet is too old to store this data. */ @Nullable public Sha256Hash getLastBlockSeenHash() { lock.lock(); try { return lastBlockSeenHash; } finally { lock.unlock(); } } public void setLastBlockSeenHash(@Nullable Sha256Hash lastBlockSeenHash) { lock.lock(); try { this.lastBlockSeenHash = lastBlockSeenHash; } finally { lock.unlock(); } } public void setLastBlockSeenHeight(int lastBlockSeenHeight) { lock.lock(); try { this.lastBlockSeenHeight = lastBlockSeenHeight; } finally { lock.unlock(); } } public void setLastBlockSeenTimeSecs(long timeSecs) { lock.lock(); try { lastBlockSeenTimeSecs = timeSecs; } finally { lock.unlock(); } } /** * Returns the UNIX time in seconds since the epoch extracted from the last best seen block header. This timestamp * is <b>not</b> the local time at which the block was first observed by this application but rather what the block * (i.e. miner) self declares. It is allowed to have some significant drift from the real time at which the block * was found, although most miners do use accurate times. If this wallet is old and does not have a recorded * time then this method returns zero. */ public long getLastBlockSeenTimeSecs() { lock.lock(); try { return lastBlockSeenTimeSecs; } finally { lock.unlock(); } } /** * Returns a {@link Date} representing the time extracted from the last best seen block header. This timestamp * is <b>not</b> the local time at which the block was first observed by this application but rather what the block * (i.e. miner) self declares. It is allowed to have some significant drift from the real time at which the block * was found, although most miners do use accurate times. If this wallet is old and does not have a recorded * time then this method returns null. */ @Nullable public Date getLastBlockSeenTime() { final long secs = getLastBlockSeenTimeSecs(); if (secs == 0) return null; else return new Date(secs * 1000); } /** * Returns the height of the last seen best-chain block. Can be 0 if a wallet is brand new or -1 if the wallet * is old and doesn't have that data. */ public int getLastBlockSeenHeight() { lock.lock(); try { return lastBlockSeenHeight; } finally { lock.unlock(); } } /** * Convenience wrapper around {@link Wallet#encrypt(com.google.bitcoin.crypto.KeyCrypter, * org.spongycastle.crypto.params.KeyParameter)} which uses the default Scrypt key derivation algorithm and * parameters, derives a key from the given password and returns the created key. */ public KeyParameter encrypt(CharSequence password) { checkNotNull(password); checkArgument(password.length() > 0); KeyCrypter scrypt = new KeyCrypterScrypt(); KeyParameter derivedKey = scrypt.deriveKey(password); encrypt(scrypt, derivedKey); return derivedKey; } /** * Encrypt the wallet using the KeyCrypter and the AES key. A good default KeyCrypter to use is * {@link com.google.bitcoin.crypto.KeyCrypterScrypt}. * * @param keyCrypter The KeyCrypter that specifies how to encrypt/ decrypt a key * @param aesKey AES key to use (normally created using KeyCrypter#deriveKey and cached as it is time consuming to create from a password) * @throws KeyCrypterException Thrown if the wallet encryption fails. If so, the wallet state is unchanged. */ public void encrypt(KeyCrypter keyCrypter, KeyParameter aesKey) { lock.lock(); try { checkNotNull(keyCrypter); checkState(getEncryptionType() == EncryptionType.UNENCRYPTED, "Wallet is already encrypted"); // Create a new arraylist that will contain the encrypted keys ArrayList<ECKey> encryptedKeyChain = new ArrayList<ECKey>(); for (ECKey key : keychain) { if (key.isEncrypted()) { // Key is already encrypted - add as is. encryptedKeyChain.add(key); } else { // Encrypt the key. ECKey encryptedKey = key.encrypt(keyCrypter, aesKey); // Check that the encrypted key can be successfully decrypted. // This is done as it is a critical failure if the private key cannot be decrypted successfully // (all bitcoin controlled by that private key is lost forever). // For a correctly constructed keyCrypter the encryption should always be reversible so it is just being as cautious as possible. if (!ECKey.encryptionIsReversible(key, encryptedKey, keyCrypter, aesKey)) { // Abort encryption throw new KeyCrypterException("The key " + key.toString() + " cannot be successfully decrypted after encryption so aborting wallet encryption."); } encryptedKeyChain.add(encryptedKey); } } // Now ready to use the encrypted keychain so go through the old keychain clearing all the unencrypted private keys. // (This is to avoid the possibility of key recovery from memory). for (ECKey key : keychain) { if (!key.isEncrypted()) { key.clearPrivateKey(); } } // Replace the old keychain with the encrypted one. keychain = encryptedKeyChain; // The wallet is now encrypted. this.keyCrypter = keyCrypter; saveNow(); } finally { lock.unlock(); } } /** * Decrypt the wallet with the wallets keyCrypter and AES key. * * @param aesKey AES key to use (normally created using KeyCrypter#deriveKey and cached as it is time consuming to create from a password) * @throws KeyCrypterException Thrown if the wallet decryption fails. If so, the wallet state is unchanged. */ public void decrypt(KeyParameter aesKey) { lock.lock(); try { // Check the wallet is already encrypted - you cannot decrypt an unencrypted wallet. checkState(getEncryptionType() != EncryptionType.UNENCRYPTED, "Wallet is already decrypted"); // Check that the wallet keyCrypter is non-null. // This is set either at construction (if an encrypted wallet is created) or by wallet encryption. checkNotNull(keyCrypter); // Create a new arraylist that will contain the decrypted keys ArrayList<ECKey> decryptedKeyChain = new ArrayList<ECKey>(); for (ECKey key : keychain) { // Decrypt the key. if (!key.isEncrypted()) { // Not encrypted - add to chain as is. decryptedKeyChain.add(key); } else { ECKey decryptedECKey = key.decrypt(keyCrypter, aesKey); decryptedKeyChain.add(decryptedECKey); } } // Replace the old keychain with the unencrypted one. keychain = decryptedKeyChain; // The wallet is now unencrypted. keyCrypter = null; saveNow(); } finally { lock.unlock(); } } /** * Create a new, random encrypted ECKey and add it to the wallet. * * @param keyCrypter The keyCrypter to use in encrypting the new key * @param aesKey The AES key to use to encrypt the new key * @return ECKey the new, encrypted ECKey */ public ECKey addNewEncryptedKey(KeyCrypter keyCrypter, KeyParameter aesKey) { ECKey newKey = (new ECKey()).encrypt(checkNotNull(keyCrypter), checkNotNull(aesKey)); addKey(newKey); return newKey; } /** * <p>Convenience wrapper around {@link Wallet#addNewEncryptedKey(com.google.bitcoin.crypto.KeyCrypter, * org.spongycastle.crypto.params.KeyParameter)} which just derives the key afresh and uses the pre-set * keycrypter. The wallet must have been encrypted using one of the encrypt methods previously.</p> * * <p>Note that key derivation is deliberately very slow! So if you plan to add multiple keys, it can be * faster to use the other method instead and re-use the {@link KeyParameter} object instead.</p> */ public ECKey addNewEncryptedKey(CharSequence password) { lock.lock(); try { checkNotNull(keyCrypter, "Wallet is not encrypted, you must call encrypt() first."); return addNewEncryptedKey(keyCrypter, keyCrypter.deriveKey(password)); } finally { lock.unlock(); } } /** * Check whether the password can decrypt the first key in the wallet. * This can be used to check the validity of an entered password. * * @return boolean true if password supplied can decrypt the first private key in the wallet, false otherwise. */ public boolean checkPassword(CharSequence password) { lock.lock(); try { return keyCrypter != null && checkAESKey(keyCrypter.deriveKey(checkNotNull(password))); } finally { lock.unlock(); } } /** * Check whether the AES key can decrypt the first encrypted key in the wallet. * * @return boolean true if AES key supplied can decrypt the first encrypted private key in the wallet, false otherwise. */ public boolean checkAESKey(KeyParameter aesKey) { lock.lock(); try { // If no keys then cannot decrypt. if (!getKeys().iterator().hasNext()) return false; // Find the first encrypted key in the wallet. ECKey firstEncryptedECKey = null; Iterator<ECKey> iterator = getKeys().iterator(); while (iterator.hasNext() && firstEncryptedECKey == null) { ECKey loopECKey = iterator.next(); if (loopECKey.isEncrypted()) { firstEncryptedECKey = loopECKey; } } // There are no encrypted keys in the wallet. if (firstEncryptedECKey == null) return false; String originalAddress = firstEncryptedECKey.toAddress(getNetworkParameters()).toString(); if (firstEncryptedECKey.isEncrypted() && firstEncryptedECKey.getEncryptedPrivateKey() != null) { try { ECKey rebornKey = firstEncryptedECKey.decrypt(keyCrypter, aesKey); // Check that the decrypted private key's address is correct ie it decrypted accurately. String rebornAddress = rebornKey.toAddress(getNetworkParameters()).toString(); return originalAddress.equals(rebornAddress); } catch (KeyCrypterException ede) { // The AES key supplied is incorrect. return false; } } return false; } finally { lock.unlock(); } } /** * Get the wallet's KeyCrypter. * (Used in encrypting/ decrypting an ECKey). */ public KeyCrypter getKeyCrypter() { lock.lock(); try { return keyCrypter; } finally { lock.unlock(); } } /** * Sets the wallet's KeyCrypter. * Note that this does not encrypt the wallet, and should only be used if the keyCrypter can not be included in the * constructor during initial wallet loading. * Note that if the keyCrypter was not properly set during wallet load, {@link Wallet#getEncryptionType()} and * {@link Wallet#isEncrypted()} will not return the correct results. */ public void setKeyCrypter(KeyCrypter keyCrypter) { lock.lock(); try { checkState(this.keyCrypter == null); this.keyCrypter = keyCrypter; } finally { lock.unlock(); } } /** * Get the type of encryption used for this wallet. * * (This is a convenience method - the encryption type is actually stored in the keyCrypter). */ public EncryptionType getEncryptionType() { lock.lock(); try { if (keyCrypter == null) { // Unencrypted wallet. return EncryptionType.UNENCRYPTED; } else { return keyCrypter.getUnderstoodEncryptionType(); } } finally { lock.unlock(); } } /** Returns true if the wallet is encrypted using any scheme, false if not. */ public boolean isEncrypted() { return getEncryptionType() != EncryptionType.UNENCRYPTED; } /** * Get the version of the Wallet. * This is an int you can use to indicate which versions of wallets your code understands, * and which come from the future (and hence cannot be safely loaded). */ public int getVersion() { return version; } /** * Set the version number of the wallet. See {@link Wallet#getVersion()}. */ public void setVersion(int version) { this.version = version; } /** * Set the description of the wallet. * This is a Unicode encoding string typically entered by the user as descriptive text for the wallet. */ public void setDescription(String description) { this.description = description; } /** * Get the description of the wallet. See {@link Wallet#setDescription(String))} */ public String getDescription() { return description; } @Override public int getBloomFilterElementCount() { int size = getKeychainSize() * 2; for (Transaction tx : getTransactions(false)) { for (TransactionOutput out : tx.getOutputs()) { try { if (isTxOutputBloomFilterable(out)) size++; } catch (ScriptException e) { throw new RuntimeException(e); // If it is ours, we parsed the script correctly, so this shouldn't happen } } } // Some scripts may have more than one bloom element. That should normally be okay, // because under-counting just increases false-positive rate. size += watchedScripts.size(); return size; } /** * If we are watching any scripts, the bloom filter must update on peers whenever an output is * identified. This is because we don't necessarily have the associated pubkey, so we can't * watch for it on spending transactions. */ @Override public boolean isRequiringUpdateAllBloomFilter() { return !watchedScripts.isEmpty(); } /** * Gets a bloom filter that contains all of the public keys from this wallet, and which will provide the given * false-positive rate. See the docs for {@link BloomFilter} for a brief explanation of anonymity when using filters. */ public BloomFilter getBloomFilter(double falsePositiveRate) { return getBloomFilter(getBloomFilterElementCount(), falsePositiveRate, (long)(Math.random()*Long.MAX_VALUE)); } /** * Gets a bloom filter that contains all of the public keys from this wallet, * and which will provide the given false-positive rate if it has size elements. * Keep in mind that you will get 2 elements in the bloom filter for each key in the wallet. * * This is used to generate a BloomFilter which can be #{link BloomFilter.merge}d with another. * It could also be used if you have a specific target for the filter's size. * * See the docs for {@link BloomFilter(int, double)} for a brief explanation of anonymity when using bloom filters. */ @Override public BloomFilter getBloomFilter(int size, double falsePositiveRate, long nTweak) { BloomFilter filter = new BloomFilter(size, falsePositiveRate, nTweak); lock.lock(); try { for (ECKey key : keychain) { filter.insert(key.getPubKey()); filter.insert(key.getPubKeyHash()); } for (Script script : watchedScripts) { for (ScriptChunk chunk : script.getChunks()) { // Only add long (at least 64 bit) data to the bloom filter. // If any long constants become popular in scripts, we will need logic // here to exclude them. if (!chunk.isOpCode() && chunk.data.length >= MINIMUM_BLOOM_DATA_LENGTH) { filter.insert(chunk.data); } } } } finally { lock.unlock(); } for (Transaction tx : getTransactions(false)) { for (int i = 0; i < tx.getOutputs().size(); i++) { TransactionOutput out = tx.getOutputs().get(i); try { if (isTxOutputBloomFilterable(out)) { TransactionOutPoint outPoint = new TransactionOutPoint(params, i, tx); filter.insert(outPoint.bitcoinSerialize()); } } catch (ScriptException e) { throw new RuntimeException(e); // If it is ours, we parsed the script correctly, so this shouldn't happen } } } return filter; } private boolean isTxOutputBloomFilterable(TransactionOutput out) { return (out.isMine(this) && out.getScriptPubKey().isSentToRawPubKey()) || out.isWatched(this); } /** Returns the {@link CoinSelector} object which controls which outputs can be spent by this wallet. */ public CoinSelector getCoinSelector() { lock.lock(); try { return coinSelector; } finally { lock.unlock(); } } /** * A coin selector is responsible for choosing which outputs to spend when creating transactions. The default * selector implements a policy of spending transactions that appeared in the best chain and pending transactions * that were created by this wallet, but not others. You can override the coin selector for any given send * operation by changing {@link Wallet.SendRequest#coinSelector}. */ public void setCoinSelector(@Nonnull CoinSelector coinSelector) { lock.lock(); try { this.coinSelector = checkNotNull(coinSelector); } finally { lock.unlock(); } } /** * Convenience wrapper for <tt>setCoinSelector(Wallet.AllowUnconfirmedCoinSelector.get())</tt>. If this method * is called on the wallet then transactions will be used for spending regardless of their confidence. This can * be dangerous - only use this if you absolutely know what you're doing! */ public void allowSpendingUnconfirmedTransactions() { setCoinSelector(AllowUnconfirmedCoinSelector.get()); } private static class BalanceFutureRequest { public SettableFuture<BigInteger> future; public BigInteger value; public BalanceType type; } @GuardedBy("lock") private List<BalanceFutureRequest> balanceFutureRequests = Lists.newLinkedList(); /** * <p>Returns a future that will complete when the balance of the given type has becom equal or larger to the given * value. If the wallet already has a large enough balance the future is returned in a pre-completed state. Note * that this method is not blocking, if you want to actually wait immediately, you have to call .get() on * the result.</p> * * <p>Also note that by the time the future completes, the wallet may have changed yet again if something else * is going on in parallel, so you should treat the returned balance as advisory and be prepared for sending * money to fail! Finally please be aware that any listeners on the future will run either on the calling thread * if it completes immediately, or eventually on a background thread if the balance is not yet at the right * level. If you do something that means you know the balance should be sufficient to trigger the future, * you can use {@link com.google.bitcoin.utils.Threading#waitForUserCode()} to block until the future had a * chance to be updated.</p> */ public ListenableFuture<BigInteger> getBalanceFuture(final BigInteger value, final BalanceType type) { lock.lock(); try { final SettableFuture<BigInteger> future = SettableFuture.create(); final BigInteger current = getBalance(type); if (current.compareTo(value) >= 0) { // Already have enough. future.set(current); } else { // Will be checked later in checkBalanceFutures. We don't just add an event listener for ourselves // here so that running getBalanceFuture().get() in the user code thread works - generally we must // avoid giving the user back futures that require the user code thread to be free. BalanceFutureRequest req = new BalanceFutureRequest(); req.future = future; req.value = value; req.type = type; balanceFutureRequests.add(req); } return future; } finally { lock.unlock(); } } // Runs any balance futures in the user code thread. private void checkBalanceFuturesLocked(@Nullable BigInteger avail) { checkState(lock.isHeldByCurrentThread()); BigInteger estimated = null; final ListIterator<BalanceFutureRequest> it = balanceFutureRequests.listIterator(); while (it.hasNext()) { final BalanceFutureRequest req = it.next(); BigInteger val = null; if (req.type == BalanceType.AVAILABLE) { if (avail == null) avail = getBalance(BalanceType.AVAILABLE); if (avail.compareTo(req.value) < 0) continue; val = avail; } else if (req.type == BalanceType.ESTIMATED) { if (estimated == null) estimated = getBalance(BalanceType.ESTIMATED); if (estimated.compareTo(req.value) < 0) continue; val = estimated; } // Found one that's finished. it.remove(); final BigInteger v = checkNotNull(val); // Don't run any user-provided future listeners with our lock held. Threading.USER_THREAD.execute(new Runnable() { @Override public void run() { req.future.set(v); } }); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Extensions to the wallet format. /** * By providing an object implementing the {@link WalletExtension} interface, you can save and load arbitrary * additional data that will be stored with the wallet. Each extension is identified by an ID, so attempting to * add the same extension twice (or two different objects that use the same ID) will throw an IllegalStateException. */ public void addExtension(WalletExtension extension) { String id = checkNotNull(extension).getWalletExtensionID(); lock.lock(); try { if (extensions.containsKey(id)) throw new IllegalStateException("Cannot add two extensions with the same ID: " + id); extensions.put(id, extension); saveNow(); } finally { lock.unlock(); } } /** * Atomically adds extension or returns an existing extension if there is one with the same id alreadypresent. */ public WalletExtension addOrGetExistingExtension(WalletExtension extension) { String id = checkNotNull(extension).getWalletExtensionID(); lock.lock(); try { WalletExtension previousExtension = extensions.get(id); if (previousExtension != null) return previousExtension; extensions.put(id, extension); saveNow(); return extension; } finally { lock.unlock(); } } /** * Either adds extension as a new extension or replaces the existing extension if one already exists with the same * id. This also triggers wallet auto-saving, so may be useful even when called with the same extension as is * already present. */ public void addOrUpdateExtension(WalletExtension extension) { String id = checkNotNull(extension).getWalletExtensionID(); lock.lock(); try { extensions.put(id, extension); saveNow(); } finally { lock.unlock(); } } /** Returns a snapshot of all registered extension objects. The extensions themselves are not copied. */ public Map<String, WalletExtension> getExtensions() { lock.lock(); try { return ImmutableMap.copyOf(extensions); } finally { lock.unlock(); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Boilerplate for running event listeners - dispatches events onto the user code thread (where we don't do // anything and hold no locks). private void queueOnTransactionConfidenceChanged(final Transaction tx) { checkState(lock.isHeldByCurrentThread()); for (final ListenerRegistration<WalletEventListener> registration : eventListeners) { if (registration.executor == Threading.SAME_THREAD) { registration.listener.onTransactionConfidenceChanged(this, tx); } else { registration.executor.execute(new Runnable() { @Override public void run() { registration.listener.onTransactionConfidenceChanged(Wallet.this, tx); } }); } } } private void maybeQueueOnWalletChanged() { // Don't invoke the callback in some circumstances, eg, whilst we are re-organizing or fiddling with // transactions due to a new block arriving. It will be called later instead. checkState(lock.isHeldByCurrentThread()); checkState(onWalletChangedSuppressions >= 0); if (onWalletChangedSuppressions > 0) return; for (final ListenerRegistration<WalletEventListener> registration : eventListeners) { registration.executor.execute(new Runnable() { @Override public void run() { registration.listener.onWalletChanged(Wallet.this); } }); } } private void queueOnCoinsReceived(final Transaction tx, final BigInteger balance, final BigInteger newBalance) { checkState(lock.isHeldByCurrentThread()); for (final ListenerRegistration<WalletEventListener> registration : eventListeners) { registration.executor.execute(new Runnable() { @Override public void run() { registration.listener.onCoinsReceived(Wallet.this, tx, balance, newBalance); } }); } } private void queueOnCoinsSent(final Transaction tx, final BigInteger prevBalance, final BigInteger newBalance) { checkState(lock.isHeldByCurrentThread()); for (final ListenerRegistration<WalletEventListener> registration : eventListeners) { registration.executor.execute(new Runnable() { @Override public void run() { registration.listener.onCoinsSent(Wallet.this, tx, prevBalance, newBalance); } }); } } private void queueOnReorganize() { checkState(lock.isHeldByCurrentThread()); checkState(insideReorg); for (final ListenerRegistration<WalletEventListener> registration : eventListeners) { registration.executor.execute(new Runnable() { @Override public void run() { registration.listener.onReorganize(Wallet.this); } }); } } private void queueOnKeysAdded(final List<ECKey> keys) { checkState(lock.isHeldByCurrentThread()); for (final ListenerRegistration<WalletEventListener> registration : eventListeners) { registration.executor.execute(new Runnable() { @Override public void run() { registration.listener.onKeysAdded(Wallet.this, keys); } }); } } private void queueOnScriptsAdded(final List<Script> scripts) { checkState(lock.isHeldByCurrentThread()); for (final ListenerRegistration<WalletEventListener> registration : eventListeners) { registration.executor.execute(new Runnable() { @Override public void run() { registration.listener.onScriptsAdded(Wallet.this, scripts); } }); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Fee calculation code. private class FeeCalculation { private CoinSelection bestCoinSelection; private TransactionOutput bestChangeOutput; public FeeCalculation(SendRequest req, BigInteger value, List<TransactionInput> originalInputs, boolean needAtLeastReferenceFee, LinkedList<TransactionOutput> candidates) throws InsufficientMoneyException { checkState(lock.isHeldByCurrentThread()); // There are 3 possibilities for what adding change might do: // 1) No effect // 2) Causes increase in fee (change < 0.01 COINS) // 3) Causes the transaction to have a dust output or change < fee increase (ie change will be thrown away) // If we get either of the last 2, we keep note of what the inputs looked like at the time and try to // add inputs as we go up the list (keeping track of minimum inputs for each category). At the end, we pick // the best input set as the one which generates the lowest total fee. BigInteger additionalValueForNextCategory = null; CoinSelection selection3 = null; CoinSelection selection2 = null; TransactionOutput selection2Change = null; CoinSelection selection1 = null; TransactionOutput selection1Change = null; // We keep track of the last size of the transaction we calculated but only if the act of adding inputs and // change resulted in the size crossing a 1000 byte boundary. Otherwise it stays at zero. int lastCalculatedSize = 0; BigInteger valueNeeded, valueMissing = null; while (true) { resetTxInputs(req, originalInputs); BigInteger fees = req.fee == null ? BigInteger.ZERO : req.fee; if (lastCalculatedSize > 0) { // If the size is exactly 1000 bytes then we'll over-pay, but this should be rare. fees = fees.add(BigInteger.valueOf((lastCalculatedSize / 1000) + 1).multiply(req.feePerKb)); } else { fees = fees.add(req.feePerKb); // First time around the loop. } if (needAtLeastReferenceFee && fees.compareTo(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE) < 0) fees = Transaction.REFERENCE_DEFAULT_MIN_TX_FEE; valueNeeded = value.add(fees); if (additionalValueForNextCategory != null) valueNeeded = valueNeeded.add(additionalValueForNextCategory); BigInteger additionalValueSelected = additionalValueForNextCategory; // Of the coins we could spend, pick some that we actually will spend. CoinSelector selector = req.coinSelector == null ? coinSelector : req.coinSelector; CoinSelection selection = selector.select(valueNeeded, candidates); // Can we afford this? if (selection.valueGathered.compareTo(valueNeeded) < 0) { valueMissing = valueNeeded.subtract(selection.valueGathered); break; } checkState(selection.gathered.size() > 0 || originalInputs.size() > 0); // We keep track of an upper bound on transaction size to calculate fees that need to be added. // Note that the difference between the upper bound and lower bound is usually small enough that it // will be very rare that we pay a fee we do not need to. // // We can't be sure a selection is valid until we check fee per kb at the end, so we just store // them here temporarily. boolean eitherCategory2Or3 = false; boolean isCategory3 = false; BigInteger change = selection.valueGathered.subtract(valueNeeded); if (additionalValueSelected != null) change = change.add(additionalValueSelected); // If change is < 0.01 BTC, we will need to have at least minfee to be accepted by the network if (req.ensureMinRequiredFee && !change.equals(BigInteger.ZERO) && change.compareTo(Utils.CENT) < 0 && fees.compareTo(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE) < 0) { // This solution may fit into category 2, but it may also be category 3, we'll check that later eitherCategory2Or3 = true; additionalValueForNextCategory = Utils.CENT; // If the change is smaller than the fee we want to add, this will be negative change = change.subtract(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.subtract(fees)); } int size = 0; TransactionOutput changeOutput = null; if (change.compareTo(BigInteger.ZERO) > 0) { // The value of the inputs is greater than what we want to send. Just like in real life then, // we need to take back some coins ... this is called "change". Add another output that sends the change // back to us. The address comes either from the request or getChangeAddress() as a default. Address changeAddress = req.changeAddress; if (changeAddress == null) changeAddress = getChangeAddress(); changeOutput = new TransactionOutput(params, req.tx, change, changeAddress); // If the change output would result in this transaction being rejected as dust, just drop the change and make it a fee if (req.ensureMinRequiredFee && Transaction.MIN_NONDUST_OUTPUT.compareTo(change) >= 0) { // This solution definitely fits in category 3 isCategory3 = true; additionalValueForNextCategory = Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.add( Transaction.MIN_NONDUST_OUTPUT.add(BigInteger.ONE)); } else { size += changeOutput.bitcoinSerialize().length + VarInt.sizeOf(req.tx.getOutputs().size()) - VarInt.sizeOf(req.tx.getOutputs().size() - 1); // This solution is either category 1 or 2 if (!eitherCategory2Or3) // must be category 1 additionalValueForNextCategory = null; } } else { if (eitherCategory2Or3) { // This solution definitely fits in category 3 (we threw away change because it was smaller than MIN_TX_FEE) isCategory3 = true; additionalValueForNextCategory = Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.add(BigInteger.ONE); } } // Now add unsigned inputs for the selected coins. for (TransactionOutput output : selection.gathered) { TransactionInput input = req.tx.addInput(output); // If the scriptBytes don't default to none, our size calculations will be thrown off. checkState(input.getScriptBytes().length == 0); } // Estimate transaction size and loop again if we need more fee per kb. The serialized tx doesn't // include things we haven't added yet like input signatures/scripts or the change output. size += req.tx.bitcoinSerialize().length; size += estimateBytesForSigning(selection); if (size/1000 > lastCalculatedSize/1000 && req.feePerKb.compareTo(BigInteger.ZERO) > 0) { lastCalculatedSize = size; // We need more fees anyway, just try again with the same additional value additionalValueForNextCategory = additionalValueSelected; continue; } if (isCategory3) { if (selection3 == null) selection3 = selection; } else if (eitherCategory2Or3) { // If we are in selection2, we will require at least CENT additional. If we do that, there is no way // we can end up back here because CENT additional will always get us to 1 checkState(selection2 == null); checkState(additionalValueForNextCategory.equals(Utils.CENT)); selection2 = selection; selection2Change = checkNotNull(changeOutput); // If we get no change in category 2, we are actually in category 3 } else { // Once we get a category 1 (change kept), we should break out of the loop because we can't do better checkState(selection1 == null); checkState(additionalValueForNextCategory == null); selection1 = selection; selection1Change = changeOutput; } if (additionalValueForNextCategory != null) { if (additionalValueSelected != null) checkState(additionalValueForNextCategory.compareTo(additionalValueSelected) > 0); continue; } break; } resetTxInputs(req, originalInputs); if (selection3 == null && selection2 == null && selection1 == null) { checkNotNull(valueMissing); log.warn("Insufficient value in wallet for send: needed {} more", bitcoinValueToFriendlyString(valueMissing)); throw new InsufficientMoneyException(valueMissing); } BigInteger lowestFee = null; bestCoinSelection = null; bestChangeOutput = null; if (selection1 != null) { if (selection1Change != null) lowestFee = selection1.valueGathered.subtract(selection1Change.getValue()); else lowestFee = selection1.valueGathered; bestCoinSelection = selection1; bestChangeOutput = selection1Change; } if (selection2 != null) { BigInteger fee = selection2.valueGathered.subtract(checkNotNull(selection2Change).getValue()); if (lowestFee == null || fee.compareTo(lowestFee) < 0) { lowestFee = fee; bestCoinSelection = selection2; bestChangeOutput = selection2Change; } } if (selection3 != null) { if (lowestFee == null || selection3.valueGathered.compareTo(lowestFee) < 0) { bestCoinSelection = selection3; bestChangeOutput = null; } } } private void resetTxInputs(SendRequest req, List<TransactionInput> originalInputs) { req.tx.clearInputs(); for (TransactionInput input : originalInputs) req.tx.addInput(input); } } private int estimateBytesForSigning(CoinSelection selection) { int size = 0; for (TransactionOutput output : selection.gathered) { try { if (output.getScriptPubKey().isSentToAddress()) { // Send-to-address spends usually take maximum pubkey.length (as it may be compressed or not) + 75 bytes final ECKey key = findKeyFromPubHash(output.getScriptPubKey().getPubKeyHash()); size += checkNotNull(key, "Coin selection includes unspendable outputs").getPubKey().length + 75; } else if (output.getScriptPubKey().isSentToRawPubKey()) size += 74; // Send-to-pubkey spends usually take maximum 74 bytes to spend else throw new IllegalStateException("Unknown output type returned in coin selection"); } catch (ScriptException e) { // If this happens it means an output script in a wallet tx could not be understood. That should never // happen, if it does it means the wallet has got into an inconsistent state. throw new IllegalStateException(e); } } return size; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Managing wallet-triggered transaction broadcast and key rotation. /** * <p>Specifies that the given {@link TransactionBroadcaster}, typically a {@link PeerGroup}, should be used for * sending transactions to the Bitcoin network by default. Some sendCoins methods let you specify a broadcaster * explicitly, in that case, they don't use this broadcaster. If null is specified then the wallet won't attempt * to broadcast transactions itself.</p> * * <p>You don't normally need to call this. A {@link PeerGroup} will automatically set itself as the wallets * broadcaster when you use {@link PeerGroup#addWallet(Wallet)}. A wallet can use the broadcaster when you ask * it to send money, but in future also at other times to implement various features that may require asynchronous * re-organisation of the wallet contents on the block chain. For instance, in future the wallet may choose to * optimise itself to reduce fees or improve privacy.</p> */ public void setTransactionBroadcaster(@Nullable com.google.bitcoin.core.TransactionBroadcaster broadcaster) { Transaction[] toBroadcast = {}; lock.lock(); try { if (vTransactionBroadcaster == broadcaster) return; vTransactionBroadcaster = broadcaster; if (broadcaster == null) return; toBroadcast = pending.values().toArray(toBroadcast); } finally { lock.unlock(); } // Now use it to upload any pending transactions we have that are marked as not being seen by any peers yet. // Don't hold the wallet lock whilst doing this, so if the broadcaster accesses the wallet at some point there // is no inversion. for (Transaction tx : toBroadcast) { checkState(tx.getConfidence().getConfidenceType() == ConfidenceType.PENDING); // Re-broadcast even if it's marked as already seen for two reasons // 1) Old wallets may have transactions marked as broadcast by 1 peer when in reality the network // never saw it, due to bugs. // 2) It can't really hurt. log.info("New broadcaster so uploading waiting tx {}", tx.getHash()); broadcaster.broadcastTransaction(tx); } } /** * When a key rotation time is set, and money controlled by keys created before the given timestamp T will be * automatically respent to any key that was created after T. This can be used to recover from a situation where * a set of keys is believed to be compromised. Once the time is set transactions will be created and broadcast * immediately. New coins that come in after calling this method will be automatically respent immediately. The * rotation time is persisted to the wallet. You can stop key rotation by calling this method again with zero * as the argument. */ public void setKeyRotationTime(Date time) { setKeyRotationTime(time.getTime() / 1000); } /** * Returns a UNIX time since the epoch in seconds, or zero if unconfigured. */ public Date getKeyRotationTime() { return new Date(vKeyRotationTimestamp * 1000); } /** * <p>When a key rotation time is set, and money controlled by keys created before the given timestamp T will be * automatically respent to any key that was created after T. This can be used to recover from a situation where * a set of keys is believed to be compromised. Once the time is set transactions will be created and broadcast * immediately. New coins that come in after calling this method will be automatically respent immediately. The * rotation time is persisted to the wallet. You can stop key rotation by calling this method again with zero * as the argument, or by using {@link #setKeyRotationEnabled(boolean)}.</p> * * <p>Note that this method won't do anything unless you call {@link #setKeyRotationEnabled(boolean)} first.</p> */ public void setKeyRotationTime(long unixTimeSeconds) { vKeyRotationTimestamp = unixTimeSeconds; if (unixTimeSeconds > 0) { log.info("Key rotation time set: {}", unixTimeSeconds); maybeRotateKeys(); } saveNow(); } /** Toggles key rotation on and off. Note that this state is not serialized. Activating it can trigger tx sends. */ public void setKeyRotationEnabled(boolean enabled) { vKeyRotationEnabled = enabled; if (enabled) maybeRotateKeys(); } /** Returns whether the keys creation time is before the key rotation time, if one was set. */ public boolean isKeyRotating(ECKey key) { long time = vKeyRotationTimestamp; return time != 0 && key.getCreationTimeSeconds() < time; } // Checks to see if any coins are controlled by rotating keys and if so, spends them. private void maybeRotateKeys() { checkState(!lock.isHeldByCurrentThread()); // TODO: Handle chain replays and encrypted wallets here. if (!vKeyRotationEnabled) return; // Snapshot volatiles so this method has an atomic view. long keyRotationTimestamp = vKeyRotationTimestamp; if (keyRotationTimestamp == 0) return; // Nothing to do. TransactionBroadcaster broadcaster = vTransactionBroadcaster; // Because transactions are size limited, we might not be able to re-key the entire wallet in one go. So // loop around here until we no longer produce transactions with the max number of inputs. That means we're // fully done, at least for now (we may still get more transactions later and this method will be reinvoked). Transaction tx; do { tx = rekeyOneBatch(keyRotationTimestamp, broadcaster); } while (tx != null && tx.getInputs().size() == KeyTimeCoinSelector.MAX_SIMULTANEOUS_INPUTS); } @Nullable private Transaction rekeyOneBatch(long keyRotationTimestamp, final TransactionBroadcaster broadcaster) { final Transaction rekeyTx; lock.lock(); try { // Firstly, see if we have any keys that are beyond the rotation time, and any before. ECKey safeKey = null; boolean haveRotatingKeys = false; for (ECKey key : keychain) { final long t = key.getCreationTimeSeconds(); if (t < keyRotationTimestamp) { haveRotatingKeys = true; } else { safeKey = key; } } if (!haveRotatingKeys) return null; if (safeKey == null) { log.warn("Key rotation requested but no keys newer than the timestamp are available."); return null; } // Build the transaction using some custom logic for our special needs. Last parameter to // KeyTimeCoinSelector is whether to ignore pending transactions or not. // // We ignore pending outputs because trying to rotate these is basically racing an attacker, and // we're quite likely to lose and create stuck double spends. Also, some users who have 0.9 wallets // have already got stuck double spends in their wallet due to the Bloom-filtering block reordering // bug that was fixed in 0.10, thus, making a re-key transaction depend on those would cause it to // never confirm at all. CoinSelector selector = new KeyTimeCoinSelector(this, keyRotationTimestamp, true); CoinSelection toMove = selector.select(BigInteger.ZERO, calculateAllSpendCandidates(true)); if (toMove.valueGathered.equals(BigInteger.ZERO)) return null; // Nothing to do. rekeyTx = new Transaction(params); for (TransactionOutput output : toMove.gathered) { rekeyTx.addInput(output); } rekeyTx.addOutput(toMove.valueGathered, safeKey); if (!adjustOutputDownwardsForFee(rekeyTx, toMove, BigInteger.ZERO, Transaction.REFERENCE_DEFAULT_MIN_TX_FEE)) { log.error("Failed to adjust rekey tx for fees."); return null; } rekeyTx.getConfidence().setSource(TransactionConfidence.Source.SELF); rekeyTx.setPurpose(Transaction.Purpose.KEY_ROTATION); rekeyTx.signInputs(Transaction.SigHash.ALL, this); // KeyTimeCoinSelector should never select enough inputs to push us oversize. checkState(rekeyTx.bitcoinSerialize().length < Transaction.MAX_STANDARD_TX_SIZE); commitTx(rekeyTx); } catch (VerificationException e) { throw new RuntimeException(e); // Cannot happen. } finally { lock.unlock(); } if (broadcaster == null) return rekeyTx; log.info("Attempting to send key rotation tx: {}", rekeyTx); // We must broadcast the tx in a separate thread to avoid inverting any locks. Otherwise we may be running // with the blockchain lock held (whilst receiving a block) and thus re-entering the peerGroup would invert // blockchain <-> peergroup. new Thread() { @Override public void run() { // Handle the future results just for logging. try { Futures.addCallback(broadcaster.broadcastTransaction(rekeyTx), new FutureCallback<Transaction>() { @Override public void onSuccess(Transaction transaction) { log.info("Successfully broadcast key rotation tx: {}", transaction); } @Override public void onFailure(Throwable throwable) { log.error("Failed to broadcast key rotation tx", throwable); } }); } catch (Exception e) { log.error("Failed to broadcast rekey tx, will try again later", e); } } }.start(); return rekeyTx; } /** * Returns the wallet lock under which most operations happen. This is here to satisfy the * {@link com.google.bitcoin.core.PeerFilterProvider} interface and generally should not be used directly by apps. * In particular, do <b>not</b> hold this lock if you're display a send confirm screen to the user or for any other * long length of time, as it may cause processing holdups elsewhere. Instead, for the "confirm payment screen" * use case you should complete a candidate transaction, present it to the user (e.g. for fee purposes) and then * when they confirm - which may be quite some time later - recalculate the transaction and check if it's the same. * If not, redisplay the confirm window and try again. */ public ReentrantLock getLock() { return lock; } }
core/src/main/java/com/google/bitcoin/core/Wallet.java
/** * Copyright 2013 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.bitcoin.core; import com.google.bitcoin.core.TransactionConfidence.ConfidenceType; import com.google.bitcoin.crypto.KeyCrypter; import com.google.bitcoin.crypto.KeyCrypterException; import com.google.bitcoin.crypto.KeyCrypterScrypt; import com.google.bitcoin.script.Script; import com.google.bitcoin.script.ScriptBuilder; import com.google.bitcoin.script.ScriptChunk; import com.google.bitcoin.store.UnreadableWalletException; import com.google.bitcoin.store.WalletProtobufSerializer; import com.google.bitcoin.utils.ListenerRegistration; import com.google.bitcoin.utils.Threading; import com.google.bitcoin.wallet.*; import com.google.bitcoin.wallet.WalletTransaction.Pool; import com.google.common.collect.*; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import org.bitcoinj.wallet.Protos.Wallet.EncryptionType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.crypto.params.KeyParameter; import org.spongycastle.util.encoders.Hex; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import static com.google.bitcoin.core.Utils.bitcoinValueToFriendlyString; import static com.google.bitcoin.core.Utils.bitcoinValueToPlainString; import static com.google.common.base.Preconditions.*; // To do list: // // This whole class has evolved over a period of years and needs a ground-up rewrite. // // - Take all wallet-relevant data out of Transaction and put it into WalletTransaction. Make Transaction immutable. // - Only store relevant transaction outputs, don't bother storing the rest of the data. // - Split block chain and tx output tracking into a superclass that doesn't have any key or spending related code. // - Simplify how transactions are tracked and stored: in particular, have the wallet maintain positioning information // for transactions independent of the transactions themselves, so the timeline can be walked without having to // process and sort every single transaction. // - Decompose the class where possible: break logic out into classes that can be customized/replaced by the user. // - [Auto]saving to a backing store // - Key management // - just generally make Wallet smaller and easier to work with // - Make clearing of transactions able to only rewind the wallet a certain distance instead of all blocks. // - Make it scale: // - eliminate all the algorithms with quadratic complexity (or worse) // - don't require everything to be held in RAM at once // - consider allowing eviction of no longer re-orgable transactions or keys that were used up /** * <p>A Wallet stores keys and a record of transactions that send and receive value from those keys. Using these, * it is able to create new transactions that spend the recorded transactions, and this is the fundamental operation * of the Bitcoin protocol.</p> * * <p>To learn more about this class, read <b><a href="http://code.google.com/p/bitcoinj/wiki/WorkingWithTheWallet"> * working with the wallet.</a></b></p> * * <p>To fill up a Wallet with transactions, you need to use it in combination with a {@link BlockChain} and various * other objects, see the <a href="http://code.google.com/p/bitcoinj/wiki/GettingStarted">Getting started</a> tutorial * on the website to learn more about how to set everything up.</p> * * <p>Wallets can be serialized using either Java serialization - this is not compatible across versions of bitcoinj, * or protocol buffer serialization. You need to save the wallet whenever it changes, there is an auto-save feature * that simplifies this for you although you're still responsible for manually triggering a save when your app is about * to quit because the auto-save feature waits a moment before actually committing to disk to avoid IO thrashing when * the wallet is changing very fast (eg due to a block chain sync). See * {@link Wallet#autosaveToFile(java.io.File, long, java.util.concurrent.TimeUnit, com.google.bitcoin.wallet.WalletFiles.Listener)} * for more information about this.</p> */ public class Wallet implements Serializable, BlockChainListener, PeerFilterProvider { private static final Logger log = LoggerFactory.getLogger(Wallet.class); private static final long serialVersionUID = 2L; private static final int MINIMUM_BLOOM_DATA_LENGTH = 8; protected final ReentrantLock lock = Threading.lock("wallet"); // The various pools below give quick access to wallet-relevant transactions by the state they're in: // // Pending: Transactions that didn't make it into the best chain yet. Pending transactions can be killed if a // double-spend against them appears in the best chain, in which case they move to the dead pool. // If a double-spend appears in the pending state as well, currently we just ignore the second // and wait for the miners to resolve the race. // Unspent: Transactions that appeared in the best chain and have outputs we can spend. Note that we store the // entire transaction in memory even though for spending purposes we only really need the outputs, the // reason being that this simplifies handling of re-orgs. It would be worth fixing this in future. // Spent: Transactions that appeared in the best chain but don't have any spendable outputs. They're stored here // for history browsing/auditing reasons only and in future will probably be flushed out to some other // kind of cold storage or just removed. // Dead: Transactions that we believe will never confirm get moved here, out of pending. Note that the Satoshi // client has no notion of dead-ness: the assumption is that double spends won't happen so there's no // need to notify the user about them. We take a more pessimistic approach and try to track the fact that // transactions have been double spent so applications can do something intelligent (cancel orders, show // to the user in the UI, etc). A transaction can leave dead and move into spent/unspent if there is a // re-org to a chain that doesn't include the double spend. final Map<Sha256Hash, Transaction> pending; final Map<Sha256Hash, Transaction> unspent; final Map<Sha256Hash, Transaction> spent; final Map<Sha256Hash, Transaction> dead; // All transactions together. final Map<Sha256Hash, Transaction> transactions; // A list of public/private EC keys owned by this user. Access it using addKey[s], hasKey[s] and findPubKeyFromHash. private ArrayList<ECKey> keychain; // A list of scripts watched by this wallet. private Set<Script> watchedScripts; private final NetworkParameters params; @Nullable private Sha256Hash lastBlockSeenHash; private int lastBlockSeenHeight; private long lastBlockSeenTimeSecs; private transient CopyOnWriteArrayList<ListenerRegistration<WalletEventListener>> eventListeners; // A listener that relays confidence changes from the transaction confidence object to the wallet event listener, // as a convenience to API users so they don't have to register on every transaction themselves. private transient TransactionConfidence.Listener txConfidenceListener; // If a TX hash appears in this set then notifyNewBestBlock will ignore it, as its confidence was already set up // in receive() via Transaction.setBlockAppearance(). As the BlockChain always calls notifyNewBestBlock even if // it sent transactions to the wallet, without this we'd double count. private transient HashSet<Sha256Hash> ignoreNextNewBlock; // Whether or not to ignore nLockTime > 0 transactions that are received to the mempool. private boolean acceptRiskyTransactions; // Stuff for notifying transaction objects that we changed their confidences. The purpose of this is to avoid // spuriously sending lots of repeated notifications to listeners that API users aren't really interested in as a // side effect of how the code is written (e.g. during re-orgs confidence data gets adjusted multiple times). private int onWalletChangedSuppressions; private boolean insideReorg; private Map<Transaction, TransactionConfidence.Listener.ChangeReason> confidenceChanged; private volatile WalletFiles vFileManager; // Object that is used to send transactions asynchronously when the wallet requires it. private volatile TransactionBroadcaster vTransactionBroadcaster; // UNIX time in seconds. Money controlled by keys created before this time will be automatically respent to a key // that was created after it. Useful when you believe some keys have been compromised. private volatile long vKeyRotationTimestamp; private volatile boolean vKeyRotationEnabled; private transient CoinSelector coinSelector = new DefaultCoinSelector(); // The keyCrypter for the wallet. This specifies the algorithm used for encrypting and decrypting the private keys. private KeyCrypter keyCrypter; // The wallet version. This is an int that can be used to track breaking changes in the wallet format. // You can also use it to detect wallets that come from the future (ie they contain features you // do not know how to deal with). private int version; // User-provided description that may help people keep track of what a wallet is for. private String description; // Stores objects that know how to serialize/unserialize themselves to byte streams and whether they're mandatory // or not. The string key comes from the extension itself. private final HashMap<String, WalletExtension> extensions; // Object that performs risk analysis of received pending transactions. We might reject transactions that seem like // a high risk of being a double spending attack. private RiskAnalysis.Analyzer riskAnalyzer = DefaultRiskAnalysis.FACTORY; /** * Creates a new, empty wallet with no keys and no transactions. If you want to restore a wallet from disk instead, * see loadFromFile. */ public Wallet(NetworkParameters params) { this.params = checkNotNull(params); keychain = new ArrayList<ECKey>(); watchedScripts = Sets.newHashSet(); unspent = new HashMap<Sha256Hash, Transaction>(); spent = new HashMap<Sha256Hash, Transaction>(); pending = new HashMap<Sha256Hash, Transaction>(); dead = new HashMap<Sha256Hash, Transaction>(); transactions = new HashMap<Sha256Hash, Transaction>(); eventListeners = new CopyOnWriteArrayList<ListenerRegistration<WalletEventListener>>(); extensions = new HashMap<String, WalletExtension>(); confidenceChanged = new HashMap<Transaction, TransactionConfidence.Listener.ChangeReason>(); createTransientState(); } /** * Create a wallet with a keyCrypter to use in encrypting and decrypting keys. */ public Wallet(NetworkParameters params, KeyCrypter keyCrypter) { this(params); this.keyCrypter = checkNotNull(keyCrypter); } private void createTransientState() { ignoreNextNewBlock = new HashSet<Sha256Hash>(); txConfidenceListener = new TransactionConfidence.Listener() { @Override public void onConfidenceChanged(Transaction tx, TransactionConfidence.Listener.ChangeReason reason) { // This will run on the user code thread so we shouldn't do anything too complicated here. // We only want to queue a wallet changed event and auto-save if the number of peers announcing // the transaction has changed, as that confidence change is made by the networking code which // doesn't necessarily know at that point which wallets contain which transactions, so it's up // to us to listen for that. Other types of confidence changes (type, etc) are triggered by us, // so we'll queue up a wallet change event in other parts of the code. if (reason == ChangeReason.SEEN_PEERS) { lock.lock(); try { checkBalanceFuturesLocked(null); queueOnTransactionConfidenceChanged(tx); maybeQueueOnWalletChanged(); } finally { lock.unlock(); } } } }; acceptRiskyTransactions = false; } public NetworkParameters getNetworkParameters() { return params; } /** * Returns a snapshot of the keychain. This view is not live. */ public List<ECKey> getKeys() { lock.lock(); try { return new ArrayList<ECKey>(keychain); } finally { lock.unlock(); } } /** * Returns a snapshot of the watched scripts. This view is not live. */ public List<Script> getWatchedScripts() { lock.lock(); try { return new ArrayList<Script>(watchedScripts); } finally { lock.unlock(); } } /** * Removes the given key from the keychain. Be very careful with this - losing a private key <b>destroys the * money associated with it</b>. * @return Whether the key was removed or not. */ public boolean removeKey(ECKey key) { lock.lock(); try { return keychain.remove(key); } finally { lock.unlock(); } } /** * Returns the number of keys in the keychain. */ public int getKeychainSize() { lock.lock(); try { return keychain.size(); } finally { lock.unlock(); } } /** Saves the wallet first to the given temp file, then renames to the dest file. */ public void saveToFile(File temp, File destFile) throws IOException { FileOutputStream stream = null; lock.lock(); try { stream = new FileOutputStream(temp); saveToFileStream(stream); // Attempt to force the bits to hit the disk. In reality the OS or hard disk itself may still decide // to not write through to physical media for at least a few seconds, but this is the best we can do. stream.flush(); stream.getFD().sync(); stream.close(); stream = null; if (Utils.isWindows()) { // Work around an issue on Windows whereby you can't rename over existing files. File canonical = destFile.getCanonicalFile(); if (!canonical.delete()) throw new IOException("Failed to delete canonical wallet file for replacement with autosave"); if (temp.renameTo(canonical)) return; // else fall through. throw new IOException("Failed to rename " + temp + " to " + canonical); } else if (!temp.renameTo(destFile)) { throw new IOException("Failed to rename " + temp + " to " + destFile); } } catch (RuntimeException e) { log.error("Failed whilst saving wallet", e); throw e; } finally { lock.unlock(); if (stream != null) { stream.close(); } if (temp.exists()) { log.warn("Temp file still exists after failed save."); } } } /** * Uses protobuf serialization to save the wallet to the given file. To learn more about this file format, see * {@link WalletProtobufSerializer}. Writes out first to a temporary file in the same directory and then renames * once written. */ public void saveToFile(File f) throws IOException { File directory = f.getAbsoluteFile().getParentFile(); File temp = File.createTempFile("wallet", null, directory); saveToFile(temp, f); } /** * <p>Whether or not the wallet will ignore received pending transactions that fail the selected * {@link RiskAnalysis}. By default, if a transaction is considered risky then it won't enter the wallet * and won't trigger any event listeners. If you set this property to true, then all transactions will * be allowed in regardless of risk. Currently, the {@link DefaultRiskAnalysis} checks for non-finality of * transactions. You should not encounter these outside of special protocols.</p> * * <p>Note that this property is not serialized. You have to set it each time a Wallet object is constructed, * even if it's loaded from a protocol buffer.</p> */ public void setAcceptRiskyTransactions(boolean acceptRiskyTransactions) { lock.lock(); try { this.acceptRiskyTransactions = acceptRiskyTransactions; } finally { lock.unlock(); } } /** * See {@link Wallet#setAcceptRiskyTransactions(boolean)} for an explanation of this property. */ public boolean doesAcceptRiskyTransactions() { lock.lock(); try { return acceptRiskyTransactions; } finally { lock.unlock(); } } /** * Sets the {@link RiskAnalysis} implementation to use for deciding whether received pending transactions are risky * or not. If the analyzer says a transaction is risky, by default it will be dropped. You can customize this * behaviour with {@link #setAcceptRiskyTransactions(boolean)}. */ public void setRiskAnalyzer(RiskAnalysis.Analyzer analyzer) { lock.lock(); try { this.riskAnalyzer = checkNotNull(analyzer); } finally { lock.unlock(); } } /** * Gets the current {@link RiskAnalysis} implementation. The default is {@link DefaultRiskAnalysis}. */ public RiskAnalysis.Analyzer getRiskAnalyzer() { lock.lock(); try { return riskAnalyzer; } finally { lock.unlock(); } } /** * <p>Sets up the wallet to auto-save itself to the given file, using temp files with atomic renames to ensure * consistency. After connecting to a file, you no longer need to save the wallet manually, it will do it * whenever necessary. Protocol buffer serialization will be used.</p> * * <p>If delayTime is set, a background thread will be created and the wallet will only be saved to * disk every so many time units. If no changes have occurred for the given time period, nothing will be written. * In this way disk IO can be rate limited. It's a good idea to set this as otherwise the wallet can change very * frequently, eg if there are a lot of transactions in it or during block sync, and there will be a lot of redundant * writes. Note that when a new key is added, that always results in an immediate save regardless of * delayTime. <b>You should still save the wallet manually when your program is about to shut down as the JVM * will not wait for the background thread.</b></p> * * <p>An event listener can be provided. If a delay >0 was specified, it will be called on a background thread * with the wallet locked when an auto-save occurs. If delay is zero or you do something that always triggers * an immediate save, like adding a key, the event listener will be invoked on the calling threads.</p> * * @param f The destination file to save to. * @param delayTime How many time units to wait until saving the wallet on a background thread. * @param timeUnit the unit of measurement for delayTime. * @param eventListener callback to be informed when the auto-save thread does things, or null */ public WalletFiles autosaveToFile(File f, long delayTime, TimeUnit timeUnit, @Nullable WalletFiles.Listener eventListener) { lock.lock(); try { checkState(vFileManager == null, "Already auto saving this wallet."); WalletFiles manager = new WalletFiles(this, f, delayTime, timeUnit); if (eventListener != null) manager.setListener(eventListener); vFileManager = manager; return manager; } finally { lock.unlock(); } } /** * <p> * Disables auto-saving, after it had been enabled with * {@link Wallet#autosaveToFile(java.io.File, long, java.util.concurrent.TimeUnit, com.google.bitcoin.wallet.WalletFiles.Listener)} * before. This method blocks until finished. * </p> */ public void shutdownAutosaveAndWait() { lock.lock(); try { WalletFiles files = vFileManager; vFileManager = null; checkState(files != null, "Auto saving not enabled."); files.shutdownAndWait(); } finally { lock.unlock(); } } private void saveLater() { WalletFiles files = vFileManager; if (files != null) files.saveLater(); } /** If auto saving is enabled, do an immediate sync write to disk ignoring any delays. */ private void saveNow() { WalletFiles files = vFileManager; if (files != null) { try { files.saveNow(); // This calls back into saveToFile(). } catch (IOException e) { // Can't really do much at this point, just let the API user know. log.error("Failed to save wallet to disk!", e); Thread.UncaughtExceptionHandler handler = Threading.uncaughtExceptionHandler; if (handler != null) handler.uncaughtException(Thread.currentThread(), e); } } } /** * Uses protobuf serialization to save the wallet to the given file stream. To learn more about this file format, see * {@link WalletProtobufSerializer}. */ public void saveToFileStream(OutputStream f) throws IOException { lock.lock(); try { new WalletProtobufSerializer().writeWallet(this, f); } finally { lock.unlock(); } } /** Returns the parameters this wallet was created with. */ public NetworkParameters getParams() { return params; } /** * Returns a wallet deserialized from the given file. */ public static Wallet loadFromFile(File f) throws UnreadableWalletException { try { FileInputStream stream = null; try { stream = new FileInputStream(f); return loadFromFileStream(stream); } finally { if (stream != null) stream.close(); } } catch (IOException e) { throw new UnreadableWalletException("Could not open file", e); } } public boolean isConsistent() { lock.lock(); try { boolean success = true; Set<Transaction> transactions = getTransactions(true); Set<Sha256Hash> hashes = new HashSet<Sha256Hash>(); for (Transaction tx : transactions) { hashes.add(tx.getHash()); } int size1 = transactions.size(); if (size1 != hashes.size()) { log.error("Two transactions with same hash"); success = false; } int size2 = unspent.size() + spent.size() + pending.size() + dead.size(); if (size1 != size2) { log.error("Inconsistent wallet sizes: {} {}", size1, size2); success = false; } for (Transaction tx : unspent.values()) { if (!tx.isConsistent(this, false)) { success = false; log.error("Inconsistent unspent tx {}", tx.getHashAsString()); } } for (Transaction tx : spent.values()) { if (!tx.isConsistent(this, true)) { success = false; log.error("Inconsistent spent tx {}", tx.getHashAsString()); } } if (!success) { try { log.error(toString()); } catch (RuntimeException x) { log.error("Printing inconsistent wallet failed", x); } } return success; } finally { lock.unlock(); } } /** * Returns a wallet deserialized from the given input stream. */ public static Wallet loadFromFileStream(InputStream stream) throws UnreadableWalletException { Wallet wallet = new WalletProtobufSerializer().readWallet(stream); if (!wallet.isConsistent()) { log.error("Loaded an inconsistent wallet"); } return wallet; } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); createTransientState(); } /** * Called by the {@link BlockChain} when we receive a new filtered block that contains a transactions previously * received by a call to @{link receivePending}.<p> * * This is necessary for the internal book-keeping Wallet does. When a transaction is received that sends us * coins it is added to a pool so we can use it later to create spends. When a transaction is received that * consumes outputs they are marked as spent so they won't be used in future.<p> * * A transaction that spends our own coins can be received either because a spend we created was accepted by the * network and thus made it into a block, or because our keys are being shared between multiple instances and * some other node spent the coins instead. We still have to know about that to avoid accidentally trying to * double spend.<p> * * A transaction may be received multiple times if is included into blocks in parallel chains. The blockType * parameter describes whether the containing block is on the main/best chain or whether it's on a presently * inactive side chain. We must still record these transactions and the blocks they appear in because a future * block might change which chain is best causing a reorganize. A re-org can totally change our balance! */ public void notifyTransactionIsInBlock(Sha256Hash txHash, StoredBlock block, BlockChain.NewBlockType blockType, int relativityOffset) throws VerificationException { lock.lock(); try { Transaction tx = transactions.get(txHash); if (tx == null) { log.error("TX {} not found despite being sent to wallet", txHash); return; } receive(tx, block, blockType, relativityOffset); } finally { lock.unlock(); } if (blockType == AbstractBlockChain.NewBlockType.BEST_CHAIN) { // If some keys are considered to be bad, possibly move money assigned to them now. // This has to run outside the wallet lock as it may trigger broadcasting of new transactions. maybeRotateKeys(); } } /** * <p>Called when we have found a transaction (via network broadcast or otherwise) that is relevant to this wallet * and want to record it. Note that we <b>cannot verify these transactions at all</b>, they may spend fictional * coins or be otherwise invalid. They are useful to inform the user about coins they can expect to receive soon, * and if you trust the sender of the transaction you can choose to assume they are in fact valid and will not * be double spent as an optimization.</p> * * <p>This is the same as {@link Wallet#receivePending(Transaction, java.util.List)} but allows you to override the * {@link Wallet#isPendingTransactionRelevant(Transaction)} sanity-check to keep track of transactions that are not * spendable or spend our coins. This can be useful when you want to keep track of transaction confidence on * arbitrary transactions. Note that transactions added in this way will still be relayed to peers and appear in * transaction lists like any other pending transaction (even when not relevant).</p> */ public void receivePending(Transaction tx, @Nullable List<Transaction> dependencies, boolean overrideIsRelevant) throws VerificationException { // Can run in a peer thread. This method will only be called if a prior call to isPendingTransactionRelevant // returned true, so we already know by this point that it sends coins to or from our wallet, or is a double // spend against one of our other pending transactions. lock.lock(); try { tx.verify(); // Ignore it if we already know about this transaction. Receiving a pending transaction never moves it // between pools. EnumSet<Pool> containingPools = getContainingPools(tx); if (!containingPools.equals(EnumSet.noneOf(Pool.class))) { log.debug("Received tx we already saw in a block or created ourselves: " + tx.getHashAsString()); return; } // Repeat the check of relevancy here, even though the caller may have already done so - this is to avoid // race conditions where receivePending may be being called in parallel. if (!overrideIsRelevant && !isPendingTransactionRelevant(tx)) return; if (isTransactionRisky(tx, dependencies) && !acceptRiskyTransactions) return; BigInteger valueSentToMe = tx.getValueSentToMe(this); BigInteger valueSentFromMe = tx.getValueSentFromMe(this); if (log.isInfoEnabled()) { log.info(String.format("Received a pending transaction %s that spends %s BTC from our own wallet," + " and sends us %s BTC", tx.getHashAsString(), Utils.bitcoinValueToFriendlyString(valueSentFromMe), Utils.bitcoinValueToFriendlyString(valueSentToMe))); } if (tx.getConfidence().getSource().equals(TransactionConfidence.Source.UNKNOWN)) { log.warn("Wallet received transaction with an unknown source. Consider tagging it!"); } // If this tx spends any of our unspent outputs, mark them as spent now, then add to the pending pool. This // ensures that if some other client that has our keys broadcasts a spend we stay in sync. Also updates the // timestamp on the transaction and registers/runs event listeners. commitTx(tx); } finally { lock.unlock(); } // maybeRotateKeys() will ignore pending transactions so we don't bother calling it here (see the comments // in that function for an explanation of why). } /** * Given a transaction and an optional list of dependencies (recursive/flattened), returns true if the given * transaction would be rejected by the analyzer, or false otherwise. The result of this call is independent * of the value of {@link #doesAcceptRiskyTransactions()}. Risky transactions yield a logged warning. If you * want to know the reason why a transaction is risky, create an instance of the {@link RiskAnalysis} yourself * using the factory returned by {@link #getRiskAnalyzer()} and use it directly. */ public boolean isTransactionRisky(Transaction tx, @Nullable List<Transaction> dependencies) { lock.lock(); try { if (dependencies == null) dependencies = ImmutableList.of(); RiskAnalysis analysis = riskAnalyzer.create(this, tx, dependencies); RiskAnalysis.Result result = analysis.analyze(); if (result != RiskAnalysis.Result.OK) { log.warn("Pending transaction {} was considered risky: {}", tx.getHashAsString(), analysis); return true; } return false; } finally { lock.unlock(); } } /** * <p>Called when we have found a transaction (via network broadcast or otherwise) that is relevant to this wallet * and want to record it. Note that we <b>cannot verify these transactions at all</b>, they may spend fictional * coins or be otherwise invalid. They are useful to inform the user about coins they can expect to receive soon, * and if you trust the sender of the transaction you can choose to assume they are in fact valid and will not * be double spent as an optimization.</p> * * <p>Before this method is called, {@link Wallet#isPendingTransactionRelevant(Transaction)} should have been * called to decide whether the wallet cares about the transaction - if it does, then this method expects the * transaction and any dependencies it has which are still in the memory pool.</p> */ public void receivePending(Transaction tx, @Nullable List<Transaction> dependencies) throws VerificationException { receivePending(tx, dependencies, false); } /** * This method is used by a {@link Peer} to find out if a transaction that has been announced is interesting, * that is, whether we should bother downloading its dependencies and exploring the transaction to decide how * risky it is. If this method returns true then {@link Wallet#receivePending(Transaction, java.util.List)} * will soon be called with the transactions dependencies as well. */ public boolean isPendingTransactionRelevant(Transaction tx) throws ScriptException { lock.lock(); try { // Ignore it if we already know about this transaction. Receiving a pending transaction never moves it // between pools. EnumSet<Pool> containingPools = getContainingPools(tx); if (!containingPools.equals(EnumSet.noneOf(Pool.class))) { log.debug("Received tx we already saw in a block or created ourselves: " + tx.getHashAsString()); return false; } // We only care about transactions that: // - Send us coins // - Spend our coins if (!isTransactionRelevant(tx)) { log.debug("Received tx that isn't relevant to this wallet, discarding."); return false; } if (isTransactionRisky(tx, null) && !acceptRiskyTransactions) { log.warn("Received transaction {} with a lock time of {}, but not configured to accept these, discarding", tx.getHashAsString(), tx.getLockTime()); return false; } return true; } finally { lock.unlock(); } } /** * <p>Returns true if the given transaction sends coins to any of our keys, or has inputs spending any of our outputs, * and if includeDoubleSpending is true, also returns true if tx has inputs that are spending outputs which are * not ours but which are spent by pending transactions.</p> * * <p>Note that if the tx has inputs containing one of our keys, but the connected transaction is not in the wallet, * it will not be considered relevant.</p> */ public boolean isTransactionRelevant(Transaction tx) throws ScriptException { lock.lock(); try { return tx.getValueSentFromMe(this).compareTo(BigInteger.ZERO) > 0 || tx.getValueSentToMe(this).compareTo(BigInteger.ZERO) > 0 || checkForDoubleSpendAgainstPending(tx, false); } finally { lock.unlock(); } } /** * Checks if "tx" is spending any inputs of pending transactions. Not a general check, but it can work even if * the double spent inputs are not ours. Returns the pending tx that was double spent or null if none found. */ private boolean checkForDoubleSpendAgainstPending(Transaction tx, boolean takeAction) { checkState(lock.isHeldByCurrentThread()); // Compile a set of outpoints that are spent by tx. HashSet<TransactionOutPoint> outpoints = new HashSet<TransactionOutPoint>(); for (TransactionInput input : tx.getInputs()) { outpoints.add(input.getOutpoint()); } // Now for each pending transaction, see if it shares any outpoints with this tx. LinkedList<Transaction> doubleSpentTxns = Lists.newLinkedList(); for (Transaction p : pending.values()) { for (TransactionInput input : p.getInputs()) { // This relies on the fact that TransactionOutPoint equality is defined at the protocol not object // level - outpoints from two different inputs that point to the same output compare the same. TransactionOutPoint outpoint = input.getOutpoint(); if (outpoints.contains(outpoint)) { // It does, it's a double spend against the pending pool, which makes it relevant. if (!doubleSpentTxns.isEmpty() && doubleSpentTxns.getLast() == p) continue; doubleSpentTxns.add(p); } } } if (takeAction && !doubleSpentTxns.isEmpty()) { killTx(tx, doubleSpentTxns); } return !doubleSpentTxns.isEmpty(); } /** * Called by the {@link BlockChain} when we receive a new block that sends coins to one of our addresses or * spends coins from one of our addresses (note that a single transaction can do both).<p> * * This is necessary for the internal book-keeping Wallet does. When a transaction is received that sends us * coins it is added to a pool so we can use it later to create spends. When a transaction is received that * consumes outputs they are marked as spent so they won't be used in future.<p> * * A transaction that spends our own coins can be received either because a spend we created was accepted by the * network and thus made it into a block, or because our keys are being shared between multiple instances and * some other node spent the coins instead. We still have to know about that to avoid accidentally trying to * double spend.<p> * * A transaction may be received multiple times if is included into blocks in parallel chains. The blockType * parameter describes whether the containing block is on the main/best chain or whether it's on a presently * inactive side chain. We must still record these transactions and the blocks they appear in because a future * block might change which chain is best causing a reorganize. A re-org can totally change our balance! */ @Override public void receiveFromBlock(Transaction tx, StoredBlock block, BlockChain.NewBlockType blockType, int relativityOffset) throws VerificationException { lock.lock(); try { receive(tx, block, blockType, relativityOffset); } finally { lock.unlock(); } if (blockType == AbstractBlockChain.NewBlockType.BEST_CHAIN) { // If some keys are considered to be bad, possibly move money assigned to them now. // This has to run outside the wallet lock as it may trigger broadcasting of new transactions. maybeRotateKeys(); } } private void receive(Transaction tx, StoredBlock block, BlockChain.NewBlockType blockType, int relativityOffset) throws VerificationException { // Runs in a peer thread. checkState(lock.isHeldByCurrentThread()); BigInteger prevBalance = getBalance(); Sha256Hash txHash = tx.getHash(); boolean bestChain = blockType == BlockChain.NewBlockType.BEST_CHAIN; boolean sideChain = blockType == BlockChain.NewBlockType.SIDE_CHAIN; BigInteger valueSentFromMe = tx.getValueSentFromMe(this); BigInteger valueSentToMe = tx.getValueSentToMe(this); BigInteger valueDifference = valueSentToMe.subtract(valueSentFromMe); log.info("Received tx{} for {} BTC: {} [{}] in block {}", sideChain ? " on a side chain" : "", bitcoinValueToFriendlyString(valueDifference), tx.getHashAsString(), relativityOffset, block != null ? block.getHeader().getHash() : "(unit test)"); onWalletChangedSuppressions++; // If this transaction is already in the wallet we may need to move it into a different pool. At the very // least we need to ensure we're manipulating the canonical object rather than a duplicate. { Transaction tmp = transactions.get(tx.getHash()); if (tmp != null) tx = tmp; } boolean wasPending = pending.remove(txHash) != null; if (wasPending) log.info(" <-pending"); if (bestChain) { if (wasPending) { // Was pending and is now confirmed. Disconnect the outputs in case we spent any already: they will be // re-connected by processTxFromBestChain below. for (TransactionOutput output : tx.getOutputs()) { final TransactionInput spentBy = output.getSpentBy(); if (spentBy != null) spentBy.disconnect(); } } processTxFromBestChain(tx, wasPending); } else { checkState(sideChain); // Transactions that appear in a side chain will have that appearance recorded below - we assume that // some miners are also trying to include the transaction into the current best chain too, so let's treat // it as pending, except we don't need to do any risk analysis on it. if (wasPending) { // Just put it back in without touching the connections or confidence. addWalletTransaction(Pool.PENDING, tx); log.info(" ->pending"); } else { // Ignore the case where a tx appears on a side chain at the same time as the best chain (this is // quite normal and expected). Sha256Hash hash = tx.getHash(); if (!unspent.containsKey(hash) && !spent.containsKey(hash)) { // Otherwise put it (possibly back) into pending. // Committing it updates the spent flags and inserts into the pool as well. commitTx(tx); } } } if (block != null) { // Mark the tx as appearing in this block so we can find it later after a re-org. This also tells the tx // confidence object about the block and sets its work done/depth appropriately. tx.setBlockAppearance(block, bestChain, relativityOffset); if (bestChain) { // Don't notify this tx of work done in notifyNewBestBlock which will be called immediately after // this method has been called by BlockChain for all relevant transactions. Otherwise we'd double // count. ignoreNextNewBlock.add(txHash); } } onWalletChangedSuppressions--; // Side chains don't affect confidence. if (bestChain) { // notifyNewBestBlock will be invoked next and will then call maybeQueueOnWalletChanged for us. confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.TYPE); } else { maybeQueueOnWalletChanged(); } // Inform anyone interested that we have received or sent coins but only if: // - This is not due to a re-org. // - The coins appeared on the best chain. // - We did in fact receive some new money. // - We have not already informed the user about the coins when we received the tx broadcast, or for our // own spends. If users want to know when a broadcast tx becomes confirmed, they need to use tx confidence // listeners. if (!insideReorg && bestChain) { BigInteger newBalance = getBalance(); // This is slow. log.info("Balance is now: " + bitcoinValueToFriendlyString(newBalance)); if (!wasPending) { int diff = valueDifference.compareTo(BigInteger.ZERO); // We pick one callback based on the value difference, though a tx can of course both send and receive // coins from the wallet. if (diff > 0) { queueOnCoinsReceived(tx, prevBalance, newBalance); } else if (diff < 0) { queueOnCoinsSent(tx, prevBalance, newBalance); } } checkBalanceFuturesLocked(newBalance); } informConfidenceListenersIfNotReorganizing(); checkState(isConsistent()); saveNow(); } private void informConfidenceListenersIfNotReorganizing() { if (insideReorg) return; for (Map.Entry<Transaction, TransactionConfidence.Listener.ChangeReason> entry : confidenceChanged.entrySet()) { final Transaction tx = entry.getKey(); tx.getConfidence().queueListeners(entry.getValue()); queueOnTransactionConfidenceChanged(tx); } confidenceChanged.clear(); } /** * <p>Called by the {@link BlockChain} when a new block on the best chain is seen, AFTER relevant wallet * transactions are extracted and sent to us UNLESS the new block caused a re-org, in which case this will * not be called (the {@link Wallet#reorganize(StoredBlock, java.util.List, java.util.List)} method will * call this one in that case).</p> * <p/> * <p>Used to update confidence data in each transaction and last seen block hash. Triggers auto saving. * Invokes the onWalletChanged event listener if there were any affected transactions.</p> */ public void notifyNewBestBlock(StoredBlock block) throws VerificationException { // Check to see if this block has been seen before. Sha256Hash newBlockHash = block.getHeader().getHash(); if (newBlockHash.equals(getLastBlockSeenHash())) return; lock.lock(); try { // Store the new block hash. setLastBlockSeenHash(newBlockHash); setLastBlockSeenHeight(block.getHeight()); setLastBlockSeenTimeSecs(block.getHeader().getTimeSeconds()); // TODO: Clarify the code below. // Notify all the BUILDING transactions of the new block. // This is so that they can update their work done and depth. Set<Transaction> transactions = getTransactions(true); for (Transaction tx : transactions) { if (ignoreNextNewBlock.contains(tx.getHash())) { // tx was already processed in receive() due to it appearing in this block, so we don't want to // notify the tx confidence of work done twice, it'd result in miscounting. ignoreNextNewBlock.remove(tx.getHash()); } else if (tx.getConfidence().getConfidenceType() == ConfidenceType.BUILDING) { tx.getConfidence().notifyWorkDone(block.getHeader()); confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.DEPTH); } } informConfidenceListenersIfNotReorganizing(); maybeQueueOnWalletChanged(); // Coalesce writes to avoid throttling on disk access when catching up with the chain. saveLater(); } finally { lock.unlock(); } } /** * Handle when a transaction becomes newly active on the best chain, either due to receiving a new block or a * re-org. Places the tx into the right pool, handles coinbase transactions, handles double-spends and so on. */ private void processTxFromBestChain(Transaction tx, boolean forceAddToPool) throws VerificationException { checkState(lock.isHeldByCurrentThread()); checkState(!pending.containsKey(tx.getHash())); // This TX may spend our existing outputs even though it was not pending. This can happen in unit // tests, if keys are moved between wallets, if we're catching up to the chain given only a set of keys, // or if a dead coinbase transaction has moved back onto the main chain. boolean isDeadCoinbase = tx.isCoinBase() && dead.containsKey(tx.getHash()); if (isDeadCoinbase) { // There is a dead coinbase tx being received on the best chain. A coinbase tx is made dead when it moves // to a side chain but it can be switched back on a reorg and 'resurrected' back to spent or unspent. // So take it out of the dead pool. log.info(" coinbase tx {} <-dead: confidence {}", tx.getHashAsString(), tx.getConfidence().getConfidenceType().name()); dead.remove(tx.getHash()); } // Update tx and other unspent/pending transactions by connecting inputs/outputs. updateForSpends(tx, true); // Now make sure it ends up in the right pool. Also, handle the case where this TX is double-spending // against our pending transactions. Note that a tx may double spend our pending transactions and also send // us money/spend our money. boolean hasOutputsToMe = tx.getValueSentToMe(this, true).compareTo(BigInteger.ZERO) > 0; if (hasOutputsToMe) { // Needs to go into either unspent or spent (if the outputs were already spent by a pending tx). if (tx.isEveryOwnedOutputSpent(this)) { log.info(" tx {} ->spent (by pending)", tx.getHashAsString()); addWalletTransaction(Pool.SPENT, tx); } else { log.info(" tx {} ->unspent", tx.getHashAsString()); addWalletTransaction(Pool.UNSPENT, tx); } } else if (tx.getValueSentFromMe(this).compareTo(BigInteger.ZERO) > 0) { // Didn't send us any money, but did spend some. Keep it around for record keeping purposes. log.info(" tx {} ->spent", tx.getHashAsString()); addWalletTransaction(Pool.SPENT, tx); } else if (forceAddToPool) { // Was manually added to pending, so we should keep it to notify the user of confidence information log.info(" tx {} ->spent (manually added)", tx.getHashAsString()); addWalletTransaction(Pool.SPENT, tx); } checkForDoubleSpendAgainstPending(tx, true); } /** * <p>Updates the wallet by checking if this TX spends any of our outputs, and marking them as spent if so. If * fromChain is true, also checks to see if any pending transaction spends outputs of this transaction and marks * the spent flags appropriately.</p> * * <p>It can be called in two contexts. One is when we receive a transaction on the best chain but it wasn't pending, * this most commonly happens when we have a set of keys but the wallet transactions were wiped and we are catching * up with the block chain. It can also happen if a block includes a transaction we never saw at broadcast time. * If this tx double spends, it takes precedence over our pending transactions and the pending tx goes dead.</p> * * <p>The other context it can be called is from {@link Wallet#receivePending(Transaction, java.util.List)}, * ie we saw a tx be broadcast or one was submitted directly that spends our own coins. If this tx double spends * it does NOT take precedence because the winner will be resolved by the miners - we assume that our version will * win, if we are wrong then when a block appears the tx will go dead.</p> * * @param tx The transaction which is being updated. * @param fromChain If true, the tx appeared on the current best chain, if false it was pending. */ private void updateForSpends(Transaction tx, boolean fromChain) throws VerificationException { checkState(lock.isHeldByCurrentThread()); if (fromChain) checkState(!pending.containsKey(tx.getHash())); for (TransactionInput input : tx.getInputs()) { TransactionInput.ConnectionResult result = input.connect(unspent, TransactionInput.ConnectMode.ABORT_ON_CONFLICT); if (result == TransactionInput.ConnectionResult.NO_SUCH_TX) { // Not found in the unspent map. Try again with the spent map. result = input.connect(spent, TransactionInput.ConnectMode.ABORT_ON_CONFLICT); if (result == TransactionInput.ConnectionResult.NO_SUCH_TX) { // Not found in the unspent and spent maps. Try again with the pending map. result = input.connect(pending, TransactionInput.ConnectMode.ABORT_ON_CONFLICT); if (result == TransactionInput.ConnectionResult.NO_SUCH_TX) { // Doesn't spend any of our outputs or is coinbase. continue; } } } if (result == TransactionInput.ConnectionResult.ALREADY_SPENT) { if (fromChain) { // Double spend from chain: this will be handled later by checkForDoubleSpendAgainstPending. log.warn("updateForSpends: saw double spend from chain, handling later."); } else { // We saw two pending transactions that double spend each other. We don't know which will win. // This can happen in the case of bad network nodes that mutate transactions. Do a hex dump // so the exact nature of the mutation can be examined. log.warn("Saw two pending transactions double spend each other"); log.warn(" offending input is input {}", tx.getInputs().indexOf(input)); log.warn("{}: {}", tx.getHash(), new String(Hex.encode(tx.unsafeBitcoinSerialize()))); Transaction other = input.getConnectedOutput().getSpentBy().getParentTransaction(); log.warn("{}: {}", other.getHash(), new String(Hex.encode(tx.unsafeBitcoinSerialize()))); } } else if (result == TransactionInput.ConnectionResult.SUCCESS) { // Otherwise we saw a transaction spend our coins, but we didn't try and spend them ourselves yet. // The outputs are already marked as spent by the connect call above, so check if there are any more for // us to use. Move if not. Transaction connected = checkNotNull(input.getOutpoint().fromTx); log.info(" marked {} as spent", input.getOutpoint()); maybeMovePool(connected, "prevtx"); } } // Now check each output and see if there is a pending transaction which spends it. This shouldn't normally // ever occur because we expect transactions to arrive in temporal order, but this assumption can be violated // when we receive a pending transaction from the mempool that is relevant to us, which spends coins that we // didn't see arrive on the best chain yet. For instance, because of a chain replay or because of our keys were // used by another wallet somewhere else. if (fromChain) { for (Transaction pendingTx : pending.values()) { for (TransactionInput input : pendingTx.getInputs()) { TransactionInput.ConnectionResult result = input.connect(tx, TransactionInput.ConnectMode.ABORT_ON_CONFLICT); // This TX is supposed to have just appeared on the best chain, so its outputs should not be marked // as spent yet. If they are, it means something is happening out of order. checkState(result != TransactionInput.ConnectionResult.ALREADY_SPENT); if (result == TransactionInput.ConnectionResult.SUCCESS) { log.info("Connected pending tx input {}:{}", pendingTx.getHashAsString(), pendingTx.getInputs().indexOf(input)); } } // If the transactions outputs are now all spent, it will be moved into the spent pool by the // processTxFromBestChain method. } } } private void killCoinbase(Transaction coinbase) { log.warn("Coinbase killed by re-org: {}", coinbase.getHashAsString()); coinbase.getConfidence().setOverridingTransaction(null); confidenceChanged.put(coinbase, TransactionConfidence.Listener.ChangeReason.TYPE); final Sha256Hash hash = coinbase.getHash(); pending.remove(hash); unspent.remove(hash); spent.remove(hash); addWalletTransaction(Pool.DEAD, coinbase); // TODO: Properly handle the recursive nature of killing transactions here. } // Updates the wallet when a double spend occurs. overridingTx/overridingInput can be null for the case of coinbases private void killTx(Transaction overridingTx, List<Transaction> killedTx) { for (Transaction tx : killedTx) { log.warn("Saw double spend from chain override pending tx {}", tx.getHashAsString()); log.warn(" <-pending ->dead killed by {}", overridingTx.getHashAsString()); log.warn("Disconnecting each input and moving connected transactions."); pending.remove(tx.getHash()); addWalletTransaction(Pool.DEAD, tx); for (TransactionInput deadInput : tx.getInputs()) { Transaction connected = deadInput.getOutpoint().fromTx; if (connected == null) continue; deadInput.disconnect(); maybeMovePool(connected, "kill"); } tx.getConfidence().setOverridingTransaction(overridingTx); confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.TYPE); } log.warn("Now attempting to connect the inputs of the overriding transaction."); for (TransactionInput input : overridingTx.getInputs()) { TransactionInput.ConnectionResult result = input.connect(unspent, TransactionInput.ConnectMode.DISCONNECT_ON_CONFLICT); if (result == TransactionInput.ConnectionResult.SUCCESS) { maybeMovePool(input.getOutpoint().fromTx, "kill"); } else { result = input.connect(spent, TransactionInput.ConnectMode.DISCONNECT_ON_CONFLICT); if (result == TransactionInput.ConnectionResult.SUCCESS) { maybeMovePool(input.getOutpoint().fromTx, "kill"); } } } // TODO: Recursively kill other transactions that were double spent. } /** * If the transactions outputs are all marked as spent, and it's in the unspent map, move it. * If the owned transactions outputs are not all marked as spent, and it's in the spent map, move it. */ private void maybeMovePool(Transaction tx, String context) { checkState(lock.isHeldByCurrentThread()); if (tx.isEveryOwnedOutputSpent(this)) { // There's nothing left I can spend in this transaction. if (unspent.remove(tx.getHash()) != null) { if (log.isInfoEnabled()) { log.info(" {} {} <-unspent ->spent", tx.getHashAsString(), context); } spent.put(tx.getHash(), tx); } } else { if (spent.remove(tx.getHash()) != null) { if (log.isInfoEnabled()) { log.info(" {} {} <-spent ->unspent", tx.getHashAsString(), context); } unspent.put(tx.getHash(), tx); } } } /** * Adds an event listener object. Methods on this object are called when something interesting happens, * like receiving money. Runs the listener methods in the user thread. */ public void addEventListener(WalletEventListener listener) { addEventListener(listener, Threading.USER_THREAD); } /** * Adds an event listener object. Methods on this object are called when something interesting happens, * like receiving money. The listener is executed by the given executor. */ public void addEventListener(WalletEventListener listener, Executor executor) { eventListeners.add(new ListenerRegistration<WalletEventListener>(listener, executor)); } /** * Removes the given event listener object. Returns true if the listener was removed, false if that listener * was never added. */ public boolean removeEventListener(WalletEventListener listener) { return ListenerRegistration.removeFromList(listener, eventListeners); } /** * Calls {@link Wallet#commitTx} if tx is not already in the pending pool * * @return true if the tx was added to the wallet, or false if it was already in the pending pool */ public boolean maybeCommitTx(Transaction tx) throws VerificationException { tx.verify(); lock.lock(); try { if (pending.containsKey(tx.getHash())) return false; log.info("commitTx of {}", tx.getHashAsString()); BigInteger balance = getBalance(); tx.setUpdateTime(Utils.now()); // Mark the outputs we're spending as spent so we won't try and use them in future creations. This will also // move any transactions that are now fully spent to the spent map so we can skip them when creating future // spends. updateForSpends(tx, false); // Add to the pending pool. It'll be moved out once we receive this transaction on the best chain. // This also registers txConfidenceListener so wallet listeners get informed. log.info("->pending: {}", tx.getHashAsString()); tx.getConfidence().setConfidenceType(ConfidenceType.PENDING); confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.TYPE); addWalletTransaction(Pool.PENDING, tx); try { BigInteger valueSentFromMe = tx.getValueSentFromMe(this); BigInteger valueSentToMe = tx.getValueSentToMe(this); BigInteger newBalance = balance.add(valueSentToMe).subtract(valueSentFromMe); if (valueSentToMe.compareTo(BigInteger.ZERO) > 0) { checkBalanceFuturesLocked(null); queueOnCoinsReceived(tx, balance, newBalance); } if (valueSentFromMe.compareTo(BigInteger.ZERO) > 0) queueOnCoinsSent(tx, balance, newBalance); maybeQueueOnWalletChanged(); } catch (ScriptException e) { // Cannot happen as we just created this transaction ourselves. throw new RuntimeException(e); } checkState(isConsistent()); informConfidenceListenersIfNotReorganizing(); saveNow(); } finally { lock.unlock(); } return true; } /** * <p>Updates the wallet with the given transaction: puts it into the pending pool, sets the spent flags and runs * the onCoinsSent/onCoinsReceived event listener. Used in two situations:</p> * * <ol> * <li>When we have just successfully transmitted the tx we created to the network.</li> * <li>When we receive a pending transaction that didn't appear in the chain yet, and we did not create it.</li> * </ol> * * <p>Triggers an auto save.</p> */ public void commitTx(Transaction tx) throws VerificationException { checkArgument(maybeCommitTx(tx), "commitTx called on the same transaction twice"); } /** * Returns a set of all transactions in the wallet. * @param includeDead If true, transactions that were overridden by a double spend are included. */ public Set<Transaction> getTransactions(boolean includeDead) { lock.lock(); try { Set<Transaction> all = new HashSet<Transaction>(); all.addAll(unspent.values()); all.addAll(spent.values()); all.addAll(pending.values()); if (includeDead) all.addAll(dead.values()); return all; } finally { lock.unlock(); } } /** * Returns a set of all WalletTransactions in the wallet. */ public Iterable<WalletTransaction> getWalletTransactions() { lock.lock(); try { Set<WalletTransaction> all = new HashSet<WalletTransaction>(); addWalletTransactionsToSet(all, Pool.UNSPENT, unspent.values()); addWalletTransactionsToSet(all, Pool.SPENT, spent.values()); addWalletTransactionsToSet(all, Pool.DEAD, dead.values()); addWalletTransactionsToSet(all, Pool.PENDING, pending.values()); return all; } finally { lock.unlock(); } } private static void addWalletTransactionsToSet(Set<WalletTransaction> txs, Pool poolType, Collection<Transaction> pool) { for (Transaction tx : pool) { txs.add(new WalletTransaction(poolType, tx)); } } /** * Adds a transaction that has been associated with a particular wallet pool. This is intended for usage by * deserialization code, such as the {@link WalletProtobufSerializer} class. It isn't normally useful for * applications. It does not trigger auto saving. */ public void addWalletTransaction(WalletTransaction wtx) { lock.lock(); try { addWalletTransaction(wtx.getPool(), wtx.getTransaction()); } finally { lock.unlock(); } } /** * Adds the given transaction to the given pools and registers a confidence change listener on it. */ private void addWalletTransaction(Pool pool, Transaction tx) { checkState(lock.isHeldByCurrentThread()); transactions.put(tx.getHash(), tx); switch (pool) { case UNSPENT: checkState(unspent.put(tx.getHash(), tx) == null); break; case SPENT: checkState(spent.put(tx.getHash(), tx) == null); break; case PENDING: checkState(pending.put(tx.getHash(), tx) == null); break; case DEAD: checkState(dead.put(tx.getHash(), tx) == null); break; default: throw new RuntimeException("Unknown wallet transaction type " + pool); } // This is safe even if the listener has been added before, as TransactionConfidence ignores duplicate // registration requests. That makes the code in the wallet simpler. tx.getConfidence().addEventListener(txConfidenceListener, Threading.SAME_THREAD); } /** * Returns all non-dead, active transactions ordered by recency. */ public List<Transaction> getTransactionsByTime() { return getRecentTransactions(0, false); } /** * Returns an list of N transactions, ordered by increasing age. Transactions on side chains are not included. * Dead transactions (overridden by double spends) are optionally included. <p> * <p/> * Note: the current implementation is O(num transactions in wallet). Regardless of how many transactions are * requested, the cost is always the same. In future, requesting smaller numbers of transactions may be faster * depending on how the wallet is implemented (eg if backed by a database). */ public List<Transaction> getRecentTransactions(int numTransactions, boolean includeDead) { lock.lock(); try { checkArgument(numTransactions >= 0); // Firstly, put all transactions into an array. int size = getPoolSize(Pool.UNSPENT) + getPoolSize(Pool.SPENT) + getPoolSize(Pool.PENDING); if (numTransactions > size || numTransactions == 0) { numTransactions = size; } ArrayList<Transaction> all = new ArrayList<Transaction>(getTransactions(includeDead)); // Order by date. Collections.sort(all, Collections.reverseOrder(new Comparator<Transaction>() { public int compare(Transaction t1, Transaction t2) { return t1.getUpdateTime().compareTo(t2.getUpdateTime()); } })); if (numTransactions == all.size()) { return all; } else { all.subList(numTransactions, all.size()).clear(); return all; } } finally { lock.unlock(); } } /** * Returns a transaction object given its hash, if it exists in this wallet, or null otherwise. */ @Nullable public Transaction getTransaction(Sha256Hash hash) { lock.lock(); try { return transactions.get(hash); } finally { lock.unlock(); } } /** * Deletes transactions which appeared above the given block height from the wallet, but does not touch the keys. * This is useful if you have some keys and wish to replay the block chain into the wallet in order to pick them up. * Triggers auto saving. */ public void clearTransactions(int fromHeight) { lock.lock(); try { if (fromHeight == 0) { unspent.clear(); spent.clear(); pending.clear(); dead.clear(); transactions.clear(); saveLater(); } else { throw new UnsupportedOperationException(); } } finally { lock.unlock(); } } /** * Clean up the wallet. Currently, it only removes risky pending transaction from the wallet and only if their * outputs have not been spent. */ public void cleanup() { lock.lock(); try { boolean dirty = false; for (Iterator<Transaction> i = pending.values().iterator(); i.hasNext();) { Transaction tx = i.next(); if (isTransactionRisky(tx, null) && !acceptRiskyTransactions) { log.debug("Found risky transaction {} in wallet during cleanup.", tx.getHashAsString()); if (!tx.isAnyOutputSpent()) { tx.disconnectInputs(); i.remove(); transactions.remove(tx.getHash()); dirty = true; log.info("Removed transaction {} from pending pool during cleanup.", tx.getHashAsString()); } else { log.info( "Cannot remove transaction {} from pending pool during cleanup, as it's already spent partially.", tx.getHashAsString()); } } } if (dirty) { checkState(isConsistent()); saveLater(); } } finally { lock.unlock(); } } EnumSet<Pool> getContainingPools(Transaction tx) { lock.lock(); try { EnumSet<Pool> result = EnumSet.noneOf(Pool.class); Sha256Hash txHash = tx.getHash(); if (unspent.containsKey(txHash)) { result.add(Pool.UNSPENT); } if (spent.containsKey(txHash)) { result.add(Pool.SPENT); } if (pending.containsKey(txHash)) { result.add(Pool.PENDING); } if (dead.containsKey(txHash)) { result.add(Pool.DEAD); } return result; } finally { lock.unlock(); } } int getPoolSize(WalletTransaction.Pool pool) { lock.lock(); try { switch (pool) { case UNSPENT: return unspent.size(); case SPENT: return spent.size(); case PENDING: return pending.size(); case DEAD: return dead.size(); } throw new RuntimeException("Unreachable"); } finally { lock.unlock(); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // SEND APIS // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** A SendResult is returned to you as part of sending coins to a recipient. */ public static class SendResult { /** The Bitcoin transaction message that moves the money. */ public Transaction tx; /** A future that will complete once the tx message has been successfully broadcast to the network. */ public ListenableFuture<Transaction> broadcastComplete; } /** * A SendRequest gives the wallet information about precisely how to send money to a recipient or set of recipients. * Static methods are provided to help you create SendRequests and there are a few helper methods on the wallet that * just simplify the most common use cases. You may wish to customize a SendRequest if you want to attach a fee or * modify the change address. */ public static class SendRequest { /** * <p>A transaction, probably incomplete, that describes the outline of what you want to do. This typically will * mean it has some outputs to the intended destinations, but no inputs or change address (and therefore no * fees) - the wallet will calculate all that for you and update tx later.</p> * * <p>Be careful when adding outputs that you check the min output value * ({@link TransactionOutput#getMinNonDustValue(BigInteger)}) to avoid the whole transaction being rejected * because one output is dust.</p> * * <p>If there are already inputs to the transaction, make sure their out point has a connected output, * otherwise their value will be added to fee. Also ensure they are either signed or are spendable by a wallet * key, otherwise the behavior of {@link Wallet#completeTx(Wallet.SendRequest)} is undefined (likely * RuntimeException).</p> */ public Transaction tx; /** * When emptyWallet is set, all coins selected by the coin selector are sent to the first output in tx * (its value is ignored and set to {@link com.google.bitcoin.core.Wallet#getBalance()} - the fees required * for the transaction). Any additional outputs are removed. */ public boolean emptyWallet = false; /** * "Change" means the difference between the value gathered by a transactions inputs (the size of which you * don't really control as it depends on who sent you money), and the value being sent somewhere else. The * change address should be selected from this wallet, normally. <b>If null this will be chosen for you.</b> */ public Address changeAddress = null; /** * <p>A transaction can have a fee attached, which is defined as the difference between the input values * and output values. Any value taken in that is not provided to an output can be claimed by a miner. This * is how mining is incentivized in later years of the Bitcoin system when inflation drops. It also provides * a way for people to prioritize their transactions over others and is used as a way to make denial of service * attacks expensive.</p> * * <p>This is a constant fee (in satoshis) which will be added to the transaction. It is recommended that it be * at least {@link Transaction#REFERENCE_DEFAULT_MIN_TX_FEE} if it is set, as default reference clients will * otherwise simply treat the transaction as if there were no fee at all.</p> * * <p>Once {@link Wallet#completeTx(com.google.bitcoin.core.Wallet.SendRequest)} is called, this is set to the * value of the fee that was added.</p> * * <p>You might also consider adding a {@link SendRequest#feePerKb} to set the fee per kb of transaction size * (rounded down to the nearest kb) as that is how transactions are sorted when added to a block by miners.</p> */ public BigInteger fee = null; /** * <p>A transaction can have a fee attached, which is defined as the difference between the input values * and output values. Any value taken in that is not provided to an output can be claimed by a miner. This * is how mining is incentivized in later years of the Bitcoin system when inflation drops. It also provides * a way for people to prioritize their transactions over others and is used as a way to make denial of service * attacks expensive.</p> * * <p>This is a dynamic fee (in satoshis) which will be added to the transaction for each kilobyte in size * including the first. This is useful as as miners usually sort pending transactions by their fee per unit size * when choosing which transactions to add to a block. Note that, to keep this equivalent to the reference * client definition, a kilobyte is defined as 1000 bytes, not 1024.</p> * * <p>You might also consider using a {@link SendRequest#fee} to set the fee added for the first kb of size.</p> */ public BigInteger feePerKb = DEFAULT_FEE_PER_KB; /** * If you want to modify the default fee for your entire app without having to change each SendRequest you make, * you can do it here. This is primarily useful for unit tests. */ public static BigInteger DEFAULT_FEE_PER_KB = Transaction.REFERENCE_DEFAULT_MIN_TX_FEE; /** * <p>Requires that there be enough fee for a default reference client to at least relay the transaction. * (ie ensure the transaction will not be outright rejected by the network). Defaults to true, you should * only set this to false if you know what you're doing.</p> * * <p>Note that this does not enforce certain fee rules that only apply to transactions which are larger than * 26,000 bytes. If you get a transaction which is that large, you should set a fee and feePerKb of at least * {@link Transaction#REFERENCE_DEFAULT_MIN_TX_FEE}.</p> */ public boolean ensureMinRequiredFee = true; /** * The AES key to use to decrypt the private keys before signing. * If null then no decryption will be performed and if decryption is required an exception will be thrown. * You can get this from a password by doing wallet.getKeyCrypter().deriveKey(password). */ public KeyParameter aesKey = null; /** * If not null, the {@link com.google.bitcoin.wallet.CoinSelector} to use instead of the wallets default. Coin selectors are * responsible for choosing which transaction outputs (coins) in a wallet to use given the desired send value * amount. */ public CoinSelector coinSelector = null; // Tracks if this has been passed to wallet.completeTx already: just a safety check. private boolean completed; private SendRequest() {} /** * <p>Creates a new SendRequest to the given address for the given value.</p> * * <p>Be very careful when value is smaller than {@link Transaction#MIN_NONDUST_OUTPUT} as the transaction will * likely be rejected by the network in this case.</p> */ public static SendRequest to(Address destination, BigInteger value) { SendRequest req = new SendRequest(); final NetworkParameters parameters = destination.getParameters(); checkNotNull(parameters, "Address is for an unknown network"); req.tx = new Transaction(parameters); req.tx.addOutput(value, destination); return req; } /** * <p>Creates a new SendRequest to the given pubkey for the given value.</p> * * <p>Be careful to check the output's value is reasonable using * {@link TransactionOutput#getMinNonDustValue(BigInteger)} afterwards or you risk having the transaction * rejected by the network. Note that using {@link SendRequest#to(Address, java.math.BigInteger)} will result * in a smaller output, and thus the ability to use a smaller output value without rejection.</p> */ public static SendRequest to(NetworkParameters params, ECKey destination, BigInteger value) { SendRequest req = new SendRequest(); req.tx = new Transaction(params); req.tx.addOutput(value, destination); return req; } /** Simply wraps a pre-built incomplete transaction provided by you. */ public static SendRequest forTx(Transaction tx) { SendRequest req = new SendRequest(); req.tx = tx; return req; } public static SendRequest emptyWallet(Address destination) { SendRequest req = new SendRequest(); final NetworkParameters parameters = destination.getParameters(); checkNotNull(parameters, "Address is for an unknown network"); req.tx = new Transaction(parameters); req.tx.addOutput(BigInteger.ZERO, destination); req.emptyWallet = true; return req; } } /** * <p>Statelessly creates a transaction that sends the given value to address. The change is sent to * {@link Wallet#getChangeAddress()}, so you must have added at least one key.</p> * * <p>If you just want to send money quickly, you probably want * {@link Wallet#sendCoins(TransactionBroadcaster, Address, java.math.BigInteger)} instead. That will create the sending * transaction, commit to the wallet and broadcast it to the network all in one go. This method is lower level * and lets you see the proposed transaction before anything is done with it.</p> * * <p>This is a helper method that is equivalent to using {@link Wallet.SendRequest#to(Address, java.math.BigInteger)} * followed by {@link Wallet#completeTx(Wallet.SendRequest)} and returning the requests transaction object. * Note that this means a fee may be automatically added if required, if you want more control over the process, * just do those two steps yourself.</p> * * <p>IMPORTANT: This method does NOT update the wallet. If you call createSend again you may get two transactions * that spend the same coins. You have to call {@link Wallet#commitTx(Transaction)} on the created transaction to * prevent this, but that should only occur once the transaction has been accepted by the network. This implies * you cannot have more than one outstanding sending tx at once.</p> * * <p>You MUST ensure that nanocoins is larger than {@link Transaction#MIN_NONDUST_OUTPUT} or the transaction will * almost certainly be rejected by the network as dust.</p> * * @param address The Bitcoin address to send the money to. * @param nanocoins How much currency to send, in nanocoins. * @return either the created Transaction or null if there are insufficient coins. * coins as spent until commitTx is called on the result. * @throws InsufficientMoneyException if the request could not be completed due to not enough balance. */ public Transaction createSend(Address address, BigInteger nanocoins) throws InsufficientMoneyException { SendRequest req = SendRequest.to(address, nanocoins); completeTx(req); return req.tx; } /** * Sends coins to the given address but does not broadcast the resulting pending transaction. It is still stored * in the wallet, so when the wallet is added to a {@link PeerGroup} or {@link Peer} the transaction will be * announced to the network. The given {@link SendRequest} is completed first using * {@link Wallet#completeTx(Wallet.SendRequest)} to make it valid. * * @return the Transaction that was created * @throws InsufficientMoneyException if the request could not be completed due to not enough balance. */ public Transaction sendCoinsOffline(SendRequest request) throws InsufficientMoneyException { lock.lock(); try { completeTx(request); commitTx(request.tx); return request.tx; } finally { lock.unlock(); } } /** * <p>Sends coins to the given address, via the given {@link PeerGroup}. Change is returned to * {@link Wallet#getChangeAddress()}. Note that a fee may be automatically added if one may be required for the * transaction to be confirmed.</p> * * <p>The returned object provides both the transaction, and a future that can be used to learn when the broadcast * is complete. Complete means, if the PeerGroup is limited to only one connection, when it was written out to * the socket. Otherwise when the transaction is written out and we heard it back from a different peer.</p> * * <p>Note that the sending transaction is committed to the wallet immediately, not when the transaction is * successfully broadcast. This means that even if the network hasn't heard about your transaction you won't be * able to spend those same coins again.</p> * * <p>You MUST ensure that value is smaller than {@link Transaction#MIN_NONDUST_OUTPUT} or the transaction will * almost certainly be rejected by the network as dust.</p> * * @param broadcaster a {@link TransactionBroadcaster} to use to send the transactions out. * @param to Which address to send coins to. * @param value How much value to send. You can use Utils.toNanoCoins() to calculate this. * @return An object containing the transaction that was created, and a future for the broadcast of it. * @throws InsufficientMoneyException if the request could not be completed due to not enough balance. */ public SendResult sendCoins(TransactionBroadcaster broadcaster, Address to, BigInteger value) throws InsufficientMoneyException { SendRequest request = SendRequest.to(to, value); return sendCoins(broadcaster, request); } /** * <p>Sends coins according to the given request, via the given {@link TransactionBroadcaster}.</p> * * <p>The returned object provides both the transaction, and a future that can be used to learn when the broadcast * is complete. Complete means, if the PeerGroup is limited to only one connection, when it was written out to * the socket. Otherwise when the transaction is written out and we heard it back from a different peer.</p> * * <p>Note that the sending transaction is committed to the wallet immediately, not when the transaction is * successfully broadcast. This means that even if the network hasn't heard about your transaction you won't be * able to spend those same coins again.</p> * * @param broadcaster the target to use for broadcast. * @param request the SendRequest that describes what to do, get one using static methods on SendRequest itself. * @return An object containing the transaction that was created, and a future for the broadcast of it. * @throws InsufficientMoneyException if the request could not be completed due to not enough balance. */ public SendResult sendCoins(TransactionBroadcaster broadcaster, SendRequest request) throws InsufficientMoneyException { // Should not be locked here, as we're going to call into the broadcaster and that might want to hold its // own lock. sendCoinsOffline handles everything that needs to be locked. checkState(!lock.isHeldByCurrentThread()); // Commit the TX to the wallet immediately so the spent coins won't be reused. // TODO: We should probably allow the request to specify tx commit only after the network has accepted it. Transaction tx = sendCoinsOffline(request); SendResult result = new SendResult(); result.tx = tx; // The tx has been committed to the pending pool by this point (via sendCoinsOffline -> commitTx), so it has // a txConfidenceListener registered. Once the tx is broadcast the peers will update the memory pool with the // count of seen peers, the memory pool will update the transaction confidence object, that will invoke the // txConfidenceListener which will in turn invoke the wallets event listener onTransactionConfidenceChanged // method. result.broadcastComplete = broadcaster.broadcastTransaction(tx); return result; } /** * Satisfies the given {@link SendRequest} using the default transaction broadcaster configured either via * {@link PeerGroup#addWallet(Wallet)} or directly with {@link #setTransactionBroadcaster(TransactionBroadcaster)}. * * @param request the SendRequest that describes what to do, get one using static methods on SendRequest itself. * @return An object containing the transaction that was created, and a future for the broadcast of it. * @throws IllegalStateException if no transaction broadcaster has been configured. * @throws InsufficientMoneyException if the request could not be completed due to not enough balance. */ public SendResult sendCoins(SendRequest request) throws InsufficientMoneyException { TransactionBroadcaster broadcaster = vTransactionBroadcaster; checkState(broadcaster != null, "No transaction broadcaster is configured"); return sendCoins(broadcaster, request); } /** * Sends coins to the given address, via the given {@link Peer}. Change is returned to {@link Wallet#getChangeAddress()}. * If an exception is thrown by {@link Peer#sendMessage(Message)} the transaction is still committed, so the * pending transaction must be broadcast <b>by you</b> at some other time. Note that a fee may be automatically added * if one may be required for the transaction to be confirmed. * * @return The {@link Transaction} that was created or null if there was insufficient balance to send the coins. * @throws InsufficientMoneyException if the request could not be completed due to not enough balance. */ public Transaction sendCoins(Peer peer, SendRequest request) throws InsufficientMoneyException { Transaction tx = sendCoinsOffline(request); peer.sendMessage(tx); return tx; } /** * Given a spend request containing an incomplete transaction, makes it valid by adding outputs and signed inputs * according to the instructions in the request. The transaction in the request is modified by this method, as is * the fee parameter. * * @param req a SendRequest that contains the incomplete transaction and details for how to make it valid. * @throws InsufficientMoneyException if the request could not be completed due to not enough balance. * @throws IllegalArgumentException if you try and complete the same SendRequest twice, or if the given send request * cannot be completed without violating the protocol rules. */ public void completeTx(SendRequest req) throws InsufficientMoneyException { lock.lock(); try { checkArgument(!req.completed, "Given SendRequest has already been completed."); // Calculate the amount of value we need to import. BigInteger value = BigInteger.ZERO; for (TransactionOutput output : req.tx.getOutputs()) { value = value.add(output.getValue()); } BigInteger totalOutput = value; log.info("Completing send tx with {} outputs totalling {} satoshis (not including fees)", req.tx.getOutputs().size(), value); // If any inputs have already been added, we don't need to get their value from wallet BigInteger totalInput = BigInteger.ZERO; for (TransactionInput input : req.tx.getInputs()) if (input.getConnectedOutput() != null) totalInput = totalInput.add(input.getConnectedOutput().getValue()); else log.warn("SendRequest transaction already has inputs but we don't know how much they are worth - they will be added to fee."); value = value.subtract(totalInput); List<TransactionInput> originalInputs = new ArrayList<TransactionInput>(req.tx.getInputs()); // We need to know if we need to add an additional fee because one of our values are smaller than 0.01 BTC boolean needAtLeastReferenceFee = false; if (req.ensureMinRequiredFee && !req.emptyWallet) { // min fee checking is handled later for emptyWallet for (TransactionOutput output : req.tx.getOutputs()) if (output.getValue().compareTo(Utils.CENT) < 0) { if (output.getValue().compareTo(output.getMinNonDustValue()) < 0) throw new IllegalArgumentException("Tried to send dust with ensureMinRequiredFee set - no way to complete this"); needAtLeastReferenceFee = true; break; } } // Calculate a list of ALL potential candidates for spending and then ask a coin selector to provide us // with the actual outputs that'll be used to gather the required amount of value. In this way, users // can customize coin selection policies. // // Note that this code is poorly optimized: the spend candidates only alter when transactions in the wallet // change - it could be pre-calculated and held in RAM, and this is probably an optimization worth doing. // Note that output.isMine(this) needs to test the keychain which is currently an array, so it's // O(candidate outputs ^ keychain.size())! There's lots of low hanging fruit here. LinkedList<TransactionOutput> candidates = calculateAllSpendCandidates(true); CoinSelection bestCoinSelection; TransactionOutput bestChangeOutput = null; if (!req.emptyWallet) { // This can throw InsufficientMoneyException. FeeCalculation feeCalculation; feeCalculation = new FeeCalculation(req, value, originalInputs, needAtLeastReferenceFee, candidates); bestCoinSelection = feeCalculation.bestCoinSelection; bestChangeOutput = feeCalculation.bestChangeOutput; } else { // We're being asked to empty the wallet. What this means is ensuring "tx" has only a single output // of the total value we can currently spend as determined by the selector, and then subtracting the fee. checkState(req.tx.getOutputs().size() == 1, "Empty wallet TX must have a single output only."); CoinSelector selector = req.coinSelector == null ? coinSelector : req.coinSelector; bestCoinSelection = selector.select(NetworkParameters.MAX_MONEY, candidates); req.tx.getOutput(0).setValue(bestCoinSelection.valueGathered); totalOutput = bestCoinSelection.valueGathered; } for (TransactionOutput output : bestCoinSelection.gathered) req.tx.addInput(output); if (req.ensureMinRequiredFee && req.emptyWallet) { final BigInteger baseFee = req.fee == null ? BigInteger.ZERO : req.fee; final BigInteger feePerKb = req.feePerKb == null ? BigInteger.ZERO : req.feePerKb; Transaction tx = req.tx; if (!adjustOutputDownwardsForFee(tx, bestCoinSelection, baseFee, feePerKb)) throw new InsufficientMoneyException.CouldNotAdjustDownwards(); } totalInput = totalInput.add(bestCoinSelection.valueGathered); if (bestChangeOutput != null) { req.tx.addOutput(bestChangeOutput); totalOutput = totalOutput.add(bestChangeOutput.getValue()); log.info(" with {} coins change", bitcoinValueToFriendlyString(bestChangeOutput.getValue())); } final BigInteger calculatedFee = totalInput.subtract(totalOutput); if (calculatedFee.compareTo(BigInteger.ZERO) > 0) { log.info(" with a fee of {}", bitcoinValueToFriendlyString(calculatedFee)); } // Now sign the inputs, thus proving that we are entitled to redeem the connected outputs. req.tx.signInputs(Transaction.SigHash.ALL, this, req.aesKey); // Check size. int size = req.tx.bitcoinSerialize().length; if (size > Transaction.MAX_STANDARD_TX_SIZE) { throw new IllegalArgumentException( String.format("Transaction could not be created without exceeding max size: %d vs %d", size, Transaction.MAX_STANDARD_TX_SIZE)); } // Label the transaction as being self created. We can use this later to spend its change output even before // the transaction is confirmed. We deliberately won't bother notifying listeners here as there's not much // point - the user isn't interested in a confidence transition they made themselves. req.tx.getConfidence().setSource(TransactionConfidence.Source.SELF); // Label the transaction as being a user requested payment. This can be used to render GUI wallet // transaction lists more appropriately, especially when the wallet starts to generate transactions itself // for internal purposes. req.tx.setPurpose(Transaction.Purpose.USER_PAYMENT); req.completed = true; req.fee = calculatedFee; log.info(" completed: {}", req.tx); } finally { lock.unlock(); } } /** Reduce the value of the first output of a transaction to pay the given feePerKb as appropriate for its size. */ private boolean adjustOutputDownwardsForFee(Transaction tx, CoinSelection coinSelection, BigInteger baseFee, BigInteger feePerKb) { TransactionOutput output = tx.getOutput(0); // Check if we need additional fee due to the transaction's size int size = tx.bitcoinSerialize().length; size += estimateBytesForSigning(coinSelection); BigInteger fee = baseFee.add(BigInteger.valueOf((size / 1000) + 1).multiply(feePerKb)); output.setValue(output.getValue().subtract(fee)); // Check if we need additional fee due to the output's value if (output.getValue().compareTo(Utils.CENT) < 0 && fee.compareTo(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE) < 0) output.setValue(output.getValue().subtract(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.subtract(fee))); return output.getMinNonDustValue().compareTo(output.getValue()) <= 0; } /** * Returns a list of all possible outputs we could possibly spend, potentially even including immature coinbases * (which the protocol may forbid us from spending). In other words, return all outputs that this wallet holds * keys for and which are not already marked as spent. */ public LinkedList<TransactionOutput> calculateAllSpendCandidates(boolean excludeImmatureCoinbases) { lock.lock(); try { LinkedList<TransactionOutput> candidates = Lists.newLinkedList(); for (Transaction tx : Iterables.concat(unspent.values(), pending.values())) { // Do not try and spend coinbases that were mined too recently, the protocol forbids it. if (excludeImmatureCoinbases && !tx.isMature()) continue; for (TransactionOutput output : tx.getOutputs()) { if (!output.isAvailableForSpending()) continue; if (!output.isMine(this)) continue; candidates.add(output); } } return candidates; } finally { lock.unlock(); } } /** * Returns all the outputs that match addresses or scripts added via {@link #addWatchedAddress(Address)} or * {@link #addWatchedScripts(java.util.List)}. * @param excludeImmatureCoinbases Whether to ignore outputs that are unspendable due to being immature. */ public LinkedList<TransactionOutput> getWatchedOutputs(boolean excludeImmatureCoinbases) { lock.lock(); try { LinkedList<TransactionOutput> candidates = Lists.newLinkedList(); for (Transaction tx : Iterables.concat(unspent.values(), pending.values())) { if (excludeImmatureCoinbases && !tx.isMature()) continue; for (TransactionOutput output : tx.getOutputs()) { if (!output.isAvailableForSpending()) continue; try { Script scriptPubKey = output.getScriptPubKey(); if (!watchedScripts.contains(scriptPubKey)) continue; candidates.add(output); } catch (ScriptException e) { // Ignore } } } return candidates; } finally { lock.unlock(); } } /** Returns the address used for change outputs. Note: this will probably go away in future. */ public Address getChangeAddress() { lock.lock(); try { // For now let's just pick the first key in our keychain. In future we might want to do something else to // give the user better privacy here, eg in incognito mode. checkState(keychain.size() > 0, "Can't send value without an address to use for receiving change"); ECKey first = keychain.get(0); return first.toAddress(params); } finally { lock.unlock(); } } /** * Adds the given ECKey to the wallet. There is currently no way to delete keys (that would result in coin loss). * If {@link Wallet#autosaveToFile(java.io.File, long, java.util.concurrent.TimeUnit, com.google.bitcoin.wallet.WalletFiles.Listener)} * has been called, triggers an auto save bypassing the normal coalescing delay and event handlers. * If the key already exists in the wallet, does nothing and returns false. */ public boolean addKey(final ECKey key) { return addKeys(Lists.newArrayList(key)) == 1; } /** * Adds the given keys to the wallet. There is currently no way to delete keys (that would result in coin loss). * If {@link Wallet#autosaveToFile(java.io.File, long, java.util.concurrent.TimeUnit, com.google.bitcoin.wallet.WalletFiles.Listener)} * has been called, triggers an auto save bypassing the normal coalescing delay and event handlers. * Returns the number of keys added, after duplicates are ignored. The onKeyAdded event will be called for each key * in the list that was not already present. */ public int addKeys(final List<ECKey> keys) { lock.lock(); try { int added = 0; // TODO: Consider making keys a sorted list or hashset so membership testing is faster. for (final ECKey key : keys) { if (keychain.contains(key)) continue; // If the key has a keyCrypter that does not match the Wallet's then a KeyCrypterException is thrown. // This is done because only one keyCrypter is persisted per Wallet and hence all the keys must be homogenous. if (isEncrypted() && (!key.isEncrypted() || !keyCrypter.equals(key.getKeyCrypter()))) { throw new KeyCrypterException("Cannot add key " + key.toString() + " because the keyCrypter does not match the wallets. Keys must be homogenous."); } else if (key.isEncrypted() && !isEncrypted()) { throw new KeyCrypterException("Cannot add key because it's encrypted and this wallet is not."); } keychain.add(key); added++; } queueOnKeysAdded(keys); // Force an auto-save immediately rather than queueing one, as keys are too important to risk losing. saveNow(); return added; } finally { lock.unlock(); } } /** * Return true if we are watching this address. */ public boolean isAddressWatched(Address address) { Script script = ScriptBuilder.createOutputScript(address); return isWatchedScript(script); } /** * Same as {@link #addWatchedAddress(Address, long)} with the current time as the creation time. */ public boolean addWatchedAddress(final Address address) { long now = Utils.currentTimeMillis() / 1000; return addWatchedAddresses(Lists.newArrayList(address), now) == 1; } /** * Adds the given address to the wallet to be watched. Outputs can be retrieved by {@link #getWatchedOutputs(boolean)}. * * @param creationTime creation time in seconds since the epoch, for scanning the blockchain * @return whether the address was added successfully (not already present) */ public boolean addWatchedAddress(final Address address, long creationTime) { return addWatchedAddresses(Lists.newArrayList(address), creationTime) == 1; } /** * Adds the given address to the wallet to be watched. Outputs can be retrieved * by {@link #getWatchedOutputs(boolean)}. * * @return how many addresses were added successfully */ public int addWatchedAddresses(final List<Address> addresses, long creationTime) { List<Script> scripts = Lists.newArrayList(); for (Address address : addresses) { Script script = ScriptBuilder.createOutputScript(address); script.setCreationTimeSeconds(creationTime); scripts.add(script); } return addWatchedScripts(scripts); } /** * Adds the given output scripts to the wallet to be watched. Outputs can be retrieved * by {@link #getWatchedOutputs(boolean)}. * * @return how many scripts were added successfully */ public int addWatchedScripts(final List<Script> scripts) { lock.lock(); try { int added = 0; for (final Script script : scripts) { if (watchedScripts.contains(script)) continue; watchedScripts.add(script); added++; } queueOnScriptsAdded(scripts); saveNow(); return added; } finally { lock.unlock(); } } /** * Locates a keypair from the keychain given the hash of the public key. This is needed when finding out which * key we need to use to redeem a transaction output. * * @return ECKey object or null if no such key was found. */ @Nullable public ECKey findKeyFromPubHash(byte[] pubkeyHash) { lock.lock(); try { for (ECKey key : keychain) { if (Arrays.equals(key.getPubKeyHash(), pubkeyHash)) return key; } return null; } finally { lock.unlock(); } } /** Returns true if the given key is in the wallet, false otherwise. Currently an O(N) operation. */ public boolean hasKey(ECKey key) { lock.lock(); try { return keychain.contains(key); } finally { lock.unlock(); } } /** * Returns true if this wallet contains a public key which hashes to the given hash. */ public boolean isPubKeyHashMine(byte[] pubkeyHash) { return findKeyFromPubHash(pubkeyHash) != null; } /** Returns true if this wallet is watching transactions for outputs with the script. */ public boolean isWatchedScript(Script script) { lock.lock(); try { return watchedScripts.contains(script); } finally { lock.unlock(); } } /** * Locates a keypair from the keychain given the raw public key bytes. * @return ECKey or null if no such key was found. */ @Nullable public ECKey findKeyFromPubKey(byte[] pubkey) { lock.lock(); try { for (ECKey key : keychain) { if (Arrays.equals(key.getPubKey(), pubkey)) return key; } return null; } finally { lock.unlock(); } } /** * Returns true if this wallet contains a keypair with the given public key. */ public boolean isPubKeyMine(byte[] pubkey) { return findKeyFromPubKey(pubkey) != null; } /** * <p>It's possible to calculate a wallets balance from multiple points of view. This enum selects which * getBalance() should use.</p> * * <p>Consider a real-world example: you buy a snack costing $5 but you only have a $10 bill. At the start you have * $10 viewed from every possible angle. After you order the snack you hand over your $10 bill. From the * perspective of your wallet you have zero dollars (AVAILABLE). But you know in a few seconds the shopkeeper * will give you back $5 change so most people in practice would say they have $5 (ESTIMATED).</p> */ public enum BalanceType { /** * Balance calculated assuming all pending transactions are in fact included into the best chain by miners. * This includes the value of immature coinbase transactions. */ ESTIMATED, /** * Balance that can be safely used to create new spends. This is whatever the default coin selector would * make available, which by default means transaction outputs with at least 1 confirmation and pending * transactions created by our own wallet which have been propagated across the network. */ AVAILABLE } /** * Returns the AVAILABLE balance of this wallet. See {@link BalanceType#AVAILABLE} for details on what this * means. */ public BigInteger getBalance() { return getBalance(BalanceType.AVAILABLE); } /** * Returns the balance of this wallet as calculated by the provided balanceType. */ public BigInteger getBalance(BalanceType balanceType) { lock.lock(); try { if (balanceType == BalanceType.AVAILABLE) { return getBalance(coinSelector); } else if (balanceType == BalanceType.ESTIMATED) { LinkedList<TransactionOutput> all = calculateAllSpendCandidates(false); BigInteger value = BigInteger.ZERO; for (TransactionOutput out : all) value = value.add(out.getValue()); return value; } else { throw new AssertionError("Unknown balance type"); // Unreachable. } } finally { lock.unlock(); } } /** * Returns the balance that would be considered spendable by the given coin selector. Just asks it to select * as many coins as possible and returns the total. */ public BigInteger getBalance(CoinSelector selector) { lock.lock(); try { checkNotNull(selector); LinkedList<TransactionOutput> candidates = calculateAllSpendCandidates(true); CoinSelection selection = selector.select(NetworkParameters.MAX_MONEY, candidates); return selection.valueGathered; } finally { lock.unlock(); } } /** Returns the available balance, including any unspent balance at watched addresses */ public BigInteger getWatchedBalance() { return getWatchedBalance(coinSelector); } /** * Returns the balance that would be considered spendable by the given coin selector, including * any unspent balance at watched addresses. */ public BigInteger getWatchedBalance(CoinSelector selector) { lock.lock(); try { checkNotNull(selector); LinkedList<TransactionOutput> candidates = getWatchedOutputs(true); CoinSelection selection = selector.select(NetworkParameters.MAX_MONEY, candidates); return selection.valueGathered; } finally { lock.unlock(); } } @Override public String toString() { return toString(false, true, true, null); } private static final Comparator<Transaction> SORT_ORDER_BY_UPDATE_TIME = new Comparator<Transaction>() { @Override public int compare(final Transaction tx1, final Transaction tx2) { final long time1 = tx1.getUpdateTime().getTime(); final long time2 = tx2.getUpdateTime().getTime(); return -(Longs.compare(time1, time2)); } }; private static final Comparator<Transaction> SORT_ORDER_BY_HEIGHT = new Comparator<Transaction>() { @Override public int compare(final Transaction tx1, final Transaction tx2) { final int height1 = tx1.getConfidence().getAppearedAtChainHeight(); final int height2 = tx2.getConfidence().getAppearedAtChainHeight(); return -(Ints.compare(height1, height2)); } }; /** * Formats the wallet as a human readable piece of text. Intended for debugging, the format is not meant to be * stable or human readable. * @param includePrivateKeys Whether raw private key data should be included. * @param includeTransactions Whether to print transaction data. * @param includeExtensions Whether to print extension data. * @param chain If set, will be used to estimate lock times for block timelocked transactions. */ public String toString(boolean includePrivateKeys, boolean includeTransactions, boolean includeExtensions, @Nullable AbstractBlockChain chain) { lock.lock(); try { StringBuilder builder = new StringBuilder(); BigInteger estimatedBalance = getBalance(BalanceType.ESTIMATED); BigInteger availableBalance = getBalance(BalanceType.AVAILABLE); builder.append(String.format("Wallet containing %s BTC (available: %s BTC) in:%n", bitcoinValueToPlainString(estimatedBalance), bitcoinValueToPlainString(availableBalance))); builder.append(String.format(" %d pending transactions%n", pending.size())); builder.append(String.format(" %d unspent transactions%n", unspent.size())); builder.append(String.format(" %d spent transactions%n", spent.size())); builder.append(String.format(" %d dead transactions%n", dead.size())); final Date lastBlockSeenTime = getLastBlockSeenTime(); final String lastBlockSeenTimeStr = lastBlockSeenTime == null ? "time unknown" : lastBlockSeenTime.toString(); builder.append(String.format("Last seen best block: %d (%s): %s%n", getLastBlockSeenHeight(), lastBlockSeenTimeStr, getLastBlockSeenHash())); if (this.keyCrypter != null) { builder.append(String.format("Encryption: %s%n", keyCrypter.toString())); } // Do the keys. builder.append("\nKeys:\n"); for (ECKey key : keychain) { final Address address = key.toAddress(params); builder.append(" addr:"); builder.append(address.toString()); builder.append(" hash160:"); builder.append(Utils.bytesToHexString(address.getHash160())); builder.append(" "); builder.append(includePrivateKeys ? key.toStringWithPrivate() : key.toString()); builder.append("\n"); } if (!watchedScripts.isEmpty()) { builder.append("\nWatched scripts:\n"); for (Script script : watchedScripts) { builder.append(" "); builder.append(script.toString()); builder.append("\n"); } } if (includeTransactions) { // Print the transactions themselves if (pending.size() > 0) { builder.append("\n>>> PENDING:\n"); toStringHelper(builder, pending, chain, SORT_ORDER_BY_UPDATE_TIME); } if (unspent.size() > 0) { builder.append("\n>>> UNSPENT:\n"); toStringHelper(builder, unspent, chain, SORT_ORDER_BY_HEIGHT); } if (spent.size() > 0) { builder.append("\n>>> SPENT:\n"); toStringHelper(builder, spent, chain, SORT_ORDER_BY_HEIGHT); } if (dead.size() > 0) { builder.append("\n>>> DEAD:\n"); toStringHelper(builder, dead, chain, SORT_ORDER_BY_HEIGHT); } } if (includeExtensions && extensions.size() > 0) { builder.append("\n>>> EXTENSIONS:\n"); for (WalletExtension extension : extensions.values()) { builder.append(extension).append("\n\n"); } } return builder.toString(); } finally { lock.unlock(); } } private void toStringHelper(StringBuilder builder, Map<Sha256Hash, Transaction> transactionMap, @Nullable AbstractBlockChain chain, @Nullable Comparator<Transaction> sortOrder) { checkState(lock.isHeldByCurrentThread()); final Collection<Transaction> txns; if (sortOrder != null) { txns = new TreeSet<Transaction>(sortOrder); txns.addAll(transactionMap.values()); } else { txns = transactionMap.values(); } for (Transaction tx : txns) { try { builder.append("Sends "); builder.append(Utils.bitcoinValueToFriendlyString(tx.getValueSentFromMe(this))); builder.append(" and receives "); builder.append(Utils.bitcoinValueToFriendlyString(tx.getValueSentToMe(this))); builder.append(", total value "); builder.append(Utils.bitcoinValueToFriendlyString(tx.getValue(this))); builder.append(".\n"); } catch (ScriptException e) { // Ignore and don't print this line. } builder.append(tx.toString(chain)); } } private static class TxOffsetPair implements Comparable<TxOffsetPair> { public final Transaction tx; public final int offset; public TxOffsetPair(Transaction tx, int offset) { this.tx = tx; this.offset = offset; } @Override public int compareTo(TxOffsetPair o) { return Ints.compare(offset, o.offset); } } /** * <p>Don't call this directly. It's not intended for API users.</p> * * <p>Called by the {@link BlockChain} when the best chain (representing total work done) has changed. This can * cause the number of confirmations of a transaction to go higher, lower, drop to zero and can even result in * a transaction going dead (will never confirm) due to a double spend.</p> * * <p>The oldBlocks/newBlocks lists are ordered height-wise from top first to bottom last.</p> */ public void reorganize(StoredBlock splitPoint, List<StoredBlock> oldBlocks, List<StoredBlock> newBlocks) throws VerificationException { lock.lock(); try { // This runs on any peer thread with the block chain locked. // // The reorganize functionality of the wallet is tested in ChainSplitTest.java // // receive() has been called on the block that is triggering the re-org before this is called, with type // of SIDE_CHAIN. // // Note that this code assumes blocks are not invalid - if blocks contain duplicated transactions, // transactions that double spend etc then we can calculate the incorrect result. This could open up // obscure DoS attacks if someone successfully mines a throwaway invalid block and feeds it to us, just // to try and corrupt the internal data structures. We should try harder to avoid this but it's tricky // because there are so many ways the block can be invalid. // Avoid spuriously informing the user of wallet/tx confidence changes whilst we're re-organizing. checkState(confidenceChanged.size() == 0); checkState(!insideReorg); insideReorg = true; checkState(onWalletChangedSuppressions == 0); onWalletChangedSuppressions++; // Map block hash to transactions that appear in it. We ensure that the map values are sorted according // to their relative position within those blocks. ArrayListMultimap<Sha256Hash, TxOffsetPair> mapBlockTx = ArrayListMultimap.create(); for (Transaction tx : getTransactions(true)) { Map<Sha256Hash, Integer> appearsIn = tx.getAppearsInHashes(); if (appearsIn == null) continue; // Pending. for (Map.Entry<Sha256Hash, Integer> block : appearsIn.entrySet()) mapBlockTx.put(block.getKey(), new TxOffsetPair(tx, block.getValue())); } for (Sha256Hash blockHash : mapBlockTx.keySet()) Collections.sort(mapBlockTx.get(blockHash)); List<Sha256Hash> oldBlockHashes = new ArrayList<Sha256Hash>(oldBlocks.size()); log.info("Old part of chain (top to bottom):"); for (StoredBlock b : oldBlocks) { log.info(" {}", b.getHeader().getHashAsString()); oldBlockHashes.add(b.getHeader().getHash()); } log.info("New part of chain (top to bottom):"); for (StoredBlock b : newBlocks) { log.info(" {}", b.getHeader().getHashAsString()); } Collections.reverse(newBlocks); // Need bottom-to-top but we get top-to-bottom. // For each block in the old chain, disconnect the transactions in reverse order. LinkedList<Transaction> oldChainTxns = Lists.newLinkedList(); for (Sha256Hash blockHash : oldBlockHashes) { for (TxOffsetPair pair : mapBlockTx.get(blockHash)) { Transaction tx = pair.tx; final Sha256Hash txHash = tx.getHash(); if (tx.isCoinBase()) { // All the transactions that we have in our wallet which spent this coinbase are now invalid // and will never confirm. Hopefully this should never happen - that's the point of the maturity // rule that forbids spending of coinbase transactions for 100 blocks. // // This could be recursive, although of course because we don't have the full transaction // graph we can never reliably kill all transactions we might have that were rooted in // this coinbase tx. Some can just go pending forever, like the Satoshi client. However we // can do our best. // // TODO: Is it better to try and sometimes fail, or not try at all? killCoinbase(tx); } else { for (TransactionOutput output : tx.getOutputs()) { TransactionInput input = output.getSpentBy(); if (input != null) input.disconnect(); } for (TransactionInput input : tx.getInputs()) { input.disconnect(); } oldChainTxns.add(tx); unspent.remove(txHash); spent.remove(txHash); checkState(!pending.containsKey(txHash)); checkState(!dead.containsKey(txHash)); } } } // Put all the disconnected transactions back into the pending pool and re-connect them. for (Transaction tx : oldChainTxns) { // Coinbase transactions on the old part of the chain are dead for good and won't come back unless // there's another re-org. if (tx.isCoinBase()) continue; log.info(" ->pending {}", tx.getHash()); tx.getConfidence().setConfidenceType(ConfidenceType.PENDING); // Wipe height/depth/work data. confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.TYPE); addWalletTransaction(Pool.PENDING, tx); updateForSpends(tx, false); } // Note that dead transactions stay dead. Consider a chain that Finney attacks T1 and replaces it with // T2, so we move T1 into the dead pool. If there's now a re-org to a chain that doesn't include T2, it // doesn't matter - the miners deleted T1 from their mempool, will resurrect T2 and put that into the // mempool and so T1 is still seen as a losing double spend. // The old blocks have contributed to the depth and work done for all the transactions in the // wallet that are in blocks up to and including the chain split block. // The total depth and work done is calculated here and then subtracted from the appropriate transactions. int depthToSubtract = oldBlocks.size(); BigInteger workDoneToSubtract = BigInteger.ZERO; for (StoredBlock b : oldBlocks) { workDoneToSubtract = workDoneToSubtract.add(b.getHeader().getWork()); } log.info("depthToSubtract = " + depthToSubtract + ", workDoneToSubtract = " + workDoneToSubtract); // Remove depthToSubtract and workDoneToSubtract from all transactions in the wallet except for pending. subtractDepthAndWorkDone(depthToSubtract, workDoneToSubtract, spent.values()); subtractDepthAndWorkDone(depthToSubtract, workDoneToSubtract, unspent.values()); subtractDepthAndWorkDone(depthToSubtract, workDoneToSubtract, dead.values()); // The effective last seen block is now the split point so set the lastSeenBlockHash. setLastBlockSeenHash(splitPoint.getHeader().getHash()); // For each block in the new chain, work forwards calling receive() and notifyNewBestBlock(). // This will pull them back out of the pending pool, or if the tx didn't appear in the old chain and // does appear in the new chain, will treat it as such and possibly kill pending transactions that // conflict. for (StoredBlock block : newBlocks) { log.info("Replaying block {}", block.getHeader().getHashAsString()); for (TxOffsetPair pair : mapBlockTx.get(block.getHeader().getHash())) { log.info(" tx {}", pair.tx.getHash()); try { receive(pair.tx, block, BlockChain.NewBlockType.BEST_CHAIN, pair.offset); } catch (ScriptException e) { throw new RuntimeException(e); // Cannot happen as these blocks were already verified. } } notifyNewBestBlock(block); } checkState(isConsistent()); final BigInteger balance = getBalance(); log.info("post-reorg balance is {}", Utils.bitcoinValueToFriendlyString(balance)); // Inform event listeners that a re-org took place. queueOnReorganize(); insideReorg = false; onWalletChangedSuppressions--; maybeQueueOnWalletChanged(); checkBalanceFuturesLocked(balance); informConfidenceListenersIfNotReorganizing(); saveLater(); } finally { lock.unlock(); } } /** * Subtract the supplied depth and work done from the given transactions. */ private void subtractDepthAndWorkDone(int depthToSubtract, BigInteger workDoneToSubtract, Collection<Transaction> transactions) { for (Transaction tx : transactions) { if (tx.getConfidence().getConfidenceType() == ConfidenceType.BUILDING) { tx.getConfidence().setDepthInBlocks(tx.getConfidence().getDepthInBlocks() - depthToSubtract); tx.getConfidence().setWorkDone(tx.getConfidence().getWorkDone().subtract(workDoneToSubtract)); confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.DEPTH); } } } /** * Returns an immutable view of the transactions currently waiting for network confirmations. */ public Collection<Transaction> getPendingTransactions() { lock.lock(); try { return Collections.unmodifiableCollection(pending.values()); } finally { lock.unlock(); } } /** * Returns the earliest creation time of keys or watched scripts in this wallet, in seconds since the epoch, ie the min * of {@link com.google.bitcoin.core.ECKey#getCreationTimeSeconds()}. This can return zero if at least one key does * not have that data (was created before key timestamping was implemented). <p> * * This method is most often used in conjunction with {@link PeerGroup#setFastCatchupTimeSecs(long)} in order to * optimize chain download for new users of wallet apps. Backwards compatibility notice: if you get zero from this * method, you can instead use the time of the first release of your software, as it's guaranteed no users will * have wallets pre-dating this time. <p> * * If there are no keys in the wallet, the current time is returned. */ @Override public long getEarliestKeyCreationTime() { lock.lock(); try { long earliestTime = Long.MAX_VALUE; for (ECKey key : keychain) earliestTime = Math.min(key.getCreationTimeSeconds(), earliestTime); for (Script script : watchedScripts) earliestTime = Math.min(script.getCreationTimeSeconds(), earliestTime); if (earliestTime == Long.MAX_VALUE) return Utils.currentTimeMillis() / 1000; return earliestTime; } finally { lock.unlock(); } } /** Returns the hash of the last seen best-chain block, or null if the wallet is too old to store this data. */ @Nullable public Sha256Hash getLastBlockSeenHash() { lock.lock(); try { return lastBlockSeenHash; } finally { lock.unlock(); } } public void setLastBlockSeenHash(@Nullable Sha256Hash lastBlockSeenHash) { lock.lock(); try { this.lastBlockSeenHash = lastBlockSeenHash; } finally { lock.unlock(); } } public void setLastBlockSeenHeight(int lastBlockSeenHeight) { lock.lock(); try { this.lastBlockSeenHeight = lastBlockSeenHeight; } finally { lock.unlock(); } } public void setLastBlockSeenTimeSecs(long timeSecs) { lock.lock(); try { lastBlockSeenTimeSecs = timeSecs; } finally { lock.unlock(); } } /** * Returns the UNIX time in seconds since the epoch extracted from the last best seen block header. This timestamp * is <b>not</b> the local time at which the block was first observed by this application but rather what the block * (i.e. miner) self declares. It is allowed to have some significant drift from the real time at which the block * was found, although most miners do use accurate times. If this wallet is old and does not have a recorded * time then this method returns zero. */ public long getLastBlockSeenTimeSecs() { lock.lock(); try { return lastBlockSeenTimeSecs; } finally { lock.unlock(); } } /** * Returns a {@link Date} representing the time extracted from the last best seen block header. This timestamp * is <b>not</b> the local time at which the block was first observed by this application but rather what the block * (i.e. miner) self declares. It is allowed to have some significant drift from the real time at which the block * was found, although most miners do use accurate times. If this wallet is old and does not have a recorded * time then this method returns null. */ @Nullable public Date getLastBlockSeenTime() { final long secs = getLastBlockSeenTimeSecs(); if (secs == 0) return null; else return new Date(secs * 1000); } /** * Returns the height of the last seen best-chain block. Can be 0 if a wallet is brand new or -1 if the wallet * is old and doesn't have that data. */ public int getLastBlockSeenHeight() { lock.lock(); try { return lastBlockSeenHeight; } finally { lock.unlock(); } } /** * Convenience wrapper around {@link Wallet#encrypt(com.google.bitcoin.crypto.KeyCrypter, * org.spongycastle.crypto.params.KeyParameter)} which uses the default Scrypt key derivation algorithm and * parameters, derives a key from the given password and returns the created key. */ public KeyParameter encrypt(CharSequence password) { checkNotNull(password); checkArgument(password.length() > 0); KeyCrypter scrypt = new KeyCrypterScrypt(); KeyParameter derivedKey = scrypt.deriveKey(password); encrypt(scrypt, derivedKey); return derivedKey; } /** * Encrypt the wallet using the KeyCrypter and the AES key. A good default KeyCrypter to use is * {@link com.google.bitcoin.crypto.KeyCrypterScrypt}. * * @param keyCrypter The KeyCrypter that specifies how to encrypt/ decrypt a key * @param aesKey AES key to use (normally created using KeyCrypter#deriveKey and cached as it is time consuming to create from a password) * @throws KeyCrypterException Thrown if the wallet encryption fails. If so, the wallet state is unchanged. */ public void encrypt(KeyCrypter keyCrypter, KeyParameter aesKey) { lock.lock(); try { checkNotNull(keyCrypter); checkState(getEncryptionType() == EncryptionType.UNENCRYPTED, "Wallet is already encrypted"); // Create a new arraylist that will contain the encrypted keys ArrayList<ECKey> encryptedKeyChain = new ArrayList<ECKey>(); for (ECKey key : keychain) { if (key.isEncrypted()) { // Key is already encrypted - add as is. encryptedKeyChain.add(key); } else { // Encrypt the key. ECKey encryptedKey = key.encrypt(keyCrypter, aesKey); // Check that the encrypted key can be successfully decrypted. // This is done as it is a critical failure if the private key cannot be decrypted successfully // (all bitcoin controlled by that private key is lost forever). // For a correctly constructed keyCrypter the encryption should always be reversible so it is just being as cautious as possible. if (!ECKey.encryptionIsReversible(key, encryptedKey, keyCrypter, aesKey)) { // Abort encryption throw new KeyCrypterException("The key " + key.toString() + " cannot be successfully decrypted after encryption so aborting wallet encryption."); } encryptedKeyChain.add(encryptedKey); } } // Now ready to use the encrypted keychain so go through the old keychain clearing all the unencrypted private keys. // (This is to avoid the possibility of key recovery from memory). for (ECKey key : keychain) { if (!key.isEncrypted()) { key.clearPrivateKey(); } } // Replace the old keychain with the encrypted one. keychain = encryptedKeyChain; // The wallet is now encrypted. this.keyCrypter = keyCrypter; saveNow(); } finally { lock.unlock(); } } /** * Decrypt the wallet with the wallets keyCrypter and AES key. * * @param aesKey AES key to use (normally created using KeyCrypter#deriveKey and cached as it is time consuming to create from a password) * @throws KeyCrypterException Thrown if the wallet decryption fails. If so, the wallet state is unchanged. */ public void decrypt(KeyParameter aesKey) { lock.lock(); try { // Check the wallet is already encrypted - you cannot decrypt an unencrypted wallet. checkState(getEncryptionType() != EncryptionType.UNENCRYPTED, "Wallet is already decrypted"); // Check that the wallet keyCrypter is non-null. // This is set either at construction (if an encrypted wallet is created) or by wallet encryption. checkNotNull(keyCrypter); // Create a new arraylist that will contain the decrypted keys ArrayList<ECKey> decryptedKeyChain = new ArrayList<ECKey>(); for (ECKey key : keychain) { // Decrypt the key. if (!key.isEncrypted()) { // Not encrypted - add to chain as is. decryptedKeyChain.add(key); } else { ECKey decryptedECKey = key.decrypt(keyCrypter, aesKey); decryptedKeyChain.add(decryptedECKey); } } // Replace the old keychain with the unencrypted one. keychain = decryptedKeyChain; // The wallet is now unencrypted. keyCrypter = null; saveNow(); } finally { lock.unlock(); } } /** * Create a new, random encrypted ECKey and add it to the wallet. * * @param keyCrypter The keyCrypter to use in encrypting the new key * @param aesKey The AES key to use to encrypt the new key * @return ECKey the new, encrypted ECKey */ public ECKey addNewEncryptedKey(KeyCrypter keyCrypter, KeyParameter aesKey) { ECKey newKey = (new ECKey()).encrypt(checkNotNull(keyCrypter), checkNotNull(aesKey)); addKey(newKey); return newKey; } /** * <p>Convenience wrapper around {@link Wallet#addNewEncryptedKey(com.google.bitcoin.crypto.KeyCrypter, * org.spongycastle.crypto.params.KeyParameter)} which just derives the key afresh and uses the pre-set * keycrypter. The wallet must have been encrypted using one of the encrypt methods previously.</p> * * <p>Note that key derivation is deliberately very slow! So if you plan to add multiple keys, it can be * faster to use the other method instead and re-use the {@link KeyParameter} object instead.</p> */ public ECKey addNewEncryptedKey(CharSequence password) { lock.lock(); try { checkNotNull(keyCrypter, "Wallet is not encrypted, you must call encrypt() first."); return addNewEncryptedKey(keyCrypter, keyCrypter.deriveKey(password)); } finally { lock.unlock(); } } /** * Check whether the password can decrypt the first key in the wallet. * This can be used to check the validity of an entered password. * * @return boolean true if password supplied can decrypt the first private key in the wallet, false otherwise. */ public boolean checkPassword(CharSequence password) { lock.lock(); try { return keyCrypter != null && checkAESKey(keyCrypter.deriveKey(checkNotNull(password))); } finally { lock.unlock(); } } /** * Check whether the AES key can decrypt the first encrypted key in the wallet. * * @return boolean true if AES key supplied can decrypt the first encrypted private key in the wallet, false otherwise. */ public boolean checkAESKey(KeyParameter aesKey) { lock.lock(); try { // If no keys then cannot decrypt. if (!getKeys().iterator().hasNext()) return false; // Find the first encrypted key in the wallet. ECKey firstEncryptedECKey = null; Iterator<ECKey> iterator = getKeys().iterator(); while (iterator.hasNext() && firstEncryptedECKey == null) { ECKey loopECKey = iterator.next(); if (loopECKey.isEncrypted()) { firstEncryptedECKey = loopECKey; } } // There are no encrypted keys in the wallet. if (firstEncryptedECKey == null) return false; String originalAddress = firstEncryptedECKey.toAddress(getNetworkParameters()).toString(); if (firstEncryptedECKey.isEncrypted() && firstEncryptedECKey.getEncryptedPrivateKey() != null) { try { ECKey rebornKey = firstEncryptedECKey.decrypt(keyCrypter, aesKey); // Check that the decrypted private key's address is correct ie it decrypted accurately. String rebornAddress = rebornKey.toAddress(getNetworkParameters()).toString(); return originalAddress.equals(rebornAddress); } catch (KeyCrypterException ede) { // The AES key supplied is incorrect. return false; } } return false; } finally { lock.unlock(); } } /** * Get the wallet's KeyCrypter. * (Used in encrypting/ decrypting an ECKey). */ public KeyCrypter getKeyCrypter() { lock.lock(); try { return keyCrypter; } finally { lock.unlock(); } } /** * Sets the wallet's KeyCrypter. * Note that this does not encrypt the wallet, and should only be used if the keyCrypter can not be included in the * constructor during initial wallet loading. * Note that if the keyCrypter was not properly set during wallet load, {@link Wallet#getEncryptionType()} and * {@link Wallet#isEncrypted()} will not return the correct results. */ public void setKeyCrypter(KeyCrypter keyCrypter) { lock.lock(); try { checkState(this.keyCrypter == null); this.keyCrypter = keyCrypter; } finally { lock.unlock(); } } /** * Get the type of encryption used for this wallet. * * (This is a convenience method - the encryption type is actually stored in the keyCrypter). */ public EncryptionType getEncryptionType() { lock.lock(); try { if (keyCrypter == null) { // Unencrypted wallet. return EncryptionType.UNENCRYPTED; } else { return keyCrypter.getUnderstoodEncryptionType(); } } finally { lock.unlock(); } } /** Returns true if the wallet is encrypted using any scheme, false if not. */ public boolean isEncrypted() { return getEncryptionType() != EncryptionType.UNENCRYPTED; } /** * Get the version of the Wallet. * This is an int you can use to indicate which versions of wallets your code understands, * and which come from the future (and hence cannot be safely loaded). */ public int getVersion() { return version; } /** * Set the version number of the wallet. See {@link Wallet#getVersion()}. */ public void setVersion(int version) { this.version = version; } /** * Set the description of the wallet. * This is a Unicode encoding string typically entered by the user as descriptive text for the wallet. */ public void setDescription(String description) { this.description = description; } /** * Get the description of the wallet. See {@link Wallet#setDescription(String))} */ public String getDescription() { return description; } @Override public int getBloomFilterElementCount() { int size = getKeychainSize() * 2; for (Transaction tx : getTransactions(false)) { for (TransactionOutput out : tx.getOutputs()) { try { if (isTxOutputBloomFilterable(out)) size++; } catch (ScriptException e) { throw new RuntimeException(e); // If it is ours, we parsed the script correctly, so this shouldn't happen } } } // Some scripts may have more than one bloom element. That should normally be okay, // because under-counting just increases false-positive rate. size += watchedScripts.size(); return size; } /** * If we are watching any scripts, the bloom filter must update on peers whenever an output is * identified. This is because we don't necessarily have the associated pubkey, so we can't * watch for it on spending transactions. */ @Override public boolean isRequiringUpdateAllBloomFilter() { return !watchedScripts.isEmpty(); } /** * Gets a bloom filter that contains all of the public keys from this wallet, and which will provide the given * false-positive rate. See the docs for {@link BloomFilter} for a brief explanation of anonymity when using filters. */ public BloomFilter getBloomFilter(double falsePositiveRate) { return getBloomFilter(getBloomFilterElementCount(), falsePositiveRate, (long)(Math.random()*Long.MAX_VALUE)); } /** * Gets a bloom filter that contains all of the public keys from this wallet, * and which will provide the given false-positive rate if it has size elements. * Keep in mind that you will get 2 elements in the bloom filter for each key in the wallet. * * This is used to generate a BloomFilter which can be #{link BloomFilter.merge}d with another. * It could also be used if you have a specific target for the filter's size. * * See the docs for {@link BloomFilter(int, double)} for a brief explanation of anonymity when using bloom filters. */ @Override public BloomFilter getBloomFilter(int size, double falsePositiveRate, long nTweak) { BloomFilter filter = new BloomFilter(size, falsePositiveRate, nTweak); lock.lock(); try { for (ECKey key : keychain) { filter.insert(key.getPubKey()); filter.insert(key.getPubKeyHash()); } for (Script script : watchedScripts) { for (ScriptChunk chunk : script.getChunks()) { // Only add long (at least 64 bit) data to the bloom filter. // If any long constants become popular in scripts, we will need logic // here to exclude them. if (!chunk.isOpCode() && chunk.data.length >= MINIMUM_BLOOM_DATA_LENGTH) { filter.insert(chunk.data); } } } } finally { lock.unlock(); } for (Transaction tx : getTransactions(false)) { for (int i = 0; i < tx.getOutputs().size(); i++) { TransactionOutput out = tx.getOutputs().get(i); try { if (isTxOutputBloomFilterable(out)) { TransactionOutPoint outPoint = new TransactionOutPoint(params, i, tx); filter.insert(outPoint.bitcoinSerialize()); } } catch (ScriptException e) { throw new RuntimeException(e); // If it is ours, we parsed the script correctly, so this shouldn't happen } } } return filter; } private boolean isTxOutputBloomFilterable(TransactionOutput out) { return (out.isMine(this) && out.getScriptPubKey().isSentToRawPubKey()) || out.isWatched(this); } /** Returns the {@link CoinSelector} object which controls which outputs can be spent by this wallet. */ public CoinSelector getCoinSelector() { lock.lock(); try { return coinSelector; } finally { lock.unlock(); } } /** * A coin selector is responsible for choosing which outputs to spend when creating transactions. The default * selector implements a policy of spending transactions that appeared in the best chain and pending transactions * that were created by this wallet, but not others. You can override the coin selector for any given send * operation by changing {@link Wallet.SendRequest#coinSelector}. */ public void setCoinSelector(@Nonnull CoinSelector coinSelector) { lock.lock(); try { this.coinSelector = checkNotNull(coinSelector); } finally { lock.unlock(); } } /** * Convenience wrapper for <tt>setCoinSelector(Wallet.AllowUnconfirmedCoinSelector.get())</tt>. If this method * is called on the wallet then transactions will be used for spending regardless of their confidence. This can * be dangerous - only use this if you absolutely know what you're doing! */ public void allowSpendingUnconfirmedTransactions() { setCoinSelector(AllowUnconfirmedCoinSelector.get()); } private static class BalanceFutureRequest { public SettableFuture<BigInteger> future; public BigInteger value; public BalanceType type; } @GuardedBy("lock") private List<BalanceFutureRequest> balanceFutureRequests = Lists.newLinkedList(); /** * <p>Returns a future that will complete when the balance of the given type has becom equal or larger to the given * value. If the wallet already has a large enough balance the future is returned in a pre-completed state. Note * that this method is not blocking, if you want to actually wait immediately, you have to call .get() on * the result.</p> * * <p>Also note that by the time the future completes, the wallet may have changed yet again if something else * is going on in parallel, so you should treat the returned balance as advisory and be prepared for sending * money to fail! Finally please be aware that any listeners on the future will run either on the calling thread * if it completes immediately, or eventually on a background thread if the balance is not yet at the right * level. If you do something that means you know the balance should be sufficient to trigger the future, * you can use {@link com.google.bitcoin.utils.Threading#waitForUserCode()} to block until the future had a * chance to be updated.</p> */ public ListenableFuture<BigInteger> getBalanceFuture(final BigInteger value, final BalanceType type) { lock.lock(); try { final SettableFuture<BigInteger> future = SettableFuture.create(); final BigInteger current = getBalance(type); if (current.compareTo(value) >= 0) { // Already have enough. future.set(current); } else { // Will be checked later in checkBalanceFutures. We don't just add an event listener for ourselves // here so that running getBalanceFuture().get() in the user code thread works - generally we must // avoid giving the user back futures that require the user code thread to be free. BalanceFutureRequest req = new BalanceFutureRequest(); req.future = future; req.value = value; req.type = type; balanceFutureRequests.add(req); } return future; } finally { lock.unlock(); } } // Runs any balance futures in the user code thread. private void checkBalanceFuturesLocked(@Nullable BigInteger avail) { checkState(lock.isHeldByCurrentThread()); BigInteger estimated = null; final ListIterator<BalanceFutureRequest> it = balanceFutureRequests.listIterator(); while (it.hasNext()) { final BalanceFutureRequest req = it.next(); BigInteger val = null; if (req.type == BalanceType.AVAILABLE) { if (avail == null) avail = getBalance(BalanceType.AVAILABLE); if (avail.compareTo(req.value) < 0) continue; val = avail; } else if (req.type == BalanceType.ESTIMATED) { if (estimated == null) estimated = getBalance(BalanceType.ESTIMATED); if (estimated.compareTo(req.value) < 0) continue; val = estimated; } // Found one that's finished. it.remove(); final BigInteger v = checkNotNull(val); // Don't run any user-provided future listeners with our lock held. Threading.USER_THREAD.execute(new Runnable() { @Override public void run() { req.future.set(v); } }); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Extensions to the wallet format. /** * By providing an object implementing the {@link WalletExtension} interface, you can save and load arbitrary * additional data that will be stored with the wallet. Each extension is identified by an ID, so attempting to * add the same extension twice (or two different objects that use the same ID) will throw an IllegalStateException. */ public void addExtension(WalletExtension extension) { String id = checkNotNull(extension).getWalletExtensionID(); lock.lock(); try { if (extensions.containsKey(id)) throw new IllegalStateException("Cannot add two extensions with the same ID: " + id); extensions.put(id, extension); saveNow(); } finally { lock.unlock(); } } /** * Atomically adds extension or returns an existing extension if there is one with the same id alreadypresent. */ public WalletExtension addOrGetExistingExtension(WalletExtension extension) { String id = checkNotNull(extension).getWalletExtensionID(); lock.lock(); try { WalletExtension previousExtension = extensions.get(id); if (previousExtension != null) return previousExtension; extensions.put(id, extension); saveNow(); return extension; } finally { lock.unlock(); } } /** * Either adds extension as a new extension or replaces the existing extension if one already exists with the same * id. This also triggers wallet auto-saving, so may be useful even when called with the same extension as is * already present. */ public void addOrUpdateExtension(WalletExtension extension) { String id = checkNotNull(extension).getWalletExtensionID(); lock.lock(); try { extensions.put(id, extension); saveNow(); } finally { lock.unlock(); } } /** Returns a snapshot of all registered extension objects. The extensions themselves are not copied. */ public Map<String, WalletExtension> getExtensions() { lock.lock(); try { return ImmutableMap.copyOf(extensions); } finally { lock.unlock(); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Boilerplate for running event listeners - dispatches events onto the user code thread (where we don't do // anything and hold no locks). private void queueOnTransactionConfidenceChanged(final Transaction tx) { checkState(lock.isHeldByCurrentThread()); for (final ListenerRegistration<WalletEventListener> registration : eventListeners) { if (registration.executor == Threading.SAME_THREAD) { registration.listener.onTransactionConfidenceChanged(this, tx); } else { registration.executor.execute(new Runnable() { @Override public void run() { registration.listener.onTransactionConfidenceChanged(Wallet.this, tx); } }); } } } private void maybeQueueOnWalletChanged() { // Don't invoke the callback in some circumstances, eg, whilst we are re-organizing or fiddling with // transactions due to a new block arriving. It will be called later instead. checkState(lock.isHeldByCurrentThread()); checkState(onWalletChangedSuppressions >= 0); if (onWalletChangedSuppressions > 0) return; for (final ListenerRegistration<WalletEventListener> registration : eventListeners) { registration.executor.execute(new Runnable() { @Override public void run() { registration.listener.onWalletChanged(Wallet.this); } }); } } private void queueOnCoinsReceived(final Transaction tx, final BigInteger balance, final BigInteger newBalance) { checkState(lock.isHeldByCurrentThread()); for (final ListenerRegistration<WalletEventListener> registration : eventListeners) { registration.executor.execute(new Runnable() { @Override public void run() { registration.listener.onCoinsReceived(Wallet.this, tx, balance, newBalance); } }); } } private void queueOnCoinsSent(final Transaction tx, final BigInteger prevBalance, final BigInteger newBalance) { checkState(lock.isHeldByCurrentThread()); for (final ListenerRegistration<WalletEventListener> registration : eventListeners) { registration.executor.execute(new Runnable() { @Override public void run() { registration.listener.onCoinsSent(Wallet.this, tx, prevBalance, newBalance); } }); } } private void queueOnReorganize() { checkState(lock.isHeldByCurrentThread()); checkState(insideReorg); for (final ListenerRegistration<WalletEventListener> registration : eventListeners) { registration.executor.execute(new Runnable() { @Override public void run() { registration.listener.onReorganize(Wallet.this); } }); } } private void queueOnKeysAdded(final List<ECKey> keys) { checkState(lock.isHeldByCurrentThread()); for (final ListenerRegistration<WalletEventListener> registration : eventListeners) { registration.executor.execute(new Runnable() { @Override public void run() { registration.listener.onKeysAdded(Wallet.this, keys); } }); } } private void queueOnScriptsAdded(final List<Script> scripts) { checkState(lock.isHeldByCurrentThread()); for (final ListenerRegistration<WalletEventListener> registration : eventListeners) { registration.executor.execute(new Runnable() { @Override public void run() { registration.listener.onScriptsAdded(Wallet.this, scripts); } }); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Fee calculation code. private class FeeCalculation { private CoinSelection bestCoinSelection; private TransactionOutput bestChangeOutput; public FeeCalculation(SendRequest req, BigInteger value, List<TransactionInput> originalInputs, boolean needAtLeastReferenceFee, LinkedList<TransactionOutput> candidates) throws InsufficientMoneyException { checkState(lock.isHeldByCurrentThread()); // There are 3 possibilities for what adding change might do: // 1) No effect // 2) Causes increase in fee (change < 0.01 COINS) // 3) Causes the transaction to have a dust output or change < fee increase (ie change will be thrown away) // If we get either of the last 2, we keep note of what the inputs looked like at the time and try to // add inputs as we go up the list (keeping track of minimum inputs for each category). At the end, we pick // the best input set as the one which generates the lowest total fee. BigInteger additionalValueForNextCategory = null; CoinSelection selection3 = null; CoinSelection selection2 = null; TransactionOutput selection2Change = null; CoinSelection selection1 = null; TransactionOutput selection1Change = null; // We keep track of the last size of the transaction we calculated but only if the act of adding inputs and // change resulted in the size crossing a 1000 byte boundary. Otherwise it stays at zero. int lastCalculatedSize = 0; BigInteger valueNeeded, valueMissing = null; while (true) { resetTxInputs(req, originalInputs); BigInteger fees = req.fee == null ? BigInteger.ZERO : req.fee; if (lastCalculatedSize > 0) { // If the size is exactly 1000 bytes then we'll over-pay, but this should be rare. fees = fees.add(BigInteger.valueOf((lastCalculatedSize / 1000) + 1).multiply(req.feePerKb)); } else { fees = fees.add(req.feePerKb); // First time around the loop. } if (needAtLeastReferenceFee && fees.compareTo(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE) < 0) fees = Transaction.REFERENCE_DEFAULT_MIN_TX_FEE; valueNeeded = value.add(fees); if (additionalValueForNextCategory != null) valueNeeded = valueNeeded.add(additionalValueForNextCategory); BigInteger additionalValueSelected = additionalValueForNextCategory; // Of the coins we could spend, pick some that we actually will spend. CoinSelector selector = req.coinSelector == null ? coinSelector : req.coinSelector; CoinSelection selection = selector.select(valueNeeded, candidates); // Can we afford this? if (selection.valueGathered.compareTo(valueNeeded) < 0) { valueMissing = valueNeeded.subtract(selection.valueGathered); break; } checkState(selection.gathered.size() > 0 || originalInputs.size() > 0); // We keep track of an upper bound on transaction size to calculate fees that need to be added. // Note that the difference between the upper bound and lower bound is usually small enough that it // will be very rare that we pay a fee we do not need to. // // We can't be sure a selection is valid until we check fee per kb at the end, so we just store // them here temporarily. boolean eitherCategory2Or3 = false; boolean isCategory3 = false; BigInteger change = selection.valueGathered.subtract(valueNeeded); if (additionalValueSelected != null) change = change.add(additionalValueSelected); // If change is < 0.01 BTC, we will need to have at least minfee to be accepted by the network if (req.ensureMinRequiredFee && !change.equals(BigInteger.ZERO) && change.compareTo(Utils.CENT) < 0 && fees.compareTo(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE) < 0) { // This solution may fit into category 2, but it may also be category 3, we'll check that later eitherCategory2Or3 = true; additionalValueForNextCategory = Utils.CENT; // If the change is smaller than the fee we want to add, this will be negative change = change.subtract(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.subtract(fees)); } int size = 0; TransactionOutput changeOutput = null; if (change.compareTo(BigInteger.ZERO) > 0) { // The value of the inputs is greater than what we want to send. Just like in real life then, // we need to take back some coins ... this is called "change". Add another output that sends the change // back to us. The address comes either from the request or getChangeAddress() as a default. Address changeAddress = req.changeAddress; if (changeAddress == null) changeAddress = getChangeAddress(); changeOutput = new TransactionOutput(params, req.tx, change, changeAddress); // If the change output would result in this transaction being rejected as dust, just drop the change and make it a fee if (req.ensureMinRequiredFee && Transaction.MIN_NONDUST_OUTPUT.compareTo(change) >= 0) { // This solution definitely fits in category 3 isCategory3 = true; additionalValueForNextCategory = Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.add( Transaction.MIN_NONDUST_OUTPUT.add(BigInteger.ONE)); } else { size += changeOutput.bitcoinSerialize().length + VarInt.sizeOf(req.tx.getOutputs().size()) - VarInt.sizeOf(req.tx.getOutputs().size() - 1); // This solution is either category 1 or 2 if (!eitherCategory2Or3) // must be category 1 additionalValueForNextCategory = null; } } else { if (eitherCategory2Or3) { // This solution definitely fits in category 3 (we threw away change because it was smaller than MIN_TX_FEE) isCategory3 = true; additionalValueForNextCategory = Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.add(BigInteger.ONE); } } // Now add unsigned inputs for the selected coins. for (TransactionOutput output : selection.gathered) { TransactionInput input = req.tx.addInput(output); // If the scriptBytes don't default to none, our size calculations will be thrown off. checkState(input.getScriptBytes().length == 0); } // Estimate transaction size and loop again if we need more fee per kb. The serialized tx doesn't // include things we haven't added yet like input signatures/scripts or the change output. size += req.tx.bitcoinSerialize().length; size += estimateBytesForSigning(selection); if (size/1000 > lastCalculatedSize/1000 && req.feePerKb.compareTo(BigInteger.ZERO) > 0) { lastCalculatedSize = size; // We need more fees anyway, just try again with the same additional value additionalValueForNextCategory = additionalValueSelected; continue; } if (isCategory3) { if (selection3 == null) selection3 = selection; } else if (eitherCategory2Or3) { // If we are in selection2, we will require at least CENT additional. If we do that, there is no way // we can end up back here because CENT additional will always get us to 1 checkState(selection2 == null); checkState(additionalValueForNextCategory.equals(Utils.CENT)); selection2 = selection; selection2Change = checkNotNull(changeOutput); // If we get no change in category 2, we are actually in category 3 } else { // Once we get a category 1 (change kept), we should break out of the loop because we can't do better checkState(selection1 == null); checkState(additionalValueForNextCategory == null); selection1 = selection; selection1Change = changeOutput; } if (additionalValueForNextCategory != null) { if (additionalValueSelected != null) checkState(additionalValueForNextCategory.compareTo(additionalValueSelected) > 0); continue; } break; } resetTxInputs(req, originalInputs); if (selection3 == null && selection2 == null && selection1 == null) { checkNotNull(valueMissing); log.warn("Insufficient value in wallet for send: needed {} more", bitcoinValueToFriendlyString(valueMissing)); throw new InsufficientMoneyException(valueMissing); } BigInteger lowestFee = null; bestCoinSelection = null; bestChangeOutput = null; if (selection1 != null) { if (selection1Change != null) lowestFee = selection1.valueGathered.subtract(selection1Change.getValue()); else lowestFee = selection1.valueGathered; bestCoinSelection = selection1; bestChangeOutput = selection1Change; } if (selection2 != null) { BigInteger fee = selection2.valueGathered.subtract(checkNotNull(selection2Change).getValue()); if (lowestFee == null || fee.compareTo(lowestFee) < 0) { lowestFee = fee; bestCoinSelection = selection2; bestChangeOutput = selection2Change; } } if (selection3 != null) { if (lowestFee == null || selection3.valueGathered.compareTo(lowestFee) < 0) { bestCoinSelection = selection3; bestChangeOutput = null; } } } private void resetTxInputs(SendRequest req, List<TransactionInput> originalInputs) { req.tx.clearInputs(); for (TransactionInput input : originalInputs) req.tx.addInput(input); } } private int estimateBytesForSigning(CoinSelection selection) { int size = 0; for (TransactionOutput output : selection.gathered) { try { if (output.getScriptPubKey().isSentToAddress()) { // Send-to-address spends usually take maximum pubkey.length (as it may be compressed or not) + 75 bytes final ECKey key = findKeyFromPubHash(output.getScriptPubKey().getPubKeyHash()); size += checkNotNull(key, "Coin selection includes unspendable outputs").getPubKey().length + 75; } else if (output.getScriptPubKey().isSentToRawPubKey()) size += 74; // Send-to-pubkey spends usually take maximum 74 bytes to spend else throw new IllegalStateException("Unknown output type returned in coin selection"); } catch (ScriptException e) { // If this happens it means an output script in a wallet tx could not be understood. That should never // happen, if it does it means the wallet has got into an inconsistent state. throw new IllegalStateException(e); } } return size; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Managing wallet-triggered transaction broadcast and key rotation. /** * <p>Specifies that the given {@link TransactionBroadcaster}, typically a {@link PeerGroup}, should be used for * sending transactions to the Bitcoin network by default. Some sendCoins methods let you specify a broadcaster * explicitly, in that case, they don't use this broadcaster. If null is specified then the wallet won't attempt * to broadcast transactions itself.</p> * * <p>You don't normally need to call this. A {@link PeerGroup} will automatically set itself as the wallets * broadcaster when you use {@link PeerGroup#addWallet(Wallet)}. A wallet can use the broadcaster when you ask * it to send money, but in future also at other times to implement various features that may require asynchronous * re-organisation of the wallet contents on the block chain. For instance, in future the wallet may choose to * optimise itself to reduce fees or improve privacy.</p> */ public void setTransactionBroadcaster(@Nullable com.google.bitcoin.core.TransactionBroadcaster broadcaster) { Transaction[] toBroadcast = {}; lock.lock(); try { if (vTransactionBroadcaster == broadcaster) return; vTransactionBroadcaster = broadcaster; if (broadcaster == null) return; toBroadcast = pending.values().toArray(toBroadcast); } finally { lock.unlock(); } // Now use it to upload any pending transactions we have that are marked as not being seen by any peers yet. // Don't hold the wallet lock whilst doing this, so if the broadcaster accesses the wallet at some point there // is no inversion. for (Transaction tx : toBroadcast) { checkState(tx.getConfidence().getConfidenceType() == ConfidenceType.PENDING); // Re-broadcast even if it's marked as already seen for two reasons // 1) Old wallets may have transactions marked as broadcast by 1 peer when in reality the network // never saw it, due to bugs. // 2) It can't really hurt. log.info("New broadcaster so uploading waiting tx {}", tx.getHash()); broadcaster.broadcastTransaction(tx); } } /** * When a key rotation time is set, and money controlled by keys created before the given timestamp T will be * automatically respent to any key that was created after T. This can be used to recover from a situation where * a set of keys is believed to be compromised. Once the time is set transactions will be created and broadcast * immediately. New coins that come in after calling this method will be automatically respent immediately. The * rotation time is persisted to the wallet. You can stop key rotation by calling this method again with zero * as the argument. */ public void setKeyRotationTime(Date time) { setKeyRotationTime(time.getTime() / 1000); } /** * Returns a UNIX time since the epoch in seconds, or zero if unconfigured. */ public Date getKeyRotationTime() { return new Date(vKeyRotationTimestamp * 1000); } /** * <p>When a key rotation time is set, and money controlled by keys created before the given timestamp T will be * automatically respent to any key that was created after T. This can be used to recover from a situation where * a set of keys is believed to be compromised. Once the time is set transactions will be created and broadcast * immediately. New coins that come in after calling this method will be automatically respent immediately. The * rotation time is persisted to the wallet. You can stop key rotation by calling this method again with zero * as the argument, or by using {@link #setKeyRotationEnabled(boolean)}.</p> * * <p>Note that this method won't do anything unless you call {@link #setKeyRotationEnabled(boolean)} first.</p> */ public void setKeyRotationTime(long unixTimeSeconds) { vKeyRotationTimestamp = unixTimeSeconds; if (unixTimeSeconds > 0) { log.info("Key rotation time set: {}", unixTimeSeconds); maybeRotateKeys(); } saveNow(); } /** Toggles key rotation on and off. Note that this state is not serialized. Activating it can trigger tx sends. */ public void setKeyRotationEnabled(boolean enabled) { vKeyRotationEnabled = enabled; if (enabled) maybeRotateKeys(); } /** Returns whether the keys creation time is before the key rotation time, if one was set. */ public boolean isKeyRotating(ECKey key) { long time = vKeyRotationTimestamp; return time != 0 && key.getCreationTimeSeconds() < time; } // Checks to see if any coins are controlled by rotating keys and if so, spends them. private void maybeRotateKeys() { checkState(!lock.isHeldByCurrentThread()); // TODO: Handle chain replays and encrypted wallets here. if (!vKeyRotationEnabled) return; // Snapshot volatiles so this method has an atomic view. long keyRotationTimestamp = vKeyRotationTimestamp; if (keyRotationTimestamp == 0) return; // Nothing to do. TransactionBroadcaster broadcaster = vTransactionBroadcaster; // Because transactions are size limited, we might not be able to re-key the entire wallet in one go. So // loop around here until we no longer produce transactions with the max number of inputs. That means we're // fully done, at least for now (we may still get more transactions later and this method will be reinvoked). Transaction tx; do { tx = rekeyOneBatch(keyRotationTimestamp, broadcaster); } while (tx != null && tx.getInputs().size() == KeyTimeCoinSelector.MAX_SIMULTANEOUS_INPUTS); } @Nullable private Transaction rekeyOneBatch(long keyRotationTimestamp, final TransactionBroadcaster broadcaster) { final Transaction rekeyTx; lock.lock(); try { // Firstly, see if we have any keys that are beyond the rotation time, and any before. ECKey safeKey = null; boolean haveRotatingKeys = false; for (ECKey key : keychain) { final long t = key.getCreationTimeSeconds(); if (t < keyRotationTimestamp) { haveRotatingKeys = true; } else { safeKey = key; } } if (!haveRotatingKeys) return null; if (safeKey == null) { log.warn("Key rotation requested but no keys newer than the timestamp are available."); return null; } // Build the transaction using some custom logic for our special needs. Last parameter to // KeyTimeCoinSelector is whether to ignore pending transactions or not. // // We ignore pending outputs because trying to rotate these is basically racing an attacker, and // we're quite likely to lose and create stuck double spends. Also, some users who have 0.9 wallets // have already got stuck double spends in their wallet due to the Bloom-filtering block reordering // bug that was fixed in 0.10, thus, making a re-key transaction depend on those would cause it to // never confirm at all. CoinSelector selector = new KeyTimeCoinSelector(this, keyRotationTimestamp, true); CoinSelection toMove = selector.select(BigInteger.ZERO, calculateAllSpendCandidates(true)); if (toMove.valueGathered.equals(BigInteger.ZERO)) return null; // Nothing to do. rekeyTx = new Transaction(params); for (TransactionOutput output : toMove.gathered) { rekeyTx.addInput(output); } rekeyTx.addOutput(toMove.valueGathered, safeKey); if (!adjustOutputDownwardsForFee(rekeyTx, toMove, BigInteger.ZERO, Transaction.REFERENCE_DEFAULT_MIN_TX_FEE)) { log.error("Failed to adjust rekey tx for fees."); return null; } rekeyTx.getConfidence().setSource(TransactionConfidence.Source.SELF); rekeyTx.setPurpose(Transaction.Purpose.KEY_ROTATION); rekeyTx.signInputs(Transaction.SigHash.ALL, this); // KeyTimeCoinSelector should never select enough inputs to push us oversize. checkState(rekeyTx.bitcoinSerialize().length < Transaction.MAX_STANDARD_TX_SIZE); commitTx(rekeyTx); } catch (VerificationException e) { throw new RuntimeException(e); // Cannot happen. } finally { lock.unlock(); } if (broadcaster == null) return rekeyTx; log.info("Attempting to send key rotation tx: {}", rekeyTx); // We must broadcast the tx in a separate thread to avoid inverting any locks. Otherwise we may be running // with the blockchain lock held (whilst receiving a block) and thus re-entering the peerGroup would invert // blockchain <-> peergroup. new Thread() { @Override public void run() { // Handle the future results just for logging. try { Futures.addCallback(broadcaster.broadcastTransaction(rekeyTx), new FutureCallback<Transaction>() { @Override public void onSuccess(Transaction transaction) { log.info("Successfully broadcast key rotation tx: {}", transaction); } @Override public void onFailure(Throwable throwable) { log.error("Failed to broadcast key rotation tx", throwable); } }); } catch (Exception e) { log.error("Failed to broadcast rekey tx, will try again later", e); } } }.start(); return rekeyTx; } /** * Returns the wallet lock under which most operations happen. This is here to satisfy the * {@link com.google.bitcoin.core.PeerFilterProvider} interface and generally should not be used directly by apps. * In particular, do <b>not</b> hold this lock if you're display a send confirm screen to the user or for any other * long length of time, as it may cause processing holdups elsewhere. Instead, for the "confirm payment screen" * use case you should complete a candidate transaction, present it to the user (e.g. for fee purposes) and then * when they confirm - which may be quite some time later - recalculate the transaction and check if it's the same. * If not, redisplay the confirm window and try again. */ public ReentrantLock getLock() { return lock; } }
Fixed comment for Wallet.sendCoins regarding MIN_NONDUST_OUTPUT.
core/src/main/java/com/google/bitcoin/core/Wallet.java
Fixed comment for Wallet.sendCoins regarding MIN_NONDUST_OUTPUT.
Java
apache-2.0
296ba4af8d0ff2b2e16b9eab5d1ecd36d1c50277
0
HyungJon/HubTurbo,HyungJon/HubTurbo,Honoo/HubTurbo,Sumei1009/HubTurbo,gaieepo/HubTurbo,Sumei1009/HubTurbo,saav/HubTurbo,ianngiaw/HubTurbo,gaieepo/HubTurbo,Honoo/HubTurbo,ianngiaw/HubTurbo,saav/HubTurbo
package ui; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.beans.value.WeakChangeListener; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.control.ListView; import javafx.scene.control.cell.CheckBoxListCell; import javafx.scene.layout.VBox; import javafx.util.Callback; public class BetterCheckListView extends VBox { private ObservableList<BetterCheckListItem> items; private ListView<BetterCheckListItem> listView; private ArrayList<ChangeListener<Boolean>> listeners; public BetterCheckListView(ObservableList<String> items) { listeners = new ArrayList<>(); this.listView = new ListView<BetterCheckListItem>(); getChildren().add(listView); setItems(items); } boolean singleSelection = false; public BetterCheckListView setSingleSelection(boolean single) { singleSelection = single; return this; } boolean disabled = false; public void setItems(ObservableList<String> items) { // It's assumed that we won't need to observe this list in the // long term, so we don't use the same list object // Old listeners can be garbage collected listeners.clear(); ObservableList<BetterCheckListItem> newItems = FXCollections.observableArrayList(); WeakReference<BetterCheckListView> that = new WeakReference<>(this); for (int i=0; i<items.size(); i++) { final int j = i; BetterCheckListItem item = new BetterCheckListItem(items.get(i), false); ChangeListener<Boolean> strongListener = new ChangeListener<Boolean>() { public void changed(ObservableValue<? extends Boolean> ov, Boolean oldValue, Boolean newValue) { if (!disabled) { if (singleSelection) { disabled = true; for (BetterCheckListItem item : that.get().items) { item.setChecked(false); } that.get().items.get(j).setChecked(true); disabled = false; } } } }; WeakChangeListener<Boolean> weakListener = new WeakChangeListener<Boolean>(strongListener); item.checkedProperty().addListener(weakListener); // Retain a reference to this listener, so it doesn't get // garbage collected prematurely listeners.add(strongListener); newItems.add(item); } this.items = newItems; refresh(); } public void setChecked(int i, boolean state) { this.items.get(i).setChecked(state); } public boolean getChecked(int i) { return this.items.get(i).isChecked(); } public List<Integer> getCheckedIndices() { ArrayList<Integer> result = new ArrayList<>(); for (int i=0; i<items.size(); i++) { if (items.get(i).isChecked()) { result.add(i); } } return result; } private void refresh() { listView.setCellFactory(CheckBoxListCell.forListView(new Callback<BetterCheckListItem, ObservableValue<Boolean>>() { @Override public ObservableValue<Boolean> call(BetterCheckListItem item) { return item.checkedProperty(); } })); listView.setItems(items); } }
src/ui/BetterCheckListView.java
package ui; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.beans.value.WeakChangeListener; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.control.ListView; import javafx.scene.control.cell.CheckBoxListCell; import javafx.scene.layout.VBox; import javafx.util.Callback; public class BetterCheckListView extends VBox { private ObservableList<BetterCheckListItem> items; private ListView<BetterCheckListItem> listView; private ArrayList<WeakChangeListener<Boolean>> listeners; public BetterCheckListView(ObservableList<String> items) { listeners = new ArrayList<>(); this.listView = new ListView<BetterCheckListItem>(); getChildren().add(listView); setItems(items); } boolean singleSelection = false; public BetterCheckListView setSingleSelection(boolean single) { singleSelection = single; return this; } boolean disabled = false; public void setItems(ObservableList<String> items) { // It's assumed that we won't need to observe this list in the // long term, so we don't use the same list object // Old listeners can be garbage collected listeners.clear(); ObservableList<BetterCheckListItem> newItems = FXCollections.observableArrayList(); WeakReference<BetterCheckListView> that = new WeakReference<>(this); for (int i=0; i<items.size(); i++) { final int j = i; BetterCheckListItem item = new BetterCheckListItem(items.get(i), false); WeakChangeListener<Boolean> listener = new WeakChangeListener<Boolean>(new ChangeListener<Boolean>() { public void changed(ObservableValue<? extends Boolean> ov, Boolean oldValue, Boolean newValue) { if (!disabled) { if (singleSelection) { disabled = true; for (BetterCheckListItem item : that.get().items) { item.setChecked(false); } that.get().items.get(j).setChecked(true); disabled = false; } } } }); item.checkedProperty().addListener(listener); // Retain a reference to this listener, so it doesn't get // garbage collected prematurely listeners.add(listener); newItems.add(item); } this.items = newItems; refresh(); } public void setChecked(int i, boolean state) { this.items.get(i).setChecked(state); } public boolean getChecked(int i) { return this.items.get(i).isChecked(); } public List<Integer> getCheckedIndices() { ArrayList<Integer> result = new ArrayList<>(); for (int i=0; i<items.size(); i++) { if (items.get(i).isChecked()) { result.add(i); } } return result; } private void refresh() { listView.setCellFactory(CheckBoxListCell.forListView(new Callback<BetterCheckListItem, ObservableValue<Boolean>>() { @Override public ObservableValue<Boolean> call(BetterCheckListItem item) { return item.checkedProperty(); } })); listView.setItems(items); } }
Fixed Label exclusivity bug #20
src/ui/BetterCheckListView.java
Fixed Label exclusivity bug #20
Java
apache-2.0
9312ef7af5e9be173dd84b599e6642f9d4641e15
0
rozza/mongo-java-driver,jyemin/mongo-java-driver,kay-kim/mongo-java-driver,jyemin/mongo-java-driver,jsonking/mongo-java-driver,PSCGroup/mongo-java-driver,gianpaj/mongo-java-driver,jsonking/mongo-java-driver,rozza/mongo-java-driver
/* * Copyright (c) 2008-2014 MongoDB, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mongodb.gridfs; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.DatabaseTestCase; import com.mongodb.MongoException; import org.bson.types.ObjectId; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import static java.nio.charset.Charset.defaultCharset; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class GridFSTest extends DatabaseTestCase { private GridFS gridFS; @Before public void setUp() { super.setUp(); gridFS = new GridFS(database); } @Test public void testSmall() throws Exception { testInOut("this is a simple test"); } @Test public void testBig() throws Exception { int target = GridFS.DEFAULT_CHUNKSIZE * 3; StringBuilder buf = new StringBuilder(target); while (buf.length() < target) { buf.append("asdasdkjasldkjasldjlasjdlajsdljasldjlasjdlkasjdlaskjdlaskjdlsakjdlaskjdasldjsad"); } String s = buf.toString(); testInOut(s); } void testOutStream(final String s) throws Exception { int[] start = getCurrentCollectionCounts(); GridFSInputFile in = gridFS.createFile(); OutputStream writeStream = in.getOutputStream(); writeStream.write(s.getBytes(defaultCharset()), 0, s.length()); writeStream.close(); GridFSDBFile out = gridFS.findOne(new BasicDBObject("_id", in.getId())); assert (out.getId().equals(in.getId())); assert (out.getChunkSize() == (long) GridFS.DEFAULT_CHUNKSIZE); ByteArrayOutputStream bout = new ByteArrayOutputStream(); out.writeTo(bout); String outString = new String(bout.toByteArray(), defaultCharset()); assert (outString.equals(s)); out.remove(); int[] end = getCurrentCollectionCounts(); assertEquals(start[0], end[0]); assertEquals(start[1], end[1]); } @Test public void testOutStreamSmall() throws Exception { testOutStream("this is a simple test"); } @Test public void testOutStreamBig() throws Exception { int target = (int) (GridFS.DEFAULT_CHUNKSIZE * 3.5); StringBuilder buf = new StringBuilder(target); while (buf.length() < target) { buf.append("asdasdkjasldkjasldjlasjdlajsdljasldjlasjdlkasjdlaskjdlaskjdlsakjdlaskjdasldjsad"); } String s = buf.toString(); testOutStream(s); } @Test public void testOutStreamBigAligned() throws Exception { int target = (GridFS.DEFAULT_CHUNKSIZE * 4); StringBuilder buf = new StringBuilder(target); while (buf.length() < target) { buf.append("a"); } String s = buf.toString(); testOutStream(s); } @Test public void testMetadata() throws Exception { GridFSInputFile in = gridFS.createFile("foo".getBytes(defaultCharset())); in.put("meta", 5); in.save(); GridFSDBFile out = gridFS.findOne(new BasicDBObject("_id", in.getId())); assert (out.get("meta").equals(5)); } @Test public void testBadChunkSize() throws Exception { byte[] randomBytes = new byte[256]; GridFSInputFile inputFile = gridFS.createFile(randomBytes); inputFile.setFilename("bad_chunk_size.bin"); try { inputFile.save(0); fail("should have received an exception about a chunk size being zero"); } catch (MongoException e) { //We expect this exception to complain about the chunksize assertTrue(e.toString().contains("chunkSize must be greater than zero")); } } @Test public void testMultipleChunks() throws Exception { int fileSize = 1024 * 128; byte[] randomBytes = new byte[fileSize]; for (int idx = 0; idx < fileSize; ++idx) { randomBytes[idx] = (byte) (256 * Math.random()); } GridFSInputFile inputFile = gridFS.createFile(randomBytes); inputFile.setFilename("bad_chunk_size.bin"); //For good measure let's save and restore the bytes inputFile.save(1024); GridFSDBFile savedFile = gridFS.findOne(new BasicDBObject("_id", inputFile.getId())); ByteArrayOutputStream savedFileByteStream = new ByteArrayOutputStream(); savedFile.writeTo(savedFileByteStream); byte[] savedFileBytes = savedFileByteStream.toByteArray(); assertArrayEquals(randomBytes, savedFileBytes); } @Test public void getBigChunkSize() throws Exception { GridFSInputFile file = gridFS.createFile("512kb_bucket"); file.setChunkSize(file.getChunkSize() * 2); OutputStream os = file.getOutputStream(); for (int i = 0; i < 1024; i++) { os.write(new byte[GridFS.DEFAULT_CHUNKSIZE / 1024 + 1]); } os.close(); } @Test public void testInputStreamSkipping() throws Exception { //int chunkSize = 5; int chunkSize = GridFS.DEFAULT_CHUNKSIZE; int fileSize = (int) (7.25 * chunkSize); byte[] fileBytes = new byte[fileSize]; for (int idx = 0; idx < fileSize; ++idx) { fileBytes[idx] = (byte) (idx % 251); } //Don't want chunks to be aligned at byte position 0 GridFSInputFile inputFile = gridFS.createFile(fileBytes); inputFile.setFilename("input_stream_skipping.bin"); inputFile.save(chunkSize); GridFSDBFile savedFile = gridFS.findOne(new BasicDBObject("_id", inputFile.getId())); InputStream inputStream = savedFile.getInputStream(); //Quick run-through, make sure the file is as expected for (int idx = 0; idx < fileSize; ++idx) { assertEquals((byte) (idx % 251), (byte) inputStream.read()); } inputStream = savedFile.getInputStream(); long skipped = inputStream.skip(1); assertEquals(1, skipped); int position = 1; assertEquals((byte) (position++ % 251), (byte) inputStream.read()); skipped = inputStream.skip(chunkSize); assertEquals(chunkSize, skipped); position += chunkSize; assertEquals((byte) (position++ % 251), (byte) inputStream.read()); skipped = inputStream.skip(-1); assertEquals(0, skipped); skipped = inputStream.skip(0); assertEquals(0, skipped); skipped = inputStream.skip(3 * chunkSize); assertEquals(3 * chunkSize, skipped); position += 3 * chunkSize; assertEquals((byte) (position++ % 251), (byte) inputStream.read()); //Make sure skipping works when we skip to an exact chunk boundary long toSkip = inputStream.available(); skipped = inputStream.skip(toSkip); assertEquals(toSkip, skipped); position += toSkip; assertEquals((byte) (position++ % 251), (byte) inputStream.read()); skipped = inputStream.skip(2 * fileSize); assertEquals(fileSize - position, skipped); assertEquals(-1, inputStream.read()); } @Test public void testCustomFileID() throws IOException { int chunkSize = 10; int fileSize = (int) (3.25 * chunkSize); byte[] fileBytes = new byte[fileSize]; for (int idx = 0; idx < fileSize; ++idx) { fileBytes[idx] = (byte) (idx % 251); } GridFSInputFile inputFile = gridFS.createFile(fileBytes); int id = 1; inputFile.setId(id); inputFile.setFilename("custom_file_id.bin"); inputFile.save(chunkSize); assertEquals(id, inputFile.getId()); GridFSDBFile savedFile = gridFS.findOne(new BasicDBObject("_id", id)); InputStream inputStream = savedFile.getInputStream(); for (int idx = 0; idx < fileSize; ++idx) { assertEquals((byte) (idx % 251), (byte) inputStream.read()); } } void testInOut(final String s) throws Exception { int[] start = getCurrentCollectionCounts(); GridFSInputFile in = gridFS.createFile(s.getBytes(defaultCharset())); in.save(); GridFSDBFile out = gridFS.findOne(new BasicDBObject("_id", in.getId())); assert (out.getId().equals(in.getId())); assert (out.getChunkSize() == (long) GridFS.DEFAULT_CHUNKSIZE); ByteArrayOutputStream bout = new ByteArrayOutputStream(); out.writeTo(bout); String outString = new String(bout.toByteArray(), defaultCharset()); assert (outString.equals(s)); out.remove(); int[] end = getCurrentCollectionCounts(); assertEquals(start[0], end[0]); assertEquals(start[1], end[1]); } int[] getCurrentCollectionCounts() { int[] i = new int[2]; i[0] = gridFS.getFilesCollection().find().count(); i[1] = gridFS.getChunksCollection().find().count(); return i; } @Test(expected = IllegalArgumentException.class) public void testRemoveWhenObjectIdIsNull() { ObjectId objectId = null; gridFS.remove(objectId); } @Test(expected = IllegalArgumentException.class) public void testRemoveWhenFileNameIsNull() { String fileName = null; gridFS.remove(fileName); } @Test(expected = IllegalArgumentException.class) public void testRemoveWhenQueryIsNull() { DBObject dbObjectQuery = null; gridFS.remove(dbObjectQuery); } }
driver-compat/src/test/unit/com/mongodb/gridfs/GridFSTest.java
/* * Copyright (c) 2008-2014 MongoDB, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mongodb.gridfs; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.DatabaseTestCase; import com.mongodb.MongoException; import org.bson.types.ObjectId; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import static java.nio.charset.Charset.defaultCharset; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class GridFSTest extends DatabaseTestCase { private GridFS gridFS; @Before public void setUp() { super.setUp(); gridFS = new GridFS(database); } @Test public void testSmall() throws Exception { testInOut("this is a simple test"); } @Test public void testBig() throws Exception { int target = GridFS.DEFAULT_CHUNKSIZE * 3; StringBuilder buf = new StringBuilder(target); while (buf.length() < target) { buf.append("asdasdkjasldkjasldjlasjdlajsdljasldjlasjdlkasjdlaskjdlaskjdlsakjdlaskjdasldjsad"); } String s = buf.toString(); testInOut(s); } void testOutStream(final String s) throws Exception { int[] start = getCurrentCollectionCounts(); GridFSInputFile in = gridFS.createFile(); OutputStream writeStream = in.getOutputStream(); writeStream.write(s.getBytes(defaultCharset()), 0, s.length()); writeStream.close(); GridFSDBFile out = gridFS.findOne(new BasicDBObject("_id", in.getId())); assert (out.getId().equals(in.getId())); assert (out.getChunkSize() == (long) GridFS.DEFAULT_CHUNKSIZE); ByteArrayOutputStream bout = new ByteArrayOutputStream(); out.writeTo(bout); String outString = new String(bout.toByteArray(), defaultCharset()); assert (outString.equals(s)); out.remove(); int[] end = getCurrentCollectionCounts(); assertEquals(start[0], end[0]); assertEquals(start[1], end[1]); } @Test public void testOutStreamSmall() throws Exception { testOutStream("this is a simple test"); } @Test public void testOutStreamBig() throws Exception { int target = (int) (GridFS.DEFAULT_CHUNKSIZE * 3.5); StringBuilder buf = new StringBuilder(target); while (buf.length() < target) { buf.append("asdasdkjasldkjasldjlasjdlajsdljasldjlasjdlkasjdlaskjdlaskjdlsakjdlaskjdasldjsad"); } String s = buf.toString(); testOutStream(s); } @Test public void testOutStreamBigAligned() throws Exception { int target = (GridFS.DEFAULT_CHUNKSIZE * 4); StringBuilder buf = new StringBuilder(target); while (buf.length() < target) { buf.append("a"); } String s = buf.toString(); testOutStream(s); } @Test public void testMetadata() throws Exception { GridFSInputFile in = gridFS.createFile("foo".getBytes(defaultCharset())); in.put("meta", 5); in.save(); GridFSDBFile out = gridFS.findOne(new BasicDBObject("_id", in.getId())); assert (out.get("meta").equals(5)); } @Test public void testBadChunkSize() throws Exception { int fileSize = 2 * database.getMongo().getMaxBsonObjectSize(); if (fileSize > 1024 * 1024 * 1024) { //If this is the case, GridFS is probably obsolete... fileSize = 10 * 1024 * 1024; } byte[] randomBytes = new byte[fileSize]; for (int idx = 0; idx < fileSize; ++idx) { randomBytes[idx] = (byte) (256 * Math.random()); } GridFSInputFile inputFile = gridFS.createFile(randomBytes); inputFile.setFilename("bad_chunk_size.bin"); try { inputFile.save(0); fail("should have received an exception about a chunk size being zero"); } catch (MongoException mongoExc) { //We expect this exception to complain about the chunksize assertTrue(mongoExc.toString().contains("chunkSize must be greater than zero")); } //For good measure let's save and restore the bytes inputFile.save(database.getMongo().getMaxBsonObjectSize() - 500 * 1000); GridFSDBFile savedFile = gridFS.findOne(new BasicDBObject("_id", inputFile.getId())); ByteArrayOutputStream savedFileByteStream = new ByteArrayOutputStream(); savedFile.writeTo(savedFileByteStream); byte[] savedFileBytes = savedFileByteStream.toByteArray(); assertArrayEquals(randomBytes, savedFileBytes); } @Test public void getBigChunkSize() throws Exception { GridFSInputFile file = gridFS.createFile("512kb_bucket"); file.setChunkSize(file.getChunkSize() * 2); OutputStream os = file.getOutputStream(); for (int i = 0; i < 1024; i++) { os.write(new byte[GridFS.DEFAULT_CHUNKSIZE / 1024 + 1]); } os.close(); } @Test public void testInputStreamSkipping() throws Exception { //int chunkSize = 5; int chunkSize = GridFS.DEFAULT_CHUNKSIZE; int fileSize = (int) (7.25 * chunkSize); byte[] fileBytes = new byte[fileSize]; for (int idx = 0; idx < fileSize; ++idx) { fileBytes[idx] = (byte) (idx % 251); } //Don't want chunks to be aligned at byte position 0 GridFSInputFile inputFile = gridFS.createFile(fileBytes); inputFile.setFilename("input_stream_skipping.bin"); inputFile.save(chunkSize); GridFSDBFile savedFile = gridFS.findOne(new BasicDBObject("_id", inputFile.getId())); InputStream inputStream = savedFile.getInputStream(); //Quick run-through, make sure the file is as expected for (int idx = 0; idx < fileSize; ++idx) { assertEquals((byte) (idx % 251), (byte) inputStream.read()); } inputStream = savedFile.getInputStream(); long skipped = inputStream.skip(1); assertEquals(1, skipped); int position = 1; assertEquals((byte) (position++ % 251), (byte) inputStream.read()); skipped = inputStream.skip(chunkSize); assertEquals(chunkSize, skipped); position += chunkSize; assertEquals((byte) (position++ % 251), (byte) inputStream.read()); skipped = inputStream.skip(-1); assertEquals(0, skipped); skipped = inputStream.skip(0); assertEquals(0, skipped); skipped = inputStream.skip(3 * chunkSize); assertEquals(3 * chunkSize, skipped); position += 3 * chunkSize; assertEquals((byte) (position++ % 251), (byte) inputStream.read()); //Make sure skipping works when we skip to an exact chunk boundary long toSkip = inputStream.available(); skipped = inputStream.skip(toSkip); assertEquals(toSkip, skipped); position += toSkip; assertEquals((byte) (position++ % 251), (byte) inputStream.read()); skipped = inputStream.skip(2 * fileSize); assertEquals(fileSize - position, skipped); assertEquals(-1, inputStream.read()); } @Test public void testCustomFileID() throws IOException { int chunkSize = 10; int fileSize = (int) (3.25 * chunkSize); byte[] fileBytes = new byte[fileSize]; for (int idx = 0; idx < fileSize; ++idx) { fileBytes[idx] = (byte) (idx % 251); } GridFSInputFile inputFile = gridFS.createFile(fileBytes); int id = 1; inputFile.setId(id); inputFile.setFilename("custom_file_id.bin"); inputFile.save(chunkSize); assertEquals(id, inputFile.getId()); GridFSDBFile savedFile = gridFS.findOne(new BasicDBObject("_id", id)); InputStream inputStream = savedFile.getInputStream(); for (int idx = 0; idx < fileSize; ++idx) { assertEquals((byte) (idx % 251), (byte) inputStream.read()); } } void testInOut(final String s) throws Exception { int[] start = getCurrentCollectionCounts(); GridFSInputFile in = gridFS.createFile(s.getBytes(defaultCharset())); in.save(); GridFSDBFile out = gridFS.findOne(new BasicDBObject("_id", in.getId())); assert (out.getId().equals(in.getId())); assert (out.getChunkSize() == (long) GridFS.DEFAULT_CHUNKSIZE); ByteArrayOutputStream bout = new ByteArrayOutputStream(); out.writeTo(bout); String outString = new String(bout.toByteArray(), defaultCharset()); assert (outString.equals(s)); out.remove(); int[] end = getCurrentCollectionCounts(); assertEquals(start[0], end[0]); assertEquals(start[1], end[1]); } int[] getCurrentCollectionCounts() { int[] i = new int[2]; i[0] = gridFS.getFilesCollection().find().count(); i[1] = gridFS.getChunksCollection().find().count(); return i; } @Test(expected = IllegalArgumentException.class) public void testRemoveWhenObjectIdIsNull() { ObjectId objectId = null; gridFS.remove(objectId); } @Test(expected = IllegalArgumentException.class) public void testRemoveWhenFileNameIsNull() { String fileName = null; gridFS.remove(fileName); } @Test(expected = IllegalArgumentException.class) public void testRemoveWhenQueryIsNull() { DBObject dbObjectQuery = null; gridFS.remove(dbObjectQuery); } }
Re-wrote GridFSTest.testBadChunkSize to use less memory
driver-compat/src/test/unit/com/mongodb/gridfs/GridFSTest.java
Re-wrote GridFSTest.testBadChunkSize to use less memory
Java
apache-2.0
faed1288367699573e8fcc0699eff4aa421bacc9
0
jpw-erigo/cloudturbine,jpw-erigo/cloudturbine,cycronix/cloudturbine,jpw-erigo/cloudturbine,jpw-erigo/cloudturbine,cycronix/cloudturbine,cycronix/cloudturbine,cycronix/cloudturbine
/* Copyright 2017-2018 Erigo Technologies LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package erigo.ctstream; import javafx.application.Platform; import javafx.embed.swing.JFXPanel; import javafx.event.ActionEvent; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.geometry.VPos; import javafx.scene.control.*; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.Priority; import javafx.scene.layout.TilePane; import javafx.scene.paint.Color; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.DirectoryChooser; import javax.swing.SwingUtilities; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; /** * * JDialog to launch CTweb server. The guts of this dialog is a JavaFX scene. * * @author John P. Wilson * @version 03/08/2018 * */ public class LaunchCTweb extends javax.swing.JDialog { private static final long serialVersionUID = 1L; private JFXPanel fxPanel = null; private CTstream ctStream = null; // UI controls private TextField dataFolderTF = null; private TextField portTF = null; private TextField otherOptionsTF = null; /** * Constrcutor * * @param ctStreamI The CTstream object * @param parentFrameI This dialog will be located relative to its parent frame. */ public LaunchCTweb(CTstream ctStreamI, javax.swing.JFrame parentFrameI) { super(parentFrameI, "Launch CTweb", true); ctStream = ctStreamI; GridBagLayout gbl = new GridBagLayout(); setLayout(gbl); GridBagConstraints gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.BOTH; gbc.weightx = 100; gbc.weighty = 100; gbc.insets = new java.awt.Insets(0,0,0,0); fxPanel = new JFXPanel(); Utility.add(this,fxPanel,gbl,gbc,0,0,1,1); // Handle the close operation in the windowClosing() method of the // registered WindowListener object. This will get around // JFrame's default behavior of automatically hiding the window when // the user clicks on the '[x]' button. setDefaultCloseOperation( javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { setVisible(false); } }); setLocationRelativeTo(parentFrameI); // The JavaFX UI needs to be created on the JavaFX thread Platform.runLater(new Runnable() { @Override public void run() { initializeJavaFX(); } }); } /** * Create the JavaFX UI. This method runs on the JavaFX thread. */ private void initializeJavaFX() { Scene scene = createJavaFXInterface(); fxPanel.setScene(scene); // Set size, position and visibility of the dialog // These need to be set on the JDialog object, and as such should run on Swing's event-dispatching thread (EDT) SwingUtilities.invokeLater(new Runnable() { public void run() { pack(); setLocationRelativeTo(getParent()); setVisible(true); // this method won't return until setVisible(false) is called } }); } /** * This method contains the guts of creating the UI. * * @return the created Scene. */ private Scene createJavaFXInterface() { GridPane root = new GridPane(); Scene scene = new Scene(root, Color.ALICEBLUE); // For debug: display grid lines // root.setGridLinesVisible(true); // Center this GridPane within its parent root.setAlignment(Pos.CENTER); root.setHgap(10); root.setVgap(10); root.setPadding(new Insets(25, 25, 25, 25)); root.setMaxWidth(Double.MAX_VALUE); int row = 0; // Row 1: data folder Label tempL = new Label("Data folder"); dataFolderTF = new TextField(ctStream.outputFolder); dataFolderTF.setPrefWidth(150); Button browseB = new Button("Browse..."); browseB.setOnAction(this::selectDirAction); root.add(tempL, 0, row, 1, 1); root.add(dataFolderTF, 1, row, 1, 1); root.add(browseB, 2, row, 1, 1); // Row 2: Port row = row + 1; tempL = new Label("Port"); portTF = new TextField(Integer.toString(ctStream.webScanPort)); // Don't have this control fill the width portTF.setPrefWidth(75); portTF.setMaxWidth(Control.USE_PREF_SIZE); root.add(tempL, 0, row, 1, 1); // root.add(portTF, 1, row, 1, 1); // Here's a way to specify all the constraints for the portTF node: position, row/col span, hor/ver alignment, growth policy, insets root.add(portTF,1,row); root.setConstraints(portTF,1,row,1,1, HPos.LEFT, VPos.CENTER,Priority.NEVER,Priority.NEVER,new Insets(0,0,0,0)); // Row 3: other command line options row = row + 1; tempL = new Label("Other options"); otherOptionsTF = new TextField(ctStream.otherCTwebOptions); otherOptionsTF.setPrefWidth(150); root.add(tempL, 0, row, 1, 1); // root.add(otherOptionsTF, 1, row, 1, 1); // Here's a way to specify all the constraints for the otherOptionsTF node: position, row/col span, hor/ver alignment, growth policy, insets root.add(otherOptionsTF,1,row); root.setConstraints(otherOptionsTF,1,row,1,1, HPos.LEFT, VPos.CENTER,Priority.ALWAYS,Priority.NEVER,new Insets(0,0,0,0)); // Row 4: command button row = row + 1; Button launchB = new Button("Launch"); launchB.setOnAction(this::launchAction); Button cancelB = new Button("Cancel"); cancelB.setOnAction(this::cancelAction); TilePane tileP = new TilePane(); tileP.setPadding(new Insets(10, 0, 0, 10)); tileP.setVgap(5); tileP.setHgap(5); tileP.setPrefColumns(2); tileP.getChildren().add(launchB); tileP.getChildren().add(cancelB); tileP.setAlignment(Pos.CENTER); root.add(tileP, 0, row, 3, 1); // Set constraints on the columns; have second column grow ColumnConstraints column1 = new ColumnConstraints(); ColumnConstraints column2 = new ColumnConstraints(50,150,Double.MAX_VALUE); column2.setHgrow(Priority.ALWAYS); ColumnConstraints column3 = new ColumnConstraints(); root.getColumnConstraints().addAll(column1, column2, column3); return scene; } /** * User clicked the "Browse..." button; allow them to select a directory from the file system. * * @param event The action event that has occurred. */ private void selectDirAction(ActionEvent event) { DirectoryChooser directoryChooser = new DirectoryChooser(); directoryChooser.setTitle("Select CT data directory"); // If the current selection is a Folder, initialize the browser dialog to that Folder File currentSel = new File(dataFolderTF.getText().trim()); if (currentSel.isDirectory()) { directoryChooser.setInitialDirectory(currentSel); } File selectedDirectory = directoryChooser.showDialog(fxPanel.getScene().getWindow()); if(selectedDirectory != null){ dataFolderTF.setText(selectedDirectory.getAbsolutePath()); } } /** * User clicked the Launch button; try to launch the CTweb server. * * @param event The action event that has occurred. */ private void launchAction(ActionEvent event) { // Data folder String folderStr = dataFolderTF.getText().trim(); // See if this folder exists File folderF = new File(folderStr); if (!folderF.isDirectory()) { // The folder doesn't exist; see if we can create it try { boolean bSuccess = folderF.mkdirs(); if (!bSuccess) { throw new Exception("Unable to create folder"); } } catch (Exception e) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Data folder"); alert.setHeaderText(null); alert.setContentText("The data folder doesn't exist and could not be created."); alert.showAndWait(); } } // Port number; should be an integer greater than 0 String portStr = portTF.getText().trim(); int portNum = 0; try { portNum = Integer.parseInt(portStr); if (portNum < 1) { throw new NumberFormatException("Bad port value"); } } catch (NumberFormatException nfe) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Data server port"); alert.setHeaderText(null); alert.setContentText("The data server port must be an integer greater than 0."); alert.showAndWait(); } // Save the port number ctStream.webScanPort = portNum; // Other options entered by the user String otherOptionsStr = otherOptionsTF.getText().trim(); // Save the other options ctStream.otherCTwebOptions = otherOptionsStr; // Fill in arguments from the user's settings ArrayList<String> argList=new ArrayList<String>(); argList.add("-p"); argList.add(Integer.toString(portNum)); // If there are other options, add them if (!otherOptionsStr.isEmpty()) { String[] optionStrings = otherOptionsStr.split("\\s+"); for (String nextStr : optionStrings) { argList.add(nextStr); } } // For a discussion of File.getPath(), File.getAbsolutePath() and File.getCanonicalPath() see // https://stackoverflow.com/questions/1099300/whats-the-difference-between-getpath-getabsolutepath-and-getcanonicalpath // Using getPath() here, which gets the path string that the File object was constructed with. argList.add(folderF.getPath()); // Launch CTweb process new Thread(new Runnable() { @Override public void run() { // Convert ArrayList to an array of Strings // See example at https://www.tutorialspoint.com/java/util/arraylist_toarray.htm String strList[] = new String[argList.size()]; strList = argList.toArray(strList); System.err.println("CTweb arguments:"); for (String nextStr : strList) { System.err.println("\t" + nextStr); } /* // Launch CTweb directly try { // I don't think this ever returns (unless the server dies) ctweb.CTweb.main(strList); } catch (Exception e) { e.printStackTrace(); } */ // Launch CTweb using reflection // From https://stackoverflow.com/questions/15582476/how-to-call-main-method-of-a-class-using-reflection-in-java try { // We will assume CTweb.jar is located in the same directory as CTstream.jar // For some reason we aren't able to locate CTweb.jar even if "CTweb.jar" is included on // CTstream's Class-Path in the manifest. I have some notion that the default class // loader is looking *internally* in CTstream.jar rather than at external files // outside of this JAR. Anyway, if this were working, we could just use the following line: // final Class<?> ctwebClass = Class.forName("ctweb.CTweb"); File ctwebFile = new File("./CTweb.jar"); URL ctwebURL = ctwebFile.toURI().toURL(); URL[] urlList = new URL[1]; urlList[0] = ctwebURL; URLClassLoader loader = new URLClassLoader(urlList, this.getClass().getClassLoader()); final Class<?> ctwebClass = Class.forName("ctweb.CTweb",true, loader); final Method method = ctwebClass.getMethod("main", String[].class); final Object[] args = new Object[1]; args[0] = (String[]) strList; // I don't think this ever returns (unless the server dies) method.invoke(null, args); } catch (final Exception e) { e.printStackTrace(); } } }).start(); // Shut down the JDialog // For thread safety: Schedule a job for Swing's event-dispatching thread (EDT) SwingUtilities.invokeLater(new Runnable() { public void run() { setVisible(false); } }); } /** * User clicked the Cancel button; pop down this dialog. * * @param event The action event that has occurred. */ private void cancelAction(ActionEvent event) { // Time to shut down this JDialog // For thread safety: Schedule a job for Swing's event-dispatching thread (EDT) SwingUtilities.invokeLater(new Runnable() { public void run() { setVisible(false); } }); } }
JavaCode/CTstream/src/main/java/erigo/ctstream/LaunchCTweb.java
/* Copyright 2017 Erigo Technologies LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package erigo.ctstream; import javafx.application.Platform; import javafx.embed.swing.JFXPanel; import javafx.event.ActionEvent; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.geometry.VPos; import javafx.scene.control.*; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.Priority; import javafx.scene.layout.TilePane; import javafx.scene.paint.Color; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.DirectoryChooser; import javax.swing.SwingUtilities; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; /** * * JDialog to launch CTweb server. The guts of this dialog is a JavaFX scene. * * @author John P. Wilson * @version 02/19/2018 * */ public class LaunchCTweb extends javax.swing.JDialog { private static final long serialVersionUID = 1L; private JFXPanel fxPanel = null; private GridPane grid = null; private CTstream ctStream = null; // UI controls private TextField dataFolderTF = null; private TextField portTF = null; private TextField otherOptionsTF = null; /** * Constrcutor * * @param ctStreamI The CTstream object * @param parentFrameI This dialog will be located relative to its parent frame. */ public LaunchCTweb(CTstream ctStreamI, javax.swing.JFrame parentFrameI) { super(parentFrameI, "Launch CTweb", true); ctStream = ctStreamI; GridBagLayout gbl = new GridBagLayout(); setLayout(gbl); GridBagConstraints gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.BOTH; gbc.weightx = 100; gbc.weighty = 100; gbc.insets = new java.awt.Insets(0,0,0,0); fxPanel = new JFXPanel(); Utility.add(this,fxPanel,gbl,gbc,0,0,1,1); // For some unknown reason, the GridPane inside the JFXPanel doesn't automatically resize as the dialog is // being resized. Here's an attempt to force the resize, but it doesn't work. /* addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { // Dialog has been resized; request new layout for the JFXPanel (needs to be done on the JavaFX thread) Platform.runLater(new Runnable() { @Override public void run() { if (grid != null) { fxPanel.validate(); grid.requestLayout(); } } }); } }); */ // Handle the close operation in the windowClosing() method of the // registered WindowListener object. This will get around // JFrame's default behavior of automatically hiding the window when // the user clicks on the '[x]' button. setDefaultCloseOperation( javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { setVisible(false); } }); setLocationRelativeTo(parentFrameI); // The JavaFX UI needs to be created on the JavaFX thread Platform.runLater(new Runnable() { @Override public void run() { initializeJavaFX(); } }); } /** * Create the JavaFX UI. This method runs on the JavaFX thread. */ private void initializeJavaFX() { Scene scene = createJavaFXInterface(); fxPanel.setScene(scene); // Set size, position and visibility of the dialog // These need to be set on the JDialog object, and as such should run on Swing's event-dispatching thread (EDT) SwingUtilities.invokeLater(new Runnable() { public void run() { pack(); setLocationRelativeTo(getParent()); setVisible(true); // this method won't return until setVisible(false) is called } }); } /** * This method contains the guts of creating the UI. * * @return the created Scene. */ private Scene createJavaFXInterface() { Group root = new Group(); Scene scene = new Scene(root, Color.ALICEBLUE); grid = new GridPane(); // For debug: display grid lines // grid.setGridLinesVisible(true); // Center this GridPane within its parent grid.setAlignment(Pos.CENTER); grid.setHgap(10); grid.setVgap(10); grid.setPadding(new Insets(25, 25, 25, 25)); grid.setMaxWidth(Double.MAX_VALUE); root.getChildren().add(grid); int row = 0; // Row 1: data folder Label tempL = new Label("Data folder"); dataFolderTF = new TextField(ctStream.outputFolder); dataFolderTF.setPrefWidth(150); Button browseB = new Button("Browse..."); browseB.setOnAction(this::selectDirAction); grid.add(tempL, 0, row, 1, 1); grid.add(dataFolderTF, 1, row, 1, 1); grid.add(browseB, 2, row, 1, 1); // Row 2: Port row = row + 1; tempL = new Label("Port"); portTF = new TextField(Integer.toString(ctStream.webScanPort)); // Don't have this control fill the width portTF.setPrefWidth(75); portTF.setMaxWidth(Control.USE_PREF_SIZE); grid.add(tempL, 0, row, 1, 1); // grid.add(portTF, 1, row, 1, 1); // Here's a way to specify all the constraints for the portTF node: position, row/col span, hor/ver alignment, growth policy, insets grid.add(portTF,1,row); grid.setConstraints(portTF,1,row,1,1, HPos.LEFT, VPos.CENTER,Priority.NEVER,Priority.NEVER,new Insets(0,0,0,0)); // Row 3: other command line options row = row + 1; tempL = new Label("Other options"); otherOptionsTF = new TextField(ctStream.otherCTwebOptions); otherOptionsTF.setPrefWidth(150); grid.add(tempL, 0, row, 1, 1); // grid.add(otherOptionsTF, 1, row, 1, 1); // Here's a way to specify all the constraints for the otherOptionsTF node: position, row/col span, hor/ver alignment, growth policy, insets grid.add(otherOptionsTF,1,row); grid.setConstraints(otherOptionsTF,1,row,1,1, HPos.LEFT, VPos.CENTER,Priority.ALWAYS,Priority.NEVER,new Insets(0,0,0,0)); // Row 4: command button row = row + 1; Button launchB = new Button("Launch"); launchB.setOnAction(this::launchAction); Button cancelB = new Button("Cancel"); cancelB.setOnAction(this::cancelAction); TilePane tileP = new TilePane(); tileP.setPadding(new Insets(10, 0, 0, 10)); tileP.setVgap(5); tileP.setHgap(5); tileP.setPrefColumns(2); tileP.getChildren().add(launchB); tileP.getChildren().add(cancelB); tileP.setAlignment(Pos.CENTER); grid.add(tileP, 0, row, 3, 1); // Set constraints on the columns; have second column grow ColumnConstraints column1 = new ColumnConstraints(); ColumnConstraints column2 = new ColumnConstraints(50,150,Double.MAX_VALUE); column2.setHgrow(Priority.ALWAYS); ColumnConstraints column3 = new ColumnConstraints(); grid.getColumnConstraints().addAll(column1, column2, column3); return scene; } /** * User clicked the "Browse..." button; allow them to select a directory from the file system. * * @param event The action event that has occurred. */ private void selectDirAction(ActionEvent event) { DirectoryChooser directoryChooser = new DirectoryChooser(); directoryChooser.setTitle("Select CT data directory"); // If the current selection is a Folder, initialize the browser dialog to that Folder File currentSel = new File(dataFolderTF.getText().trim()); if (currentSel.isDirectory()) { directoryChooser.setInitialDirectory(currentSel); } File selectedDirectory = directoryChooser.showDialog(fxPanel.getScene().getWindow()); if(selectedDirectory != null){ dataFolderTF.setText(selectedDirectory.getAbsolutePath()); } } /** * User clicked the Launch button; try to launch the CTweb server. * * @param event The action event that has occurred. */ private void launchAction(ActionEvent event) { // Data folder String folderStr = dataFolderTF.getText().trim(); // See if this folder exists File folderF = new File(folderStr); if (!folderF.isDirectory()) { // The folder doesn't exist; see if we can create it try { boolean bSuccess = folderF.mkdirs(); if (!bSuccess) { throw new Exception("Unable to create folder"); } } catch (Exception e) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Data folder"); alert.setHeaderText(null); alert.setContentText("The data folder doesn't exist and could not be created."); alert.showAndWait(); } } // Port number; should be an integer greater than 0 String portStr = portTF.getText().trim(); int portNum = 0; try { portNum = Integer.parseInt(portStr); if (portNum < 1) { throw new NumberFormatException("Bad port value"); } } catch (NumberFormatException nfe) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Data server port"); alert.setHeaderText(null); alert.setContentText("The data server port must be an integer greater than 0."); alert.showAndWait(); } // Save the port number ctStream.webScanPort = portNum; // Other options entered by the user String otherOptionsStr = otherOptionsTF.getText().trim(); // Save the other options ctStream.otherCTwebOptions = otherOptionsStr; // Fill in arguments from the user's settings ArrayList<String> argList=new ArrayList(); argList.add("-p"); argList.add(Integer.toString(portNum)); // If there are other options, add them if (!otherOptionsStr.isEmpty()) { String[] optionStrings = otherOptionsStr.split("\\s+"); for (String nextStr : optionStrings) { argList.add(nextStr); } } // For a discussion of File.getPath(), File.getAbsolutePath() and File.getCanonicalPath() see // https://stackoverflow.com/questions/1099300/whats-the-difference-between-getpath-getabsolutepath-and-getcanonicalpath // Using getPath() here, which gets the path string that the File object was constructed with. argList.add(folderF.getPath()); // Launch CTweb process new Thread(new Runnable() { @Override public void run() { // Convert ArrayList to an array of Strings // See example at https://www.tutorialspoint.com/java/util/arraylist_toarray.htm String strList[] = new String[argList.size()]; strList = argList.toArray(strList); System.err.println("CTweb arguments:"); for (String nextStr : strList) { System.err.println("\t" + nextStr); } /* // Launch CTweb directly try { // I don't think this ever returns (unless the server dies) ctweb.CTweb.main(strList); } catch (Exception e) { e.printStackTrace(); } */ // Launch CTweb using reflection // From https://stackoverflow.com/questions/15582476/how-to-call-main-method-of-a-class-using-reflection-in-java try { // We will assume CTweb.jar is located in the same directory as CTstream.jar // For some reason we aren't able to locate CTweb.jar even if "CTweb.jar" is included on // CTstream's Class-Path in the manifest. I have some notion that the default class // loader is looking *internally* in CTstream.jar rather than at external files // outside of this JAR. Anyway, if this were working, we could just use the following line: // final Class<?> ctwebClass = Class.forName("ctweb.CTweb"); File ctwebFile = new File("./CTweb.jar"); URL ctwebURL = ctwebFile.toURI().toURL(); URL[] urlList = new URL[1]; urlList[0] = ctwebURL; URLClassLoader loader = new URLClassLoader(urlList, this.getClass().getClassLoader()); final Class<?> ctwebClass = Class.forName("ctweb.CTweb",true, loader); final Method method = ctwebClass.getMethod("main", String[].class); final Object[] args = new Object[1]; args[0] = (String[]) strList; // I don't think this ever returns (unless the server dies) method.invoke(null, args); } catch (final Exception e) { e.printStackTrace(); } } }).start(); // Shut down the JDialog // For thread safety: Schedule a job for Swing's event-dispatching thread (EDT) SwingUtilities.invokeLater(new Runnable() { public void run() { setVisible(false); } }); } /** * User clicked the Cancel button; pop down this dialog. * * @param event The action event that has occurred. */ private void cancelAction(ActionEvent event) { // Time to shut down this JDialog // For thread safety: Schedule a job for Swing's event-dispatching thread (EDT) SwingUtilities.invokeLater(new Runnable() { public void run() { setVisible(false); } }); } }
CTstream.LaunchCTweb: minor change to allow the dialog to be resizeable; this was enabled by changing the root container from Group to GridPane
JavaCode/CTstream/src/main/java/erigo/ctstream/LaunchCTweb.java
CTstream.LaunchCTweb: minor change to allow the dialog to be resizeable; this was enabled by changing the root container from Group to GridPane
Java
apache-2.0
0bd7da4dce943f606bbe6c33db625c9244b464c0
0
oleksiyp/Aeron,real-logic/Aeron,EvilMcJerkface/Aeron,real-logic/Aeron,galderz/Aeron,galderz/Aeron,mikeb01/Aeron,EvilMcJerkface/Aeron,EvilMcJerkface/Aeron,mikeb01/Aeron,galderz/Aeron,mikeb01/Aeron,oleksiyp/Aeron,mikeb01/Aeron,real-logic/Aeron,galderz/Aeron,EvilMcJerkface/Aeron,real-logic/Aeron,oleksiyp/Aeron
/* * Copyright 2014-2017 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.aeron.driver; import io.aeron.ArrayListUtil; import io.aeron.CommonContext; import io.aeron.driver.buffer.RawLogFactory; import io.aeron.driver.MediaDriver.Context; import io.aeron.driver.buffer.RawLog; import io.aeron.driver.cmd.DriverConductorCmd; import io.aeron.driver.exceptions.ControlProtocolException; import io.aeron.driver.media.ReceiveChannelEndpoint; import io.aeron.driver.media.SendChannelEndpoint; import io.aeron.driver.media.UdpChannel; import io.aeron.driver.status.*; import io.aeron.driver.uri.AeronUri; import org.agrona.BitUtil; import org.agrona.concurrent.*; import org.agrona.concurrent.ringbuffer.RingBuffer; import org.agrona.concurrent.status.AtomicCounter; import org.agrona.concurrent.status.CountersManager; import org.agrona.concurrent.status.Position; import org.agrona.concurrent.status.ReadablePosition; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.function.Consumer; import static io.aeron.CommonContext.RELIABLE_STREAM_PARAM_NAME; import static io.aeron.driver.Configuration.*; import static io.aeron.driver.status.SystemCounterDescriptor.CLIENT_KEEP_ALIVES; import static io.aeron.driver.status.SystemCounterDescriptor.ERRORS; import static io.aeron.driver.status.SystemCounterDescriptor.UNBLOCKED_COMMANDS; import static io.aeron.ErrorCode.*; import static io.aeron.logbuffer.FrameDescriptor.computeMaxMessageLength; import static io.aeron.logbuffer.LogBufferDescriptor.*; import static io.aeron.protocol.DataHeaderFlyweight.createDefaultHeader; /** * Driver Conductor that takes commands from publishers and subscribers and orchestrates the media driver. */ public class DriverConductor implements Agent { private final long imageLivenessTimeoutNs; private final long clientLivenessTimeoutNs; private final long publicationUnblockTimeoutNs; private final long statusMessageTimeoutNs; private long timeOfLastToDriverPositionChange; private long lastConsumerCommandPosition; private long timeOfLastTimeoutCheck; private int nextSessionId = BitUtil.generateRandomisedId(); private final NetworkPublicationThreadLocals networkPublicationThreadLocals = new NetworkPublicationThreadLocals(); private final Context context; private final RawLogFactory rawLogFactory; private final ReceiverProxy receiverProxy; private final SenderProxy senderProxy; private final ClientProxy clientProxy; private final DriverConductorProxy fromReceiverConductorProxy; private final RingBuffer toDriverCommands; private final ClientListenerAdapter clientListenerAdapter; private final OneToOneConcurrentArrayQueue<DriverConductorCmd> fromReceiverDriverConductorCmdQueue; private final OneToOneConcurrentArrayQueue<DriverConductorCmd> fromSenderDriverConductorCmdQueue; private final HashMap<String, SendChannelEndpoint> sendChannelEndpointByChannelMap = new HashMap<>(); private final HashMap<String, ReceiveChannelEndpoint> receiveChannelEndpointByChannelMap = new HashMap<>(); private final ArrayList<PublicationLink> publicationLinks = new ArrayList<>(); private final ArrayList<NetworkPublication> networkPublications = new ArrayList<>(); private final ArrayList<SubscriptionLink> subscriptionLinks = new ArrayList<>(); private final ArrayList<PublicationImage> publicationImages = new ArrayList<>(); private final ArrayList<AeronClient> clients = new ArrayList<>(); private final ArrayList<IpcPublication> ipcPublications = new ArrayList<>(); private final EpochClock epochClock; private final NanoClock nanoClock; private final Consumer<DriverConductorCmd> onDriverConductorCmdFunc = this::onDriverConductorCmd; private final CountersManager countersManager; private final AtomicCounter clientKeepAlives; public DriverConductor(final Context ctx) { context = ctx; imageLivenessTimeoutNs = ctx.imageLivenessTimeoutNs(); clientLivenessTimeoutNs = ctx.clientLivenessTimeoutNs(); publicationUnblockTimeoutNs = ctx.publicationUnblockTimeoutNs(); statusMessageTimeoutNs = ctx.statusMessageTimeout(); fromReceiverDriverConductorCmdQueue = ctx.toConductorFromReceiverCommandQueue(); fromSenderDriverConductorCmdQueue = ctx.toConductorFromSenderCommandQueue(); receiverProxy = ctx.receiverProxy(); senderProxy = ctx.senderProxy(); rawLogFactory = ctx.rawLogBuffersFactory(); epochClock = ctx.epochClock(); nanoClock = ctx.nanoClock(); toDriverCommands = ctx.toDriverCommands(); clientProxy = ctx.clientProxy(); fromReceiverConductorProxy = ctx.fromReceiverDriverConductorProxy(); countersManager = context.countersManager(); clientKeepAlives = context.systemCounters().get(CLIENT_KEEP_ALIVES); clientListenerAdapter = new ClientListenerAdapter( context.systemCounters().get(ERRORS), ctx.errorLog(), toDriverCommands, clientProxy, this); toDriverCommands.consumerHeartbeatTime(epochClock.time()); final long now = nanoClock.nanoTime(); timeOfLastTimeoutCheck = now; timeOfLastToDriverPositionChange = now; lastConsumerCommandPosition = toDriverCommands.consumerPosition(); } public void onClose() { networkPublications.forEach(NetworkPublication::close); publicationImages.forEach(PublicationImage::close); ipcPublications.forEach(IpcPublication::close); sendChannelEndpointByChannelMap.values().forEach(SendChannelEndpoint::close); receiveChannelEndpointByChannelMap.values().forEach(ReceiveChannelEndpoint::close); } public String roleName() { return "driver-conductor"; } public int doWork() throws Exception { int workCount = 0; workCount += clientListenerAdapter.receive(); workCount += fromReceiverDriverConductorCmdQueue.drain(onDriverConductorCmdFunc); workCount += fromSenderDriverConductorCmdQueue.drain(onDriverConductorCmdFunc); final long now = nanoClock.nanoTime(); workCount += processTimers(now); final ArrayList<PublicationImage> publicationImages = this.publicationImages; for (int i = 0, size = publicationImages.size(); i < size; i++) { publicationImages.get(i).trackRebuild(now, statusMessageTimeoutNs); } final ArrayList<NetworkPublication> networkPublications = this.networkPublications; for (int i = 0, size = networkPublications.size(); i < size; i++) { workCount += networkPublications.get(i).updatePublishersLimit(); } final ArrayList<IpcPublication> ipcPublications = this.ipcPublications; for (int i = 0, size = ipcPublications.size(); i < size; i++) { workCount += ipcPublications.get(i).updatePublishersLimit(toDriverCommands.consumerHeartbeatTime()); } return workCount; } public void onClosePublication(final NetworkPublication publication) { publication.close(); } public void onCreatePublicationImage( final int sessionId, final int streamId, final int initialTermId, final int activeTermId, final int initialTermOffset, final int termBufferLength, final int senderMtuLength, final InetSocketAddress controlAddress, final InetSocketAddress sourceAddress, final ReceiveChannelEndpoint channelEndpoint) { channelEndpoint.validateSenderMtuLength(senderMtuLength); channelEndpoint.validateWindowMaxLength(context.initialWindowLength()); final UdpChannel udpChannel = channelEndpoint.udpChannel(); final String channel = udpChannel.originalUriString(); final long registrationId = nextImageCorrelationId(); final long joiningPosition = computePosition( activeTermId, initialTermOffset, Integer.numberOfTrailingZeros(termBufferLength), initialTermId); final List<SubscriberPosition> subscriberPositions = createSubscriberPositions( sessionId, streamId, channelEndpoint, joiningPosition); if (subscriberPositions.size() > 0) { final RawLog rawLog = newPublicationImageLog( sessionId, streamId, initialTermId, termBufferLength, senderMtuLength, udpChannel, registrationId); final CongestionControl congestionControl = context.congestionControlSupplier().newInstance( registrationId, udpChannel, streamId, sessionId, termBufferLength, senderMtuLength, nanoClock, context, countersManager); final PublicationImage image = new PublicationImage( registrationId, imageLivenessTimeoutNs, channelEndpoint, controlAddress, sessionId, streamId, initialTermId, activeTermId, initialTermOffset, rawLog, udpChannel.isMulticast() ? NAK_MULTICAST_DELAY_GENERATOR : NAK_UNICAST_DELAY_GENERATOR, positionArray(subscriberPositions), ReceiverHwm.allocate(countersManager, registrationId, sessionId, streamId, channel), ReceiverPos.allocate(countersManager, registrationId, sessionId, streamId, channel), nanoClock, context.epochClock(), context.systemCounters(), sourceAddress, congestionControl, context.lossReport(), subscriberPositions.get(0).subscription().isReliable()); for (int i = 0, size = subscriberPositions.size(); i < size; i++) { subscriberPositions.get(i).addLink(image); } publicationImages.add(image); receiverProxy.newPublicationImage(channelEndpoint, image); clientProxy.onAvailableImage( registrationId, streamId, sessionId, rawLog.fileName(), subscriberPositions, generateSourceIdentity(sourceAddress)); } } SendChannelEndpoint senderChannelEndpoint(final UdpChannel channel) { return sendChannelEndpointByChannelMap.get(channel.canonicalForm()); } ReceiveChannelEndpoint receiverChannelEndpoint(final UdpChannel channel) { return receiveChannelEndpointByChannelMap.get(channel.canonicalForm()); } IpcPublication getIpcSharedPublication(final long streamId) { return findIpcSharedPublication(ipcPublications, streamId); } void onAddNetworkPublication( final String channel, final int streamId, final long registrationId, final long clientId, final boolean isExclusive) { final UdpChannel udpChannel = UdpChannel.parse(channel); final AeronUri aeronUri = udpChannel.aeronUri(); final int mtuLength = getMtuLength(aeronUri, context.mtuLength()); final int termLength = getTermBufferLength(aeronUri, context.publicationTermBufferLength()); final SendChannelEndpoint channelEndpoint = getOrCreateSendChannelEndpoint(udpChannel); NetworkPublication publication = null; if (!isExclusive) { publication = findPublication(networkPublications, streamId, channelEndpoint); } if (null == publication) { final int sessionId = nextSessionId++; final int initialTermId = BitUtil.generateRandomisedId(); final RetransmitHandler retransmitHandler = new RetransmitHandler( nanoClock, context.systemCounters(), RETRANSMIT_UNICAST_DELAY_GENERATOR, RETRANSMIT_UNICAST_LINGER_GENERATOR); final FlowControl flowControl = udpChannel.isMulticast() || udpChannel.hasExplicitControl() ? context.multicastFlowControlSupplier().newInstance(udpChannel, streamId, registrationId) : context.unicastFlowControlSupplier().newInstance(udpChannel, streamId, registrationId); publication = new NetworkPublication( registrationId, channelEndpoint, nanoClock, toDriverCommands::consumerHeartbeatTime, newNetworkPublicationLog(sessionId, streamId, initialTermId, udpChannel, registrationId, termLength), PublisherLimit.allocate(countersManager, registrationId, sessionId, streamId, channel), SenderPos.allocate(countersManager, registrationId, sessionId, streamId, channel), SenderLimit.allocate(countersManager, registrationId, sessionId, streamId, channel), sessionId, streamId, initialTermId, mtuLength, context.systemCounters(), flowControl, retransmitHandler, networkPublicationThreadLocals, publicationUnblockTimeoutNs, isExclusive); channelEndpoint.incRef(); networkPublications.add(publication); senderProxy.newNetworkPublication(publication); linkSpies(subscriptionLinks, publication); } else if (publication.mtuLength() != mtuLength) { throw new IllegalStateException("Existing publication has different MTU length: existing=" + publication.mtuLength() + " requested=" + mtuLength); } publicationLinks.add(new PublicationLink(registrationId, publication, getOrAddClient(clientId))); clientProxy.onPublicationReady( registrationId, streamId, publication.sessionId(), publication.rawLog().fileName(), publication.publisherLimitId(), isExclusive); } void cleanupPublication(final NetworkPublication publication) { if (publication.hasSpies()) { clientProxy.onUnavailableImage( correlationId(publication.rawLog().metaData()), publication.streamId(), publication.channelEndpoint().originalUriString()); for (int i = 0, size = subscriptionLinks.size(); i < size; i++) { subscriptionLinks.get(i).unlink(publication); } } senderProxy.removeNetworkPublication(publication); final SendChannelEndpoint channelEndpoint = publication.channelEndpoint(); if (channelEndpoint.shouldBeClosed()) { channelEndpoint.closeStatusIndicator(); sendChannelEndpointByChannelMap.remove(channelEndpoint.udpChannel().canonicalForm()); senderProxy.closeSendChannelEndpoint(channelEndpoint); } } void cleanupSubscriptionLink(final SubscriptionLink subscription) { final ReceiveChannelEndpoint channelEndpoint = subscription.channelEndpoint(); if (null != channelEndpoint) { final int streamId = subscription.streamId(); if (0 == channelEndpoint.decRefToStream(subscription.streamId())) { receiverProxy.removeSubscription(channelEndpoint, streamId); } if (channelEndpoint.shouldBeClosed()) { channelEndpoint.closeStatusIndicator(); receiveChannelEndpointByChannelMap.remove(channelEndpoint.udpChannel().canonicalForm()); receiverProxy.closeReceiveChannelEndpoint(channelEndpoint); } } } void transitionToLinger(final PublicationImage image) { clientProxy.onUnavailableImage(image.correlationId(), image.streamId(), image.channelUriString()); receiverProxy.removeCoolDown(image.channelEndpoint(), image.sessionId(), image.streamId()); } void transitionToLinger(final IpcPublication publication) { clientProxy.onUnavailableImage(publication.correlationId(), publication.streamId(), CommonContext.IPC_CHANNEL); } void cleanupImage(final PublicationImage image) { for (int i = 0, size = subscriptionLinks.size(); i < size; i++) { subscriptionLinks.get(i).unlink(image); } } void cleanupIpcPublication(final IpcPublication publication) { for (int i = 0, size = subscriptionLinks.size(); i < size; i++) { subscriptionLinks.get(i).unlink(publication); } } private List<SubscriberPosition> createSubscriberPositions( final int sessionId, final int streamId, final ReceiveChannelEndpoint channelEndpoint, final long joiningPosition) { final ArrayList<SubscriberPosition> subscriberPositions = new ArrayList<>(); for (int i = 0, size = subscriptionLinks.size(); i < size; i++) { final SubscriptionLink subscription = subscriptionLinks.get(i); if (subscription.matches(channelEndpoint, streamId)) { final Position position = SubscriberPos.allocate( countersManager, subscription.registrationId(), sessionId, streamId, subscription.uri(), joiningPosition); position.setOrdered(joiningPosition); subscriberPositions.add(new SubscriberPosition(subscription, position)); } } return subscriberPositions; } void onAddIpcPublication( final String channel, final int streamId, final long registrationId, final long clientId, final boolean isExclusive) { final IpcPublication ipcPublication = getOrAddIpcPublication(streamId, channel, isExclusive); publicationLinks.add(new PublicationLink(registrationId, ipcPublication, getOrAddClient(clientId))); clientProxy.onPublicationReady( registrationId, streamId, ipcPublication.sessionId(), ipcPublication.rawLog().fileName(), ipcPublication.publisherLimitId(), isExclusive); linkIpcSubscriptions(ipcPublication); } void onRemovePublication(final long registrationId, final long correlationId) { PublicationLink publicationLink = null; final ArrayList<PublicationLink> publicationLinks = this.publicationLinks; for (int i = 0, size = publicationLinks.size(), lastIndex = size - 1; i < size; i++) { final PublicationLink publication = publicationLinks.get(i); if (registrationId == publication.registrationId()) { publicationLink = publication; ArrayListUtil.fastUnorderedRemove(publicationLinks, i, lastIndex); break; } } if (null == publicationLink) { throw new ControlProtocolException(UNKNOWN_PUBLICATION, "Unknown publication: " + registrationId); } publicationLink.close(); clientProxy.operationSucceeded(correlationId); } void onAddDestination(final long registrationId, final String destinationChannel, final long correlationId) { SendChannelEndpoint sendChannelEndpoint = null; for (int i = 0, size = networkPublications.size(); i < size; i++) { final NetworkPublication publication = networkPublications.get(i); if (registrationId == publication.registrationId()) { sendChannelEndpoint = publication.channelEndpoint(); break; } } if (null == sendChannelEndpoint) { throw new ControlProtocolException(UNKNOWN_PUBLICATION, "Unknown publication: " + registrationId); } sendChannelEndpoint.validateAllowsManualControl(); final AeronUri aeronUri = AeronUri.parse(destinationChannel); final InetSocketAddress dstAddress = UdpChannel.destinationAddress(aeronUri); senderProxy.addDestination(sendChannelEndpoint, dstAddress); clientProxy.operationSucceeded(correlationId); } void onRemoveDestination(final long registrationId, final String destinationChannel, final long correlationId) { SendChannelEndpoint sendChannelEndpoint = null; for (int i = 0, size = networkPublications.size(); i < size; i++) { final NetworkPublication publication = networkPublications.get(i); if (registrationId == publication.registrationId()) { sendChannelEndpoint = publication.channelEndpoint(); break; } } if (null == sendChannelEndpoint) { throw new ControlProtocolException(UNKNOWN_PUBLICATION, "Unknown publication: " + registrationId); } sendChannelEndpoint.validateAllowsManualControl(); final AeronUri aeronUri = AeronUri.parse(destinationChannel); final InetSocketAddress dstAddress = UdpChannel.destinationAddress(aeronUri); senderProxy.removeDestination(sendChannelEndpoint, dstAddress); clientProxy.operationSucceeded(correlationId); } void onAddNetworkSubscription( final String channel, final int streamId, final long registrationId, final long clientId) { final UdpChannel udpChannel = UdpChannel.parse(channel); final String reliableParam = udpChannel.aeronUri().get(RELIABLE_STREAM_PARAM_NAME, "true"); final boolean isReliable = !"false".equals(reliableParam); checkForClashingSubscription(isReliable, udpChannel, streamId); final ReceiveChannelEndpoint channelEndpoint = getOrCreateReceiveChannelEndpoint(udpChannel); final int refCount = channelEndpoint.incRefToStream(streamId); if (1 == refCount) { receiverProxy.addSubscription(channelEndpoint, streamId); } final AeronClient client = getOrAddClient(clientId); final SubscriptionLink subscription = new NetworkSubscriptionLink( registrationId, channelEndpoint, streamId, channel, client, context.clientLivenessTimeoutNs(), isReliable); subscriptionLinks.add(subscription); clientProxy.operationSucceeded(registrationId); linkMatchingImages(channelEndpoint, subscription); } void onAddIpcSubscription(final String channel, final int streamId, final long registrationId, final long clientId) { final IpcSubscriptionLink subscription = new IpcSubscriptionLink( registrationId, streamId, channel, getOrAddClient(clientId), context.clientLivenessTimeoutNs()); subscriptionLinks.add(subscription); clientProxy.operationSucceeded(registrationId); for (int i = 0, size = ipcPublications.size(); i < size; i++) { final IpcPublication publication = ipcPublications.get(i); if (publication.streamId() == streamId && IpcPublication.Status.ACTIVE == publication.status()) { linkIpcSubscription(subscription, publication); } } } void onAddSpySubscription(final String channel, final int streamId, final long registrationId, final long clientId) { final UdpChannel udpChannel = UdpChannel.parse(channel); final AeronClient client = getOrAddClient(clientId); final SpySubscriptionLink subscriptionLink = new SpySubscriptionLink( registrationId, udpChannel, streamId, client, context.clientLivenessTimeoutNs()); subscriptionLinks.add(subscriptionLink); clientProxy.operationSucceeded(registrationId); final SendChannelEndpoint channelEndpoint = sendChannelEndpointByChannelMap.get(udpChannel.canonicalForm()); for (int i = 0, size = networkPublications.size(); i < size; i++) { final NetworkPublication publication = networkPublications.get(i); if (streamId == publication.streamId() && channelEndpoint == publication.channelEndpoint() && NetworkPublication.Status.ACTIVE == publication.status()) { linkSpy(publication, subscriptionLink); } } } void onRemoveSubscription(final long registrationId, final long correlationId) { final SubscriptionLink subscription = removeSubscriptionLink(subscriptionLinks, registrationId); if (null == subscription) { throw new ControlProtocolException(UNKNOWN_SUBSCRIPTION, "Unknown Subscription: " + registrationId); } subscription.close(); final ReceiveChannelEndpoint channelEndpoint = subscription.channelEndpoint(); if (null != channelEndpoint) { final int refCount = channelEndpoint.decRefToStream(subscription.streamId()); if (0 == refCount) { receiverProxy.removeSubscription(channelEndpoint, subscription.streamId()); } if (channelEndpoint.shouldBeClosed()) { channelEndpoint.closeStatusIndicator(); receiveChannelEndpointByChannelMap.remove(channelEndpoint.udpChannel().canonicalForm()); receiverProxy.closeReceiveChannelEndpoint(channelEndpoint); while (!channelEndpoint.isClosed()) { Thread.yield(); } } } clientProxy.operationSucceeded(correlationId); } void onClientKeepalive(final long clientId) { clientKeepAlives.addOrdered(1); final AeronClient client = findClient(clients, clientId); if (null != client) { client.timeOfLastKeepalive(nanoClock.nanoTime()); } } private void onHeartbeatCheckTimeouts(final long nanoTimeNow) { toDriverCommands.consumerHeartbeatTime(epochClock.time()); onCheckManagedResources(clients, nanoTimeNow); onCheckManagedResources(publicationLinks, nanoTimeNow); onCheckManagedResources(networkPublications, nanoTimeNow); onCheckManagedResources(subscriptionLinks, nanoTimeNow); onCheckManagedResources(publicationImages, nanoTimeNow); onCheckManagedResources(ipcPublications, nanoTimeNow); } private void onCheckForBlockedToDriverCommands(final long nanoTimeNow) { final long consumerPosition = toDriverCommands.consumerPosition(); if (consumerPosition == lastConsumerCommandPosition) { if (toDriverCommands.producerPosition() > consumerPosition && nanoTimeNow > (timeOfLastToDriverPositionChange + clientLivenessTimeoutNs)) { if (toDriverCommands.unblock()) { context.systemCounters().get(UNBLOCKED_COMMANDS).orderedIncrement(); } } } else { timeOfLastToDriverPositionChange = nanoTimeNow; lastConsumerCommandPosition = consumerPosition; } } private static NetworkPublication findPublication( final ArrayList<NetworkPublication> publications, final int streamId, final SendChannelEndpoint channelEndpoint) { for (int i = 0, size = publications.size(); i < size; i++) { final NetworkPublication publication = publications.get(i); if (streamId == publication.streamId() && channelEndpoint == publication.channelEndpoint() && NetworkPublication.Status.ACTIVE == publication.status() && !publication.isExclusive()) { return publication; } } return null; } private RawLog newNetworkPublicationLog( final int sessionId, final int streamId, final int initialTermId, final UdpChannel udpChannel, final long registrationId, final int termBufferLength) { final RawLog rawLog = rawLogFactory.newNetworkPublication( udpChannel.canonicalForm(), sessionId, streamId, registrationId, termBufferLength); final UnsafeBuffer logMetaData = rawLog.metaData(); storeDefaultFrameHeader(logMetaData, createDefaultHeader(sessionId, streamId, initialTermId)); initialiseTailWithTermId(logMetaData, 0, initialTermId); initialTermId(logMetaData, initialTermId); mtuLength(logMetaData, context.mtuLength()); correlationId(logMetaData, registrationId); timeOfLastStatusMessage(logMetaData, 0); return rawLog; } private RawLog newIpcPublicationLog( final int termBufferLength, final int sessionId, final int streamId, final int initialTermId, final long registrationId) { final RawLog rawLog = rawLogFactory.newIpcPublication(sessionId, streamId, registrationId, termBufferLength); final UnsafeBuffer logMetaData = rawLog.metaData(); storeDefaultFrameHeader(logMetaData, createDefaultHeader(sessionId, streamId, initialTermId)); initialiseTailWithTermId(logMetaData, 0, initialTermId); initialTermId(logMetaData, initialTermId); mtuLength(logMetaData, computeMaxMessageLength(termBufferLength)); correlationId(logMetaData, registrationId); timeOfLastStatusMessage(logMetaData, 0); return rawLog; } private static int getTermBufferLength(final AeronUri aeronUri, final int defaultTermLength) { final String termLengthParam = aeronUri.get(CommonContext.TERM_LENGTH_PARAM_NAME); int termLength = defaultTermLength; if (null != termLengthParam) { termLength = Integer.parseInt(termLengthParam); Configuration.validateTermBufferLength(termLength); } return termLength; } private RawLog newPublicationImageLog( final int sessionId, final int streamId, final int initialTermId, final int termBufferLength, final int senderMtuLength, final UdpChannel udpChannel, final long correlationId) { final RawLog rawLog = rawLogFactory.newNetworkedImage( udpChannel.canonicalForm(), sessionId, streamId, correlationId, termBufferLength); final UnsafeBuffer logMetaData = rawLog.metaData(); storeDefaultFrameHeader(logMetaData, createDefaultHeader(sessionId, streamId, initialTermId)); initialTermId(logMetaData, initialTermId); mtuLength(logMetaData, senderMtuLength); correlationId(logMetaData, correlationId); timeOfLastStatusMessage(logMetaData, 0); return rawLog; } private SendChannelEndpoint getOrCreateSendChannelEndpoint(final UdpChannel udpChannel) { SendChannelEndpoint channelEndpoint = sendChannelEndpointByChannelMap.get(udpChannel.canonicalForm()); if (null == channelEndpoint) { channelEndpoint = context.sendChannelEndpointSupplier().newInstance( udpChannel, SendChannelStatus.allocate(countersManager, udpChannel.originalUriString()), context); sendChannelEndpointByChannelMap.put(udpChannel.canonicalForm(), channelEndpoint); senderProxy.registerSendChannelEndpoint(channelEndpoint); } return channelEndpoint; } private void checkForClashingSubscription(final boolean isReliable, final UdpChannel udpChannel, final int streamId) { final ReceiveChannelEndpoint channelEndpoint = receiveChannelEndpointByChannelMap.get( udpChannel.canonicalForm()); if (null != channelEndpoint) { final ArrayList<SubscriptionLink> existingLinks = subscriptionLinks; for (int i = 0, size = existingLinks.size(); i < size; i++) { final SubscriptionLink subscription = existingLinks.get(i); if (subscription.matches(channelEndpoint, streamId) && isReliable != subscription.isReliable()) { throw new IllegalStateException( "Option conflicts with existing subscriptions: reliable=" + isReliable); } } } } private void linkMatchingImages(final ReceiveChannelEndpoint channelEndpoint, final SubscriptionLink subscription) { final long registrationId = subscription.registrationId(); final int streamId = subscription.streamId(); final String channel = subscription.uri(); for (int i = 0, size = publicationImages.size(); i < size; i++) { final PublicationImage image = publicationImages.get(i); if (image.matches(channelEndpoint, streamId) && image.isAcceptingSubscriptions()) { final long rebuildPosition = image.rebuildPosition(); final int sessionId = image.sessionId(); final Position position = SubscriberPos.allocate( countersManager, registrationId, sessionId, streamId, channel, rebuildPosition); position.setOrdered(rebuildPosition); image.addSubscriber(position); subscription.link(image, position); clientProxy.onAvailableImage( image.correlationId(), streamId, sessionId, image.rawLog().fileName(), Collections.singletonList(new SubscriberPosition(subscription, position)), generateSourceIdentity(image.sourceAddress())); } } } private void linkIpcSubscriptions(final IpcPublication publication) { final int streamId = publication.streamId(); final ArrayList<SubscriptionLink> subscriptionLinks = this.subscriptionLinks; for (int i = 0, size = subscriptionLinks.size(); i < size; i++) { final SubscriptionLink subscription = subscriptionLinks.get(i); if (subscription.matches(streamId) && !subscription.isLinked(publication)) { linkIpcSubscription((IpcSubscriptionLink)subscription, publication); } } } private static ReadablePosition[] positionArray(final List<SubscriberPosition> subscriberPositions) { final int size = subscriberPositions.size(); final ReadablePosition[] positions = new ReadablePosition[subscriberPositions.size()]; for (int i = 0; i < size; i++) { positions[i] = subscriberPositions.get(i).position(); } return positions; } private void linkIpcSubscription(final IpcSubscriptionLink subscription, final IpcPublication publication) { final long joiningPosition = publication.joiningPosition(); final long registrationId = subscription.registrationId(); final int sessionId = publication.sessionId(); final int streamId = subscription.streamId(); final String channel = subscription.uri(); final Position position = SubscriberPos.allocate( countersManager, registrationId, sessionId, streamId, channel, joiningPosition); position.setOrdered(joiningPosition); subscription.link(publication, position); publication.addSubscriber(position); clientProxy.onAvailableImage( publication.correlationId(), streamId, sessionId, publication.rawLog().fileName(), Collections.singletonList(new SubscriberPosition(subscription, position)), channel); } private void linkSpy(final NetworkPublication publication, final SubscriptionLink subscription) { final long joiningPosition = publication.spyJoiningPosition(); final long registrationId = subscription.registrationId(); final int streamId = publication.streamId(); final int sessionId = publication.sessionId(); final String channel = subscription.uri(); final Position position = SubscriberPos.allocate( countersManager, registrationId, sessionId, streamId, channel, joiningPosition); position.setOrdered(joiningPosition); publication.addSubscriber(position); subscription.link(publication, position); clientProxy.onAvailableImage( correlationId(publication.rawLog().metaData()), streamId, sessionId, publication.rawLog().fileName(), Collections.singletonList(new SubscriberPosition(subscription, position)), channel); } private ReceiveChannelEndpoint getOrCreateReceiveChannelEndpoint(final UdpChannel udpChannel) { ReceiveChannelEndpoint channelEndpoint = receiveChannelEndpointByChannelMap.get(udpChannel.canonicalForm()); if (null == channelEndpoint) { channelEndpoint = context.receiveChannelEndpointSupplier().newInstance( udpChannel, new DataPacketDispatcher(fromReceiverConductorProxy, receiverProxy.receiver()), ReceiveChannelStatus.allocate(countersManager, udpChannel.originalUriString()), context); receiveChannelEndpointByChannelMap.put(udpChannel.canonicalForm(), channelEndpoint); receiverProxy.registerReceiveChannelEndpoint(channelEndpoint); } return channelEndpoint; } private void onDriverConductorCmd(final DriverConductorCmd cmd) { cmd.execute(this); } private AeronClient getOrAddClient(final long clientId) { AeronClient client = findClient(clients, clientId); if (null == client) { client = new AeronClient(clientId, clientLivenessTimeoutNs, nanoClock.nanoTime()); clients.add(client); } return client; } private IpcPublication getOrAddIpcPublication(final int streamId, final String channel, final boolean isExclusive) { IpcPublication publication = null; if (!isExclusive) { publication = findIpcSharedPublication(ipcPublications, streamId); } if (null == publication) { publication = addIpcPublication(streamId, channel, isExclusive); } return publication; } private IpcPublication addIpcPublication(final int streamId, final String channel, final boolean isExclusive) { final int termLength = getTermBufferLength(AeronUri.parse(channel), context.ipcTermBufferLength()); final long registrationId = nextImageCorrelationId(); final int sessionId = nextSessionId++; final int initialTermId = BitUtil.generateRandomisedId(); final RawLog rawLog = newIpcPublicationLog( termLength, sessionId, streamId, initialTermId, registrationId); final Position publisherLimit = PublisherLimit.allocate( countersManager, registrationId, sessionId, streamId, channel); final IpcPublication publication = new IpcPublication( registrationId, sessionId, streamId, publisherLimit, rawLog, publicationUnblockTimeoutNs, context.systemCounters(), isExclusive); ipcPublications.add(publication); return publication; } private long nextImageCorrelationId() { return toDriverCommands.nextCorrelationId(); } private static AeronClient findClient(final ArrayList<AeronClient> clients, final long clientId) { AeronClient aeronClient = null; for (int i = 0, size = clients.size(); i < size; i++) { final AeronClient client = clients.get(i); if (client.clientId() == clientId) { aeronClient = client; break; } } return aeronClient; } private static SubscriptionLink removeSubscriptionLink( final ArrayList<SubscriptionLink> subscriptionLinks, final long registrationId) { SubscriptionLink subscriptionLink = null; for (int i = 0, size = subscriptionLinks.size(), lastIndex = size - 1; i < size; i++) { final SubscriptionLink subscription = subscriptionLinks.get(i); if (subscription.registrationId() == registrationId) { subscriptionLink = subscription; ArrayListUtil.fastUnorderedRemove(subscriptionLinks, i, lastIndex); break; } } return subscriptionLink; } private static IpcPublication findIpcSharedPublication( final ArrayList<IpcPublication> ipcPublications, final long streamId) { IpcPublication ipcPublication = null; for (int i = 0, size = ipcPublications.size(); i < size; i++) { final IpcPublication publication = ipcPublications.get(i); if (publication.streamId() == streamId && !publication.isExclusive() && IpcPublication.Status.ACTIVE == publication.status()) { ipcPublication = publication; break; } } return ipcPublication; } private static String generateSourceIdentity(final InetSocketAddress address) { return address.getHostString() + ':' + address.getPort(); } private <T extends DriverManagedResource> void onCheckManagedResources(final ArrayList<T> list, final long time) { for (int lastIndex = list.size() - 1, i = lastIndex; i >= 0; i--) { final DriverManagedResource resource = list.get(i); resource.onTimeEvent(time, this); if (resource.hasReachedEndOfLife()) { ArrayListUtil.fastUnorderedRemove(list, i, lastIndex); lastIndex--; resource.delete(); } } } private int processTimers(final long now) { int workCount = 0; if (now > (timeOfLastTimeoutCheck + HEARTBEAT_TIMEOUT_NS)) { onHeartbeatCheckTimeouts(now); onCheckForBlockedToDriverCommands(now); timeOfLastTimeoutCheck = now; workCount = 1; } return workCount; } private static int getMtuLength(final AeronUri aeronUri, final int defaultMtuLength) { int mtuLength = defaultMtuLength; final String mtu = aeronUri.get(CommonContext.MTU_LENGTH_URI_PARAM_NAME); if (null != mtu) { mtuLength = Integer.parseInt(mtu); Configuration.validateMtuLength(mtuLength); } return mtuLength; } private void linkSpies(final ArrayList<SubscriptionLink> links, final NetworkPublication publication) { for (int i = 0, size = links.size(); i < size; i++) { final SubscriptionLink subscription = links.get(i); if (subscription.matches(publication) && !subscription.isLinked(publication)) { linkSpy(publication, subscription); } } } }
aeron-driver/src/main/java/io/aeron/driver/DriverConductor.java
/* * Copyright 2014-2017 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.aeron.driver; import io.aeron.ArrayListUtil; import io.aeron.CommonContext; import io.aeron.driver.buffer.RawLogFactory; import io.aeron.driver.MediaDriver.Context; import io.aeron.driver.buffer.RawLog; import io.aeron.driver.cmd.DriverConductorCmd; import io.aeron.driver.exceptions.ControlProtocolException; import io.aeron.driver.media.ReceiveChannelEndpoint; import io.aeron.driver.media.SendChannelEndpoint; import io.aeron.driver.media.UdpChannel; import io.aeron.driver.status.*; import io.aeron.driver.uri.AeronUri; import org.agrona.BitUtil; import org.agrona.concurrent.*; import org.agrona.concurrent.ringbuffer.RingBuffer; import org.agrona.concurrent.status.AtomicCounter; import org.agrona.concurrent.status.CountersManager; import org.agrona.concurrent.status.Position; import org.agrona.concurrent.status.ReadablePosition; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.function.Consumer; import static io.aeron.CommonContext.RELIABLE_STREAM_PARAM_NAME; import static io.aeron.driver.Configuration.*; import static io.aeron.driver.status.SystemCounterDescriptor.CLIENT_KEEP_ALIVES; import static io.aeron.driver.status.SystemCounterDescriptor.ERRORS; import static io.aeron.driver.status.SystemCounterDescriptor.UNBLOCKED_COMMANDS; import static io.aeron.ErrorCode.*; import static io.aeron.logbuffer.FrameDescriptor.computeMaxMessageLength; import static io.aeron.logbuffer.LogBufferDescriptor.*; import static io.aeron.protocol.DataHeaderFlyweight.createDefaultHeader; /** * Driver Conductor that takes commands from publishers and subscribers and orchestrates the media driver. */ public class DriverConductor implements Agent { private final long imageLivenessTimeoutNs; private final long clientLivenessTimeoutNs; private final long publicationUnblockTimeoutNs; private long timeOfLastToDriverPositionChange; private long lastConsumerCommandPosition; private long timeOfLastTimeoutCheck; private int nextSessionId = BitUtil.generateRandomisedId(); private final NetworkPublicationThreadLocals networkPublicationThreadLocals = new NetworkPublicationThreadLocals(); private final Context context; private final RawLogFactory rawLogFactory; private final ReceiverProxy receiverProxy; private final SenderProxy senderProxy; private final ClientProxy clientProxy; private final DriverConductorProxy fromReceiverConductorProxy; private final RingBuffer toDriverCommands; private final ClientListenerAdapter clientListenerAdapter; private final OneToOneConcurrentArrayQueue<DriverConductorCmd> fromReceiverDriverConductorCmdQueue; private final OneToOneConcurrentArrayQueue<DriverConductorCmd> fromSenderDriverConductorCmdQueue; private final HashMap<String, SendChannelEndpoint> sendChannelEndpointByChannelMap = new HashMap<>(); private final HashMap<String, ReceiveChannelEndpoint> receiveChannelEndpointByChannelMap = new HashMap<>(); private final ArrayList<PublicationLink> publicationLinks = new ArrayList<>(); private final ArrayList<NetworkPublication> networkPublications = new ArrayList<>(); private final ArrayList<SubscriptionLink> subscriptionLinks = new ArrayList<>(); private final ArrayList<PublicationImage> publicationImages = new ArrayList<>(); private final ArrayList<AeronClient> clients = new ArrayList<>(); private final ArrayList<IpcPublication> ipcPublications = new ArrayList<>(); private final EpochClock epochClock; private final NanoClock nanoClock; private final Consumer<DriverConductorCmd> onDriverConductorCmdFunc = this::onDriverConductorCmd; private final CountersManager countersManager; private final AtomicCounter clientKeepAlives; public DriverConductor(final Context ctx) { context = ctx; imageLivenessTimeoutNs = ctx.imageLivenessTimeoutNs(); clientLivenessTimeoutNs = ctx.clientLivenessTimeoutNs(); publicationUnblockTimeoutNs = ctx.publicationUnblockTimeoutNs(); fromReceiverDriverConductorCmdQueue = ctx.toConductorFromReceiverCommandQueue(); fromSenderDriverConductorCmdQueue = ctx.toConductorFromSenderCommandQueue(); receiverProxy = ctx.receiverProxy(); senderProxy = ctx.senderProxy(); rawLogFactory = ctx.rawLogBuffersFactory(); epochClock = ctx.epochClock(); nanoClock = ctx.nanoClock(); toDriverCommands = ctx.toDriverCommands(); clientProxy = ctx.clientProxy(); fromReceiverConductorProxy = ctx.fromReceiverDriverConductorProxy(); countersManager = context.countersManager(); clientKeepAlives = context.systemCounters().get(CLIENT_KEEP_ALIVES); clientListenerAdapter = new ClientListenerAdapter( context.systemCounters().get(ERRORS), ctx.errorLog(), toDriverCommands, clientProxy, this); toDriverCommands.consumerHeartbeatTime(epochClock.time()); final long now = nanoClock.nanoTime(); timeOfLastTimeoutCheck = now; timeOfLastToDriverPositionChange = now; lastConsumerCommandPosition = toDriverCommands.consumerPosition(); } public void onClose() { networkPublications.forEach(NetworkPublication::close); publicationImages.forEach(PublicationImage::close); ipcPublications.forEach(IpcPublication::close); sendChannelEndpointByChannelMap.values().forEach(SendChannelEndpoint::close); receiveChannelEndpointByChannelMap.values().forEach(ReceiveChannelEndpoint::close); } public String roleName() { return "driver-conductor"; } public int doWork() throws Exception { int workCount = 0; workCount += clientListenerAdapter.receive(); workCount += fromReceiverDriverConductorCmdQueue.drain(onDriverConductorCmdFunc); workCount += fromSenderDriverConductorCmdQueue.drain(onDriverConductorCmdFunc); final long now = nanoClock.nanoTime(); workCount += processTimers(now); final ArrayList<PublicationImage> publicationImages = this.publicationImages; for (int i = 0, size = publicationImages.size(); i < size; i++) { publicationImages.get(i).trackRebuild(now, context.statusMessageTimeout()); } final ArrayList<NetworkPublication> networkPublications = this.networkPublications; for (int i = 0, size = networkPublications.size(); i < size; i++) { workCount += networkPublications.get(i).updatePublishersLimit(); } final ArrayList<IpcPublication> ipcPublications = this.ipcPublications; for (int i = 0, size = ipcPublications.size(); i < size; i++) { workCount += ipcPublications.get(i).updatePublishersLimit(toDriverCommands.consumerHeartbeatTime()); } return workCount; } public void onClosePublication(final NetworkPublication publication) { publication.close(); } public void onCreatePublicationImage( final int sessionId, final int streamId, final int initialTermId, final int activeTermId, final int initialTermOffset, final int termBufferLength, final int senderMtuLength, final InetSocketAddress controlAddress, final InetSocketAddress sourceAddress, final ReceiveChannelEndpoint channelEndpoint) { channelEndpoint.validateSenderMtuLength(senderMtuLength); channelEndpoint.validateWindowMaxLength(context.initialWindowLength()); final UdpChannel udpChannel = channelEndpoint.udpChannel(); final String channel = udpChannel.originalUriString(); final long registrationId = nextImageCorrelationId(); final long joiningPosition = computePosition( activeTermId, initialTermOffset, Integer.numberOfTrailingZeros(termBufferLength), initialTermId); final List<SubscriberPosition> subscriberPositions = createSubscriberPositions( sessionId, streamId, channelEndpoint, joiningPosition); if (subscriberPositions.size() > 0) { final RawLog rawLog = newPublicationImageLog( sessionId, streamId, initialTermId, termBufferLength, senderMtuLength, udpChannel, registrationId); final CongestionControl congestionControl = context.congestionControlSupplier().newInstance( registrationId, udpChannel, streamId, sessionId, termBufferLength, senderMtuLength, nanoClock, context, countersManager); final PublicationImage image = new PublicationImage( registrationId, imageLivenessTimeoutNs, channelEndpoint, controlAddress, sessionId, streamId, initialTermId, activeTermId, initialTermOffset, rawLog, udpChannel.isMulticast() ? NAK_MULTICAST_DELAY_GENERATOR : NAK_UNICAST_DELAY_GENERATOR, positionArray(subscriberPositions), ReceiverHwm.allocate(countersManager, registrationId, sessionId, streamId, channel), ReceiverPos.allocate(countersManager, registrationId, sessionId, streamId, channel), nanoClock, context.epochClock(), context.systemCounters(), sourceAddress, congestionControl, context.lossReport(), subscriberPositions.get(0).subscription().isReliable()); for (int i = 0, size = subscriberPositions.size(); i < size; i++) { subscriberPositions.get(i).addLink(image); } publicationImages.add(image); receiverProxy.newPublicationImage(channelEndpoint, image); clientProxy.onAvailableImage( registrationId, streamId, sessionId, rawLog.fileName(), subscriberPositions, generateSourceIdentity(sourceAddress)); } } SendChannelEndpoint senderChannelEndpoint(final UdpChannel channel) { return sendChannelEndpointByChannelMap.get(channel.canonicalForm()); } ReceiveChannelEndpoint receiverChannelEndpoint(final UdpChannel channel) { return receiveChannelEndpointByChannelMap.get(channel.canonicalForm()); } IpcPublication getIpcSharedPublication(final long streamId) { return findIpcSharedPublication(ipcPublications, streamId); } void onAddNetworkPublication( final String channel, final int streamId, final long registrationId, final long clientId, final boolean isExclusive) { final UdpChannel udpChannel = UdpChannel.parse(channel); final AeronUri aeronUri = udpChannel.aeronUri(); final int mtuLength = getMtuLength(aeronUri, context.mtuLength()); final int termLength = getTermBufferLength(aeronUri, context.publicationTermBufferLength()); final SendChannelEndpoint channelEndpoint = getOrCreateSendChannelEndpoint(udpChannel); NetworkPublication publication = null; if (!isExclusive) { publication = findPublication(networkPublications, streamId, channelEndpoint); } if (null == publication) { final int sessionId = nextSessionId++; final int initialTermId = BitUtil.generateRandomisedId(); final RetransmitHandler retransmitHandler = new RetransmitHandler( nanoClock, context.systemCounters(), RETRANSMIT_UNICAST_DELAY_GENERATOR, RETRANSMIT_UNICAST_LINGER_GENERATOR); final FlowControl flowControl = udpChannel.isMulticast() || udpChannel.hasExplicitControl() ? context.multicastFlowControlSupplier().newInstance(udpChannel, streamId, registrationId) : context.unicastFlowControlSupplier().newInstance(udpChannel, streamId, registrationId); publication = new NetworkPublication( registrationId, channelEndpoint, nanoClock, toDriverCommands::consumerHeartbeatTime, newNetworkPublicationLog(sessionId, streamId, initialTermId, udpChannel, registrationId, termLength), PublisherLimit.allocate(countersManager, registrationId, sessionId, streamId, channel), SenderPos.allocate(countersManager, registrationId, sessionId, streamId, channel), SenderLimit.allocate(countersManager, registrationId, sessionId, streamId, channel), sessionId, streamId, initialTermId, mtuLength, context.systemCounters(), flowControl, retransmitHandler, networkPublicationThreadLocals, publicationUnblockTimeoutNs, isExclusive); channelEndpoint.incRef(); networkPublications.add(publication); senderProxy.newNetworkPublication(publication); linkSpies(subscriptionLinks, publication); } else if (publication.mtuLength() != mtuLength) { throw new IllegalStateException("Existing publication has different MTU length: existing=" + publication.mtuLength() + " requested=" + mtuLength); } publicationLinks.add(new PublicationLink(registrationId, publication, getOrAddClient(clientId))); clientProxy.onPublicationReady( registrationId, streamId, publication.sessionId(), publication.rawLog().fileName(), publication.publisherLimitId(), isExclusive); } void cleanupPublication(final NetworkPublication publication) { if (publication.hasSpies()) { clientProxy.onUnavailableImage( correlationId(publication.rawLog().metaData()), publication.streamId(), publication.channelEndpoint().originalUriString()); for (int i = 0, size = subscriptionLinks.size(); i < size; i++) { subscriptionLinks.get(i).unlink(publication); } } senderProxy.removeNetworkPublication(publication); final SendChannelEndpoint channelEndpoint = publication.channelEndpoint(); if (channelEndpoint.shouldBeClosed()) { channelEndpoint.closeStatusIndicator(); sendChannelEndpointByChannelMap.remove(channelEndpoint.udpChannel().canonicalForm()); senderProxy.closeSendChannelEndpoint(channelEndpoint); } } void cleanupSubscriptionLink(final SubscriptionLink subscription) { final ReceiveChannelEndpoint channelEndpoint = subscription.channelEndpoint(); if (null != channelEndpoint) { final int streamId = subscription.streamId(); if (0 == channelEndpoint.decRefToStream(subscription.streamId())) { receiverProxy.removeSubscription(channelEndpoint, streamId); } if (channelEndpoint.shouldBeClosed()) { channelEndpoint.closeStatusIndicator(); receiveChannelEndpointByChannelMap.remove(channelEndpoint.udpChannel().canonicalForm()); receiverProxy.closeReceiveChannelEndpoint(channelEndpoint); } } } void transitionToLinger(final PublicationImage image) { clientProxy.onUnavailableImage(image.correlationId(), image.streamId(), image.channelUriString()); receiverProxy.removeCoolDown(image.channelEndpoint(), image.sessionId(), image.streamId()); } void transitionToLinger(final IpcPublication publication) { clientProxy.onUnavailableImage(publication.correlationId(), publication.streamId(), CommonContext.IPC_CHANNEL); } void cleanupImage(final PublicationImage image) { for (int i = 0, size = subscriptionLinks.size(); i < size; i++) { subscriptionLinks.get(i).unlink(image); } } void cleanupIpcPublication(final IpcPublication publication) { for (int i = 0, size = subscriptionLinks.size(); i < size; i++) { subscriptionLinks.get(i).unlink(publication); } } private List<SubscriberPosition> createSubscriberPositions( final int sessionId, final int streamId, final ReceiveChannelEndpoint channelEndpoint, final long joiningPosition) { final ArrayList<SubscriberPosition> subscriberPositions = new ArrayList<>(); for (int i = 0, size = subscriptionLinks.size(); i < size; i++) { final SubscriptionLink subscription = subscriptionLinks.get(i); if (subscription.matches(channelEndpoint, streamId)) { final Position position = SubscriberPos.allocate( countersManager, subscription.registrationId(), sessionId, streamId, subscription.uri(), joiningPosition); position.setOrdered(joiningPosition); subscriberPositions.add(new SubscriberPosition(subscription, position)); } } return subscriberPositions; } void onAddIpcPublication( final String channel, final int streamId, final long registrationId, final long clientId, final boolean isExclusive) { final IpcPublication ipcPublication = getOrAddIpcPublication(streamId, channel, isExclusive); publicationLinks.add(new PublicationLink(registrationId, ipcPublication, getOrAddClient(clientId))); clientProxy.onPublicationReady( registrationId, streamId, ipcPublication.sessionId(), ipcPublication.rawLog().fileName(), ipcPublication.publisherLimitId(), isExclusive); linkIpcSubscriptions(ipcPublication); } void onRemovePublication(final long registrationId, final long correlationId) { PublicationLink publicationLink = null; final ArrayList<PublicationLink> publicationLinks = this.publicationLinks; for (int i = 0, size = publicationLinks.size(), lastIndex = size - 1; i < size; i++) { final PublicationLink publication = publicationLinks.get(i); if (registrationId == publication.registrationId()) { publicationLink = publication; ArrayListUtil.fastUnorderedRemove(publicationLinks, i, lastIndex); break; } } if (null == publicationLink) { throw new ControlProtocolException(UNKNOWN_PUBLICATION, "Unknown publication: " + registrationId); } publicationLink.close(); clientProxy.operationSucceeded(correlationId); } void onAddDestination(final long registrationId, final String destinationChannel, final long correlationId) { SendChannelEndpoint sendChannelEndpoint = null; for (int i = 0, size = networkPublications.size(); i < size; i++) { final NetworkPublication publication = networkPublications.get(i); if (registrationId == publication.registrationId()) { sendChannelEndpoint = publication.channelEndpoint(); break; } } if (null == sendChannelEndpoint) { throw new ControlProtocolException(UNKNOWN_PUBLICATION, "Unknown publication: " + registrationId); } sendChannelEndpoint.validateAllowsManualControl(); final AeronUri aeronUri = AeronUri.parse(destinationChannel); final InetSocketAddress dstAddress = UdpChannel.destinationAddress(aeronUri); senderProxy.addDestination(sendChannelEndpoint, dstAddress); clientProxy.operationSucceeded(correlationId); } void onRemoveDestination(final long registrationId, final String destinationChannel, final long correlationId) { SendChannelEndpoint sendChannelEndpoint = null; for (int i = 0, size = networkPublications.size(); i < size; i++) { final NetworkPublication publication = networkPublications.get(i); if (registrationId == publication.registrationId()) { sendChannelEndpoint = publication.channelEndpoint(); break; } } if (null == sendChannelEndpoint) { throw new ControlProtocolException(UNKNOWN_PUBLICATION, "Unknown publication: " + registrationId); } sendChannelEndpoint.validateAllowsManualControl(); final AeronUri aeronUri = AeronUri.parse(destinationChannel); final InetSocketAddress dstAddress = UdpChannel.destinationAddress(aeronUri); senderProxy.removeDestination(sendChannelEndpoint, dstAddress); clientProxy.operationSucceeded(correlationId); } void onAddNetworkSubscription( final String channel, final int streamId, final long registrationId, final long clientId) { final UdpChannel udpChannel = UdpChannel.parse(channel); final String reliableParam = udpChannel.aeronUri().get(RELIABLE_STREAM_PARAM_NAME, "true"); final boolean isReliable = !"false".equals(reliableParam); checkForClashingSubscription(isReliable, udpChannel, streamId); final ReceiveChannelEndpoint channelEndpoint = getOrCreateReceiveChannelEndpoint(udpChannel); final int refCount = channelEndpoint.incRefToStream(streamId); if (1 == refCount) { receiverProxy.addSubscription(channelEndpoint, streamId); } final AeronClient client = getOrAddClient(clientId); final SubscriptionLink subscription = new NetworkSubscriptionLink( registrationId, channelEndpoint, streamId, channel, client, context.clientLivenessTimeoutNs(), isReliable); subscriptionLinks.add(subscription); clientProxy.operationSucceeded(registrationId); linkMatchingImages(channelEndpoint, subscription); } void onAddIpcSubscription(final String channel, final int streamId, final long registrationId, final long clientId) { final IpcSubscriptionLink subscription = new IpcSubscriptionLink( registrationId, streamId, channel, getOrAddClient(clientId), context.clientLivenessTimeoutNs()); subscriptionLinks.add(subscription); clientProxy.operationSucceeded(registrationId); for (int i = 0, size = ipcPublications.size(); i < size; i++) { final IpcPublication publication = ipcPublications.get(i); if (publication.streamId() == streamId && IpcPublication.Status.ACTIVE == publication.status()) { linkIpcSubscription(subscription, publication); } } } void onAddSpySubscription(final String channel, final int streamId, final long registrationId, final long clientId) { final UdpChannel udpChannel = UdpChannel.parse(channel); final AeronClient client = getOrAddClient(clientId); final SpySubscriptionLink subscriptionLink = new SpySubscriptionLink( registrationId, udpChannel, streamId, client, context.clientLivenessTimeoutNs()); subscriptionLinks.add(subscriptionLink); clientProxy.operationSucceeded(registrationId); final SendChannelEndpoint channelEndpoint = sendChannelEndpointByChannelMap.get(udpChannel.canonicalForm()); for (int i = 0, size = networkPublications.size(); i < size; i++) { final NetworkPublication publication = networkPublications.get(i); if (streamId == publication.streamId() && channelEndpoint == publication.channelEndpoint() && NetworkPublication.Status.ACTIVE == publication.status()) { linkSpy(publication, subscriptionLink); } } } void onRemoveSubscription(final long registrationId, final long correlationId) { final SubscriptionLink subscription = removeSubscriptionLink(subscriptionLinks, registrationId); if (null == subscription) { throw new ControlProtocolException(UNKNOWN_SUBSCRIPTION, "Unknown Subscription: " + registrationId); } subscription.close(); final ReceiveChannelEndpoint channelEndpoint = subscription.channelEndpoint(); if (null != channelEndpoint) { final int refCount = channelEndpoint.decRefToStream(subscription.streamId()); if (0 == refCount) { receiverProxy.removeSubscription(channelEndpoint, subscription.streamId()); } if (channelEndpoint.shouldBeClosed()) { channelEndpoint.closeStatusIndicator(); receiveChannelEndpointByChannelMap.remove(channelEndpoint.udpChannel().canonicalForm()); receiverProxy.closeReceiveChannelEndpoint(channelEndpoint); while (!channelEndpoint.isClosed()) { Thread.yield(); } } } clientProxy.operationSucceeded(correlationId); } void onClientKeepalive(final long clientId) { clientKeepAlives.addOrdered(1); final AeronClient client = findClient(clients, clientId); if (null != client) { client.timeOfLastKeepalive(nanoClock.nanoTime()); } } private void onHeartbeatCheckTimeouts(final long nanoTimeNow) { toDriverCommands.consumerHeartbeatTime(epochClock.time()); onCheckManagedResources(clients, nanoTimeNow); onCheckManagedResources(publicationLinks, nanoTimeNow); onCheckManagedResources(networkPublications, nanoTimeNow); onCheckManagedResources(subscriptionLinks, nanoTimeNow); onCheckManagedResources(publicationImages, nanoTimeNow); onCheckManagedResources(ipcPublications, nanoTimeNow); } private void onCheckForBlockedToDriverCommands(final long nanoTimeNow) { final long consumerPosition = toDriverCommands.consumerPosition(); if (consumerPosition == lastConsumerCommandPosition) { if (toDriverCommands.producerPosition() > consumerPosition && nanoTimeNow > (timeOfLastToDriverPositionChange + clientLivenessTimeoutNs)) { if (toDriverCommands.unblock()) { context.systemCounters().get(UNBLOCKED_COMMANDS).orderedIncrement(); } } } else { timeOfLastToDriverPositionChange = nanoTimeNow; lastConsumerCommandPosition = consumerPosition; } } private static NetworkPublication findPublication( final ArrayList<NetworkPublication> publications, final int streamId, final SendChannelEndpoint channelEndpoint) { for (int i = 0, size = publications.size(); i < size; i++) { final NetworkPublication publication = publications.get(i); if (streamId == publication.streamId() && channelEndpoint == publication.channelEndpoint() && NetworkPublication.Status.ACTIVE == publication.status() && !publication.isExclusive()) { return publication; } } return null; } private RawLog newNetworkPublicationLog( final int sessionId, final int streamId, final int initialTermId, final UdpChannel udpChannel, final long registrationId, final int termBufferLength) { final RawLog rawLog = rawLogFactory.newNetworkPublication( udpChannel.canonicalForm(), sessionId, streamId, registrationId, termBufferLength); final UnsafeBuffer logMetaData = rawLog.metaData(); storeDefaultFrameHeader(logMetaData, createDefaultHeader(sessionId, streamId, initialTermId)); initialiseTailWithTermId(logMetaData, 0, initialTermId); initialTermId(logMetaData, initialTermId); mtuLength(logMetaData, context.mtuLength()); correlationId(logMetaData, registrationId); timeOfLastStatusMessage(logMetaData, 0); return rawLog; } private RawLog newIpcPublicationLog( final int termBufferLength, final int sessionId, final int streamId, final int initialTermId, final long registrationId) { final RawLog rawLog = rawLogFactory.newIpcPublication(sessionId, streamId, registrationId, termBufferLength); final UnsafeBuffer logMetaData = rawLog.metaData(); storeDefaultFrameHeader(logMetaData, createDefaultHeader(sessionId, streamId, initialTermId)); initialiseTailWithTermId(logMetaData, 0, initialTermId); initialTermId(logMetaData, initialTermId); mtuLength(logMetaData, computeMaxMessageLength(termBufferLength)); correlationId(logMetaData, registrationId); timeOfLastStatusMessage(logMetaData, 0); return rawLog; } private static int getTermBufferLength(final AeronUri aeronUri, final int defaultTermLength) { final String termLengthParam = aeronUri.get(CommonContext.TERM_LENGTH_PARAM_NAME); int termLength = defaultTermLength; if (null != termLengthParam) { termLength = Integer.parseInt(termLengthParam); Configuration.validateTermBufferLength(termLength); } return termLength; } private RawLog newPublicationImageLog( final int sessionId, final int streamId, final int initialTermId, final int termBufferLength, final int senderMtuLength, final UdpChannel udpChannel, final long correlationId) { final RawLog rawLog = rawLogFactory.newNetworkedImage( udpChannel.canonicalForm(), sessionId, streamId, correlationId, termBufferLength); final UnsafeBuffer logMetaData = rawLog.metaData(); storeDefaultFrameHeader(logMetaData, createDefaultHeader(sessionId, streamId, initialTermId)); initialTermId(logMetaData, initialTermId); mtuLength(logMetaData, senderMtuLength); correlationId(logMetaData, correlationId); timeOfLastStatusMessage(logMetaData, 0); return rawLog; } private SendChannelEndpoint getOrCreateSendChannelEndpoint(final UdpChannel udpChannel) { SendChannelEndpoint channelEndpoint = sendChannelEndpointByChannelMap.get(udpChannel.canonicalForm()); if (null == channelEndpoint) { channelEndpoint = context.sendChannelEndpointSupplier().newInstance( udpChannel, SendChannelStatus.allocate(countersManager, udpChannel.originalUriString()), context); sendChannelEndpointByChannelMap.put(udpChannel.canonicalForm(), channelEndpoint); senderProxy.registerSendChannelEndpoint(channelEndpoint); } return channelEndpoint; } private void checkForClashingSubscription(final boolean isReliable, final UdpChannel udpChannel, final int streamId) { final ReceiveChannelEndpoint channelEndpoint = receiveChannelEndpointByChannelMap.get( udpChannel.canonicalForm()); if (null != channelEndpoint) { final ArrayList<SubscriptionLink> existingLinks = subscriptionLinks; for (int i = 0, size = existingLinks.size(); i < size; i++) { final SubscriptionLink subscription = existingLinks.get(i); if (subscription.matches(channelEndpoint, streamId) && isReliable != subscription.isReliable()) { throw new IllegalStateException( "Option conflicts with existing subscriptions: reliable=" + isReliable); } } } } private void linkMatchingImages(final ReceiveChannelEndpoint channelEndpoint, final SubscriptionLink subscription) { final long registrationId = subscription.registrationId(); final int streamId = subscription.streamId(); final String channel = subscription.uri(); for (int i = 0, size = publicationImages.size(); i < size; i++) { final PublicationImage image = publicationImages.get(i); if (image.matches(channelEndpoint, streamId) && image.isAcceptingSubscriptions()) { final long rebuildPosition = image.rebuildPosition(); final int sessionId = image.sessionId(); final Position position = SubscriberPos.allocate( countersManager, registrationId, sessionId, streamId, channel, rebuildPosition); position.setOrdered(rebuildPosition); image.addSubscriber(position); subscription.link(image, position); clientProxy.onAvailableImage( image.correlationId(), streamId, sessionId, image.rawLog().fileName(), Collections.singletonList(new SubscriberPosition(subscription, position)), generateSourceIdentity(image.sourceAddress())); } } } private void linkIpcSubscriptions(final IpcPublication publication) { final int streamId = publication.streamId(); final ArrayList<SubscriptionLink> subscriptionLinks = this.subscriptionLinks; for (int i = 0, size = subscriptionLinks.size(); i < size; i++) { final SubscriptionLink subscription = subscriptionLinks.get(i); if (subscription.matches(streamId) && !subscription.isLinked(publication)) { linkIpcSubscription((IpcSubscriptionLink)subscription, publication); } } } private static ReadablePosition[] positionArray(final List<SubscriberPosition> subscriberPositions) { final int size = subscriberPositions.size(); final ReadablePosition[] positions = new ReadablePosition[subscriberPositions.size()]; for (int i = 0; i < size; i++) { positions[i] = subscriberPositions.get(i).position(); } return positions; } private void linkIpcSubscription(final IpcSubscriptionLink subscription, final IpcPublication publication) { final long joiningPosition = publication.joiningPosition(); final long registrationId = subscription.registrationId(); final int sessionId = publication.sessionId(); final int streamId = subscription.streamId(); final String channel = subscription.uri(); final Position position = SubscriberPos.allocate( countersManager, registrationId, sessionId, streamId, channel, joiningPosition); position.setOrdered(joiningPosition); subscription.link(publication, position); publication.addSubscriber(position); clientProxy.onAvailableImage( publication.correlationId(), streamId, sessionId, publication.rawLog().fileName(), Collections.singletonList(new SubscriberPosition(subscription, position)), channel); } private void linkSpy(final NetworkPublication publication, final SubscriptionLink subscription) { final long joiningPosition = publication.spyJoiningPosition(); final long registrationId = subscription.registrationId(); final int streamId = publication.streamId(); final int sessionId = publication.sessionId(); final String channel = subscription.uri(); final Position position = SubscriberPos.allocate( countersManager, registrationId, sessionId, streamId, channel, joiningPosition); position.setOrdered(joiningPosition); publication.addSubscriber(position); subscription.link(publication, position); clientProxy.onAvailableImage( correlationId(publication.rawLog().metaData()), streamId, sessionId, publication.rawLog().fileName(), Collections.singletonList(new SubscriberPosition(subscription, position)), channel); } private ReceiveChannelEndpoint getOrCreateReceiveChannelEndpoint(final UdpChannel udpChannel) { ReceiveChannelEndpoint channelEndpoint = receiveChannelEndpointByChannelMap.get(udpChannel.canonicalForm()); if (null == channelEndpoint) { channelEndpoint = context.receiveChannelEndpointSupplier().newInstance( udpChannel, new DataPacketDispatcher(fromReceiverConductorProxy, receiverProxy.receiver()), ReceiveChannelStatus.allocate(countersManager, udpChannel.originalUriString()), context); receiveChannelEndpointByChannelMap.put(udpChannel.canonicalForm(), channelEndpoint); receiverProxy.registerReceiveChannelEndpoint(channelEndpoint); } return channelEndpoint; } private void onDriverConductorCmd(final DriverConductorCmd cmd) { cmd.execute(this); } private AeronClient getOrAddClient(final long clientId) { AeronClient client = findClient(clients, clientId); if (null == client) { client = new AeronClient(clientId, clientLivenessTimeoutNs, nanoClock.nanoTime()); clients.add(client); } return client; } private IpcPublication getOrAddIpcPublication(final int streamId, final String channel, final boolean isExclusive) { IpcPublication publication = null; if (!isExclusive) { publication = findIpcSharedPublication(ipcPublications, streamId); } if (null == publication) { publication = addIpcPublication(streamId, channel, isExclusive); } return publication; } private IpcPublication addIpcPublication(final int streamId, final String channel, final boolean isExclusive) { final int termLength = getTermBufferLength(AeronUri.parse(channel), context.ipcTermBufferLength()); final long registrationId = nextImageCorrelationId(); final int sessionId = nextSessionId++; final int initialTermId = BitUtil.generateRandomisedId(); final RawLog rawLog = newIpcPublicationLog( termLength, sessionId, streamId, initialTermId, registrationId); final Position publisherLimit = PublisherLimit.allocate( countersManager, registrationId, sessionId, streamId, channel); final IpcPublication publication = new IpcPublication( registrationId, sessionId, streamId, publisherLimit, rawLog, publicationUnblockTimeoutNs, context.systemCounters(), isExclusive); ipcPublications.add(publication); return publication; } private long nextImageCorrelationId() { return toDriverCommands.nextCorrelationId(); } private static AeronClient findClient(final ArrayList<AeronClient> clients, final long clientId) { AeronClient aeronClient = null; for (int i = 0, size = clients.size(); i < size; i++) { final AeronClient client = clients.get(i); if (client.clientId() == clientId) { aeronClient = client; break; } } return aeronClient; } private static SubscriptionLink removeSubscriptionLink( final ArrayList<SubscriptionLink> subscriptionLinks, final long registrationId) { SubscriptionLink subscriptionLink = null; for (int i = 0, size = subscriptionLinks.size(), lastIndex = size - 1; i < size; i++) { final SubscriptionLink subscription = subscriptionLinks.get(i); if (subscription.registrationId() == registrationId) { subscriptionLink = subscription; ArrayListUtil.fastUnorderedRemove(subscriptionLinks, i, lastIndex); break; } } return subscriptionLink; } private static IpcPublication findIpcSharedPublication( final ArrayList<IpcPublication> ipcPublications, final long streamId) { IpcPublication ipcPublication = null; for (int i = 0, size = ipcPublications.size(); i < size; i++) { final IpcPublication publication = ipcPublications.get(i); if (publication.streamId() == streamId && !publication.isExclusive() && IpcPublication.Status.ACTIVE == publication.status()) { ipcPublication = publication; break; } } return ipcPublication; } private static String generateSourceIdentity(final InetSocketAddress address) { return address.getHostString() + ':' + address.getPort(); } private <T extends DriverManagedResource> void onCheckManagedResources(final ArrayList<T> list, final long time) { for (int lastIndex = list.size() - 1, i = lastIndex; i >= 0; i--) { final DriverManagedResource resource = list.get(i); resource.onTimeEvent(time, this); if (resource.hasReachedEndOfLife()) { ArrayListUtil.fastUnorderedRemove(list, i, lastIndex); lastIndex--; resource.delete(); } } } private int processTimers(final long now) { int workCount = 0; if (now > (timeOfLastTimeoutCheck + HEARTBEAT_TIMEOUT_NS)) { onHeartbeatCheckTimeouts(now); onCheckForBlockedToDriverCommands(now); timeOfLastTimeoutCheck = now; workCount = 1; } return workCount; } private static int getMtuLength(final AeronUri aeronUri, final int defaultMtuLength) { int mtuLength = defaultMtuLength; final String mtu = aeronUri.get(CommonContext.MTU_LENGTH_URI_PARAM_NAME); if (null != mtu) { mtuLength = Integer.parseInt(mtu); Configuration.validateMtuLength(mtuLength); } return mtuLength; } private void linkSpies(final ArrayList<SubscriptionLink> links, final NetworkPublication publication) { for (int i = 0, size = links.size(); i < size; i++) { final SubscriptionLink subscription = links.get(i); if (subscription.matches(publication) && !subscription.isLinked(publication)) { linkSpy(publication, subscription); } } } }
[Java] Save indirection to status message timeout value.
aeron-driver/src/main/java/io/aeron/driver/DriverConductor.java
[Java] Save indirection to status message timeout value.
Java
apache-2.0
76e1f1ca8c00ca3fa3ffddf2190e9a285bc9d985
0
billho/symphony,billho/symphony,billho/symphony
/* * Symphony - A modern community (forum/SNS/blog) platform written in Java. * Copyright (C) 2012-2017, b3log.org & hacpai.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.b3log.symphony.api.v2; import org.b3log.latke.Keys; import org.b3log.latke.ioc.inject.Inject; import org.b3log.latke.logging.Level; import org.b3log.latke.logging.Logger; import org.b3log.latke.model.Pagination; import org.b3log.latke.model.User; import org.b3log.latke.servlet.HTTPRequestContext; import org.b3log.latke.servlet.HTTPRequestMethod; import org.b3log.latke.servlet.annotation.After; import org.b3log.latke.servlet.annotation.Before; import org.b3log.latke.servlet.annotation.RequestProcessing; import org.b3log.latke.servlet.annotation.RequestProcessor; import org.b3log.latke.util.Paginator; import org.b3log.latke.util.Strings; import org.b3log.symphony.model.*; import org.b3log.symphony.processor.advice.AnonymousViewCheck; import org.b3log.symphony.processor.advice.PermissionGrant; import org.b3log.symphony.processor.advice.stopwatch.StopwatchEndAdvice; import org.b3log.symphony.processor.advice.stopwatch.StopwatchStartAdvice; import org.b3log.symphony.processor.advice.validate.UserRegisterValidation; import org.b3log.symphony.service.*; import org.b3log.symphony.util.StatusCodes; import org.json.JSONObject; import javax.servlet.http.HttpServletRequest; import java.util.List; /** * User API v2. * <p> * <ul> * <li>Gets a user (/api/v2/user/{userName}), GET</li> * <li>Gets a user's articles (/api/v2/user/{userName}/articles), GET</li> * <li>Gets a user's comments (/api/v2/user/{userName}/comments), GET</li> * <li>Gets a user's watching articles (/api/v2/user/{userName}/watching/articles), GET</li> * <li>Gets a user's following users (/api/v2/user/{userName}/following/users), GET</li> * <li>Gets a user's following tags (/api/v2/user/{userName}/following/tags), GET</li> * <li>Gets a user's following articles (/api/v2/user/{userName}/following/articles), GET</li> * <li>Gets a user's followers (/api/v2/user/{userName}/followers), GET</li> * </ul> * </p> * * @author <a href="http://88250.b3log.org">Liang Ding</a> * @version 1.2.0.1, Jun 30, 2017 * @since 2.1.0 */ @RequestProcessor public class UserAPI2 { /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(UserAPI2.class); /** * User query service. */ @Inject private UserQueryService userQueryService; /** * Avatar query service. */ @Inject private AvatarQueryService avatarQueryService; /** * Article query service. */ @Inject private ArticleQueryService articleQueryService; /** * Comment query service. */ @Inject private CommentQueryService commentQueryService; /** * Follow query service. */ @Inject private FollowQueryService followQueryService; /** * Gets a user's followers. * * @param context the specified context * @param request the specified request * @param userName the specified username */ @RequestProcessing(value = {"/api/v2/user/{userName}/followers"}, method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void getUserFollowers(final HTTPRequestContext context, final HttpServletRequest request, final String userName) { int page = 1; final String p = request.getParameter("p"); if (Strings.isNumeric(p)) { page = Integer.parseInt(p); } final JSONObject ret = new JSONObject(); context.renderJSONPretty(ret); ret.put(Keys.STATUS_CODE, StatusCodes.ERR); ret.put(Keys.MSG, ""); if (UserRegisterValidation.invalidUserName(userName)) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } JSONObject data = null; try { final JSONObject user = userQueryService.getUserByName(userName); if (null == user) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } final String followingId = user.optString(Keys.OBJECT_ID); final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); final JSONObject followersResult = followQueryService.getFollowerUsers(avatarViewMode, followingId, page, V2s.PAGE_SIZE); final List<JSONObject> followers = (List<JSONObject>) followersResult.opt(Keys.RESULTS); V2s.cleanUsers(followers); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); data = new JSONObject(); data.put(User.USERS, followers); final int followerUserCnt = followersResult.optInt(Pagination.PAGINATION_RECORD_COUNT); final int pageCount = (int) Math.ceil((double) followerUserCnt / (double) V2s.PAGE_SIZE); final JSONObject pagination = new JSONObject(); final List<Integer> pageNums = Paginator.paginate(page, V2s.PAGE_SIZE, pageCount, V2s.WINDOW_SIZE); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); data.put(Pagination.PAGINATION, pagination); final JSONObject currentUser = userQueryService.getCurrentUser(request); if (null != currentUser) { final String currentUserId = currentUser.optString(Keys.OBJECT_ID); final boolean isFollowing = followQueryService.isFollowing(currentUserId, followingId, Follow.FOLLOWING_TYPE_C_USER); data.put(Common.IS_FOLLOWING, isFollowing); } ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); } catch (final Exception e) { final String msg = "Gets a user's followers failed"; LOGGER.log(Level.ERROR, msg, e); ret.put(Keys.MSG, msg); } ret.put(Common.DATA, data); } /** * Gets a user's following articles. * * @param context the specified context * @param request the specified request * @param userName the specified username */ @RequestProcessing(value = {"/api/v2/user/{userName}/following/articles"}, method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void getUserFollowingArticles(final HTTPRequestContext context, final HttpServletRequest request, final String userName) { int page = 1; final String p = request.getParameter("p"); if (Strings.isNumeric(p)) { page = Integer.parseInt(p); } final JSONObject ret = new JSONObject(); context.renderJSONPretty(ret); ret.put(Keys.STATUS_CODE, StatusCodes.ERR); ret.put(Keys.MSG, ""); if (UserRegisterValidation.invalidUserName(userName)) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } JSONObject data = null; try { final JSONObject user = userQueryService.getUserByName(userName); if (null == user) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } final String followerId = user.optString(Keys.OBJECT_ID); final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); final JSONObject followingArticlesResult = followQueryService.getFollowingArticles(avatarViewMode, followerId, page, V2s.PAGE_SIZE); final List<JSONObject> articles = (List<JSONObject>) followingArticlesResult.opt(Keys.RESULTS); V2s.cleanArticles(articles); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); data = new JSONObject(); data.put(Article.ARTICLES, articles); final int followingArticleCnt = followingArticlesResult.optInt(Pagination.PAGINATION_RECORD_COUNT); final int pageCount = (int) Math.ceil(followingArticleCnt / (double) V2s.PAGE_SIZE); final JSONObject pagination = new JSONObject(); final List<Integer> pageNums = Paginator.paginate(page, V2s.PAGE_SIZE, pageCount, V2s.WINDOW_SIZE); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); data.put(Pagination.PAGINATION, pagination); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); } catch (final Exception e) { final String msg = "Gets a user's following articles failed"; LOGGER.log(Level.ERROR, msg, e); ret.put(Keys.MSG, msg); } ret.put(Common.DATA, data); } /** * Gets a user's following tags. * * @param context the specified context * @param request the specified request * @param userName the specified username */ @RequestProcessing(value = {"/api/v2/user/{userName}/following/tags"}, method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void getUserFollowingTags(final HTTPRequestContext context, final HttpServletRequest request, final String userName) { int page = 1; final String p = request.getParameter("p"); if (Strings.isNumeric(p)) { page = Integer.parseInt(p); } final JSONObject ret = new JSONObject(); context.renderJSONPretty(ret); ret.put(Keys.STATUS_CODE, StatusCodes.ERR); ret.put(Keys.MSG, ""); if (UserRegisterValidation.invalidUserName(userName)) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } JSONObject data = null; try { final JSONObject user = userQueryService.getUserByName(userName); if (null == user) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } final String followerId = user.optString(Keys.OBJECT_ID); final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); final JSONObject followingTagsResult = followQueryService.getFollowingTags( followerId, page, V2s.PAGE_SIZE); final List<JSONObject> tags = (List<JSONObject>) followingTagsResult.opt(Keys.RESULTS); V2s.cleanTags(tags); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); data = new JSONObject(); data.put(Tag.TAGS, tags); final int followingTagCnt = followingTagsResult.optInt(Pagination.PAGINATION_RECORD_COUNT); final int pageCount = (int) Math.ceil(followingTagCnt / (double) V2s.PAGE_SIZE); final JSONObject pagination = new JSONObject(); final List<Integer> pageNums = Paginator.paginate(page, V2s.PAGE_SIZE, pageCount, V2s.WINDOW_SIZE); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); data.put(Pagination.PAGINATION, pagination); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); } catch (final Exception e) { final String msg = "Gets a user's following tags failed"; LOGGER.log(Level.ERROR, msg, e); ret.put(Keys.MSG, msg); } ret.put(Common.DATA, data); } /** * Gets a user's following users. * * @param context the specified context * @param request the specified request * @param userName the specified username */ @RequestProcessing(value = {"/api/v2/user/{userName}/following/users"}, method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void getUserFollowingUsers(final HTTPRequestContext context, final HttpServletRequest request, final String userName) { int page = 1; final String p = request.getParameter("p"); if (Strings.isNumeric(p)) { page = Integer.parseInt(p); } final JSONObject ret = new JSONObject(); context.renderJSONPretty(ret); ret.put(Keys.STATUS_CODE, StatusCodes.ERR); ret.put(Keys.MSG, ""); if (UserRegisterValidation.invalidUserName(userName)) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } JSONObject data = null; try { final JSONObject user = userQueryService.getUserByName(userName); if (null == user) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } final String followerId = user.optString(Keys.OBJECT_ID); final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); final JSONObject followingUsersResult = followQueryService.getFollowingUsers(avatarViewMode, followerId, page, V2s.PAGE_SIZE); final List<JSONObject> users = (List<JSONObject>) followingUsersResult.opt(Keys.RESULTS); V2s.cleanUsers(users); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); data = new JSONObject(); data.put(User.USERS, users); final int followingUserCnt = followingUsersResult.optInt(Pagination.PAGINATION_RECORD_COUNT); final int pageCount = (int) Math.ceil((double) followingUserCnt / (double) V2s.PAGE_SIZE); final JSONObject pagination = new JSONObject(); final List<Integer> pageNums = Paginator.paginate(page, V2s.PAGE_SIZE, pageCount, V2s.WINDOW_SIZE); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); data.put(Pagination.PAGINATION, pagination); final JSONObject currentUser = userQueryService.getCurrentUser(request); if (null != currentUser) { final String currentUserId = currentUser.optString(Keys.OBJECT_ID); final boolean isFollowing = followQueryService.isFollowing(currentUserId, followerId, Follow.FOLLOWING_TYPE_C_USER); data.put(Common.IS_FOLLOWING, isFollowing); } ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); } catch (final Exception e) { final String msg = "Gets a user's following users failed"; LOGGER.log(Level.ERROR, msg, e); ret.put(Keys.MSG, msg); } ret.put(Common.DATA, data); } /** * Gets a user's watching articles. * * @param context the specified context * @param request the specified request * @param userName the specified username */ @RequestProcessing(value = {"/api/v2/user/{userName}/watching/articles"}, method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void getUserWatchingArticles(final HTTPRequestContext context, final HttpServletRequest request, final String userName) { int page = 1; final String p = request.getParameter("p"); if (Strings.isNumeric(p)) { page = Integer.parseInt(p); } final JSONObject ret = new JSONObject(); context.renderJSONPretty(ret); ret.put(Keys.STATUS_CODE, StatusCodes.ERR); ret.put(Keys.MSG, ""); if (UserRegisterValidation.invalidUserName(userName)) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } JSONObject data = null; try { final JSONObject user = userQueryService.getUserByName(userName); if (null == user) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } final String followerId = user.optString(Keys.OBJECT_ID); final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); final JSONObject watchingArticlesResult = followQueryService.getWatchingArticles(avatarViewMode, followerId, page, V2s.PAGE_SIZE); final List<JSONObject> articles = (List<JSONObject>) watchingArticlesResult.opt(Keys.RESULTS); V2s.cleanArticles(articles); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); data = new JSONObject(); data.put(Article.ARTICLES, articles); final int followingArticleCnt = watchingArticlesResult.optInt(Pagination.PAGINATION_RECORD_COUNT); final int pageCount = (int) Math.ceil(followingArticleCnt / (double) V2s.PAGE_SIZE); final JSONObject pagination = new JSONObject(); final List<Integer> pageNums = Paginator.paginate(page, V2s.PAGE_SIZE, pageCount, V2s.WINDOW_SIZE); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); data.put(Pagination.PAGINATION, pagination); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); } catch (final Exception e) { final String msg = "Gets a user's watching articles failed"; LOGGER.log(Level.ERROR, msg, e); ret.put(Keys.MSG, msg); } ret.put(Common.DATA, data); } /** * Gets a user's comments. * * @param context the specified context * @param request the specified request * @param userName the specified username */ @RequestProcessing(value = {"/api/v2/user/{userName}/comments"}, method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void getUserComments(final HTTPRequestContext context, final HttpServletRequest request, final String userName) { int page = 1; final String p = request.getParameter("p"); if (Strings.isNumeric(p)) { page = Integer.parseInt(p); } final JSONObject ret = new JSONObject(); context.renderJSONPretty(ret); ret.put(Keys.STATUS_CODE, StatusCodes.ERR); ret.put(Keys.MSG, ""); if (UserRegisterValidation.invalidUserName(userName)) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } JSONObject data = null; try { final JSONObject user = userQueryService.getUserByName(userName); if (null == user) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); final JSONObject currentUser = userQueryService.getCurrentUser(request); final List<JSONObject> comments = commentQueryService.getUserComments(avatarViewMode, user.optString(Keys.OBJECT_ID), Comment.COMMENT_ANONYMOUS_C_PUBLIC, page, V2s.PAGE_SIZE, currentUser); V2s.cleanComments(comments); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); data = new JSONObject(); data.put(Comment.COMMENTS, comments); final int commentCnt = user.optInt(UserExt.USER_COMMENT_COUNT); final int pageCount = (int) Math.ceil((double) commentCnt / (double) V2s.PAGE_SIZE); final JSONObject pagination = new JSONObject(); final List<Integer> pageNums = Paginator.paginate(page, V2s.PAGE_SIZE, pageCount, V2s.WINDOW_SIZE); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); data.put(Pagination.PAGINATION, pagination); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); } catch (final Exception e) { final String msg = "Gets a user's comments failed"; LOGGER.log(Level.ERROR, msg, e); ret.put(Keys.MSG, msg); } ret.put(Common.DATA, data); } /** * Gets a user's articles. * * @param context the specified context * @param request the specified request * @param userName the specified username */ @RequestProcessing(value = {"/api/v2/user/{userName}/articles"}, method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void getUserArticles(final HTTPRequestContext context, final HttpServletRequest request, final String userName) { int page = 1; final String p = request.getParameter("p"); if (Strings.isNumeric(p)) { page = Integer.parseInt(p); } final JSONObject ret = new JSONObject(); context.renderJSONPretty(ret); ret.put(Keys.STATUS_CODE, StatusCodes.ERR); ret.put(Keys.MSG, ""); if (UserRegisterValidation.invalidUserName(userName)) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } JSONObject data = null; try { final JSONObject user = userQueryService.getUserByName(userName); if (null == user) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); final List<JSONObject> articles = articleQueryService.getUserArticles(avatarViewMode, user.optString(Keys.OBJECT_ID), Article.ARTICLE_ANONYMOUS_C_PUBLIC, page, V2s.PAGE_SIZE); V2s.cleanArticles(articles); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); data = new JSONObject(); data.put(Article.ARTICLES, articles); final int articleCnt = user.optInt(UserExt.USER_ARTICLE_COUNT); final int pageCount = (int) Math.ceil((double) articleCnt / (double) V2s.PAGE_SIZE); final JSONObject pagination = new JSONObject(); final List<Integer> pageNums = Paginator.paginate(page, V2s.PAGE_SIZE, pageCount, V2s.WINDOW_SIZE); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); data.put(Pagination.PAGINATION, pagination); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); } catch (final Exception e) { final String msg = "Gets a user's articles failed"; LOGGER.log(Level.ERROR, msg, e); ret.put(Keys.MSG, msg); } ret.put(Common.DATA, data); } /** * Gets a user by the specified username. * * @param context the specified context * @param request the specified request * @param userName the specified username */ @RequestProcessing(value = {"/api/v2/user/{userName}"}, method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void getUser(final HTTPRequestContext context, final HttpServletRequest request, final String userName) { final JSONObject ret = new JSONObject(); context.renderJSONPretty(ret); ret.put(Keys.STATUS_CODE, StatusCodes.ERR); ret.put(Keys.MSG, ""); if (UserRegisterValidation.invalidUserName(userName)) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } JSONObject data = null; try { final JSONObject user = userQueryService.getUserByName(userName); if (null == user) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); avatarQueryService.fillUserAvatarURL(avatarViewMode, user); data = new JSONObject(); data.put(User.USER, user); V2s.cleanUser(user); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); } catch (final Exception e) { final String msg = "Gets a user failed"; LOGGER.log(Level.ERROR, msg, e); ret.put(Keys.MSG, msg); } ret.put(Common.DATA, data); } }
src/main/java/org/b3log/symphony/api/v2/UserAPI2.java
/* * Symphony - A modern community (forum/SNS/blog) platform written in Java. * Copyright (C) 2012-2017, b3log.org & hacpai.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.b3log.symphony.api.v2; import org.b3log.latke.Keys; import org.b3log.latke.ioc.inject.Inject; import org.b3log.latke.logging.Level; import org.b3log.latke.logging.Logger; import org.b3log.latke.model.Pagination; import org.b3log.latke.model.User; import org.b3log.latke.servlet.HTTPRequestContext; import org.b3log.latke.servlet.HTTPRequestMethod; import org.b3log.latke.servlet.annotation.After; import org.b3log.latke.servlet.annotation.Before; import org.b3log.latke.servlet.annotation.RequestProcessing; import org.b3log.latke.servlet.annotation.RequestProcessor; import org.b3log.latke.util.Paginator; import org.b3log.latke.util.Strings; import org.b3log.symphony.model.*; import org.b3log.symphony.processor.advice.AnonymousViewCheck; import org.b3log.symphony.processor.advice.PermissionGrant; import org.b3log.symphony.processor.advice.stopwatch.StopwatchEndAdvice; import org.b3log.symphony.processor.advice.stopwatch.StopwatchStartAdvice; import org.b3log.symphony.processor.advice.validate.UserRegisterValidation; import org.b3log.symphony.service.*; import org.b3log.symphony.util.StatusCodes; import org.json.JSONObject; import javax.servlet.http.HttpServletRequest; import java.util.List; /** * User API v2. * <p> * <ul> * <li>Gets a user (/api/v2/user/{userName}), GET</li> * <li>Gets a user's articles (/api/v2/user/{userName}/articles), GET</li> * <li>Gets a user's comments (/api/v2/user/{userName}/comments), GET</li> * <li>Gets a user's watching articles (/api/v2/user/{userName}/watching/articles), GET</li> * <li>Gets a user's following users (/api/v2/user/{userName}/following/users), GET</li> * <li>Gets a user's following tags (/api/v2/user/{userName}/following/tags), GET</li> * <li>Gets a user's following articles (/api/v2/user/{userName}/following/articles), GET</li> * <li>Gets a user's followers (/api/v2/user/{userName}/followers), GET</li> * </ul> * </p> * * @author <a href="http://88250.b3log.org">Liang Ding</a> * @version 1.2.0.1, Jun 30, 2017 * @since 2.1.0 */ @RequestProcessor public class UserAPI2 { /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(UserAPI2.class); /** * User query service. */ @Inject private UserQueryService userQueryService; /** * Avatar query service. */ @Inject private AvatarQueryService avatarQueryService; /** * Article query service. */ @Inject private ArticleQueryService articleQueryService; /** * Comment query service. */ @Inject private CommentQueryService commentQueryService; /** * Follow query service. */ @Inject private FollowQueryService followQueryService; /** * Gets a user's followers. * * @param context the specified context * @param request the specified request * @param userName the specified username */ @RequestProcessing(value = {"/api/v2/user/{userName}/followers"}, method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void getUserFollowers(final HTTPRequestContext context, final HttpServletRequest request, final String userName) { int page = 1; final String p = request.getParameter("p"); if (Strings.isNumeric(p)) { page = Integer.parseInt(p); } final JSONObject ret = new JSONObject(); context.renderJSONPretty(ret); ret.put(Keys.STATUS_CODE, StatusCodes.ERR); ret.put(Keys.MSG, ""); if (UserRegisterValidation.invalidUserName(userName)) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } JSONObject data = null; try { final JSONObject user = userQueryService.getUserByName(userName); if (null == user) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } final String followingId = user.optString(Keys.OBJECT_ID); final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); final JSONObject followersResult = followQueryService.getFollowerUsers(avatarViewMode, followingId, page, V2s.PAGE_SIZE); final List<JSONObject> followers = (List<JSONObject>) followersResult.opt(Keys.RESULTS); V2s.cleanUsers(followers); data = new JSONObject(); data.put(User.USERS, followers); final JSONObject currentUser = userQueryService.getCurrentUser(request); if (null != currentUser) { final String followerId = currentUser.optString(Keys.OBJECT_ID); final boolean isFollowing = followQueryService.isFollowing(followerId, followingId, Follow.FOLLOWING_TYPE_C_USER); data.put(Common.IS_FOLLOWING, isFollowing); } ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); final int followerUserCnt = followersResult.optInt(Pagination.PAGINATION_RECORD_COUNT); final int pageCount = (int) Math.ceil((double) followerUserCnt / (double) V2s.PAGE_SIZE); final JSONObject pagination = new JSONObject(); final List<Integer> pageNums = Paginator.paginate(page, V2s.PAGE_SIZE, pageCount, V2s.WINDOW_SIZE); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); data.put(Pagination.PAGINATION, pagination); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); } catch (final Exception e) { final String msg = "Gets a user's followers failed"; LOGGER.log(Level.ERROR, msg, e); ret.put(Keys.MSG, msg); } ret.put(Common.DATA, data); } /** * Gets a user's following articles. * * @param context the specified context * @param request the specified request * @param userName the specified username */ @RequestProcessing(value = {"/api/v2/user/{userName}/following/articles"}, method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void getUserFollowingArticles(final HTTPRequestContext context, final HttpServletRequest request, final String userName) { int page = 1; final String p = request.getParameter("p"); if (Strings.isNumeric(p)) { page = Integer.parseInt(p); } final JSONObject ret = new JSONObject(); context.renderJSONPretty(ret); ret.put(Keys.STATUS_CODE, StatusCodes.ERR); ret.put(Keys.MSG, ""); if (UserRegisterValidation.invalidUserName(userName)) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } JSONObject data = null; try { final JSONObject user = userQueryService.getUserByName(userName); if (null == user) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } final String followerId = user.optString(Keys.OBJECT_ID); final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); final JSONObject followingArticlesResult = followQueryService.getFollowingArticles(avatarViewMode, followerId, page, V2s.PAGE_SIZE); final List<JSONObject> articles = (List<JSONObject>) followingArticlesResult.opt(Keys.RESULTS); V2s.cleanArticles(articles); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); data = new JSONObject(); data.put(Article.ARTICLES, articles); final int followingArticleCnt = followingArticlesResult.optInt(Pagination.PAGINATION_RECORD_COUNT); final int pageCount = (int) Math.ceil(followingArticleCnt / (double) V2s.PAGE_SIZE); final JSONObject pagination = new JSONObject(); final List<Integer> pageNums = Paginator.paginate(page, V2s.PAGE_SIZE, pageCount, V2s.WINDOW_SIZE); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); data.put(Pagination.PAGINATION, pagination); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); } catch (final Exception e) { final String msg = "Gets a user's following articles failed"; LOGGER.log(Level.ERROR, msg, e); ret.put(Keys.MSG, msg); } ret.put(Common.DATA, data); } /** * Gets a user's following tags. * * @param context the specified context * @param request the specified request * @param userName the specified username */ @RequestProcessing(value = {"/api/v2/user/{userName}/following/tags"}, method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void getUserFollowingTags(final HTTPRequestContext context, final HttpServletRequest request, final String userName) { int page = 1; final String p = request.getParameter("p"); if (Strings.isNumeric(p)) { page = Integer.parseInt(p); } final JSONObject ret = new JSONObject(); context.renderJSONPretty(ret); ret.put(Keys.STATUS_CODE, StatusCodes.ERR); ret.put(Keys.MSG, ""); if (UserRegisterValidation.invalidUserName(userName)) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } JSONObject data = null; try { final JSONObject user = userQueryService.getUserByName(userName); if (null == user) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } final String followerId = user.optString(Keys.OBJECT_ID); final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); final JSONObject followingTagsResult = followQueryService.getFollowingTags( followerId, page, V2s.PAGE_SIZE); final List<JSONObject> tags = (List<JSONObject>) followingTagsResult.opt(Keys.RESULTS); V2s.cleanTags(tags); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); data = new JSONObject(); data.put(Tag.TAGS, tags); final int followingTagCnt = followingTagsResult.optInt(Pagination.PAGINATION_RECORD_COUNT); final int pageCount = (int) Math.ceil(followingTagCnt / (double) V2s.PAGE_SIZE); final JSONObject pagination = new JSONObject(); final List<Integer> pageNums = Paginator.paginate(page, V2s.PAGE_SIZE, pageCount, V2s.WINDOW_SIZE); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); data.put(Pagination.PAGINATION, pagination); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); } catch (final Exception e) { final String msg = "Gets a user's following tags failed"; LOGGER.log(Level.ERROR, msg, e); ret.put(Keys.MSG, msg); } ret.put(Common.DATA, data); } /** * Gets a user's following users. * * @param context the specified context * @param request the specified request * @param userName the specified username */ @RequestProcessing(value = {"/api/v2/user/{userName}/following/users"}, method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void getUserFollowingUsers(final HTTPRequestContext context, final HttpServletRequest request, final String userName) { int page = 1; final String p = request.getParameter("p"); if (Strings.isNumeric(p)) { page = Integer.parseInt(p); } final JSONObject ret = new JSONObject(); context.renderJSONPretty(ret); ret.put(Keys.STATUS_CODE, StatusCodes.ERR); ret.put(Keys.MSG, ""); if (UserRegisterValidation.invalidUserName(userName)) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } JSONObject data = null; try { final JSONObject user = userQueryService.getUserByName(userName); if (null == user) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } final String followerId = user.optString(Keys.OBJECT_ID); final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); final JSONObject followingUsersResult = followQueryService.getFollowingUsers(avatarViewMode, followerId, page, V2s.PAGE_SIZE); final List<JSONObject> users = (List<JSONObject>) followingUsersResult.opt(Keys.RESULTS); V2s.cleanUsers(users); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); data = new JSONObject(); data.put(User.USERS, users); final int followingUserCnt = followingUsersResult.optInt(Pagination.PAGINATION_RECORD_COUNT); final int pageCount = (int) Math.ceil((double) followingUserCnt / (double) V2s.PAGE_SIZE); final JSONObject pagination = new JSONObject(); final List<Integer> pageNums = Paginator.paginate(page, V2s.PAGE_SIZE, pageCount, V2s.WINDOW_SIZE); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); data.put(Pagination.PAGINATION, pagination); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); } catch (final Exception e) { final String msg = "Gets a user's following users failed"; LOGGER.log(Level.ERROR, msg, e); ret.put(Keys.MSG, msg); } ret.put(Common.DATA, data); } /** * Gets a user's watching articles. * * @param context the specified context * @param request the specified request * @param userName the specified username */ @RequestProcessing(value = {"/api/v2/user/{userName}/watching/articles"}, method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void getUserWatchingArticles(final HTTPRequestContext context, final HttpServletRequest request, final String userName) { int page = 1; final String p = request.getParameter("p"); if (Strings.isNumeric(p)) { page = Integer.parseInt(p); } final JSONObject ret = new JSONObject(); context.renderJSONPretty(ret); ret.put(Keys.STATUS_CODE, StatusCodes.ERR); ret.put(Keys.MSG, ""); if (UserRegisterValidation.invalidUserName(userName)) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } JSONObject data = null; try { final JSONObject user = userQueryService.getUserByName(userName); if (null == user) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } final String followerId = user.optString(Keys.OBJECT_ID); final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); final JSONObject watchingArticlesResult = followQueryService.getWatchingArticles(avatarViewMode, followerId, page, V2s.PAGE_SIZE); final List<JSONObject> articles = (List<JSONObject>) watchingArticlesResult.opt(Keys.RESULTS); V2s.cleanArticles(articles); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); data = new JSONObject(); data.put(Article.ARTICLES, articles); final int followingArticleCnt = watchingArticlesResult.optInt(Pagination.PAGINATION_RECORD_COUNT); final int pageCount = (int) Math.ceil(followingArticleCnt / (double) V2s.PAGE_SIZE); final JSONObject pagination = new JSONObject(); final List<Integer> pageNums = Paginator.paginate(page, V2s.PAGE_SIZE, pageCount, V2s.WINDOW_SIZE); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); data.put(Pagination.PAGINATION, pagination); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); } catch (final Exception e) { final String msg = "Gets a user's watching articles failed"; LOGGER.log(Level.ERROR, msg, e); ret.put(Keys.MSG, msg); } ret.put(Common.DATA, data); } /** * Gets a user's comments. * * @param context the specified context * @param request the specified request * @param userName the specified username */ @RequestProcessing(value = {"/api/v2/user/{userName}/comments"}, method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void getUserComments(final HTTPRequestContext context, final HttpServletRequest request, final String userName) { int page = 1; final String p = request.getParameter("p"); if (Strings.isNumeric(p)) { page = Integer.parseInt(p); } final JSONObject ret = new JSONObject(); context.renderJSONPretty(ret); ret.put(Keys.STATUS_CODE, StatusCodes.ERR); ret.put(Keys.MSG, ""); if (UserRegisterValidation.invalidUserName(userName)) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } JSONObject data = null; try { final JSONObject user = userQueryService.getUserByName(userName); if (null == user) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); final JSONObject currentUser = userQueryService.getCurrentUser(request); final List<JSONObject> comments = commentQueryService.getUserComments(avatarViewMode, user.optString(Keys.OBJECT_ID), Comment.COMMENT_ANONYMOUS_C_PUBLIC, page, V2s.PAGE_SIZE, currentUser); V2s.cleanComments(comments); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); data = new JSONObject(); data.put(Comment.COMMENTS, comments); final int commentCnt = user.optInt(UserExt.USER_COMMENT_COUNT); final int pageCount = (int) Math.ceil((double) commentCnt / (double) V2s.PAGE_SIZE); final JSONObject pagination = new JSONObject(); final List<Integer> pageNums = Paginator.paginate(page, V2s.PAGE_SIZE, pageCount, V2s.WINDOW_SIZE); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); data.put(Pagination.PAGINATION, pagination); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); } catch (final Exception e) { final String msg = "Gets a user's comments failed"; LOGGER.log(Level.ERROR, msg, e); ret.put(Keys.MSG, msg); } ret.put(Common.DATA, data); } /** * Gets a user's articles. * * @param context the specified context * @param request the specified request * @param userName the specified username */ @RequestProcessing(value = {"/api/v2/user/{userName}/articles"}, method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void getUserArticles(final HTTPRequestContext context, final HttpServletRequest request, final String userName) { int page = 1; final String p = request.getParameter("p"); if (Strings.isNumeric(p)) { page = Integer.parseInt(p); } final JSONObject ret = new JSONObject(); context.renderJSONPretty(ret); ret.put(Keys.STATUS_CODE, StatusCodes.ERR); ret.put(Keys.MSG, ""); if (UserRegisterValidation.invalidUserName(userName)) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } JSONObject data = null; try { final JSONObject user = userQueryService.getUserByName(userName); if (null == user) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); final List<JSONObject> articles = articleQueryService.getUserArticles(avatarViewMode, user.optString(Keys.OBJECT_ID), Article.ARTICLE_ANONYMOUS_C_PUBLIC, page, V2s.PAGE_SIZE); V2s.cleanArticles(articles); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); data = new JSONObject(); data.put(Article.ARTICLES, articles); final int articleCnt = user.optInt(UserExt.USER_ARTICLE_COUNT); final int pageCount = (int) Math.ceil((double) articleCnt / (double) V2s.PAGE_SIZE); final JSONObject pagination = new JSONObject(); final List<Integer> pageNums = Paginator.paginate(page, V2s.PAGE_SIZE, pageCount, V2s.WINDOW_SIZE); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); data.put(Pagination.PAGINATION, pagination); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); } catch (final Exception e) { final String msg = "Gets a user's articles failed"; LOGGER.log(Level.ERROR, msg, e); ret.put(Keys.MSG, msg); } ret.put(Common.DATA, data); } /** * Gets a user by the specified username. * * @param context the specified context * @param request the specified request * @param userName the specified username */ @RequestProcessing(value = {"/api/v2/user/{userName}"}, method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void getUser(final HTTPRequestContext context, final HttpServletRequest request, final String userName) { final JSONObject ret = new JSONObject(); context.renderJSONPretty(ret); ret.put(Keys.STATUS_CODE, StatusCodes.ERR); ret.put(Keys.MSG, ""); if (UserRegisterValidation.invalidUserName(userName)) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } JSONObject data = null; try { final JSONObject user = userQueryService.getUserByName(userName); if (null == user) { ret.put(Keys.MSG, "User not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); avatarQueryService.fillUserAvatarURL(avatarViewMode, user); data = new JSONObject(); data.put(User.USER, user); V2s.cleanUser(user); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); } catch (final Exception e) { final String msg = "Gets a user failed"; LOGGER.log(Level.ERROR, msg, e); ret.put(Keys.MSG, msg); } ret.put(Common.DATA, data); } }
关注者列表 API
src/main/java/org/b3log/symphony/api/v2/UserAPI2.java
关注者列表 API
Java
apache-2.0
8f743b7088cef0bd92f00b40c1637e1c5e3ea998
0
achikin/testrail-jenkins-plugin,matthewcmorgan/testrail-jenkins-plugin,matthewcmorgan/testrail-jenkins-plugin,syl20bnr/testrail-jenkins-plugin,achikin/testrail-jenkins-plugin
package testrail.testrail; import hudson.Extension; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.tasks.*; import hudson.util.FormValidation; import net.sf.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import testrail.testrail.JunitResults.Failure; import testrail.testrail.JunitResults.JUnitResults; import testrail.testrail.JunitResults.Testcase; import testrail.testrail.JunitResults.Testsuite; import testrail.testrail.TestRailObjects.ElementNotFoundException; import testrail.testrail.TestRailObjects.ExistingTestCases; import testrail.testrail.TestRailObjects.Result; import testrail.testrail.TestRailObjects.Results; import javax.servlet.ServletException; import javax.xml.bind.JAXBException; import java.io.IOException; import java.util.Iterator; import java.util.List; /** * Sample {@link Builder}. * * <p> * When the user configures the project and enables this builder, * {@link DescriptorImpl#newInstance(StaplerRequest)} is invoked * and a new {@link TestRailNotifier} is created. The created * instance is persisted to the project configuration XML by using * XStream, so this allows you to use instance fields (like {@link #testrailSuite}) * to remember the configuration. * * <p> * When a build is performed, the {@link #perform(AbstractBuild, Launcher, BuildListener)} * method will be invoked. * * @author Kohsuke Kawaguchi */ public class TestRailNotifier extends Notifier { private final String testrailProject; private final String testrailSuite; private final String junitResults; // Fields in config.jelly must match the parameter names in the "DataBoundConstructor" @DataBoundConstructor public TestRailNotifier(String testrailProject, String testrailSuite, String junitResults) { this.testrailProject = testrailProject; this.testrailSuite = testrailSuite; this.junitResults = junitResults; } /** * We'll use this from the <tt>config.jelly</tt>. */ public String getTestrailProject() { return this.testrailProject; } public String getTestrailSuite() { return this.testrailSuite; } public String getJunitResults() { return this.junitResults; } @Override public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException { TestRailClient testrail = new TestRailClient( getDescriptor().getTestrailHost(), getDescriptor().getTestrailUser(), getDescriptor().getTestrailPassword()); ExistingTestCases testCases = null; try { testCases = new ExistingTestCases(testrail, this.testrailProject, this.testrailSuite); } catch (ElementNotFoundException e) { listener.getLogger().println("Cannot find project on TestRail server. Please check your Jenkins job and system configurations."); return false; } String[] caseNames = null; try { caseNames = testCases.listTestCases(); } catch (ElementNotFoundException e) { listener.getLogger().println("Failed to list test cases"); listener.getLogger().println("Element not found:" + e.getMessage()); } listener.getLogger().println("Munging test result files."); Results results = new Results(); String base = String.valueOf(build.getProject().getRootDir() + "/workspace"); //build.getWorkspace()); listener.getLogger().println("base dir: " + base); String [] includesDirs = { this.junitResults }; JUnitResults junitResults = null; try { junitResults = new JUnitResults(base, includesDirs); } catch (JAXBException e) { listener.getLogger().println(e.getMessage()); } List<Testsuite> suites = junitResults.getSuites(); Iterator<Testsuite> testsuiteIterator = suites.iterator(); while (testsuiteIterator.hasNext()) { Testsuite suite = testsuiteIterator.next(); String junitSuiteName = suite.getName(); List<Testcase> cases = suite.getCases(); if (cases == null || cases.isEmpty()) { continue; } Iterator<Testcase> iterator = cases.iterator(); while (iterator.hasNext()) { Testcase junitCase = iterator.next(); String junitCaseName = junitCase.getName(); int testrailCaseId; try { testrailCaseId = testCases.getCaseId(junitSuiteName, junitCaseName); } catch (ElementNotFoundException e) { int sectionId; try { sectionId = testCases.getSectionId(junitSuiteName); } catch (ElementNotFoundException e2) { try { sectionId = testCases.addSection(junitSuiteName); } catch (ElementNotFoundException e3) { listener.getLogger().println("Unable to add test section " + junitSuiteName); listener.getLogger().println(e.getMessage()); return false; } } testrailCaseId = testCases.addCase(junitCaseName, sectionId); } int testrailCaseStatus; String testrailCaseComment = null; Failure testrailCaseFailure = junitCase.getFailure(); if (testrailCaseFailure != null) { testrailCaseStatus = 5; // Failed testrailCaseComment = testrailCaseFailure.getText(); } else { testrailCaseStatus = 1; // Passed } results.addResult(new Result(testrailCaseId, testrailCaseStatus, testrailCaseComment)); } } listener.getLogger().println("Uploading results to TestRail."); String runComment = "Automated results from Jenkins: " + BuildWrapper.all().jenkins.getRootUrl() + "/" + build.getUrl().toString(); int runId = testrail.addRun(testCases.getProjectId(), testCases.getSuiteId(), runComment); TestRailResponse response = testrail.addResultsForCases(runId, results); boolean buildResult = (200 == response.getStatus()); if (buildResult) { listener.getLogger().println("Successfully uploaded test reaults."); } else { listener.getLogger().println("Failed to add results to TestRail."); listener.getLogger().println("status: " + response.getStatus()); listener.getLogger().println("body :\n" + response.getBody()); } testrail.closeRun(runId); return buildResult; } // Overridden for better type safety. // If your plugin doesn't really define any property on Descriptor, // you don't have to do this. @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl)super.getDescriptor(); } public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; //null; } /** * Descriptor for {@link TestRailNotifier}. Used as a singleton. * The class is marked as public so that it can be accessed from views. * * <p> * See <tt>src/main/resources/hudson/plugins/hello_world/TestRailRecorder/*.jelly</tt> * for the actual HTML fragment for the configuration screen. */ @Extension // This indicates to Jenkins that this is an implementation of an extension point. public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> { /** * To persist global configuration information, * simply store it in a field and call save(). * * <p> * If you don't want fields to be persisted, use <tt>transient</tt>. */ private String testrailHost; private String testrailUser; private String testrailPassword; /** * In order to load the persisted global configuration, you have to * call load() in the constructor. */ public DescriptorImpl() { load(); } /** * Performs on-the-fly validation of the form field 'name'. * * @param value * This parameter receives the value that the user has typed. * @return * Indicates the outcome of the validation. This is sent to the browser. */ public FormValidation doCheckTestrailProject(@QueryParameter String value) throws IOException, ServletException { if (value.length() == 0) { return FormValidation.error("Please set a project name."); } TestRailClient testrail = new TestRailClient(getTestrailHost(), getTestrailUser(), getTestrailPassword()); if (!testrail.serverReachable() || !testrail.authenticationWorks()) { return FormValidation.warning("Please fix your TestRail configuration in Manage Jenkins -> Configure System."); } try { int projectId = testrail.getProjectId(value); } catch (ElementNotFoundException e) { return FormValidation.error("Project " + value + " not found on TestRail server."); } return FormValidation.ok(); } public FormValidation doCheckTestrailSuite(@QueryParameter String value, @QueryParameter String testrailProject) throws IOException, ServletException { if (value.length() == 0) { return FormValidation.error("Please set a suite name."); } TestRailClient testrail = new TestRailClient(getTestrailHost(), getTestrailUser(), getTestrailPassword()); if (!testrail.serverReachable() || !testrail.authenticationWorks()) { return FormValidation.warning("Please fix your TestRail configuration in Manage Jenkins -> Configure System."); } else { int projectId; try { projectId = testrail.getProjectId(testrailProject); } catch (ElementNotFoundException e) { return FormValidation.error("Project " + testrailProject + " not found on TestRail server."); } try { int suiteId = testrail.getSuiteId(projectId, value); } catch (ElementNotFoundException e) { return FormValidation.error("Suite " + value + " not found on TestRail server."); } } return FormValidation.ok(); } public FormValidation doCheckJunitResults(@QueryParameter String value) throws IOException, ServletException { if (value.length() == 0) return FormValidation.warning("Please select test result path."); // TODO: Should we check to see if the files exist? Probably not. return FormValidation.ok(); } public FormValidation doCheckTestrailHost(@QueryParameter String value) throws IOException, ServletException { if (value.length() == 0) { return FormValidation.warning("Please add your TestRail host URI."); } // TODO: There is probably a better way to do URL validation. if (!value.startsWith("http://") && !value.startsWith("https://")) { return FormValidation.error("Host must be a valid URL."); } TestRailClient testrail = new TestRailClient(value, "", ""); if (!testrail.serverReachable()) { return FormValidation.error("Host is not reachable."); } return FormValidation.ok(); } public FormValidation doCheckTestrailUser(@QueryParameter String value, @QueryParameter String testrailHost, @QueryParameter String testrailPassword) throws IOException, ServletException { if (value.length() == 0) { return FormValidation.warning("Please add your user's email address."); } if (testrailPassword.length() > 0) { TestRailClient testrail = new TestRailClient(testrailHost, value, testrailPassword); if (testrail.serverReachable() && !testrail.authenticationWorks()){ return FormValidation.error("Invalid user/password combination."); } } return FormValidation.ok(); } public FormValidation doCheckTestrailPassword(@QueryParameter String value, @QueryParameter String testrailHost, @QueryParameter String testrailUser) throws IOException, ServletException { if (value.length() == 0) { return FormValidation.warning("Please add your password."); } if (testrailUser.length() > 0) { TestRailClient testrail = new TestRailClient(testrailHost, testrailUser, value); if (testrail.serverReachable() && !testrail.authenticationWorks()){ return FormValidation.error("Invalid user/password combination."); } } return FormValidation.ok(); } public boolean isApplicable(Class<? extends AbstractProject> aClass) { // Indicates that this builder can be used with all kinds of project types return true; } /** * This human readable name is used in the configuration screen. */ public String getDisplayName() { return "Publish test results to TestRail"; } @Override public boolean configure(StaplerRequest req, JSONObject formData) throws FormException { // To persist global configuration information, // set that to properties and call save(). testrailHost = formData.getString("testrailHost"); testrailUser = formData.getString("testrailUser"); testrailPassword = formData.getString("testrailPassword"); // ^Can also use req.bindJSON(this, formData); // (easier when there are many fields; need set* methods for this, like setTestrailHost) save(); return super.configure(req,formData); } /** * This method returns true if the global configuration says we should speak French. * * The method name is bit awkward because global.jelly calls this method to determine * the initial state of the checkbox by the naming convention. */ public String getTestrailHost() { return testrailHost; } public String getTestrailUser() { return testrailUser; } public String getTestrailPassword() { return testrailPassword; } } }
src/main/java/testrail/testrail/TestRailNotifier.java
package testrail.testrail; import hudson.Extension; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.tasks.*; import hudson.util.FormValidation; import net.sf.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import testrail.testrail.JunitResults.Failure; import testrail.testrail.JunitResults.JUnitResults; import testrail.testrail.JunitResults.Testcase; import testrail.testrail.JunitResults.Testsuite; import testrail.testrail.TestRailObjects.ElementNotFoundException; import testrail.testrail.TestRailObjects.ExistingTestCases; import testrail.testrail.TestRailObjects.Result; import testrail.testrail.TestRailObjects.Results; import javax.servlet.ServletException; import javax.xml.bind.JAXBException; import java.io.IOException; import java.util.Iterator; import java.util.List; /** * Sample {@link Builder}. * * <p> * When the user configures the project and enables this builder, * {@link DescriptorImpl#newInstance(StaplerRequest)} is invoked * and a new {@link TestRailNotifier} is created. The created * instance is persisted to the project configuration XML by using * XStream, so this allows you to use instance fields (like {@link #testrailSuite}) * to remember the configuration. * * <p> * When a build is performed, the {@link #perform(AbstractBuild, Launcher, BuildListener)} * method will be invoked. * * @author Kohsuke Kawaguchi */ public class TestRailNotifier extends Notifier { private final String testrailProject; private final String testrailSuite; private final String junitResults; // Fields in config.jelly must match the parameter names in the "DataBoundConstructor" @DataBoundConstructor public TestRailNotifier(String testrailProject, String testrailSuite, String junitResults) { this.testrailProject = testrailProject; this.testrailSuite = testrailSuite; this.junitResults = junitResults; } /** * We'll use this from the <tt>config.jelly</tt>. */ public String getTestrailProject() { return this.testrailProject; } public String getTestrailSuite() { return this.testrailSuite; } public String getJunitResults() { return this.junitResults; } @Override public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException { TestRailClient testrail = new TestRailClient( getDescriptor().getTestrailHost(), getDescriptor().getTestrailUser(), getDescriptor().getTestrailPassword()); ExistingTestCases testCases = null; try { testCases = new ExistingTestCases(testrail, this.testrailProject, this.testrailSuite); } catch (ElementNotFoundException e) { listener.getLogger().println("Cannot find project on TestRail server. Please check your Jenkins job and system configurations."); return false; } String[] caseNames = null; try { caseNames = testCases.listTestCases(); } catch (ElementNotFoundException e) { listener.getLogger().println("Failed to list test cases"); listener.getLogger().println("Element not found:" + e.getMessage()); } listener.getLogger().println("Munging test result files."); Results results = new Results(); String base = String.valueOf(build.getWorkspace()); String [] includesDirs = { this.junitResults }; JUnitResults junitResults = null; try { junitResults = new JUnitResults(base, includesDirs); } catch (JAXBException e) { listener.getLogger().println(e.getMessage()); } List<Testsuite> suites = junitResults.getSuites(); Iterator<Testsuite> testsuiteIterator = suites.iterator(); while (testsuiteIterator.hasNext()) { Testsuite suite = testsuiteIterator.next(); String junitSuiteName = suite.getName(); List<Testcase> cases = suite.getCases(); if (cases == null || cases.isEmpty()) { continue; } Iterator<Testcase> iterator = cases.iterator(); while (iterator.hasNext()) { Testcase junitCase = iterator.next(); String junitCaseName = junitCase.getName(); int testrailCaseId; try { testrailCaseId = testCases.getCaseId(junitSuiteName, junitCaseName); } catch (ElementNotFoundException e) { int sectionId; try { sectionId = testCases.getSectionId(junitSuiteName); } catch (ElementNotFoundException e2) { try { sectionId = testCases.addSection(junitSuiteName); } catch (ElementNotFoundException e3) { listener.getLogger().println("Unable to add test section " + junitSuiteName); listener.getLogger().println(e.getMessage()); return false; } } testrailCaseId = testCases.addCase(junitCaseName, sectionId); } int testrailCaseStatus; String testrailCaseComment = null; Failure testrailCaseFailure = junitCase.getFailure(); if (testrailCaseFailure != null) { testrailCaseStatus = 5; // Failed testrailCaseComment = testrailCaseFailure.getText(); } else { testrailCaseStatus = 1; // Passed } results.addResult(new Result(testrailCaseId, testrailCaseStatus, testrailCaseComment)); } } listener.getLogger().println("Uploading results to TestRail."); String runComment = "Automated results from Jenkins: " + BuildWrapper.all().jenkins.getRootUrl() + "/" + build.getUrl().toString(); int runId = testrail.addRun(testCases.getProjectId(), testCases.getSuiteId(), runComment); TestRailResponse response = testrail.addResultsForCases(runId, results); boolean buildResult = (200 == response.getStatus()); if (buildResult) { listener.getLogger().println("Successfully uploaded test reaults."); } else { listener.getLogger().println("Failed to add results to TestRail."); listener.getLogger().println("status: " + response.getStatus()); listener.getLogger().println("body :\n" + response.getBody()); } testrail.closeRun(runId); return buildResult; } // Overridden for better type safety. // If your plugin doesn't really define any property on Descriptor, // you don't have to do this. @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl)super.getDescriptor(); } public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; //null; } /** * Descriptor for {@link TestRailNotifier}. Used as a singleton. * The class is marked as public so that it can be accessed from views. * * <p> * See <tt>src/main/resources/hudson/plugins/hello_world/TestRailRecorder/*.jelly</tt> * for the actual HTML fragment for the configuration screen. */ @Extension // This indicates to Jenkins that this is an implementation of an extension point. public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> { /** * To persist global configuration information, * simply store it in a field and call save(). * * <p> * If you don't want fields to be persisted, use <tt>transient</tt>. */ private String testrailHost; private String testrailUser; private String testrailPassword; /** * In order to load the persisted global configuration, you have to * call load() in the constructor. */ public DescriptorImpl() { load(); } /** * Performs on-the-fly validation of the form field 'name'. * * @param value * This parameter receives the value that the user has typed. * @return * Indicates the outcome of the validation. This is sent to the browser. */ public FormValidation doCheckTestrailProject(@QueryParameter String value) throws IOException, ServletException { if (value.length() == 0) { return FormValidation.error("Please set a project name."); } TestRailClient testrail = new TestRailClient(getTestrailHost(), getTestrailUser(), getTestrailPassword()); if (!testrail.serverReachable() || !testrail.authenticationWorks()) { return FormValidation.warning("Please fix your TestRail configuration in Manage Jenkins -> Configure System."); } try { int projectId = testrail.getProjectId(value); } catch (ElementNotFoundException e) { return FormValidation.error("Project " + value + " not found on TestRail server."); } return FormValidation.ok(); } public FormValidation doCheckTestrailSuite(@QueryParameter String value, @QueryParameter String testrailProject) throws IOException, ServletException { if (value.length() == 0) { return FormValidation.error("Please set a suite name."); } TestRailClient testrail = new TestRailClient(getTestrailHost(), getTestrailUser(), getTestrailPassword()); if (!testrail.serverReachable() || !testrail.authenticationWorks()) { return FormValidation.warning("Please fix your TestRail configuration in Manage Jenkins -> Configure System."); } else { int projectId; try { projectId = testrail.getProjectId(testrailProject); } catch (ElementNotFoundException e) { return FormValidation.error("Project " + testrailProject + " not found on TestRail server."); } try { int suiteId = testrail.getSuiteId(projectId, value); } catch (ElementNotFoundException e) { return FormValidation.error("Suite " + value + " not found on TestRail server."); } } return FormValidation.ok(); } public FormValidation doCheckJunitResults(@QueryParameter String value) throws IOException, ServletException { if (value.length() == 0) return FormValidation.warning("Please select test result path."); // TODO: Should we check to see if the files exist? Probably not. return FormValidation.ok(); } public FormValidation doCheckTestrailHost(@QueryParameter String value) throws IOException, ServletException { if (value.length() == 0) { return FormValidation.warning("Please add your TestRail host URI."); } // TODO: There is probably a better way to do URL validation. if (!value.startsWith("http://") && !value.startsWith("https://")) { return FormValidation.error("Host must be a valid URL."); } TestRailClient testrail = new TestRailClient(value, "", ""); if (!testrail.serverReachable()) { return FormValidation.error("Host is not reachable."); } return FormValidation.ok(); } public FormValidation doCheckTestrailUser(@QueryParameter String value, @QueryParameter String testrailHost, @QueryParameter String testrailPassword) throws IOException, ServletException { if (value.length() == 0) { return FormValidation.warning("Please add your user's email address."); } if (testrailPassword.length() > 0) { TestRailClient testrail = new TestRailClient(testrailHost, value, testrailPassword); if (testrail.serverReachable() && !testrail.authenticationWorks()){ return FormValidation.error("Invalid user/password combination."); } } return FormValidation.ok(); } public FormValidation doCheckTestrailPassword(@QueryParameter String value, @QueryParameter String testrailHost, @QueryParameter String testrailUser) throws IOException, ServletException { if (value.length() == 0) { return FormValidation.warning("Please add your password."); } if (testrailUser.length() > 0) { TestRailClient testrail = new TestRailClient(testrailHost, testrailUser, value); if (testrail.serverReachable() && !testrail.authenticationWorks()){ return FormValidation.error("Invalid user/password combination."); } } return FormValidation.ok(); } public boolean isApplicable(Class<? extends AbstractProject> aClass) { // Indicates that this builder can be used with all kinds of project types return true; } /** * This human readable name is used in the configuration screen. */ public String getDisplayName() { return "Publish test results to TestRail"; } @Override public boolean configure(StaplerRequest req, JSONObject formData) throws FormException { // To persist global configuration information, // set that to properties and call save(). testrailHost = formData.getString("testrailHost"); testrailUser = formData.getString("testrailUser"); testrailPassword = formData.getString("testrailPassword"); // ^Can also use req.bindJSON(this, formData); // (easier when there are many fields; need set* methods for this, like setTestrailHost) save(); return super.configure(req,formData); } /** * This method returns true if the global configuration says we should speak French. * * The method name is bit awkward because global.jelly calls this method to determine * the initial state of the checkbox by the naming convention. */ public String getTestrailHost() { return testrailHost; } public String getTestrailUser() { return testrailUser; } public String getTestrailPassword() { return testrailPassword; } } }
Work with slave nodes. The code was assuming that everything happened on the master. It was getting the workspace directory, but unfortunately it was the workspace directory on the slave. When the master tried to open files there, the local path was wrong. I think this fixes the problem but it looks ugly and is probably the wrong solution.
src/main/java/testrail/testrail/TestRailNotifier.java
Work with slave nodes.
Java
apache-2.0
6302df67b291c99d809571c1c927874b99b7360f
0
bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud
package com.planet_ink.coffee_mud.Libraries.layouts; import java.util.List; import java.util.Vector; import com.planet_ink.coffee_mud.core.Directions; import com.planet_ink.coffee_mud.core.Log; import com.planet_ink.coffee_mud.Libraries.interfaces.AreaGenerationLibrary.LayoutNode; import com.planet_ink.coffee_mud.Libraries.interfaces.AreaGenerationLibrary.LayoutRuns; import com.planet_ink.coffee_mud.Libraries.interfaces.AreaGenerationLibrary.LayoutTypes; /* Copyright 2008-2018 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class GridCityLayout extends AbstractLayout { @Override public String name() { return "GRIDCITY"; } @Override public List<LayoutNode> generate(final int num, final int dir) { final Vector<LayoutNode> set = new Vector<LayoutNode>(); final int diameter = (int)Math.round(Math.sqrt(num)); final int plusX = (diff(diameter,diameter,num) > diff(diameter+1,diameter,num)) ? 1 : 0; final LayoutSet lSet = new LayoutSet(set,num); lSet.drawABox(diameter+plusX,diameter); int middle=(diameter+plusX)/2; LayoutNode firstNode=null; for(int x=0;x<diameter+plusX;x+=2) { LayoutNode n = lSet.getNode(new long[]{x,0}); if(n!=null) { if((dir==Directions.NORTH)&&(x>=middle-1)&&(x<=middle+1)) firstNode=n; for(int y=0;y<diameter-1;y++) { lSet.use(n,LayoutTypes.street); n.flagRun(LayoutRuns.ns); LayoutNode nn = lSet.getNextNode(n, Directions.NORTH); if(nn==null) nn=lSet.makeNextNode(n, Directions.NORTH); n.crossLink(nn); n=nn; } lSet.use(n,LayoutTypes.street); n.flagRun(LayoutRuns.ns); if((dir==Directions.SOUTH)&&(x>=middle-1)&&(x<=middle+1)) firstNode=n; } } final int endX=diameter+plusX-1; middle=(-diameter+1)/2; for(int y=-2;y>=-diameter+1;y-=2) { LayoutNode n = lSet.getNode(new long[]{0,y}); if(n!=null) { if((dir==Directions.EAST)&&(y>=middle-1)&&(y<=middle+1)) firstNode=n; for(int x=0;x<endX;x++) { lSet.use(n,LayoutTypes.street); n.flagRun(LayoutRuns.ew); LayoutNode nn = lSet.getNextNode(n, Directions.EAST); if(nn==null) nn=lSet.makeNextNode(n, Directions.EAST); n.crossLink(nn); n=nn; } lSet.use(n,LayoutTypes.street); n.flagRun(LayoutRuns.ew); if((dir==Directions.WEST)&&(y>=middle-1)&&(y<=middle+1)) firstNode=n; } } boolean north=true; for(int y=0;y>=(-diameter)+1;y-=2) { for(int x=1;x<endX;x++) { final LayoutNode n = lSet.getNode(new long[]{x,y}); LayoutNode nn = lSet.getNextNode(n, Directions.NORTH); if(nn==null) { if(north) { if(y>(-diameter)+2) { nn = lSet.makeNextNode( n, Directions.NORTH); } } if(nn != null) { n.crossLink(nn); lSet.use(nn,LayoutTypes.interior); } north = !north; } } } for(int y=-2;y>=(-diameter)+1;y-=2) { for(int x=1;x<endX;x++) { final LayoutNode n = lSet.getNode(new long[]{x,y}); LayoutNode nn = lSet.getNextNode(n, Directions.SOUTH); if(nn==null) { nn = lSet.makeNextNode( n, Directions.SOUTH); if(nn != null) { n.crossLink(nn); lSet.use(nn,LayoutTypes.interior); } } } } lSet.fillInFlags(); if(firstNode == null) { if(set.size()>0) firstNode=set.get(0); } if(firstNode != null) { set.remove(firstNode); set.insertElementAt(firstNode, 0); } else Log.errOut("GridCityLayout","Not able to find start room for direction: "+dir); return set; } }
com/planet_ink/coffee_mud/Libraries/layouts/GridCityLayout.java
package com.planet_ink.coffee_mud.Libraries.layouts; import java.util.List; import java.util.Vector; import com.planet_ink.coffee_mud.core.Directions; import com.planet_ink.coffee_mud.core.Log; import com.planet_ink.coffee_mud.Libraries.interfaces.AreaGenerationLibrary.LayoutNode; import com.planet_ink.coffee_mud.Libraries.interfaces.AreaGenerationLibrary.LayoutRuns; import com.planet_ink.coffee_mud.Libraries.interfaces.AreaGenerationLibrary.LayoutTypes; /* Copyright 2008-2018 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class GridCityLayout extends AbstractLayout { @Override public String name() { return "GRIDCITY"; } @Override public List<LayoutNode> generate(int num, int dir) { final Vector<LayoutNode> set = new Vector<LayoutNode>(); final int diameter = (int)Math.round(Math.sqrt(num)); final int plusX = (diff(diameter,diameter,num) > diff(diameter+1,diameter,num)) ? 1 : 0; final LayoutSet lSet = new LayoutSet(set,num); lSet.drawABox(diameter+plusX,diameter); int middle=(diameter+plusX)/2; LayoutNode firstNode=null; for(int x=0;x<diameter+plusX;x+=2) { LayoutNode n = lSet.getNode(new long[]{x,0}); if(n!=null) { if((dir==Directions.NORTH)&&(x>=middle-1)&&(x<=middle+1)) firstNode=n; for(int y=0;y<diameter-1;y++) { lSet.use(n,LayoutTypes.street); n.flagRun(LayoutRuns.ns); LayoutNode nn = lSet.getNextNode(n, Directions.NORTH); if(nn==null) nn=lSet.makeNextNode(n, Directions.NORTH); n.crossLink(nn); n=nn; } lSet.use(n,LayoutTypes.street); n.flagRun(LayoutRuns.ns); if((dir==Directions.SOUTH)&&(x>=middle-1)&&(x<=middle+1)) firstNode=n; } } final int endX=diameter+plusX-1; middle=(-diameter+1)/2; for(int y=-2;y>=-diameter+1;y-=2) { LayoutNode n = lSet.getNode(new long[]{0,y}); if(n!=null) { if((dir==Directions.EAST)&&(y>=middle-1)&&(y<=middle+1)) firstNode=n; for(int x=0;x<endX;x++) { lSet.use(n,LayoutTypes.street); n.flagRun(LayoutRuns.ew); LayoutNode nn = lSet.getNextNode(n, Directions.EAST); if(nn==null) nn=lSet.makeNextNode(n, Directions.EAST); n.crossLink(nn); n=nn; } lSet.use(n,LayoutTypes.street); n.flagRun(LayoutRuns.ew); if((dir==Directions.WEST)&&(y>=middle-1)&&(y<=middle+1)) firstNode=n; } } boolean north=true; for(int y=0;y>=(-diameter)+1;y-=2) { for(int x=1;x<endX;x++) { final LayoutNode n = lSet.getNode(new long[]{x,y}); LayoutNode nn = lSet.getNextNode(n, Directions.NORTH); if(nn==null) { if(north) { if(y>(-diameter)+2) { nn = lSet.makeNextNode( n, Directions.NORTH); } } if(nn != null) { n.crossLink(nn); lSet.use(nn,LayoutTypes.interior); } north = !north; } } } for(int y=-2;y>=(-diameter)+1;y-=2) { for(int x=1;x<endX;x++) { final LayoutNode n = lSet.getNode(new long[]{x,y}); LayoutNode nn = lSet.getNextNode(n, Directions.SOUTH); if(nn==null) { nn = lSet.makeNextNode( n, Directions.SOUTH); if(nn != null) { n.crossLink(nn); lSet.use(nn,LayoutTypes.interior); } } } } lSet.fillInFlags(); if(firstNode != null) { set.remove(firstNode); set.insertElementAt(firstNode, 0); } else Log.errOut("GridCityLayout","Not able to find start room for direction: "+dir); return set; } }
one more layout fix for oceanfloor. git-svn-id: 0cdf8356e41b2d8ccbb41bb76c82068fe80b2514@17063 0d6f1817-ed0e-0410-87c9-987e46238f29
com/planet_ink/coffee_mud/Libraries/layouts/GridCityLayout.java
one more layout fix for oceanfloor.
Java
bsd-2-clause
11f5536ecff3417dd30ef9b60077a1c46ba7d9d6
0
dzidzitop/jaj_taglib
/* Copyright (c) 2011-2013, Dźmitry Laŭčuk All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package afc.jsp.tag; import java.io.IOException; import java.util.TreeMap; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.tagext.JspFragment; import javax.servlet.jsp.tagext.SimpleTagSupport; import afc.util.DevNull; /** * <p>An abstract simple tag whose sub-classes produce a sequence of events which can be handled by * event handlers to render a complex structure by small pieces. * Event handlers are <tt>event</tt> tags in the <tt>builder</tt> tag body. The <tt>name</tt> attribute of the * <tt>event</tt> tag defines the event this tag subscribes to. * The algorithmic part of the rendering process is implemented by the <tt>{@link #build}</tt> function. * Each time an event is raised by <tt>builder</tt> (see <tt>{@link #raiseEvent(String)}</tt>) * the correspondent <tt>event</tt> tag body is evaluated. All parameters to the event handler (if any) * are passed in the JSP context.</p> * * <p>The advantage of this approach to render content is clear separation between code that generates * structure (it is enclosed in tag's @{code build()} function) and code that renders output (it is * enclosed in event handler tags' bodies). This allows for having simple and straightforward JSP code * while keeping all algorithmic complexity in Java code (which is easier to create, test, and document). * In addition, it is possible to implement different representations on top of the same algorithm.</p> * * <p>An example below demonstrates a simple use case of the <tt>builder</tt>/<tt>event</tt> tags.</p> * <h2>Example.</h2> * <h3>The builder tag.</h3> * <p><pre>{@code * public class DigitsTag extends BuilderTagBase * { * protected void build() throws IOException, JspException * { * raiseEvent("start"); * for (int i = 0; i &amp; 10; ++i) { * if (i != 0) { * raiseEvent("separator"); * } * getJspContext().setAttribute("digit", i); * raiseEvent("digit"); * } * raiseEvent("end"); * } * }}</pre></p> * <h3>JSP fragment.</h3> * <p><pre>{@code * <afc:digits> * <afc:event name="start">digits: [</afc:event> * <afc:event name="end">];</afc:event> * <afc:event name="digit">${digit}</afc:event> * <afc:event name="separator"> </afc:event> * </afc:digits>}</pre></p> * <h3>JSP output.</h3> * <p><pre>{@code digits: [0 1 2 3 4 5 6 7 8 9];}</pre></p> * <p>In this example the JSP code has neither loops nor branches.</p> * * <h2>Additional details.</h2> * <p> * <ul> * <li><tt>builder</tt>'s body is evaluated once and before <tt>build()</tt> is invoked. The content generated * while evaluating the body is omitted</li> * <li>it is allowed to have no body for the <tt>builder</tt> tag. The <tt>build()</tt> function is invoked in this case * while having no output rendered</li> * <li>if an exception is thrown while evaluating <tt>builder</tt>'s body then <tt>build()</tt> is not invoked</li> * <li><tt>event</tt> tags could be direct or indirect inner tags of the <tt>builder</tt> tag to be registered * as event handlers</tt> * <li>only a single event handler could be registered to listen for a given event</li> * <li>it is allowed to have no event handler for an event. In this case the events will be ignored with no error. * Event handler tags with empty bodies will have the same effect</li> * </ul> * </p> * * @author D&#378;mitry La&#365;&#269;uk */ public abstract class BuilderTagBase extends SimpleTagSupport { private final TreeMap<String, EventTag> events = new TreeMap<String, EventTag>(); void register(final EventTag eventHandler) throws JspTagException { final String name = eventHandler.getName(); // TODO check if this could be checked by a tag validator if (name == null || name.length() == 0) { throw new JspTagException("Event name is undefined."); } // TODO check if this could be checked by a tag validator if (events.put(name, eventHandler) != null) { throw new JspTagException("Duplicate event handler for the event '" + name + "'."); } } @Override public final void doTag() throws JspException, IOException { final JspFragment body = getJspBody(); if (body != null) { // else invoke build against no events body.invoke(DevNull.instance); } build(); } protected abstract void build() throws JspException, IOException; protected final void raiseEvent(final String name) throws JspException, IOException { final EventTag event = events.get(name); if (event != null) { event.raise(); } } }
src/java/afc/jsp/tag/BuilderTagBase.java
/* Copyright (c) 2011-2013, Dźmitry Laŭčuk All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package afc.jsp.tag; import java.io.IOException; import java.util.TreeMap; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.tagext.JspFragment; import javax.servlet.jsp.tagext.SimpleTagSupport; import afc.util.DevNull; /** * <p>An abstract simple tag whose sub-classes produce a sequence of events which can be handled by * event handlers to render a complex structure by small pieces. * Event handlers are <tt>event</tt> tags in the <tt>builder</tt> tag body. The <tt>name</tt> attribute of the * <tt>event</tt> tag defines the event this tag subscribes to. * The algorithmic part of the rendering process is implemented by the <tt>{@link #build}</tt> function. * Each time an event is raised by <tt>builder</tt> (see <tt>{@link #raiseEvent(String)}</tt>) * the correspondent <tt>event</tt> tag body is evaluated. All parameters to the event handler (if any) * are passed in the JSP context.</p> * * <p>The advantage of this approach to render content is clear separation between code that generates * structure (it is enclosed in tag's @{code build()} function) and code that renders output (it is * enclosed in event handler tags' bodies). This allows for having simple and straightforward JSP code * while keeping all algorithmic complexity in Java code (which is easier to create, test, and document). * In addition, it is possible to implement different representations on top of the same algorithm.</p> * * <p>An example below demonstrates a simple use case of the <tt>builder</tt>/<tt>event</tt> tags.</p> * <h2>Example.</h2> * <h3>The builder tag.</h3> * <p><pre>{@code * public class DigitsTag extends BuilderTagBase * { * protected void build() throws IOException, JspException * { * raiseEvent("start"); * for (int i = 0; i &amp; 10; ++i) { * if (i != 0) { * raiseEvent("separator"); * } * getJspContext().setAttribute("digit", i); * raiseEvent("digit"); * } * raiseEvent("end"); * } * }}</pre></p> * <h3>JSP fragment.</h3> * <p><pre>{@code * <afc:digits> * <afc:event name="start">digits: [</afc:event> * <afc:event name="end">];</afc:event> * <afc:event name="digit">${digit}</afc:event> * <afc:event name="separator"> </afc:event> * </afc:digits>}</pre></p> * <h3>JSP output.</h3> * <p><pre>{@code digits: [0 1 2 3 4 5 6 7 8 9];}</pre></p> * <p>In this example the JSP code has neither loops nor branches.</p> * * <h2>Additional details.</h2> * <p> * <ul> * <li><tt>builder</tt>'s body is evaluated once and before <tt>build()</tt> is invoked. The content generated * while evaluating the body is omitted</li> * <li>it is allowed to have no body for the <tt>builder</tt> tag. The <tt>build()</tt> function is invoked in this case * while having no output rendered</li> * <li>if an exception is thrown while evaluating <tt>builder</tt>'s body then <tt>build()</tt> is not invoked</li> * <li><tt>event</tt> tags could be direct or indirect inner tags of the <tt>builder</tt> tag to be registered * as event handlers</tt> * <li>only a single event handler could be registered to listen for a given event</li> * <li>it is allowed to have no event handler for an event. In this case the events will be ignored with no error. * Event handler tags with empty bodies will have the same effect</li> * </ul> * </p> * * @author D&#378;mitry La&#365;&#269;uk */ public abstract class BuilderTagBase extends SimpleTagSupport { private final TreeMap<String, EventTag> events = new TreeMap<String, EventTag>(); void register(final EventTag event) throws JspTagException { final String name = event.getName(); // TODO check if this could be checked by a tag validator if (name == null || name.length() == 0) { throw new JspTagException("Event name is undefined."); } // TODO check if this could be checked by a tag validator if (events.put(event.getName(), event) != null) { throw new JspTagException("Duplicate event handler for the event '" + name + "'."); } } @Override public final void doTag() throws JspException, IOException { final JspFragment body = getJspBody(); if (body != null) { // else invoke build against no events body.invoke(DevNull.instance); } build(); } protected abstract void build() throws JspException, IOException; protected final void raiseEvent(final String name) throws JspException, IOException { final EventTag event = events.get(name); if (event != null) { event.raise(); } } }
minor changes
src/java/afc/jsp/tag/BuilderTagBase.java
minor changes
Java
bsd-2-clause
11b1c3e2b8dea96c1ba3c022a334a5345a5cc980
0
Brokkonaut/CubeQuest
package de.iani.cubequest.generation; import de.iani.cubequest.CubeQuest; import de.iani.cubequest.EventListener.GlobalChatMsgType; import de.iani.cubequest.QuestGiver; import de.iani.cubequest.QuestManager; import de.iani.cubequest.Reward; import de.iani.cubequest.exceptions.QuestDeletionFailedException; import de.iani.cubequest.interaction.InteractorProtecting; import de.iani.cubequest.quests.Quest; import de.iani.cubequest.util.ChatAndTextUtil; import de.iani.cubequest.util.ItemStackUtil; import de.iani.cubequest.util.Pair; import de.iani.cubequest.util.Util; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.SQLException; import java.time.LocalDate; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.EnumMap; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.logging.Level; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.ComponentBuilder; import net.md_5.bungee.api.chat.HoverEvent; import org.bukkit.Material; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.entity.EntityType; import org.bukkit.inventory.ItemStack; public class QuestGenerator implements ConfigurationSerializable { private static final int DAYS_TO_KEEP_DAILY_QUESTS = 3; private static QuestGenerator instance; private int questsToGenerate; private int questsToGenerateOnThisServer; private List<QuestSpecification> possibleQuests; private Set<QuestSpecification> lastUsedPossibilities; private Set<QuestSpecification> currentlyUsedPossibilities; private Deque<DailyQuestData> currentDailyQuests; private Map<MaterialValueOption, ValueMap<Material>> materialValues; private Map<EntityValueOption, ValueMap<EntityType>> entityValues; private LocalDate lastGeneratedForDay; // private Object saveLock = new Object(); public enum MaterialValueOption { DELIVER, PLACE, BREAK, FISH; } public enum EntityValueOption { KILL; } public static class QuestSpecificationAndDifficultyPair extends Pair<QuestSpecification, Double> { public QuestSpecificationAndDifficultyPair(QuestSpecification key, Double value) { super(key, value); } public QuestSpecification getQuestSpecification() { return super.getKey(); } public double getDifficulty() { return super.getValue(); } } public static class QuestSpeficicationBestFitComparator implements Comparator<QuestSpecificationAndDifficultyPair> { private double targetDifficulty; private Set<QuestSpecification> avoid1; private Set<QuestSpecification> avoid2; public QuestSpeficicationBestFitComparator(double targetDifficulty, Set<QuestSpecification> avoid1, Set<QuestSpecification> avoid2) { this.targetDifficulty = targetDifficulty; this.avoid1 = avoid1; this.avoid2 = avoid2; } @Override public int compare(QuestSpecificationAndDifficultyPair o1, QuestSpecificationAndDifficultyPair o2) { int result = 0; if (this.avoid1.contains(o1.getQuestSpecification())) { result += 1; } if (this.avoid1.contains(o2.getQuestSpecification())) { result -= 1; } if (result != 0) { return result; } if (this.avoid2.contains(o1.getQuestSpecification())) { result += 1; } if (this.avoid2.contains(o2.getQuestSpecification())) { result -= 1; } if (result != 0) { return result; } result = Double.compare(Math.abs(this.targetDifficulty - o1.getDifficulty()), Math.abs(this.targetDifficulty - o2.getDifficulty())); return (int) Math.signum(result); } } public static QuestGenerator getInstance() { if (instance == null) { File configFile = new File(CubeQuest.getInstance().getDataFolder(), "generator.yml"); if (!configFile.exists()) { instance = new QuestGenerator(); } else { YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); if (!config.contains("generator")) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not load QuestGenerator."); instance = new QuestGenerator(); } else { instance = (QuestGenerator) config.get("generator"); } } } return instance; } private QuestGenerator() { this.possibleQuests = new ArrayList<>(); this.lastUsedPossibilities = new TreeSet<>(QuestSpecification.SIMILAR_SPECIFICATIONS_COMPARATOR); this.currentlyUsedPossibilities = new TreeSet<>(QuestSpecification.SIMILAR_SPECIFICATIONS_COMPARATOR); this.materialValues = new EnumMap<>(MaterialValueOption.class); this.entityValues = new EnumMap<>(EntityValueOption.class); refreshDailyQuests(); for (MaterialValueOption option : MaterialValueOption.values()) { ValueMap<Material> map = new ValueMap<>(Material.class, 0.0025); this.materialValues.put(option, map); } for (EntityValueOption option : EntityValueOption.values()) { ValueMap<EntityType> map = new ValueMap<>(EntityType.class, 0.1); this.entityValues.put(option, map); } } @SuppressWarnings("unchecked") public QuestGenerator(Map<String, Object> serialized) throws InvalidConfigurationException { if (instance != null) { throw new IllegalStateException("Can't initilize second instance of singleton!"); } try { this.questsToGenerate = (Integer) serialized.get("questsToGenerate"); this.questsToGenerateOnThisServer = (Integer) serialized.get("questsToGenerateOnThisServer"); this.possibleQuests = (List<QuestSpecification>) serialized.get("possibleQuests"); this.lastUsedPossibilities = new TreeSet<>(QuestSpecification.SIMILAR_SPECIFICATIONS_COMPARATOR); if (serialized.containsKey("lastUsedPossibilities")) { this.lastUsedPossibilities .addAll((List<QuestSpecification>) serialized.get("lastUsedPossibilities")); } this.currentlyUsedPossibilities = new TreeSet<>(QuestSpecification.SIMILAR_SPECIFICATIONS_COMPARATOR); if (serialized.containsKey("currentlyUsedPossibilities")) { this.currentlyUsedPossibilities.addAll( (List<QuestSpecification>) serialized.get("currentlyUsedPossibilities")); } DeliveryQuestSpecification.DeliveryQuestPossibilitiesSpecification.deserialize( (Map<String, Object>) serialized.get("deliveryQuestSpecifications")); BlockBreakQuestSpecification.BlockBreakQuestPossibilitiesSpecification.deserialize( (Map<String, Object>) serialized.get("blockBreakQuestSpecifications")); BlockPlaceQuestSpecification.BlockPlaceQuestPossibilitiesSpecification.deserialize( (Map<String, Object>) serialized.get("blockPlaceQuestSpecifications")); FishingQuestSpecification.FishingQuestPossibilitiesSpecification.deserialize( (Map<String, Object>) serialized.get("fishingQuestSpecifications")); KillEntitiesQuestSpecification.KillEntitiesQuestPossibilitiesSpecification.deserialize( (Map<String, Object>) serialized.get("killEntitiesQuestSpecifications")); Map<String, Object> mValues = (Map<String, Object>) serialized.get("materialValues"); this.materialValues = (Map<MaterialValueOption, ValueMap<Material>>) Util .deserializeEnumMap(MaterialValueOption.class, mValues); Map<String, Object> eValues = (Map<String, Object>) serialized.get("entityValues"); this.entityValues = (Map<EntityValueOption, ValueMap<EntityType>>) Util .deserializeEnumMap(EntityValueOption.class, eValues); refreshDailyQuests(); this.lastGeneratedForDay = serialized.get("lastGeneratedForDay") == null ? null : LocalDate.ofEpochDay( ((Number) serialized.get("lastGeneratedForDay")).longValue()); } catch (Exception e) { throw new InvalidConfigurationException(e); } for (QuestSpecification spec : this.possibleQuests) { if (spec instanceof InteractorProtecting) { CubeQuest.getInstance().addProtecting((InteractorProtecting) spec); } } } public void refreshDailyQuests() { try { this.currentDailyQuests = new ArrayDeque<>( CubeQuest.getInstance().getDatabaseFassade().getDailyQuestData()); } catch (SQLException e) { this.currentDailyQuests = this.currentDailyQuests == null ? new ArrayDeque<>(QuestGenerator.DAYS_TO_KEEP_DAILY_QUESTS) : this.currentDailyQuests; CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not refresh current dailyQuests:", e); } } public List<QuestSpecification> getPossibleQuestsIncludingNulls() { return Collections.unmodifiableList(this.possibleQuests); } public void addPossibleQuest(QuestSpecification qs) { this.possibleQuests.add(qs); if (qs instanceof InteractorProtecting) { CubeQuest.getInstance().addProtecting((InteractorProtecting) qs); } saveConfig(); } public void removePossibleQuest(int index) { QuestSpecification spec = this.possibleQuests.set(index, null); if (spec != null) { if (spec instanceof InteractorProtecting) { CubeQuest.getInstance().removeProtecting((InteractorProtecting) spec); } saveConfig(); } } public void consolidatePossibleQuests() { this.possibleQuests.removeIf(qs -> qs == null); this.possibleQuests.sort(QuestSpecification.COMPARATOR); } public int getQuestsToGenerate() { return this.questsToGenerate; } public void setQuestsToGenerate(int questsToGenerate) { this.questsToGenerate = questsToGenerate; saveConfig(); } public int getQuestsToGenerateOnThisServer() { return this.questsToGenerateOnThisServer; } public void setQuestsToGenerateOnThisServer(int questsToGenerateOnThisServer) { this.questsToGenerateOnThisServer = questsToGenerateOnThisServer; saveConfig(); } public LocalDate getLastGeneratedForDay() { return this.lastGeneratedForDay; } public double getValue(MaterialValueOption o, Material m) { return this.materialValues.get(o).getValue(m); } public void setValue(MaterialValueOption o, Material m, double value) { this.materialValues.get(o).setValue(m, value); saveConfig(); } public double getValue(EntityValueOption o, EntityType t) { return this.entityValues.get(o).getValue(t); } public void setValue(EntityValueOption o, EntityType t, double value) { this.entityValues.get(o).setValue(t, value); saveConfig(); } public void generateDailyQuests() { CubeQuest.getInstance().getLogger().log(Level.INFO, "Starting to generate DailyQuests."); deleteOldDailyQuests(); DailyQuestData dqData; try { int dataId = CubeQuest.getInstance().getDatabaseFassade().reserveNewDailyQuestData(); dqData = new DailyQuestData(dataId, this.questsToGenerate); this.currentDailyQuests.addLast(dqData); } catch (SQLException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not create new DailyQuestData.", e); return; } this.lastGeneratedForDay = LocalDate.now(); this.lastUsedPossibilities = this.currentlyUsedPossibilities; this.currentlyUsedPossibilities = new TreeSet<>(QuestSpecification.SIMILAR_SPECIFICATIONS_COMPARATOR); Random ran; try { ran = new Random(Util.fromBytes(MessageDigest.getInstance("MD5") .digest(Util.byteArray(this.lastGeneratedForDay.toEpochDay())))); } catch (NoSuchAlgorithmException e) { throw new AssertionError(e); } List<String> selectedServers = getServersToGenerateOn(ran, dqData); for (int i = 0; i < this.questsToGenerate; i++) { double difficulty = (this.questsToGenerate > 1 ? 0.1 + i * 0.8 / (this.questsToGenerate - 1) : 0.5) + 0.1 * ran.nextDouble(); String server = selectedServers.get(i); if (server == null) { dailyQuestGenerated(i, generateQuest(i, dqData.getDateString(), difficulty, ran)); } else { delegateDailyQuestGeneration(server, i, dqData, difficulty, ran); } } saveConfig(); } private void deleteOldDailyQuests() { if (!this.currentDailyQuests.isEmpty()) { // DailyQuests von gestern aus QuestGivern austragen for (QuestGiver giver : CubeQuest.getInstance().getDailyQuestGivers()) { for (Quest q : this.currentDailyQuests.getLast().getQuests()) { giver.removeQuest(q); } } for (Quest q : this.currentDailyQuests.getLast().getQuests()) { q.setReady(false); } // Ggf. über eine Woche alte DailyQuests löschen while (this.currentDailyQuests.size() >= DAYS_TO_KEEP_DAILY_QUESTS) { DailyQuestData dqData = this.currentDailyQuests.removeFirst(); try { CubeQuest.getInstance().getDatabaseFassade().deleteDailyQuestData(dqData); } catch (SQLException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not delete DailyQuests " + dqData + ":", e); return; } ByteArrayOutputStream msgbytes = new ByteArrayOutputStream(); DataOutputStream msgout = new DataOutputStream(msgbytes); try { msgout.writeInt(GlobalChatMsgType.DAILY_QUESTS_REMOVED.ordinal()); byte[] msgarry = msgbytes.toByteArray(); CubeQuest.getInstance().getGlobalChatAPI().sendDataToServers("CubeQuest", msgarry); } catch (IOException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "IOException trying to send GlobalChatMessage!", e); return; } // Logge ggf. Fehlermeldungen von Quests, die nicht gelöscht werden können for (Quest q : dqData.getQuests()) { try { QuestManager.getInstance().deleteQuest(q); } catch (QuestDeletionFailedException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not delete DailyQuest " + q + ":", e); } } } } } private List<String> getServersToGenerateOn(Random ran, DailyQuestData dqData) { List<String> selectedServers = new ArrayList<>(); List<String> serversToSelectFrom = new ArrayList<>(); Map<String, Integer> serversToSelectFromWithAmountOfLegalSpecifications; try { serversToSelectFromWithAmountOfLegalSpecifications = CubeQuest.getInstance().getDatabaseFassade().getServersToGenerateDailyQuestOn(); } catch (SQLException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "SQL-Exception while trying to generate daily-quests! No quests generated.", e); return Collections.emptyList(); } serversToSelectFromWithAmountOfLegalSpecifications .remove(CubeQuest.getInstance().getBungeeServerName()); for (String server : serversToSelectFromWithAmountOfLegalSpecifications.keySet()) { for (int i = 0; i < serversToSelectFromWithAmountOfLegalSpecifications .get(server); i++) { serversToSelectFrom.add(server); } } if (serversToSelectFrom.isEmpty()) { serversToSelectFrom.add(null); } else { Collections.sort(serversToSelectFrom); Collections.shuffle(serversToSelectFrom, ran); } for (int i = 0; serversToSelectFrom.size() < this.questsToGenerate - this.questsToGenerateOnThisServer; i++) { serversToSelectFrom.add(serversToSelectFrom.get(i)); } for (int i = 0; i < this.questsToGenerate; i++) { selectedServers.add(i < this.questsToGenerateOnThisServer ? null : serversToSelectFrom.get(i - this.questsToGenerateOnThisServer)); } Collections.shuffle(selectedServers, ran); return selectedServers; } private void delegateDailyQuestGeneration(String server, int questOrdinal, DailyQuestData dqData, double difficulty, Random ran) { try { DelegatedGenerationData data = new DelegatedGenerationData(dqData.getDateString(), questOrdinal, difficulty, ran.nextLong()); CubeQuest.getInstance().getDatabaseFassade().addDelegatedQuestGeneration(server, data); } catch (SQLException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "IOException trying to save DelegatedGenerationData!", e); return; } ByteArrayOutputStream msgbytes = new ByteArrayOutputStream(); DataOutputStream msgout = new DataOutputStream(msgbytes); try { msgout.writeInt(GlobalChatMsgType.GENERATE_DAILY_QUEST.ordinal()); msgout.writeUTF(server); byte[] msgarry = msgbytes.toByteArray(); CubeQuest.getInstance().getGlobalChatAPI().sendDataToServers("CubeQuest", msgarry); } catch (IOException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "IOException trying to send GlobalChatMessage!", e); return; } } public Quest generateQuest(int dailyQuestOrdinal, String dateString, double difficulty, Random ran) { long diff = this.lastGeneratedForDay == null ? Long.MAX_VALUE : (LocalDate.now().toEpochDay() - this.lastGeneratedForDay.toEpochDay()); if (diff > 0) { this.lastGeneratedForDay = LocalDate.now(); this.lastUsedPossibilities = diff == 1 ? this.currentlyUsedPossibilities : new TreeSet<>(QuestSpecification.SIMILAR_SPECIFICATIONS_COMPARATOR); this.currentlyUsedPossibilities = new TreeSet<>(QuestSpecification.SIMILAR_SPECIFICATIONS_COMPARATOR); } if (this.possibleQuests.stream().noneMatch(qs -> qs != null && qs.isLegal())) { CubeQuest.getInstance().getLogger().log(Level.WARNING, "Could not generate a DailyQuest for this server as no QuestSpecifications were specified."); return null; } List<QuestSpecification> qsList = new ArrayList<>(); this.possibleQuests.forEach(qs -> { if (qs != null && qs.isLegal()) { qsList.add(qs); } }); qsList.sort(QuestSpecification.COMPARATOR); List<QuestSpecificationAndDifficultyPair> generatedList = new ArrayList<>(); qsList.forEach(qs -> generatedList.add(new QuestSpecificationAndDifficultyPair(qs, qs.generateQuest(ran) + 0.1 * ran.nextGaussian()))); int weighting = DeliveryQuestSpecification.DeliveryQuestPossibilitiesSpecification .getInstance().getWeighting(); for (int i = 0; i < weighting; i++) { DeliveryQuestSpecification qs = new DeliveryQuestSpecification(); generatedList.add(new QuestSpecificationAndDifficultyPair(qs, qs.generateQuest(ran) + 0.1 * ran.nextGaussian())); } weighting = BlockBreakQuestSpecification.BlockBreakQuestPossibilitiesSpecification .getInstance().getWeighting(); for (int i = 0; i < weighting; i++) { BlockBreakQuestSpecification qs = new BlockBreakQuestSpecification(); generatedList.add(new QuestSpecificationAndDifficultyPair(qs, qs.generateQuest(ran) + 0.1 * ran.nextGaussian())); } weighting = BlockPlaceQuestSpecification.BlockPlaceQuestPossibilitiesSpecification .getInstance().getWeighting(); for (int i = 0; i < weighting; i++) { BlockPlaceQuestSpecification qs = new BlockPlaceQuestSpecification(); generatedList.add(new QuestSpecificationAndDifficultyPair(qs, qs.generateQuest(ran) + 0.1 * ran.nextGaussian())); } weighting = FishingQuestSpecification.FishingQuestPossibilitiesSpecification.getInstance() .getWeighting(); for (int i = 0; i < weighting; i++) { FishingQuestSpecification qs = new FishingQuestSpecification(); generatedList.add(new QuestSpecificationAndDifficultyPair(qs, qs.generateQuest(ran) + 0.1 * ran.nextGaussian())); } weighting = KillEntitiesQuestSpecification.KillEntitiesQuestPossibilitiesSpecification .getInstance().getWeighting(); for (int i = 0; i < weighting; i++) { KillEntitiesQuestSpecification qs = new KillEntitiesQuestSpecification(); generatedList.add(new QuestSpecificationAndDifficultyPair(qs, qs.generateQuest(ran) + 0.1 * ran.nextGaussian())); } generatedList.sort(new QuestSpeficicationBestFitComparator(difficulty, this.currentlyUsedPossibilities, this.lastUsedPossibilities)); generatedList.subList(1, generatedList.size() - 1) .forEach(qsdp -> qsdp.getQuestSpecification().clearGeneratedQuest()); QuestSpecification resultSpecification = generatedList.get(0).getQuestSpecification(); this.currentlyUsedPossibilities.add(resultSpecification); String questName = ChatColor.GOLD + "DailyQuest " + ChatAndTextUtil.toRomanNumber(dailyQuestOrdinal + 1) + " vom " + dateString; Reward reward = generateReward(difficulty, ran); Quest result = resultSpecification.createGeneratedQuest(questName, reward); result.setReady(true); if (!CubeQuest.getInstance().isGeneratingDailyQuests()) { saveConfig(); } return result; } public boolean checkForDelegatedGeneration() { List<DelegatedGenerationData> dataList; try { dataList = CubeQuest.getInstance().getDatabaseFassade().popDelegatedQuestGenerations(); } catch (SQLException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not pop delegated quest generations.", e); return false; } if (dataList.isEmpty()) { return false; } for (DelegatedGenerationData data : dataList) { Quest generated = generateQuest(data.questOrdinal, data.dateString, data.difficulty, new Random(data.ranSeed)); try { ByteArrayOutputStream msgbytes = new ByteArrayOutputStream(); DataOutputStream msgout = new DataOutputStream(msgbytes); msgout.writeInt(GlobalChatMsgType.DAILY_QUEST_GENERATED.ordinal()); msgout.writeInt(data.questOrdinal); msgout.writeInt(generated.getId()); byte[] msgarry = msgbytes.toByteArray(); CubeQuest.getInstance().getGlobalChatAPI().sendDataToServers("CubeQuest", msgarry); } catch (IOException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "IOException trying to send GlobalChatMessage!", e); } } return true; } /** * Generiert die Belohnung für eine DailyQuest * * @param difficulty ignored * @param rewardModifier ignored * @param ran ignored * @return Feste Belohnung (nicht zufällig generiert) aus 10 QuestPoint, 5 XP und 1 Mysteriösen * Zauberbuch */ public Reward generateReward(double difficulty, Random ran) { return new Reward(0, 10, 5, new ItemStack[] {ItemStackUtil.getMysteriousSpellBook()}); } public void dailyQuestGenerated(int dailyQuestOrdinal, Quest generatedQuest) { if (!CubeQuest.getInstance().isGeneratingDailyQuests()) { return; } if (generatedQuest.getSuccessMessage() == null) { generatedQuest.setSuccessMessage(CubeQuest.PLUGIN_TAG + ChatColor.GOLD + " Du hast die " + generatedQuest.getName() + " abgeschlossen!"); } DailyQuestData dqData = this.currentDailyQuests.getLast(); generatedQuest.setVisible(true); dqData.setQuest(dailyQuestOrdinal, Util.addTimeLimit(generatedQuest, dqData.getNextDayDate())); try { dqData.saveToDatabase(); } catch (SQLException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not save DailyQuestData.", e); return; } try { ByteArrayOutputStream msgbytes = new ByteArrayOutputStream(); DataOutputStream msgout = new DataOutputStream(msgbytes); msgout.writeInt(GlobalChatMsgType.DAILY_QUEST_FINISHED.ordinal()); byte[] msgarry = msgbytes.toByteArray(); CubeQuest.getInstance().getGlobalChatAPI().sendDataToServers("CubeQuest", msgarry); } catch (IOException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "IOException trying to send GlobalChatMessage!", e); } if (dqData.getQuests().stream().allMatch(q -> q != null)) { for (QuestGiver giver : CubeQuest.getInstance().getDailyQuestGivers()) { for (Quest q : dqData.getQuests()) { giver.addQuest(q); } } CubeQuest.getInstance().getLogger().log(Level.INFO, "DailyQuests generated."); } } public List<Quest> getTodaysDailyQuests() { DailyQuestData dqData = this.currentDailyQuests.getLast(); return this.currentDailyQuests == null ? null : dqData.getQuests(); } public Collection<Quest> getAllDailyQuests() { Set<Quest> result = new LinkedHashSet<>(); for (DailyQuestData dqData : this.currentDailyQuests) { for (Quest q : dqData.getQuests()) { result.add(q); } } return result; } public int countLegalQuestSecifications() { int i = 0; for (QuestSpecification qs : this.possibleQuests) { if (qs != null && qs.isLegal()) { i++; } } try { CubeQuest.getInstance().getDatabaseFassade().setLegalQuestSpecificationCount(i); } catch (SQLException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not update count of legal QuestSpecificaitons in database.", e); } return i; } public List<BaseComponent[]> getSpecificationInfo() { List<BaseComponent[]> result = new ArrayList<>(); int index = 1; for (QuestSpecification qs : this.possibleQuests) { if (qs != null) { ClickEvent clickEvent = new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/quest removeQuestSpecification " + index); HoverEvent hoverEvent = new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder("Spezifikation an Index " + index + " entfernen.") .create()); result.add(new ComponentBuilder(index + ": ").append(qs.getSpecificationInfo()) .append(" ").append("[Löschen]").color(ChatColor.RED).event(clickEvent) .event(hoverEvent).create()); } index++; } return result; } public List<BaseComponent[]> getDeliveryReceiverSpecificationInfo() { return DeliveryQuestSpecification.DeliveryQuestPossibilitiesSpecification.getInstance() .getReceiverSpecificationInfo(); } public List<BaseComponent[]> getDeliveryContentSpecificationInfo() { return DeliveryQuestSpecification.DeliveryQuestPossibilitiesSpecification.getInstance() .getContentSpecificationInfo(); } public List<BaseComponent[]> getBlockBreakSpecificationInfo() { return BlockBreakQuestSpecification.BlockBreakQuestPossibilitiesSpecification.getInstance() .getSpecificationInfo(); } public List<BaseComponent[]> getBlockPlaceSpecificationInfo() { return BlockPlaceQuestSpecification.BlockPlaceQuestPossibilitiesSpecification.getInstance() .getSpecificationInfo(); } public List<BaseComponent[]> getFishingSpecificationInfo() { return FishingQuestSpecification.FishingQuestPossibilitiesSpecification.getInstance() .getSpecificationInfo(); } public List<BaseComponent[]> getKillEntitiesSpecificationInfo() { return KillEntitiesQuestSpecification.KillEntitiesQuestPossibilitiesSpecification .getInstance().getSpecificationInfo(); } @Override public Map<String, Object> serialize() { Map<String, Object> result = new HashMap<>(); result.put("questsToGenerate", this.questsToGenerate); result.put("questsToGenerateOnThisServer", this.questsToGenerateOnThisServer); List<QuestSpecification> possibleQSList = new ArrayList<>(this.possibleQuests); possibleQSList.removeIf(qs -> qs == null); possibleQSList.sort(QuestSpecification.COMPARATOR); result.put("possibleQuests", possibleQSList); List<QuestSpecification> lastUsedQSList = new ArrayList<>(this.lastUsedPossibilities); result.put("lastUsedPossibilities", lastUsedQSList); List<QuestSpecification> currentlyUsedQSList = new ArrayList<>(this.currentlyUsedPossibilities); result.put("currentlyUsedPossibilities", currentlyUsedQSList); result.put("deliveryQuestSpecifications", DeliveryQuestSpecification.DeliveryQuestPossibilitiesSpecification.getInstance() .serialize()); result.put("blockBreakQuestSpecifications", BlockBreakQuestSpecification.BlockBreakQuestPossibilitiesSpecification.getInstance() .serialize()); result.put("blockPlaceQuestSpecifications", BlockPlaceQuestSpecification.BlockPlaceQuestPossibilitiesSpecification.getInstance() .serialize()); result.put("fishingQuestSpecifications", FishingQuestSpecification.FishingQuestPossibilitiesSpecification.getInstance() .serialize()); result.put("killEntitiesQuestSpecifications", KillEntitiesQuestSpecification.KillEntitiesQuestPossibilitiesSpecification .getInstance().serialize()); result.put("materialValues", Util.serializedEnumMap(this.materialValues)); result.put("entityValues", Util.serializedEnumMap(this.entityValues)); result.put("lastGeneratedForDay", this.lastGeneratedForDay == null ? null : this.lastGeneratedForDay.toEpochDay()); return result; } public void saveConfig() { countLegalQuestSecifications(); CubeQuest.getInstance().getDataFolder().mkdirs(); File configFile = new File(CubeQuest.getInstance().getDataFolder(), "generator.yml"); YamlConfiguration config = new YamlConfiguration(); config.set("generator", this); try { config.save(configFile); } catch (IOException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not save QuestGenerator.", e); } } }
src/main/java/de/iani/cubequest/generation/QuestGenerator.java
package de.iani.cubequest.generation; import de.iani.cubequest.CubeQuest; import de.iani.cubequest.EventListener.GlobalChatMsgType; import de.iani.cubequest.QuestGiver; import de.iani.cubequest.QuestManager; import de.iani.cubequest.Reward; import de.iani.cubequest.exceptions.QuestDeletionFailedException; import de.iani.cubequest.interaction.InteractorProtecting; import de.iani.cubequest.quests.Quest; import de.iani.cubequest.util.ChatAndTextUtil; import de.iani.cubequest.util.ItemStackUtil; import de.iani.cubequest.util.Pair; import de.iani.cubequest.util.Util; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.SQLException; import java.time.LocalDate; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.EnumMap; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.logging.Level; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.ComponentBuilder; import net.md_5.bungee.api.chat.HoverEvent; import org.bukkit.Material; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.entity.EntityType; import org.bukkit.inventory.ItemStack; public class QuestGenerator implements ConfigurationSerializable { private static final int DAYS_TO_KEEP_DAILY_QUESTS = 3; private static QuestGenerator instance; private int questsToGenerate; private int questsToGenerateOnThisServer; private List<QuestSpecification> possibleQuests; private Set<QuestSpecification> lastUsedPossibilities; private Set<QuestSpecification> currentlyUsedPossibilities; private Deque<DailyQuestData> currentDailyQuests; private Map<MaterialValueOption, ValueMap<Material>> materialValues; private Map<EntityValueOption, ValueMap<EntityType>> entityValues; private LocalDate lastGeneratedForDay; // private Object saveLock = new Object(); public enum MaterialValueOption { DELIVER, PLACE, BREAK, FISH; } public enum EntityValueOption { KILL; } public static class QuestSpecificationAndDifficultyPair extends Pair<QuestSpecification, Double> { public QuestSpecificationAndDifficultyPair(QuestSpecification key, Double value) { super(key, value); } public QuestSpecification getQuestSpecification() { return super.getKey(); } public double getDifficulty() { return super.getValue(); } } public static class QuestSpeficicationBestFitComparator implements Comparator<QuestSpecificationAndDifficultyPair> { private double targetDifficulty; private Set<QuestSpecification> avoid1; private Set<QuestSpecification> avoid2; public QuestSpeficicationBestFitComparator(double targetDifficulty, Set<QuestSpecification> avoid1, Set<QuestSpecification> avoid2) { this.targetDifficulty = targetDifficulty; this.avoid1 = avoid1; this.avoid2 = avoid2; } @Override public int compare(QuestSpecificationAndDifficultyPair o1, QuestSpecificationAndDifficultyPair o2) { int result = 0; if (this.avoid1.contains(o1.getQuestSpecification())) { result += 1; } if (this.avoid1.contains(o2.getQuestSpecification())) { result -= 1; } if (result != 0) { return result; } if (this.avoid2.contains(o1.getQuestSpecification())) { result += 1; } if (this.avoid2.contains(o2.getQuestSpecification())) { result -= 1; } if (result != 0) { return result; } result = Double.compare(Math.abs(this.targetDifficulty - o1.getDifficulty()), Math.abs(this.targetDifficulty - o2.getDifficulty())); return (int) Math.signum(result); } } public static QuestGenerator getInstance() { if (instance == null) { File configFile = new File(CubeQuest.getInstance().getDataFolder(), "generator.yml"); if (!configFile.exists()) { instance = new QuestGenerator(); } else { YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); if (!config.contains("generator")) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not load QuestGenerator."); instance = new QuestGenerator(); } else { instance = (QuestGenerator) config.get("generator"); } } } return instance; } private QuestGenerator() { this.possibleQuests = new ArrayList<>(); this.lastUsedPossibilities = new TreeSet<>(QuestSpecification.SIMILAR_SPECIFICATIONS_COMPARATOR); this.currentlyUsedPossibilities = new TreeSet<>(QuestSpecification.SIMILAR_SPECIFICATIONS_COMPARATOR); this.materialValues = new EnumMap<>(MaterialValueOption.class); this.entityValues = new EnumMap<>(EntityValueOption.class); refreshDailyQuests(); for (MaterialValueOption option : MaterialValueOption.values()) { ValueMap<Material> map = new ValueMap<>(Material.class, 0.0025); this.materialValues.put(option, map); } for (EntityValueOption option : EntityValueOption.values()) { ValueMap<EntityType> map = new ValueMap<>(EntityType.class, 0.1); this.entityValues.put(option, map); } } @SuppressWarnings("unchecked") public QuestGenerator(Map<String, Object> serialized) throws InvalidConfigurationException { if (instance != null) { throw new IllegalStateException("Can't initilize second instance of singleton!"); } try { this.questsToGenerate = (Integer) serialized.get("questsToGenerate"); this.questsToGenerateOnThisServer = (Integer) serialized.get("questsToGenerateOnThisServer"); this.possibleQuests = (List<QuestSpecification>) serialized.get("possibleQuests"); this.lastUsedPossibilities = new TreeSet<>(QuestSpecification.SIMILAR_SPECIFICATIONS_COMPARATOR); if (serialized.containsKey("lastUsedPossibilities")) { this.lastUsedPossibilities .addAll((List<QuestSpecification>) serialized.get("lastUsedPossibilities")); } this.currentlyUsedPossibilities = new TreeSet<>(QuestSpecification.SIMILAR_SPECIFICATIONS_COMPARATOR); if (serialized.containsKey("currentlyUsedPossibilities")) { this.currentlyUsedPossibilities.addAll( (List<QuestSpecification>) serialized.get("currentlyUsedPossibilities")); } DeliveryQuestSpecification.DeliveryQuestPossibilitiesSpecification.deserialize( (Map<String, Object>) serialized.get("deliveryQuestSpecifications")); BlockBreakQuestSpecification.BlockBreakQuestPossibilitiesSpecification.deserialize( (Map<String, Object>) serialized.get("blockBreakQuestSpecifications")); BlockPlaceQuestSpecification.BlockPlaceQuestPossibilitiesSpecification.deserialize( (Map<String, Object>) serialized.get("blockPlaceQuestSpecifications")); FishingQuestSpecification.FishingQuestPossibilitiesSpecification.deserialize( (Map<String, Object>) serialized.get("fishingQuestSpecifications")); KillEntitiesQuestSpecification.KillEntitiesQuestPossibilitiesSpecification.deserialize( (Map<String, Object>) serialized.get("killEntitiesQuestSpecifications")); Map<String, Object> mValues = (Map<String, Object>) serialized.get("materialValues"); this.materialValues = (Map<MaterialValueOption, ValueMap<Material>>) Util .deserializeEnumMap(MaterialValueOption.class, mValues); Map<String, Object> eValues = (Map<String, Object>) serialized.get("entityValues"); this.entityValues = (Map<EntityValueOption, ValueMap<EntityType>>) Util .deserializeEnumMap(EntityValueOption.class, eValues); refreshDailyQuests(); this.lastGeneratedForDay = serialized.get("lastGeneratedForDay") == null ? null : LocalDate.ofEpochDay( ((Number) serialized.get("lastGeneratedForDay")).longValue()); } catch (Exception e) { throw new InvalidConfigurationException(e); } for (QuestSpecification spec : this.possibleQuests) { if (spec instanceof InteractorProtecting) { CubeQuest.getInstance().addProtecting((InteractorProtecting) spec); } } } public void refreshDailyQuests() { try { this.currentDailyQuests = new ArrayDeque<>( CubeQuest.getInstance().getDatabaseFassade().getDailyQuestData()); } catch (SQLException e) { this.currentDailyQuests = this.currentDailyQuests == null ? new ArrayDeque<>(QuestGenerator.DAYS_TO_KEEP_DAILY_QUESTS) : this.currentDailyQuests; CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not refresh current dailyQuests:", e); } } public List<QuestSpecification> getPossibleQuestsIncludingNulls() { return Collections.unmodifiableList(this.possibleQuests); } public void addPossibleQuest(QuestSpecification qs) { this.possibleQuests.add(qs); if (qs instanceof InteractorProtecting) { CubeQuest.getInstance().addProtecting((InteractorProtecting) qs); } saveConfig(); } public void removePossibleQuest(int index) { QuestSpecification spec = this.possibleQuests.set(index, null); if (spec != null) { if (spec instanceof InteractorProtecting) { CubeQuest.getInstance().removeProtecting((InteractorProtecting) spec); } saveConfig(); } } public void consolidatePossibleQuests() { this.possibleQuests.removeIf(qs -> qs == null); this.possibleQuests.sort(QuestSpecification.COMPARATOR); } public int getQuestsToGenerate() { return this.questsToGenerate; } public void setQuestsToGenerate(int questsToGenerate) { this.questsToGenerate = questsToGenerate; saveConfig(); } public int getQuestsToGenerateOnThisServer() { return this.questsToGenerateOnThisServer; } public void setQuestsToGenerateOnThisServer(int questsToGenerateOnThisServer) { this.questsToGenerateOnThisServer = questsToGenerateOnThisServer; saveConfig(); } public LocalDate getLastGeneratedForDay() { return this.lastGeneratedForDay; } public double getValue(MaterialValueOption o, Material m) { return this.materialValues.get(o).getValue(m); } public void setValue(MaterialValueOption o, Material m, double value) { this.materialValues.get(o).setValue(m, value); saveConfig(); } public double getValue(EntityValueOption o, EntityType t) { return this.entityValues.get(o).getValue(t); } public void setValue(EntityValueOption o, EntityType t, double value) { this.entityValues.get(o).setValue(t, value); saveConfig(); } public void generateDailyQuests() { CubeQuest.getInstance().getLogger().log(Level.INFO, "Starting to generate DailyQuests."); deleteOldDailyQuests(); DailyQuestData dqData; try { int dataId = CubeQuest.getInstance().getDatabaseFassade().reserveNewDailyQuestData(); dqData = new DailyQuestData(dataId, this.questsToGenerate); this.currentDailyQuests.addLast(dqData); } catch (SQLException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not create new DailyQuestData.", e); return; } this.lastGeneratedForDay = LocalDate.now(); this.lastUsedPossibilities = this.currentlyUsedPossibilities; this.currentlyUsedPossibilities = new TreeSet<>(QuestSpecification.SIMILAR_SPECIFICATIONS_COMPARATOR); Random ran; try { ran = new Random(Util.fromBytes(MessageDigest.getInstance("MD5") .digest(Util.byteArray(this.lastGeneratedForDay.toEpochDay())))); } catch (NoSuchAlgorithmException e) { throw new AssertionError(e); } List<String> selectedServers = getServersToGenerateOn(ran, dqData); for (int i = 0; i < this.questsToGenerate; i++) { double difficulty = (this.questsToGenerate > 1 ? 0.1 + i * 0.8 / (this.questsToGenerate - 1) : 0.5) + 0.1 * ran.nextDouble(); String server = selectedServers.get(i); if (server == null) { dailyQuestGenerated(i, generateQuest(i, dqData.getDateString(), difficulty, ran)); } else { delegateDailyQuestGeneration(server, i, dqData, difficulty, ran); } } saveConfig(); } private void deleteOldDailyQuests() { if (!this.currentDailyQuests.isEmpty()) { // DailyQuests von gestern aus QuestGivern austragen for (QuestGiver giver : CubeQuest.getInstance().getDailyQuestGivers()) { for (Quest q : this.currentDailyQuests.getLast().getQuests()) { giver.removeQuest(q); } } for (Quest q : this.currentDailyQuests.getLast().getQuests()) { q.setReady(false); } // Ggf. über eine Woche alte DailyQuests löschen while (this.currentDailyQuests.size() >= DAYS_TO_KEEP_DAILY_QUESTS) { DailyQuestData dqData = this.currentDailyQuests.removeFirst(); try { CubeQuest.getInstance().getDatabaseFassade().deleteDailyQuestData(dqData); } catch (SQLException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not delete DailyQuests " + dqData + ":", e); return; } ByteArrayOutputStream msgbytes = new ByteArrayOutputStream(); DataOutputStream msgout = new DataOutputStream(msgbytes); try { msgout.writeInt(GlobalChatMsgType.DAILY_QUESTS_REMOVED.ordinal()); byte[] msgarry = msgbytes.toByteArray(); CubeQuest.getInstance().getGlobalChatAPI().sendDataToServers("CubeQuest", msgarry); } catch (IOException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "IOException trying to send GlobalChatMessage!", e); return; } // Logge ggf. Fehlermeldungen von Quests, die nicht gelöscht werden können for (Quest q : dqData.getQuests()) { try { QuestManager.getInstance().deleteQuest(q); } catch (QuestDeletionFailedException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not delete DailyQuest " + q + ":", e); } } } } } private List<String> getServersToGenerateOn(Random ran, DailyQuestData dqData) { List<String> selectedServers = new ArrayList<>(); List<String> serversToSelectFrom = new ArrayList<>(); Map<String, Integer> serversToSelectFromWithAmountOfLegalSpecifications; try { serversToSelectFromWithAmountOfLegalSpecifications = CubeQuest.getInstance().getDatabaseFassade().getServersToGenerateDailyQuestOn(); } catch (SQLException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "SQL-Exception while trying to generate daily-quests! No quests generated.", e); return Collections.emptyList(); } serversToSelectFromWithAmountOfLegalSpecifications .remove(CubeQuest.getInstance().getBungeeServerName()); for (String server : serversToSelectFromWithAmountOfLegalSpecifications.keySet()) { for (int i = 0; i < serversToSelectFromWithAmountOfLegalSpecifications .get(server); i++) { serversToSelectFrom.add(server); } } if (serversToSelectFrom.isEmpty()) { serversToSelectFrom.add(null); } else { Collections.sort(serversToSelectFrom); Collections.shuffle(serversToSelectFrom, ran); } for (int i = 0; serversToSelectFrom.size() < this.questsToGenerate - this.questsToGenerateOnThisServer; i++) { serversToSelectFrom.add(serversToSelectFrom.get(i)); } for (int i = 0; i < this.questsToGenerate; i++) { selectedServers.add(i < this.questsToGenerateOnThisServer ? null : serversToSelectFrom.get(i - this.questsToGenerateOnThisServer)); } Collections.shuffle(selectedServers, ran); return selectedServers; } private void delegateDailyQuestGeneration(String server, int questOrdinal, DailyQuestData dqData, double difficulty, Random ran) { try { DelegatedGenerationData data = new DelegatedGenerationData(dqData.getDateString(), questOrdinal, difficulty, ran.nextLong()); CubeQuest.getInstance().getDatabaseFassade().addDelegatedQuestGeneration(server, data); } catch (SQLException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "IOException trying to save DelegatedGenerationData!", e); return; } ByteArrayOutputStream msgbytes = new ByteArrayOutputStream(); DataOutputStream msgout = new DataOutputStream(msgbytes); try { msgout.writeInt(GlobalChatMsgType.GENERATE_DAILY_QUEST.ordinal()); msgout.writeUTF(server); byte[] msgarry = msgbytes.toByteArray(); CubeQuest.getInstance().getGlobalChatAPI().sendDataToServers("CubeQuest", msgarry); } catch (IOException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "IOException trying to send GlobalChatMessage!", e); return; } } public Quest generateQuest(int dailyQuestOrdinal, String dateString, double difficulty, Random ran) { long diff = this.lastGeneratedForDay == null ? Long.MAX_VALUE : (LocalDate.now().toEpochDay() - this.lastGeneratedForDay.toEpochDay()); if (diff > 0) { this.lastGeneratedForDay = LocalDate.now(); this.lastUsedPossibilities = diff == 1 ? this.currentlyUsedPossibilities : new TreeSet<>(QuestSpecification.SIMILAR_SPECIFICATIONS_COMPARATOR); this.currentlyUsedPossibilities = new TreeSet<>(QuestSpecification.SIMILAR_SPECIFICATIONS_COMPARATOR); } if (this.possibleQuests.stream().noneMatch(qs -> qs != null && qs.isLegal())) { CubeQuest.getInstance().getLogger().log(Level.WARNING, "Could not generate a DailyQuest for this server as no QuestSpecifications were specified."); return null; } List<QuestSpecification> qsList = new ArrayList<>(); this.possibleQuests.forEach(qs -> { if (qs != null && qs.isLegal()) { qsList.add(qs); } }); qsList.sort(QuestSpecification.COMPARATOR); List<QuestSpecificationAndDifficultyPair> generatedList = new ArrayList<>(); qsList.forEach(qs -> generatedList.add(new QuestSpecificationAndDifficultyPair(qs, qs.generateQuest(ran) + 0.1 * ran.nextGaussian()))); int weighting = DeliveryQuestSpecification.DeliveryQuestPossibilitiesSpecification .getInstance().getWeighting(); for (int i = 0; i < weighting; i++) { DeliveryQuestSpecification qs = new DeliveryQuestSpecification(); generatedList.add(new QuestSpecificationAndDifficultyPair(qs, qs.generateQuest(ran) + 0.1 * ran.nextGaussian())); } weighting = BlockBreakQuestSpecification.BlockBreakQuestPossibilitiesSpecification .getInstance().getWeighting(); for (int i = 0; i < weighting; i++) { BlockBreakQuestSpecification qs = new BlockBreakQuestSpecification(); generatedList.add(new QuestSpecificationAndDifficultyPair(qs, qs.generateQuest(ran) + 0.1 * ran.nextGaussian())); } weighting = BlockPlaceQuestSpecification.BlockPlaceQuestPossibilitiesSpecification .getInstance().getWeighting(); for (int i = 0; i < weighting; i++) { BlockPlaceQuestSpecification qs = new BlockPlaceQuestSpecification(); generatedList.add(new QuestSpecificationAndDifficultyPair(qs, qs.generateQuest(ran) + 0.1 * ran.nextGaussian())); } weighting = FishingQuestSpecification.FishingQuestPossibilitiesSpecification.getInstance() .getWeighting(); for (int i = 0; i < weighting; i++) { FishingQuestSpecification qs = new FishingQuestSpecification(); generatedList.add(new QuestSpecificationAndDifficultyPair(qs, qs.generateQuest(ran) + 0.1 * ran.nextGaussian())); } weighting = KillEntitiesQuestSpecification.KillEntitiesQuestPossibilitiesSpecification .getInstance().getWeighting(); for (int i = 0; i < weighting; i++) { KillEntitiesQuestSpecification qs = new KillEntitiesQuestSpecification(); generatedList.add(new QuestSpecificationAndDifficultyPair(qs, qs.generateQuest(ran) + 0.1 * ran.nextGaussian())); } generatedList.sort(new QuestSpeficicationBestFitComparator(difficulty, this.currentlyUsedPossibilities, this.lastUsedPossibilities)); generatedList.subList(1, generatedList.size() - 1) .forEach(qsdp -> qsdp.getQuestSpecification().clearGeneratedQuest()); QuestSpecification resultSpecification = generatedList.get(0).getQuestSpecification(); this.currentlyUsedPossibilities.add(resultSpecification); String questName = ChatColor.GOLD + "DailyQuest " + ChatAndTextUtil.toRomanNumber(dailyQuestOrdinal + 1) + " vom " + dateString; Reward reward = generateReward(difficulty, ran); Quest result = resultSpecification.createGeneratedQuest(questName, reward); result.setReady(true); if (!CubeQuest.getInstance().isGeneratingDailyQuests()) { saveConfig(); } return result; } public boolean checkForDelegatedGeneration() { List<DelegatedGenerationData> dataList; try { dataList = CubeQuest.getInstance().getDatabaseFassade().popDelegatedQuestGenerations(); } catch (SQLException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not pop delegated quest generations.", e); return false; } if (dataList.isEmpty()) { return false; } for (DelegatedGenerationData data : dataList) { Quest generated = generateQuest(data.questOrdinal, data.dateString, data.difficulty, new Random(data.ranSeed)); try { ByteArrayOutputStream msgbytes = new ByteArrayOutputStream(); DataOutputStream msgout = new DataOutputStream(msgbytes); msgout.writeInt(GlobalChatMsgType.DAILY_QUEST_GENERATED.ordinal()); msgout.writeInt(data.questOrdinal); msgout.writeInt(generated.getId()); byte[] msgarry = msgbytes.toByteArray(); CubeQuest.getInstance().getGlobalChatAPI().sendDataToServers("CubeQuest", msgarry); } catch (IOException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "IOException trying to send GlobalChatMessage!", e); } } return true; } /** * Generiert die Belohnung für eine DailyQuest * * @param difficulty ignored * @param rewardModifier ignored * @param ran ignored * @return Feste Belohnung (nicht zufällig generiert) aus 1 QuestPoint, 5 XP und 1 Mysteriösen * Zauberbuch */ public Reward generateReward(double difficulty, Random ran) { return new Reward(0, 10, 5, new ItemStack[] {ItemStackUtil.getMysteriousSpellBook()}); } public void dailyQuestGenerated(int dailyQuestOrdinal, Quest generatedQuest) { if (!CubeQuest.getInstance().isGeneratingDailyQuests()) { return; } if (generatedQuest.getSuccessMessage() == null) { generatedQuest.setSuccessMessage(CubeQuest.PLUGIN_TAG + ChatColor.GOLD + " Du hast die " + generatedQuest.getName() + " abgeschlossen!"); } DailyQuestData dqData = this.currentDailyQuests.getLast(); generatedQuest.setVisible(true); dqData.setQuest(dailyQuestOrdinal, Util.addTimeLimit(generatedQuest, dqData.getNextDayDate())); try { dqData.saveToDatabase(); } catch (SQLException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not save DailyQuestData.", e); return; } try { ByteArrayOutputStream msgbytes = new ByteArrayOutputStream(); DataOutputStream msgout = new DataOutputStream(msgbytes); msgout.writeInt(GlobalChatMsgType.DAILY_QUEST_FINISHED.ordinal()); byte[] msgarry = msgbytes.toByteArray(); CubeQuest.getInstance().getGlobalChatAPI().sendDataToServers("CubeQuest", msgarry); } catch (IOException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "IOException trying to send GlobalChatMessage!", e); } if (dqData.getQuests().stream().allMatch(q -> q != null)) { for (QuestGiver giver : CubeQuest.getInstance().getDailyQuestGivers()) { for (Quest q : dqData.getQuests()) { giver.addQuest(q); } } CubeQuest.getInstance().getLogger().log(Level.INFO, "DailyQuests generated."); } } public List<Quest> getTodaysDailyQuests() { DailyQuestData dqData = this.currentDailyQuests.getLast(); return this.currentDailyQuests == null ? null : dqData.getQuests(); } public Collection<Quest> getAllDailyQuests() { Set<Quest> result = new LinkedHashSet<>(); for (DailyQuestData dqData : this.currentDailyQuests) { for (Quest q : dqData.getQuests()) { result.add(q); } } return result; } public int countLegalQuestSecifications() { int i = 0; for (QuestSpecification qs : this.possibleQuests) { if (qs != null && qs.isLegal()) { i++; } } try { CubeQuest.getInstance().getDatabaseFassade().setLegalQuestSpecificationCount(i); } catch (SQLException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not update count of legal QuestSpecificaitons in database.", e); } return i; } public List<BaseComponent[]> getSpecificationInfo() { List<BaseComponent[]> result = new ArrayList<>(); int index = 1; for (QuestSpecification qs : this.possibleQuests) { if (qs != null) { ClickEvent clickEvent = new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/quest removeQuestSpecification " + index); HoverEvent hoverEvent = new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder("Spezifikation an Index " + index + " entfernen.") .create()); result.add(new ComponentBuilder(index + ": ").append(qs.getSpecificationInfo()) .append(" ").append("[Löschen]").color(ChatColor.RED).event(clickEvent) .event(hoverEvent).create()); } index++; } return result; } public List<BaseComponent[]> getDeliveryReceiverSpecificationInfo() { return DeliveryQuestSpecification.DeliveryQuestPossibilitiesSpecification.getInstance() .getReceiverSpecificationInfo(); } public List<BaseComponent[]> getDeliveryContentSpecificationInfo() { return DeliveryQuestSpecification.DeliveryQuestPossibilitiesSpecification.getInstance() .getContentSpecificationInfo(); } public List<BaseComponent[]> getBlockBreakSpecificationInfo() { return BlockBreakQuestSpecification.BlockBreakQuestPossibilitiesSpecification.getInstance() .getSpecificationInfo(); } public List<BaseComponent[]> getBlockPlaceSpecificationInfo() { return BlockPlaceQuestSpecification.BlockPlaceQuestPossibilitiesSpecification.getInstance() .getSpecificationInfo(); } public List<BaseComponent[]> getFishingSpecificationInfo() { return FishingQuestSpecification.FishingQuestPossibilitiesSpecification.getInstance() .getSpecificationInfo(); } public List<BaseComponent[]> getKillEntitiesSpecificationInfo() { return KillEntitiesQuestSpecification.KillEntitiesQuestPossibilitiesSpecification .getInstance().getSpecificationInfo(); } @Override public Map<String, Object> serialize() { Map<String, Object> result = new HashMap<>(); result.put("questsToGenerate", this.questsToGenerate); result.put("questsToGenerateOnThisServer", this.questsToGenerateOnThisServer); List<QuestSpecification> possibleQSList = new ArrayList<>(this.possibleQuests); possibleQSList.removeIf(qs -> qs == null); possibleQSList.sort(QuestSpecification.COMPARATOR); result.put("possibleQuests", possibleQSList); List<QuestSpecification> lastUsedQSList = new ArrayList<>(this.lastUsedPossibilities); result.put("lastUsedPossibilities", lastUsedQSList); List<QuestSpecification> currentlyUsedQSList = new ArrayList<>(this.currentlyUsedPossibilities); result.put("currentlyUsedPossibilities", currentlyUsedQSList); result.put("deliveryQuestSpecifications", DeliveryQuestSpecification.DeliveryQuestPossibilitiesSpecification.getInstance() .serialize()); result.put("blockBreakQuestSpecifications", BlockBreakQuestSpecification.BlockBreakQuestPossibilitiesSpecification.getInstance() .serialize()); result.put("blockPlaceQuestSpecifications", BlockPlaceQuestSpecification.BlockPlaceQuestPossibilitiesSpecification.getInstance() .serialize()); result.put("fishingQuestSpecifications", FishingQuestSpecification.FishingQuestPossibilitiesSpecification.getInstance() .serialize()); result.put("killEntitiesQuestSpecifications", KillEntitiesQuestSpecification.KillEntitiesQuestPossibilitiesSpecification .getInstance().serialize()); result.put("materialValues", Util.serializedEnumMap(this.materialValues)); result.put("entityValues", Util.serializedEnumMap(this.entityValues)); result.put("lastGeneratedForDay", this.lastGeneratedForDay == null ? null : this.lastGeneratedForDay.toEpochDay()); return result; } public void saveConfig() { countLegalQuestSecifications(); CubeQuest.getInstance().getDataFolder().mkdirs(); File configFile = new File(CubeQuest.getInstance().getDataFolder(), "generator.yml"); YamlConfiguration config = new YamlConfiguration(); config.set("generator", this); try { config.save(configFile); } catch (IOException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not save QuestGenerator.", e); } } }
Adjust javadoc for generateReward.
src/main/java/de/iani/cubequest/generation/QuestGenerator.java
Adjust javadoc for generateReward.
Java
bsd-3-clause
3afde6a1b223592f3928f1e9fde13c5661a11d8b
0
NCIP/cananolab,NCIP/cananolab,NCIP/cananolab
package gov.nih.nci.calab.service.workflow; import gov.nih.nci.calab.db.DataAccessProxy; import gov.nih.nci.calab.db.IDataAccess; import gov.nih.nci.calab.domain.Aliquot; import gov.nih.nci.calab.domain.Assay; import gov.nih.nci.calab.domain.Run; import gov.nih.nci.calab.domain.RunSampleContainer; import gov.nih.nci.calab.domain.StorageElement; import gov.nih.nci.calab.dto.administration.AliquotBean; import gov.nih.nci.calab.dto.administration.ContainerBean; import gov.nih.nci.calab.dto.administration.StorageLocation; import gov.nih.nci.calab.dto.workflow.AssayBean; import gov.nih.nci.calab.dto.workflow.ExecuteWorkflowBean; import gov.nih.nci.calab.service.util.CalabConstants; import gov.nih.nci.calab.service.util.StringUtils; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.apache.log4j.Logger; public class ExecuteWorkflowService { private static Logger logger = Logger.getLogger(ExecuteWorkflowService.class); /** * Retrieve assays by assayType * * @return a list of all assays in certain type */ public List<AssayBean> getAssayByType(String assayTypeName) { // Detail here List<AssayBean> assays = new ArrayList<AssayBean>(); try { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); ida.open(); String hqlString = "select assay.id, assay.name, assay.type from Assay assay where assay.assayType ='" + assayTypeName + "'"; List results = ida.search(hqlString); for (Object obj : results) { Object[] objArray = (Object[])obj; assays.add(new AssayBean((String)objArray[0], (String)objArray[1], (String)objArray[2])); } ida.close(); } catch (Exception e) { logger.error("Error in retrieving assay by assayType -- " + assayTypeName, e); throw new RuntimeException("Error in retrieving assay by assayType -- " + assayTypeName); } return assays; } /** * Save the aliquot IDs to be associated with the given run ID. * * @param runId * @param aliquotIds * @throws Exception */ public void saveRunAliquots(String runId, String[] aliquotIds, String comments, String creator, String creationDate) throws Exception { // TODO: Would be helpful if the aliquot ID are the primary key and Run ID is the primary key try { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); ida.open(); //load run object logger.debug("ExecuteWorkflowService.saveRunAliquots(): run id = " + runId); Run doRun = (Run)ida.load(Run.class, StringUtils.convertToLong(runId)); // Create RunSampleContainer collection for (int i=0;i<aliquotIds.length;i++) { // check if the aliquot has been assigned to the run, if it is, skip it String hqlString ="select count(runcontainer.id)from RunSampleContainer runcontiner where runcontainer.run.id='" + runId + "' and runcontainer.sampleContainer.id='" + aliquotIds[i] + "'"; List results = ida.search(hqlString); if (((Integer)results.get(0)).intValue() > 0) { logger.debug("The aliquot id " + aliquotIds[i] + " is already assigned to this run, continue .... " ); continue; } RunSampleContainer doRunSC = new RunSampleContainer(); doRunSC.setComments(comments); doRunSC.setRun(doRun); logger.debug("ExecuteWorkflowService.saveRunAliquots(): aliquot id = " + aliquotIds[i]); Aliquot doAliquot = (Aliquot)ida.load(Aliquot.class, StringUtils.convertToLong(aliquotIds[i])); logger.debug("ExecuteWorkflowService.saveRunAliquots(): doAliquot = " + doAliquot); doRunSC.setSampleContainer(doAliquot); doRunSC.setCreatedBy(creator); doRunSC.setCreatedDate(StringUtils.convertToDate(creationDate, CalabConstants.DATE_FORMAT)); ida.createObject(doRunSC); } ida.close(); } catch (Exception e) { logger.error("Error in saving Run Aliquot ", e); throw new RuntimeException("Error in saving Run Aliquot "); } } public AliquotBean getAliquot(String aliquotId) { AliquotBean aliquotBean = null; try { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); ida.open(); String hqlString = "from Aliquot aliquot where aliquot.id ='" + aliquotId+ "'"; List results = ida.search(hqlString); for (Object obj : results) { Aliquot doAliquot = (Aliquot) obj; aliquotBean.setAliquotId(aliquotId); // name aliquotBean.setCreationDate(StringUtils.convertDateToString(doAliquot.getCreatedDate(), CalabConstants.DATE_FORMAT)); aliquotBean.setCreator(doAliquot.getCreatedBy()); aliquotBean.setHowCreated(doAliquot.getCreatedMethod()); // ContainerBean ContainerBean containerBean = new ContainerBean(); containerBean.setConcentration(doAliquot.getConcentration().toString()); containerBean.setConcentrationUnit(doAliquot.getConcentrationUnit()); containerBean.setContainerComments(doAliquot.getComments()); containerBean.setContainerType(doAliquot.getContainerType()); containerBean.setQuantity(doAliquot.getQuantity().toString()); containerBean.setQuantityUnit(doAliquot.getQuantityUnit()); containerBean.setSafetyPrecaution(doAliquot.getSafetyPrecaution()); containerBean.setSolvent(doAliquot.getDiluentsSolvent()); containerBean.setStorageCondition(doAliquot.getStorageCondition()); containerBean.setVolume(doAliquot.getVolume().toString()); containerBean.setVolumeUnit(doAliquot.getVolumeUnit()); // containerBean.setStorageLocationStr(); StorageLocation location = new StorageLocation(); Set storageElements = (Set)doAliquot.getStorageElementCollection(); for(Object storageObj: storageElements) { StorageElement element = (StorageElement)storageObj; if (element.getType().equals(CalabConstants.STORAGE_ROOM)) { location.setRoom(element.getLocation()); } else if (element.getType().equals(CalabConstants.STORAGE_FREEZER)) { location.setFreezer(element.getLocation()); } else if (element.getType().equals(CalabConstants.STORAGE_SHELF)) { location.setShelf(element.getLocation()); } else if (element.getType().equals(CalabConstants.STORAGE_BOX)) { location.setBox(element.getLocation()); } else if (element.getType().equals(CalabConstants.STORAGE_RACK)) { location.setRack(element.getLocation()); } else if (element.getType().equals(CalabConstants.STORAGE_LAB)) { location.setLab(element.getLocation()); } } containerBean.setStorageLocation(location); aliquotBean.setContainer(containerBean); } ida.close(); } catch (Exception e) { logger.error("Error in retrieving aliquot information with name -- " + aliquotId, e); throw new RuntimeException("Error in retrieving aliquot information with name -- " + aliquotId); } return aliquotBean; } /** * Save the aliquot IDs to be associated with the given run ID. * @param assayId * @param runBy * @param runDate * @param createdBy * @param createdDate * @throws Exception */ public String saveRun(String assayId, String runBy, String runDate,String createdBy, String createdDate ) throws Exception { // Details of Saving to RUN Table Long runId; // Run Id is the primary key of the saved Run IDataAccess ida = (new DataAccessProxy()).getInstance(IDataAccess.HIBERNATE); logger.debug("ExecuteWorkflowService.saveRun(): assayId = " + assayId); try { ida.open(); Run doRun = new Run(); // Retrieve the max sequence number for assay run String runName = CalabConstants.RUN + (getLastAssayRunNum(ida,assayId)+1); logger.debug("ExecuteWorkflowService.saveRun(): new run name = " + runName); doRun.setName(runName); doRun.setCreatedBy(createdBy); doRun.setCreatedDate(StringUtils.convertToDate(createdDate, CalabConstants.DATE_FORMAT)); doRun.setRunBy(runBy); doRun.setRunDate(StringUtils.convertToDate(runDate, CalabConstants.DATE_FORMAT)); doRun.setAssay((Assay)ida.load(Assay.class, StringUtils.convertToLong(assayId))); runId = (Long)ida.createObject(doRun); ida.close(); } catch (Exception e) { e.printStackTrace(); ida.rollback(); ida.close(); logger.error("Error in creating Run for assay. ", e); throw new RuntimeException("Error in creating Run for assay. "); } return runId.toString(); } private int getLastAssayRunNum(IDataAccess ida, String assayId) { int runNum = 0; try { String hqlString = "select run.name from Run run join run.assay assay where assay.id='" + assayId + "'"; List results = ida.search(hqlString); for (Object obj : results) { String runName = (String)obj; int runSeqNum = Integer.parseInt(runName.substring(CalabConstants.RUN.length()).trim()); if (runSeqNum > runNum) { runNum = runSeqNum; } } } catch (Exception e) { logger.error("Error in retrieving the last aliquot child aliquot number",e); throw new RuntimeException( "Error in retrieving the last aliquot child aliquot number"); } return runNum; } public ExecuteWorkflowBean getFileInfoForRunId(String runId) throws Exception { //TODO fill in details for saving RUN INFO for the run return null; } /** * Save the aliquot IDs to be associated with the given run ID. * @param fileURI * @param fileName * @param runId * @throws Exception */ public void saveFileInfo(String fileURI, String fileName, String runId) throws Exception { //TODO fill in details for saving RUN INFO for the run } /** * Get the File information for the given Run Id. * @param runId * @throws Exception */ public ExecuteWorkflowBean getAllWorkflows() throws Exception { //TODO fill in details for saving RUN INFO for the run return null; } }
src/gov/nih/nci/calab/service/workflow/ExecuteWorkflowService.java
package gov.nih.nci.calab.service.workflow; import gov.nih.nci.calab.db.DataAccessProxy; import gov.nih.nci.calab.db.IDataAccess; import gov.nih.nci.calab.domain.Aliquot; import gov.nih.nci.calab.domain.Run; import gov.nih.nci.calab.domain.RunSampleContainer; import gov.nih.nci.calab.domain.StorageElement; import gov.nih.nci.calab.dto.administration.AliquotBean; import gov.nih.nci.calab.dto.administration.ContainerBean; import gov.nih.nci.calab.dto.administration.StorageLocation; import gov.nih.nci.calab.dto.workflow.ExecuteWorkflowBean; import gov.nih.nci.calab.service.util.CalabConstants; import gov.nih.nci.calab.service.util.StringUtils; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.apache.log4j.Logger; public class ExecuteWorkflowService { private static Logger logger = Logger.getLogger(ExecuteWorkflowService.class); /** * Save the aliquot IDs to be associated with the given run ID. * * @param runId * @param aliquotIds * @throws Exception */ public void saveRunAliquots(String runId, String[] aliquotIds, String comments, String creator, String creationDate) throws Exception { // TODO: Would be helpful if the aliquot ID are the primary key and Run ID is the primary key try { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); ida.open(); //load run object Run doRun = (Run)ida.load(Run.class, StringUtils.convertToLong(runId)); // Create RunSampleContainer collection for (int i=0;i<aliquotIds.length;i++) { RunSampleContainer doRunSC = new RunSampleContainer(); doRunSC.setComments(comments); doRunSC.setRun(doRun); doRunSC.setSampleContainer((Aliquot)ida.load(Aliquot.class, StringUtils.convertToLong(aliquotIds[i]))); doRunSC.setCreatedBy(creator); doRunSC.setCreatedDate(StringUtils.convertToDate(creationDate, CalabConstants.DATE_FORMAT)); ida.createObject(doRunSC); } ida.close(); } catch (Exception e) { logger.error("Error in saving Run Aliquot ", e); throw new RuntimeException("Error in saving Run Aliquot "); } } public AliquotBean getAliquot(String aliquotId) { AliquotBean aliquotBean = null; try { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); ida.open(); String hqlString = "from Aliquot aliquot where aliquot.id ='" + aliquotId+ "'"; List results = ida.search(hqlString); for (Object obj : results) { Aliquot doAliquot = (Aliquot) obj; aliquotBean.setAliquotId(aliquotId); // name aliquotBean.setCreationDate(StringUtils.convertDateToString(doAliquot.getCreatedDate(), CalabConstants.DATE_FORMAT)); aliquotBean.setCreator(doAliquot.getCreatedBy()); aliquotBean.setHowCreated(doAliquot.getCreatedMethod()); // ContainerBean ContainerBean containerBean = new ContainerBean(); containerBean.setConcentration(doAliquot.getConcentration().toString()); containerBean.setConcentrationUnit(doAliquot.getConcentrationUnit()); containerBean.setContainerComments(doAliquot.getComments()); containerBean.setContainerType(doAliquot.getContainerType()); containerBean.setQuantity(doAliquot.getQuantity().toString()); containerBean.setQuantityUnit(doAliquot.getQuantityUnit()); containerBean.setSafetyPrecaution(doAliquot.getSafetyPrecaution()); containerBean.setSolvent(doAliquot.getDiluentsSolvent()); containerBean.setStorageCondition(doAliquot.getStorageCondition()); containerBean.setVolume(doAliquot.getVolume().toString()); containerBean.setVolumeUnit(doAliquot.getVolumeUnit()); // containerBean.setStorageLocationStr(); StorageLocation location = new StorageLocation(); Set storageElements = (Set)doAliquot.getStorageElementCollection(); for(Object storageObj: storageElements) { StorageElement element = (StorageElement)storageObj; if (element.getType().equals(CalabConstants.STORAGE_ROOM)) { location.setRoom(element.getLocation()); } else if (element.getType().equals(CalabConstants.STORAGE_FREEZER)) { location.setFreezer(element.getLocation()); } else if (element.getType().equals(CalabConstants.STORAGE_SHELF)) { location.setShelf(element.getLocation()); } else if (element.getType().equals(CalabConstants.STORAGE_BOX)) { location.setBox(element.getLocation()); } else if (element.getType().equals(CalabConstants.STORAGE_RACK)) { location.setRack(element.getLocation()); } else if (element.getType().equals(CalabConstants.STORAGE_LAB)) { location.setLab(element.getLocation()); } } containerBean.setStorageLocation(location); aliquotBean.setContainer(containerBean); } ida.close(); } catch (Exception e) { logger.error("Error in retrieving aliquot information with name -- " + aliquotId, e); throw new RuntimeException("Error in retrieving aliquot information with name -- " + aliquotId); } return aliquotBean; } /** * Save the aliquot IDs to be associated with the given run ID. * @param assayId * @param runBy * @param runDate * @param createdBy * @param createdDate * @throws Exception */ public String saveRun(String assayId, String runBy, String runDate,String createdBy, String createdDate ) throws Exception { // Details of Saving to RUN Table String runId; runId= "1"; // Run Id is the primary key of the saved Run return runId; } public ExecuteWorkflowBean getFileInfoForRunId(String runId) throws Exception { //TODO fill in details for saving RUN INFO for the run return null; } /** * Save the aliquot IDs to be associated with the given run ID. * @param fileURI * @param fileName * @param runId * @throws Exception */ public void saveFileInfo(String fileURI, String[] fileName, String runId) throws Exception { //TODO fill in details for saving RUN INFO for the run } /** * Get the File information for the given Run Id. * @param runId * @throws Exception */ public ExecuteWorkflowBean getAllWorkflows() throws Exception { //TODO fill in details for saving RUN INFO for the run return null; } }
Added getAssayByType(String), updated saveRunAlqiuot() and saveRun() SVN-Revision: 7347
src/gov/nih/nci/calab/service/workflow/ExecuteWorkflowService.java
Added getAssayByType(String), updated saveRunAlqiuot() and saveRun()
Java
isc
dbfa60f4a855b2cb33e52735f02ce14c7da6befa
0
TealCube/loot
package info.faceland.loot; import info.faceland.api.FacePlugin; import info.faceland.facecore.shade.command.CommandHandler; import info.faceland.facecore.shade.nun.ivory.config.VersionedIvoryConfiguration; import info.faceland.facecore.shade.nun.ivory.config.VersionedIvoryYamlConfiguration; import info.faceland.facecore.shade.nun.ivory.config.settings.IvorySettings; import info.faceland.loot.api.groups.ItemGroup; import info.faceland.loot.api.items.CustomItem; import info.faceland.loot.api.items.CustomItemBuilder; import info.faceland.loot.api.items.ItemBuilder; import info.faceland.loot.api.managers.CreatureModManager; import info.faceland.loot.api.managers.CustomItemManager; import info.faceland.loot.api.managers.ItemGroupManager; import info.faceland.loot.api.managers.NameManager; import info.faceland.loot.api.managers.SocketGemManager; import info.faceland.loot.api.managers.TierManager; import info.faceland.loot.api.sockets.SocketGem; import info.faceland.loot.api.sockets.SocketGemBuilder; import info.faceland.loot.api.sockets.effects.SocketEffect; import info.faceland.loot.api.tier.Tier; import info.faceland.loot.api.tier.TierBuilder; import info.faceland.loot.commands.LootCommand; import info.faceland.loot.groups.LootItemGroup; import info.faceland.loot.io.SmartTextFile; import info.faceland.loot.items.LootCustomItemBuilder; import info.faceland.loot.items.LootItemBuilder; import info.faceland.loot.listeners.spawning.EntityDeathListener; import info.faceland.loot.managers.LootCustomItemManager; import info.faceland.loot.managers.LootItemGroupManager; import info.faceland.loot.managers.LootNameManager; import info.faceland.loot.managers.LootSocketGemManager; import info.faceland.loot.managers.LootTierManager; import info.faceland.loot.sockets.LootSocketGemBuilder; import info.faceland.loot.sockets.effects.LootSocketPotionEffect; import info.faceland.loot.tier.LootTierBuilder; import info.faceland.loot.utils.converters.StringConverter; import info.faceland.utils.TextUtils; import net.nunnerycode.java.libraries.cannonball.DebugPrinter; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.event.HandlerList; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; public final class LootPlugin extends FacePlugin { private DebugPrinter debugPrinter; private VersionedIvoryYamlConfiguration itemsYAML; private VersionedIvoryYamlConfiguration tierYAML; private VersionedIvoryYamlConfiguration corestatsYAML; private VersionedIvoryYamlConfiguration customItemsYAML; private VersionedIvoryYamlConfiguration socketGemsYAML; private VersionedIvoryYamlConfiguration languageYAML; private VersionedIvoryYamlConfiguration configYAML; private VersionedIvoryYamlConfiguration creaturesYAML; private IvorySettings settings; private ItemGroupManager itemGroupManager; private TierManager tierManager; private NameManager nameManager; private CustomItemManager customItemManager; private SocketGemManager socketGemManager; private CreatureModManager creatureModManager; @Override public void preEnable() { debugPrinter = new DebugPrinter(getDataFolder().getPath(), "debug.log"); itemsYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "items.yml"), getResource("items.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (itemsYAML.update()) { getLogger().info("Updating items.yml"); debug("Updating items.yml"); } tierYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "tier.yml"), getResource("tier.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (tierYAML.update()) { getLogger().info("Updating tier.yml"); debug("Updating tier.yml"); } corestatsYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "corestats.yml"), getResource("corestats.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (corestatsYAML.update()) { getLogger().info("Updating corestats.yml"); debug("Updating corestats.yml"); } customItemsYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "customItems.yml"), getResource("customItems.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (customItemsYAML.update()) { getLogger().info("Updating customItems.yml"); debug("Updating customItems.yml"); } socketGemsYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "socketGems.yml"), getResource("socketGems.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (socketGemsYAML.update()) { getLogger().info("Updating socketGems.yml"); debug("Updating socketGems.yml"); } languageYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "language.yml"), getResource("language.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (languageYAML.update()) { getLogger().info("Updating language.yml"); debug("Updating language.yml"); } configYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "config.yml"), getResource("config.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (configYAML.update()) { getLogger().info("Updating config.yml"); debug("Updating config.yml"); } creaturesYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "creatures.yml"), getResource("creatures.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (creaturesYAML.update()) { getLogger().info("Updating creatures.yml"); debug("Updating creatures.yml"); } settings = IvorySettings.loadFromFiles(corestatsYAML, languageYAML, configYAML); itemGroupManager = new LootItemGroupManager(); tierManager = new LootTierManager(); nameManager = new LootNameManager(); customItemManager = new LootCustomItemManager(); socketGemManager = new LootSocketGemManager(); } @Override public void enable() { loadItemGroups(); loadTiers(); loadNames(); loadCustomItems(); loadSocketGems(); } private void loadSocketGems() { for (SocketGem sg : getSocketGemManager().getSocketGems()) { getSocketGemManager().removeSocketGem(sg.getName()); } Set<SocketGem> gems = new HashSet<>(); List<String> loadedSocketGems = new ArrayList<>(); for (String key : socketGemsYAML.getKeys(false)) { if (!socketGemsYAML.isConfigurationSection(key)) { continue; } ConfigurationSection cs = socketGemsYAML.getConfigurationSection(key); SocketGemBuilder builder = getNewSocketGemBuilder(key); builder.withPrefix(cs.getString("prefix")); builder.withSuffix(cs.getString("suffix")); builder.withLore(cs.getStringList("lore")); builder.withWeight(cs.getDouble("weight")); List<SocketEffect> effects = new ArrayList<>(); for (String eff : cs.getStringList("effects")) { effects.add(LootSocketPotionEffect.parseString(eff)); } builder.withSocketEffects(effects); builder.withItemGroup(itemGroupManager.getItemGroup(cs.getString("item-group"))); SocketGem gem = builder.build(); gems.add(gem); loadedSocketGems.add(gem.getName()); } for (SocketGem sg : gems) { getSocketGemManager().addSocketGem(sg); } debug("Loaded socket gems: " + loadedSocketGems.toString()); } @Override public void postEnable() { CommandHandler handler = new CommandHandler(this); handler.registerCommands(new LootCommand(this)); Bukkit.getPluginManager().registerEvents(new EntityDeathListener(this), this); //Bukkit.getPluginManager().registerEvents(new LoginListener(this), this); debug("v" + getDescription().getVersion() + " enabled"); } @Override public void preDisable() { HandlerList.unregisterAll(this); } @Override public void disable() { } @Override public void postDisable() { socketGemManager = null; customItemManager = null; nameManager = null; tierManager = null; itemGroupManager = null; settings = null; creaturesYAML = null; configYAML = null; languageYAML = null; customItemsYAML = null; corestatsYAML = null; tierYAML = null; itemsYAML = null; debugPrinter = null; } public void debug(String... messages) { debug(Level.INFO, messages); } public void debug(Level level, String... messages) { if (debugPrinter != null) { debugPrinter.debug(level, messages); } } private void loadCustomItems() { for (CustomItem ci : getCustomItemManager().getCustomItems()) { getCustomItemManager().removeCustomItem(ci.getName()); } Set<CustomItem> customItems = new HashSet<>(); List<String> loaded = new ArrayList<>(); for (String key : customItemsYAML.getKeys(false)) { if (!customItemsYAML.isConfigurationSection(key)) { continue; } ConfigurationSection cs = customItemsYAML.getConfigurationSection(key); CustomItemBuilder builder = getNewCustomItemBuilder(key); builder.withMaterial(StringConverter.toMaterial(cs.getString("material"))); builder.withDisplayName(cs.getString("display-name")); builder.withLore(cs.getStringList("lore")); CustomItem ci = builder.build(); customItems.add(ci); loaded.add(ci.getName()); } for (CustomItem ci : customItems) { getCustomItemManager().addCustomItem(ci); } debug("Loaded custom items: " + loaded.toString()); } private void loadNames() { for (String s : getNameManager().getPrefixes()) { getNameManager().removePrefix(s); } for (String s : getNameManager().getSuffixes()) { getNameManager().removeSuffix(s); } File prefixFile = new File(getDataFolder(), "prefix.txt"); File suffixFile = new File(getDataFolder(), "suffix.txt"); SmartTextFile.writeToFile(getResource("prefix.txt"), prefixFile, true); SmartTextFile.writeToFile(getResource("suffix.txt"), suffixFile, true); SmartTextFile smartPrefixFile = new SmartTextFile(prefixFile); SmartTextFile smartSuffixFile = new SmartTextFile(suffixFile); for (String s : smartPrefixFile.read()) { getNameManager().addPrefix(s); } for (String s : smartSuffixFile.read()) { getNameManager().addSuffix(s); } debug("Loaded prefixes: " + getNameManager().getPrefixes().size(), "Loaded suffixes: " + getNameManager() .getSuffixes().size()); } private void loadItemGroups() { for (ItemGroup ig : getItemGroupManager().getItemGroups()) { getItemGroupManager().removeItemGroup(ig.getName()); } Set<ItemGroup> itemGroups = new HashSet<>(); List<String> loadedItemGroups = new ArrayList<>(); for (String key : itemsYAML.getKeys(false)) { if (!itemsYAML.isList(key)) { continue; } List<String> list = itemsYAML.getStringList(key); ItemGroup ig = new LootItemGroup(key, false); for (String s : list) { Material m = StringConverter.toMaterial(s); if (m == Material.AIR) { continue; } ig.addMaterial(m); } itemGroups.add(ig); loadedItemGroups.add(key); } for (ItemGroup ig : itemGroups) { getItemGroupManager().addItemGroup(ig); } debug("Loaded item groups: " + loadedItemGroups.toString()); } private void loadTiers() { for (Tier t : getTierManager().getLoadedTiers()) { getTierManager().removeTier(t.getName()); } Set<Tier> tiers = new HashSet<>(); List<String> loadedTiers = new ArrayList<>(); for (String key : tierYAML.getKeys(false)) { if (!tierYAML.isConfigurationSection(key)) { continue; } ConfigurationSection cs = tierYAML.getConfigurationSection(key); TierBuilder builder = getNewTierBuilder(key); builder.withDisplayName(cs.getString("display-name")); builder.withDisplayColor(TextUtils.convertTag(cs.getString("display-color"))); builder.withIdentificationColor(TextUtils.convertTag(cs.getString("identification-color"))); builder.withSpawnWeight(cs.getDouble("spawn-weight")); builder.withIdentifyWeight(cs.getDouble("identify-weight")); builder.withDistanceWeight(cs.getDouble("distance-weight")); builder.withMinimumSockets(cs.getInt("minimum-sockets")); builder.withMaximumSockets(cs.getInt("maximum-sockets")); builder.withMinimumBonusLore(cs.getInt("minimum-bonus-lore")); builder.withMaximumBonusLore(cs.getInt("maximum-bonus-lore")); builder.withBaseLore(cs.getStringList("base-lore")); builder.withBonusLore(cs.getStringList("bonus-lore")); List<String> sl = cs.getStringList("item-groups"); Set<ItemGroup> itemGroups = new HashSet<>(); for (String s : sl) { ItemGroup ig; if (s.startsWith("-")) { ig = getItemGroupManager().getItemGroup(s.substring(1)); if (ig == null) { continue; } ig = ig.getInverse(); } else { ig = getItemGroupManager().getItemGroup(s); if (ig == null) { continue; } } itemGroups.add(ig.getInverse()); } builder.withItemGroups(itemGroups); builder.withMinimumDurability(cs.getDouble("minimum-durability")); builder.withMaximumDurability(cs.getDouble("maximum-durability")); Tier t = builder.build(); loadedTiers.add(t.getName()); tiers.add(t); } for (Tier t : tiers) { getTierManager().addTier(t); } debug("Loaded tiers: " + loadedTiers.toString()); } public TierBuilder getNewTierBuilder(String name) { return new LootTierBuilder(name); } public ItemBuilder getNewItemBuilder() { return new LootItemBuilder(this); } public CustomItemBuilder getNewCustomItemBuilder(String name) { return new LootCustomItemBuilder(name); } public SocketGemBuilder getNewSocketGemBuilder(String name) { return new LootSocketGemBuilder(name); } public TierManager getTierManager() { return tierManager; } public ItemGroupManager getItemGroupManager() { return itemGroupManager; } public NameManager getNameManager() { return nameManager; } public IvorySettings getSettings() { return settings; } public CustomItemManager getCustomItemManager() { return customItemManager; } public SocketGemManager getSocketGemManager() { return socketGemManager; } public CreatureModManager getCreatureModManager() { return creatureModManager; } }
src/main/java/info/faceland/loot/LootPlugin.java
package info.faceland.loot; import info.faceland.api.FacePlugin; import info.faceland.facecore.shade.command.CommandHandler; import info.faceland.facecore.shade.nun.ivory.config.VersionedIvoryConfiguration; import info.faceland.facecore.shade.nun.ivory.config.VersionedIvoryYamlConfiguration; import info.faceland.facecore.shade.nun.ivory.config.settings.IvorySettings; import info.faceland.loot.api.groups.ItemGroup; import info.faceland.loot.api.items.CustomItem; import info.faceland.loot.api.items.CustomItemBuilder; import info.faceland.loot.api.items.ItemBuilder; import info.faceland.loot.api.managers.CustomItemManager; import info.faceland.loot.api.managers.ItemGroupManager; import info.faceland.loot.api.managers.NameManager; import info.faceland.loot.api.managers.SocketGemManager; import info.faceland.loot.api.managers.TierManager; import info.faceland.loot.api.sockets.SocketGem; import info.faceland.loot.api.sockets.SocketGemBuilder; import info.faceland.loot.api.sockets.effects.SocketEffect; import info.faceland.loot.api.tier.Tier; import info.faceland.loot.api.tier.TierBuilder; import info.faceland.loot.commands.LootCommand; import info.faceland.loot.groups.LootItemGroup; import info.faceland.loot.io.SmartTextFile; import info.faceland.loot.items.LootCustomItemBuilder; import info.faceland.loot.items.LootItemBuilder; import info.faceland.loot.listeners.spawning.EntityDeathListener; import info.faceland.loot.managers.LootCustomItemManager; import info.faceland.loot.managers.LootItemGroupManager; import info.faceland.loot.managers.LootNameManager; import info.faceland.loot.managers.LootSocketGemManager; import info.faceland.loot.managers.LootTierManager; import info.faceland.loot.sockets.LootSocketGemBuilder; import info.faceland.loot.sockets.effects.LootSocketPotionEffect; import info.faceland.loot.tier.LootTierBuilder; import info.faceland.loot.utils.converters.StringConverter; import info.faceland.utils.TextUtils; import net.nunnerycode.java.libraries.cannonball.DebugPrinter; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.event.HandlerList; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; public final class LootPlugin extends FacePlugin { private DebugPrinter debugPrinter; private VersionedIvoryYamlConfiguration itemsYAML; private VersionedIvoryYamlConfiguration tierYAML; private VersionedIvoryYamlConfiguration corestatsYAML; private VersionedIvoryYamlConfiguration customItemsYAML; private VersionedIvoryYamlConfiguration socketGemsYAML; private VersionedIvoryYamlConfiguration languageYAML; private VersionedIvoryYamlConfiguration configYAML; private VersionedIvoryYamlConfiguration creaturesYAML; private IvorySettings settings; private ItemGroupManager itemGroupManager; private TierManager tierManager; private NameManager nameManager; private CustomItemManager customItemManager; private SocketGemManager socketGemManager; @Override public void preEnable() { debugPrinter = new DebugPrinter(getDataFolder().getPath(), "debug.log"); itemsYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "items.yml"), getResource("items.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (itemsYAML.update()) { getLogger().info("Updating items.yml"); debug("Updating items.yml"); } tierYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "tier.yml"), getResource("tier.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (tierYAML.update()) { getLogger().info("Updating tier.yml"); debug("Updating tier.yml"); } corestatsYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "corestats.yml"), getResource("corestats.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (corestatsYAML.update()) { getLogger().info("Updating corestats.yml"); debug("Updating corestats.yml"); } customItemsYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "customItems.yml"), getResource("customItems.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (customItemsYAML.update()) { getLogger().info("Updating customItems.yml"); debug("Updating customItems.yml"); } socketGemsYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "socketGems.yml"), getResource("socketGems.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (socketGemsYAML.update()) { getLogger().info("Updating socketGems.yml"); debug("Updating socketGems.yml"); } languageYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "language.yml"), getResource("language.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (languageYAML.update()) { getLogger().info("Updating language.yml"); debug("Updating language.yml"); } configYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "config.yml"), getResource("config.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (configYAML.update()) { getLogger().info("Updating config.yml"); debug("Updating config.yml"); } creaturesYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "creatures.yml"), getResource("creatures.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (creaturesYAML.update()) { getLogger().info("Updating creatures.yml"); debug("Updating creatures.yml"); } settings = IvorySettings.loadFromFiles(corestatsYAML, languageYAML, configYAML); itemGroupManager = new LootItemGroupManager(); tierManager = new LootTierManager(); nameManager = new LootNameManager(); customItemManager = new LootCustomItemManager(); socketGemManager = new LootSocketGemManager(); } @Override public void enable() { loadItemGroups(); loadTiers(); loadNames(); loadCustomItems(); loadSocketGems(); } private void loadSocketGems() { for (SocketGem sg : getSocketGemManager().getSocketGems()) { getSocketGemManager().removeSocketGem(sg.getName()); } Set<SocketGem> gems = new HashSet<>(); List<String> loadedSocketGems = new ArrayList<>(); for (String key : socketGemsYAML.getKeys(false)) { if (!socketGemsYAML.isConfigurationSection(key)) { continue; } ConfigurationSection cs = socketGemsYAML.getConfigurationSection(key); SocketGemBuilder builder = getNewSocketGemBuilder(key); builder.withPrefix(cs.getString("prefix")); builder.withSuffix(cs.getString("suffix")); builder.withLore(cs.getStringList("lore")); builder.withWeight(cs.getDouble("weight")); List<SocketEffect> effects = new ArrayList<>(); for (String eff : cs.getStringList("effects")) { effects.add(LootSocketPotionEffect.parseString(eff)); } builder.withSocketEffects(effects); SocketGem gem = builder.build(); gems.add(gem); loadedSocketGems.add(gem.getName()); } for (SocketGem sg : gems) { getSocketGemManager().addSocketGem(sg); } debug("Loaded socket gems: " + loadedSocketGems.toString()); } @Override public void postEnable() { CommandHandler handler = new CommandHandler(this); handler.registerCommands(new LootCommand(this)); Bukkit.getPluginManager().registerEvents(new EntityDeathListener(this), this); //Bukkit.getPluginManager().registerEvents(new LoginListener(this), this); debug("v" + getDescription().getVersion() + " enabled"); } @Override public void preDisable() { HandlerList.unregisterAll(this); } @Override public void disable() { } @Override public void postDisable() { socketGemManager = null; customItemManager = null; nameManager = null; tierManager = null; itemGroupManager = null; settings = null; creaturesYAML = null; configYAML = null; languageYAML = null; customItemsYAML = null; corestatsYAML = null; tierYAML = null; itemsYAML = null; debugPrinter = null; } public void debug(String... messages) { debug(Level.INFO, messages); } public void debug(Level level, String... messages) { if (debugPrinter != null) { debugPrinter.debug(level, messages); } } private void loadCustomItems() { for (CustomItem ci : getCustomItemManager().getCustomItems()) { getCustomItemManager().removeCustomItem(ci.getName()); } Set<CustomItem> customItems = new HashSet<>(); List<String> loaded = new ArrayList<>(); for (String key : customItemsYAML.getKeys(false)) { if (!customItemsYAML.isConfigurationSection(key)) { continue; } ConfigurationSection cs = customItemsYAML.getConfigurationSection(key); CustomItemBuilder builder = getNewCustomItemBuilder(key); builder.withMaterial(StringConverter.toMaterial(cs.getString("material"))); builder.withDisplayName(cs.getString("display-name")); builder.withLore(cs.getStringList("lore")); CustomItem ci = builder.build(); customItems.add(ci); loaded.add(ci.getName()); } for (CustomItem ci : customItems) { getCustomItemManager().addCustomItem(ci); } debug("Loaded custom items: " + loaded.toString()); } private void loadNames() { for (String s : getNameManager().getPrefixes()) { getNameManager().removePrefix(s); } for (String s : getNameManager().getSuffixes()) { getNameManager().removeSuffix(s); } File prefixFile = new File(getDataFolder(), "prefix.txt"); File suffixFile = new File(getDataFolder(), "suffix.txt"); SmartTextFile.writeToFile(getResource("prefix.txt"), prefixFile, true); SmartTextFile.writeToFile(getResource("suffix.txt"), suffixFile, true); SmartTextFile smartPrefixFile = new SmartTextFile(prefixFile); SmartTextFile smartSuffixFile = new SmartTextFile(suffixFile); for (String s : smartPrefixFile.read()) { getNameManager().addPrefix(s); } for (String s : smartSuffixFile.read()) { getNameManager().addSuffix(s); } debug("Loaded prefixes: " + getNameManager().getPrefixes().size(), "Loaded suffixes: " + getNameManager() .getSuffixes().size()); } private void loadItemGroups() { for (ItemGroup ig : getItemGroupManager().getItemGroups()) { getItemGroupManager().removeItemGroup(ig.getName()); } Set<ItemGroup> itemGroups = new HashSet<>(); List<String> loadedItemGroups = new ArrayList<>(); for (String key : itemsYAML.getKeys(false)) { if (!itemsYAML.isList(key)) { continue; } List<String> list = itemsYAML.getStringList(key); ItemGroup ig = new LootItemGroup(key, false); for (String s : list) { Material m = StringConverter.toMaterial(s); if (m == Material.AIR) { continue; } ig.addMaterial(m); } itemGroups.add(ig); loadedItemGroups.add(key); } for (ItemGroup ig : itemGroups) { getItemGroupManager().addItemGroup(ig); } debug("Loaded item groups: " + loadedItemGroups.toString()); } private void loadTiers() { for (Tier t : getTierManager().getLoadedTiers()) { getTierManager().removeTier(t.getName()); } Set<Tier> tiers = new HashSet<>(); List<String> loadedTiers = new ArrayList<>(); for (String key : tierYAML.getKeys(false)) { if (!tierYAML.isConfigurationSection(key)) { continue; } ConfigurationSection cs = tierYAML.getConfigurationSection(key); TierBuilder builder = getNewTierBuilder(key); builder.withDisplayName(cs.getString("display-name")); builder.withDisplayColor(TextUtils.convertTag(cs.getString("display-color"))); builder.withIdentificationColor(TextUtils.convertTag(cs.getString("identification-color"))); builder.withSpawnWeight(cs.getDouble("spawn-weight")); builder.withIdentifyWeight(cs.getDouble("identify-weight")); builder.withDistanceWeight(cs.getDouble("distance-weight")); builder.withMinimumSockets(cs.getInt("minimum-sockets")); builder.withMaximumSockets(cs.getInt("maximum-sockets")); builder.withMinimumBonusLore(cs.getInt("minimum-bonus-lore")); builder.withMaximumBonusLore(cs.getInt("maximum-bonus-lore")); builder.withBaseLore(cs.getStringList("base-lore")); builder.withBonusLore(cs.getStringList("bonus-lore")); List<String> sl = cs.getStringList("item-groups"); Set<ItemGroup> itemGroups = new HashSet<>(); for (String s : sl) { ItemGroup ig; if (s.startsWith("-")) { ig = getItemGroupManager().getItemGroup(s.substring(1)); if (ig == null) { continue; } ig = ig.getInverse(); } else { ig = getItemGroupManager().getItemGroup(s); if (ig == null) { continue; } } itemGroups.add(ig.getInverse()); } builder.withItemGroups(itemGroups); builder.withMinimumDurability(cs.getDouble("minimum-durability")); builder.withMaximumDurability(cs.getDouble("maximum-durability")); Tier t = builder.build(); loadedTiers.add(t.getName()); tiers.add(t); } for (Tier t : tiers) { getTierManager().addTier(t); } debug("Loaded tiers: " + loadedTiers.toString()); } public TierBuilder getNewTierBuilder(String name) { return new LootTierBuilder(name); } public ItemBuilder getNewItemBuilder() { return new LootItemBuilder(this); } public CustomItemBuilder getNewCustomItemBuilder(String name) { return new LootCustomItemBuilder(name); } public SocketGemBuilder getNewSocketGemBuilder(String name) { return new LootSocketGemBuilder(name); } public TierManager getTierManager() { return tierManager; } public ItemGroupManager getItemGroupManager() { return itemGroupManager; } public NameManager getNameManager() { return nameManager; } public IvorySettings getSettings() { return settings; } public CustomItemManager getCustomItemManager() { return customItemManager; } public SocketGemManager getSocketGemManager() { return socketGemManager; } }
loading item-group field from socketGems.yml
src/main/java/info/faceland/loot/LootPlugin.java
loading item-group field from socketGems.yml
Java
mit
74be167a2edac2f2f18d5bdc15f9983b3ad99da8
0
cs2103aug2014-w13-2j/main,cs2103aug2014-w13-2j/main
package edu.dynamic.dynamiz.UI.unitTest; import static org.junit.Assert.*; import java.util.ArrayList; import org.junit.Test; import edu.dynamic.dynamiz.UI.Displayer; import edu.dynamic.dynamiz.structure.*; public class testDisplayer { Displayer dp = new Displayer(); public void setUp(){ } @Test public void testDisplayString() { String t1 = "test String"; dp.displayString(t1); assertEquals(dp.displayString(t1),t1); } @Test public void testDisplayPrompy(){ String t1 = "Enter condition:"; int promptTag = 2; assertEquals(dp.displayPrompt(),"Please Enter Command:"); assertEquals(dp.displayPrompt(t1),"Enter condition:"); assertEquals(dp.displayPrompt(promptTag),"Please Enter Task:"); } @Test public void testDisplayTask(){ TaskItem task1 = new TaskItem("CS2106 homework", 4, new DateTime(26, 9, 2014, 23, 59)); TaskItem task2 = new TaskItem("CS2105 homework", 4, new DateTime(26, 9, 2014, 23, 59)); TaskItem task3 = new TaskItem("CS2102 homework", 4, new DateTime(26, 9, 2014, 23, 59)); assertEquals(dp.displayTaskItem(task1), task1.toString()); assertEquals(dp.displayTaskFeedBack(task1), task1.getFeedbackString()); assertEquals(dp.displayTaskFile(task1), task1.toFileString()); } @Test public void testDisplayTaskList(){ TaskItem task1 = new TaskItem("CS2106 homework", 4, new DateTime(26, 9, 2014, 23, 59)); TaskItem task2 = new TaskItem("CS2105 homework", 4, new DateTime(26, 9, 2014, 23, 59)); TaskItem task3 = new TaskItem("CS2102 homework", 4, new DateTime(26, 9, 2014, 23, 59)); ArrayList<TaskItem> testList = new ArrayList<TaskItem>(); testList.add(task1); testList.add(task2); testList.add(task3); String s = new String(); s+=task1.toString(); s+="\n"; s+=task2.toString(); s+="\n"; s+=task3.toString(); s+="\n"; assertEquals(dp.displayTaskList(testList), s); TaskItem[] testArray = new TaskItem[3]; testArray[0]=task1; testArray[1]=task2; testArray[2]=task3; assertEquals(dp.displayTaskList(testArray), s); } @Test public void testDisplayToDo(){ ToDoItem item = new ToDoItem("Do CS2103T", 1); String itemToString = new String(); itemToString = item.toString(); String itemToFile = new String(); itemToFile = item.toFileString(); System.out.println(item.toString()); assertEquals(dp.displayToDoItem(item),itemToString); assertEquals(dp.displayToDoFile(item),itemToFile); assertEquals(dp.displayToDoFeedBack(item),item.getFeedbackString()); } @Test public void testTodoList(){ ToDoItem item1 = new ToDoItem("Do CS2103T", 1); ToDoItem item2 = new ToDoItem("Do CS2103T", 2); ToDoItem item3 = new ToDoItem("Do CS2102", 1); ArrayList<ToDoItem> todoList = new ArrayList<ToDoItem>(); todoList.add(item1); todoList.add(item2); todoList.add(item3); String s = new String(); s+=item1.toString(); s+="\n"; s+=item2.toString(); s+="\n"; s+=item3.toString(); s+="\n"; assertEquals(dp.displayToDoList(todoList), s); ToDoItem[] testArray = new ToDoItem[3]; testArray[0]=item1; testArray[1]=item2; testArray[2]=item3; assertEquals(dp.displayToDoList(testArray), s); } @Test public void testDisplayEvent(){ EventItem item = new EventItem("Nana's concert", 5, new Date(27, 9, 2014)); System.out.println(item.toString()); assertEquals(dp.displayEventItem(item),item.toString()); assertEquals(dp.displayEventFile(item),item.toFileString()); assertEquals(dp.displayEventFeedBack(item),item.getFeedbackString()); } @Test public void testEventList(){ EventItem e1 = new EventItem("Nana's concert", 5, new Date(27, 9, 2014)); EventItem e2 = new EventItem("CS2105 midterms", new DateTime(4, 10, 2014, 17, 0)); EventItem e3= new EventItem("Birthday", new Date(31, 10, 2014)); ArrayList<EventItem> ls = new ArrayList<EventItem>(); ls.add(e1); ls.add(e2); ls.add(e3); String s = new String(); s+=e1.toString(); s+="\n"; s+=e2.toString(); s+="\n"; s+=e3.toString(); s+="\n"; assertEquals(dp.displayEventList(ls), s); EventItem[] testArray = new EventItem[3]; testArray[0]=e1; testArray[1]=e2; testArray[2]=e3; assertEquals(dp.displayEventList(testArray), s); } }
src/edu/dynamic/dynamiz/UI/unitTest/testDisplayer.java
package edu.dynamic.dynamiz.UI.unitTest; import static org.junit.Assert.*; import java.util.ArrayList; import org.junit.Test; import edu.dynamic.dynamiz.UI.Displayer; import edu.dynamic.dynamiz.structure.*; public class testDisplayer { Displayer dp = new Displayer(); public void setUp(){ } @Test public void testDisplayString() { String t1 = "test String"; dp.displayString(t1); assertEquals(dp.displayString(t1),t1); } @Test public void testDisplayPrompy(){ String t1 = "Enter condition:"; int promptTag = 2; assertEquals(dp.displayPrompt(),"Please Enter Command:"); assertEquals(dp.displayPrompt(t1),"Enter condition:"); assertEquals(dp.displayPrompt(promptTag),"Please Enter Task:"); } @Test public void testDisplayTask(){ TaskItem task1 = new TaskItem("CS2106 homework", 4, new DateTime(26, 9, 2014, 23, 59)); TaskItem task2 = new TaskItem("CS2105 homework", 4, new DateTime(26, 9, 2014, 23, 59)); TaskItem task3 = new TaskItem("CS2102 homework", 4, new DateTime(26, 9, 2014, 23, 59)); assertEquals(dp.displayTaskItem(task1), task1.toString()); assertEquals(dp.displayTaskFeedBack(task1), task1.getFeedbackString()); assertEquals(dp.displayTaskFile(task1), task1.toFileString()); } @Test public void testDisplayTaskList(){ TaskItem task1 = new TaskItem("CS2106 homework", 4, new DateTime(26, 9, 2014, 23, 59)); TaskItem task2 = new TaskItem("CS2105 homework", 4, new DateTime(26, 9, 2014, 23, 59)); TaskItem task3 = new TaskItem("CS2102 homework", 4, new DateTime(26, 9, 2014, 23, 59)); ArrayList<TaskItem> testList = new ArrayList<TaskItem>(); testList.add(task1); testList.add(task2); testList.add(task3); String s = new String(); s+=task1.toString(); s+="\n"; s+=task2.toString(); s+="\n"; s+=task3.toString(); s+="\n"; assertEquals(dp.displayTaskList(testList), s); } }
displayer test added
src/edu/dynamic/dynamiz/UI/unitTest/testDisplayer.java
displayer test added
Java
mit
d31678f2ae8a9f7b52332f68890321964e59016e
0
DemigodsRPG/Demigods3
package com.censoredsoftware.Modules; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import javax.xml.parsers.DocumentBuilderFactory; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.plugin.Plugin; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import redis.clients.johm.Attribute; import redis.clients.johm.CollectionMap; import redis.clients.johm.Id; import redis.clients.johm.Model; import com.censoredsoftware.Demigods.Engine.DemigodsData; import com.google.common.collect.Maps; /** * Module to handle the latest messages from a Twitter feed. */ @Model public class LatestTweetModule implements Listener { private static Plugin plugin; private static Logger log = Logger.getLogger("Minecraft"); private static URL twitterFeed; private static String pluginName, command, permission, date, link; private static boolean notify; @Id private Long Id; @Attribute private String message; @CollectionMap(key = String.class, value = String.class) private Map<String, String> messagesData; public Map<String, String> getData() { return this.messagesData; } public void save() { save(this); } public static void save(LatestTweetModule tweet) { DemigodsData.jOhm.save(tweet); } /** * Constructor to create a new LatestTweetModule. * * @param pl The demigods instance running the module. * @param screenName The screen-name to the Twitter page. * @param c The full command for viewing the latest message. * @param p The full permission node for viewing the latest message. * @param n True if notifying is allowed. */ public static LatestTweetModule recreate(Plugin pl, String screenName, String c, String p, boolean n) { LatestTweetModule module = null; try { Set<LatestTweetModule> latestTweetModules = DemigodsData.jOhm.getAll(LatestTweetModule.class); for(LatestTweetModule tweet : latestTweetModules) { module = tweet; break; } } catch(Exception ignored) {} if(module == null) { module = new LatestTweetModule(); module.messagesData = Maps.newHashMap(); } try { plugin = pl; twitterFeed = new URL("http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=" + screenName); pluginName = pl.getName(); command = c; permission = p; notify = n; module.get(); initilize(module); } catch(Exception e) { log.severe("[" + pluginName + "] Could not connect to Twitter."); e.printStackTrace(); } return module; } /** * Checks for notifications and notifies if need be. */ public static void initilize(LatestTweetModule module) { // Check for updates, and then update if need be if(notify) { // Define Notify Listener plugin.getServer().getPluginManager().registerEvents(module, plugin); for(final Player player : Bukkit.getOnlinePlayers()) { if(module.get(player)) { plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { player.sendMessage(ChatColor.GREEN + "There is a new message from the " + pluginName + " developers!"); player.sendMessage("Please view it now by using " + ChatColor.YELLOW + command); } }, 40); } } } } /** * Gets the latest message from the Twitter feed. * * @return The message. */ public synchronized String get() { String toReturn = ""; try { InputStream input = twitterFeed.openConnection().getInputStream(); Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input); NodeList messageNodes = document.getElementsByTagName("item").item(0).getChildNodes(); try { this.date = messageNodes.item(5).getTextContent().substring(0, messageNodes.item(5).getTextContent().lastIndexOf("+")); this.link = messageNodes.item(9).getTextContent().replace("http://", "https://"); } catch(Exception e) { log.warning("[" + pluginName + "] Failed to find latest tweet."); } input.close(); try { URLConnection messageCon = (new URL(link)).openConnection(); messageCon.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"); // FIXES 403 ERROR input = messageCon.getInputStream(); } catch(Exception e) { log.warning("[" + pluginName + "] Failed to open connection with twitter page."); } BufferedReader reader = new BufferedReader(new InputStreamReader(input)); String line; while((line = reader.readLine()) != null) { if(line.trim().startsWith("<p class=\"js-tweet-text tweet-text \">")) { toReturn = line.substring(line.indexOf("<p class=\"js-tweet-text tweet-text \">") + 37, line.lastIndexOf("<")); } } reader.close(); input.close(); } catch(Exception e) { log.warning("[" + pluginName + "] Failed to load twitter page."); } this.message = toReturn; save(); return toReturn; } /** * Gets the latest message from the Twitter feed. * * @return True if successful. */ public boolean get(OfflinePlayer player) { get(); String lastMessage = messagesData.get(player.getName()); return !(lastMessage != null && lastMessage.equalsIgnoreCase(message)); } /** * The Player Join Listener, listening only. */ @EventHandler(priority = EventPriority.MONITOR) public void onPlayerJoin(PlayerJoinEvent event) { // Define Variables final Player player = event.getPlayer(); final String pluginName = this.pluginName; final String command = this.command; // Official Messages if(this.notify && (player.isOp() || player.hasPermission(this.permission))) { if(get(player)) { plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { player.sendMessage(ChatColor.GREEN + "There is a new message from the " + pluginName + " developers!"); player.sendMessage("Please view it now by using " + ChatColor.YELLOW + command); } }, 40); } } } /** * The Player Command Preprocess Listener, cancelling the event if the message command is found, and executing the command inside of the listener. */ @EventHandler(priority = EventPriority.HIGHEST) private void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { // Define Variables Player player = event.getPlayer(); String command = event.getMessage(); // Check for update command if(command.toLowerCase().startsWith(this.command.toLowerCase())) { // Check Permissions if(!(player.hasPermission(this.permission) || player.isOp())) { player.sendMessage(ChatColor.RED + "You do not have permission to run this command."); event.setCancelled(true); return; } // Send the message player.sendMessage(ChatColor.DARK_AQUA + "[" + pluginName + "] " + ChatColor.RESET + "Posted on " + date); player.sendMessage(ChatColor.YELLOW + " Message: " + ChatColor.WHITE + message); player.sendMessage(" "); player.sendMessage(ChatColor.YELLOW + " " + ChatColor.WHITE + link.replace("https://", "")); // Set that the message was seen messagesData.put(player.getName(), message); save(); event.setCancelled(true); } } }
Demigods/src/com/censoredsoftware/Modules/LatestTweetModule.java
package com.censoredsoftware.Modules; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import javax.xml.parsers.DocumentBuilderFactory; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.plugin.Plugin; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import redis.clients.johm.Attribute; import redis.clients.johm.CollectionMap; import redis.clients.johm.Id; import redis.clients.johm.Model; import com.censoredsoftware.Demigods.Engine.DemigodsData; import com.google.common.collect.Maps; /** * Module to handle the latest messages from a Twitter feed. */ @Model public class LatestTweetModule implements Listener { private static Plugin plugin; private static Logger log = Logger.getLogger("Minecraft"); private static URL twitterFeed; private static String pluginName, command, permission, date, link; private static boolean notify; @Id private Long Id; @Attribute private String message; @CollectionMap(key = String.class, value = String.class) private Map<String, String> messagesData; public Map<String, String> getData() { return this.messagesData; } public void save() { save(this); } public static void save(LatestTweetModule tweet) { DemigodsData.jOhm.save(tweet); } /** * Constructor to create a new LatestTweetModule. * * @param pl The demigods instance running the module. * @param screenName The screen-name to the Twitter page. * @param c The full command for viewing the latest message. * @param p The full permission node for viewing the latest message. * @param n True if notifying is allowed. */ public static LatestTweetModule recreate(Plugin pl, String screenName, String c, String p, boolean n) { LatestTweetModule module = null; try { Set<LatestTweetModule> latestTweetModules = DemigodsData.jOhm.getAll(LatestTweetModule.class); for(LatestTweetModule tweet : latestTweetModules) { module = tweet; break; } } catch(Exception ignored) {} if(module == null) { module = new LatestTweetModule(); module.messagesData = Maps.newHashMap(); } try { plugin = pl; twitterFeed = new URL("http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=" + screenName); pluginName = pl.getName(); command = c; permission = p; notify = n; module.get(); module.save(); initilize(module); } catch(Exception e) { log.severe("[" + pluginName + "] Could not connect to Twitter."); e.printStackTrace(); } return module; } /** * Checks for notifications and notifies if need be. */ public static void initilize(LatestTweetModule module) { // Check for updates, and then update if need be if(notify) { // Define Notify Listener plugin.getServer().getPluginManager().registerEvents(module, plugin); for(final Player player : Bukkit.getOnlinePlayers()) { if(module.get(player)) { plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { player.sendMessage(ChatColor.GREEN + "There is a new message from the " + pluginName + " developers!"); player.sendMessage("Please view it now by using " + ChatColor.YELLOW + command); } }, 40); } } } } /** * Gets the latest message from the Twitter feed. * * @return The message. */ public synchronized String get() { String toReturn = ""; try { InputStream input = twitterFeed.openConnection().getInputStream(); Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input); NodeList messageNodes = document.getElementsByTagName("item").item(0).getChildNodes(); try { this.date = messageNodes.item(5).getTextContent().substring(0, messageNodes.item(5).getTextContent().lastIndexOf("+")); this.link = messageNodes.item(9).getTextContent().replace("http://", "https://"); } catch(Exception e) { log.warning("[" + pluginName + "] Failed to find latest tweet."); } input.close(); try { URLConnection messageCon = (new URL(link)).openConnection(); messageCon.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"); // FIXES 403 ERROR input = messageCon.getInputStream(); } catch(Exception e) { log.warning("[" + pluginName + "] Failed to open connection with twitter page."); } BufferedReader reader = new BufferedReader(new InputStreamReader(input)); String line; while((line = reader.readLine()) != null) { if(line.trim().startsWith("<p class=\"js-tweet-text tweet-text \">")) { toReturn = line.substring(line.indexOf("<p class=\"js-tweet-text tweet-text \">") + 37, line.lastIndexOf("<")); this.message = toReturn; } } reader.close(); input.close(); } catch(Exception e) { log.warning("[" + pluginName + "] Failed to load twitter page."); } return toReturn; } /** * Gets the latest message from the Twitter feed. * * @return True if successful. */ public boolean get(OfflinePlayer player) { get(); save(); String lastMessage = messagesData.get(player.getName()); return !(lastMessage != null && lastMessage.equalsIgnoreCase(message)); } /** * The Player Join Listener, listening only. */ @EventHandler(priority = EventPriority.MONITOR) public void onPlayerJoin(PlayerJoinEvent event) { // Define Variables final Player player = event.getPlayer(); final String pluginName = this.pluginName; final String command = this.command; // Official Messages if(this.notify && (player.isOp() || player.hasPermission(this.permission))) { if(get(player)) { plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { player.sendMessage(ChatColor.GREEN + "There is a new message from the " + pluginName + " developers!"); player.sendMessage("Please view it now by using " + ChatColor.YELLOW + command); } }, 40); } } } /** * The Player Command Preprocess Listener, cancelling the event if the message command is found, and executing the command inside of the listener. */ @EventHandler(priority = EventPriority.HIGHEST) private void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { // Define Variables Player player = event.getPlayer(); String command = event.getMessage(); // Check for update command if(command.toLowerCase().startsWith(this.command.toLowerCase())) { // Check Permissions if(!(player.hasPermission(this.permission) || player.isOp())) { player.sendMessage(ChatColor.RED + "You do not have permission to run this command."); event.setCancelled(true); return; } // Send the message player.sendMessage(ChatColor.DARK_AQUA + "[" + pluginName + "] " + ChatColor.RESET + "Posted on " + date); player.sendMessage(ChatColor.YELLOW + " Message: " + ChatColor.WHITE + message); player.sendMessage(" "); player.sendMessage(ChatColor.YELLOW + " " + ChatColor.WHITE + link.replace("https://", "")); // Set that the message was seen messagesData.put(player.getName(), message); save(); event.setCancelled(true); } } }
Try this.
Demigods/src/com/censoredsoftware/Modules/LatestTweetModule.java
Try this.
Java
mit
9241b02d41dd45745bcae6e0e902c0425ee1600d
0
phirschbeck/settlers-remake,jsettlers/settlers-remake,jsettlers/settlers-remake,andreas-eberle/settlers-remake,andreasb242/settlers-remake,phirschbeck/settlers-remake,jsettlers/settlers-remake,andreas-eberle/settlers-remake,JKatzwinkel/settlers-remake,andreas-eberle/settlers-remake,andreasb242/settlers-remake,Peter-Maximilian/settlers-remake,andreasb242/settlers-remake,phirschbeck/settlers-remake
package go.graphics; public class Color { private final float blue; private final float red; private final float green; private final float alpha; public Color(int rgbhex) { this(((rgbhex >> 16) & 0xff) / 255f, ((rgbhex >> 8) & 0xff) / 255f, ((rgbhex >> 0) & 0xff) / 255f, 1f); } public Color(float red, float green, float blue, float alpha) { this.red = red; this.green = green; this.blue = blue; this.alpha = alpha; } public float getAlpha() { return alpha; } public float getBlue() { return blue; } public float getGreen() { return green; } public float getRed() { return red; } public int getRGB() { return ((int) (alpha * 255) & 0xff) << 24 | ((int) (red * 255) & 0xff) << 16 | ((int) (green * 255) & 0xff) << 8 | ((int) (blue * 255) & 0xff); } }
src/go/graphics/Color.java
package go.graphics; public class Color { private final float blue; private final float red; private final float green; private final float alpha; public Color(int rgbhex) { this(((rgbhex >> 16) & 0xff) / 255f, ((rgbhex >> 8) & 0xff) / 255f, ((rgbhex >> 0) & 0xff) / 255f, 1f); } public Color(float red, float green, float blue, float alpha) { this.red = red; this.green = green; this.blue = blue; this.alpha = alpha; } public float getAlpha() { return alpha; } public float getBlue() { return blue; } public float getGreen() { return green; } public float getRed() { return red; } public int getRGB() { return ((int) (alpha * 255) & 0xff) << 24 | ((int) (red * 255) & 0xff) << 16 | ((int) (green * 255) & 0xff) << 8 | ((int) (blue * 255) & 0xff); } public Color multiply(float f) { return new Color(Math.min(red * f, 1), Math.min(green * f, 1), Math.min( blue * f, 1), alpha); } }
made Color.multiply not allocate a new Object if the color was unchanged or the new color is black.
src/go/graphics/Color.java
made Color.multiply not allocate a new Object if the color was unchanged or the new color is black.
Java
mit
19ec37340bf4ea765198b5d0f0d44567344d8822
0
mhogrefe/qbar
package mho.qbar.objects; import mho.wheels.iterables.IterableUtils; import mho.wheels.misc.Readers; import org.jetbrains.annotations.NotNull; import org.junit.Test; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import java.util.Optional; import static mho.qbar.objects.Interval.*; import static mho.qbar.objects.Interval.greaterThanOrEqualTo; import static mho.qbar.objects.Interval.lessThanOrEqualTo; import static mho.wheels.ordering.Ordering.*; import static org.junit.Assert.*; public class IntervalTest { @Test public void testConstants() { aeq(ZERO, "[0, 0]"); aeq(ONE, "[1, 1]"); aeq(ALL, "(-Infinity, Infinity)"); } @Test public void testGetLower() { aeq(ZERO.getLower().get(), "0"); aeq(ONE.getLower().get(), "1"); aeq(read("[-2, 5/3]").get().getLower().get(), "-2"); assertFalse(ALL.getLower().isPresent()); } @Test public void testGetUpper() { aeq(ZERO.getUpper().get(), "0"); aeq(ONE.getUpper().get(), "1"); aeq(read("[-2, 5/3]").get().getUpper().get(), "5/3"); assertFalse(ALL.getUpper().isPresent()); } @Test public void testOf_Rational_Rational() { aeq(of(Rational.read("1/3").get(), Rational.read("1/2").get()), "[1/3, 1/2]"); aeq(of(Rational.read("-5").get(), Rational.ZERO), "[-5, 0]"); aeq(of(Rational.read("2").get(), Rational.read("2").get()), "[2, 2]"); try { of(Rational.read("3").get(), Rational.read("2").get()); fail(); } catch (IllegalArgumentException ignored) {} } @Test public void testLessThanOrEqualTo() { aeq(lessThanOrEqualTo(Rational.read("1/3").get()), "(-Infinity, 1/3]"); aeq(lessThanOrEqualTo(Rational.ZERO), "(-Infinity, 0]"); } @Test public void testGreaterThanOrEqualTo() { aeq(greaterThanOrEqualTo(Rational.read("1/3").get()), "[1/3, Infinity)"); aeq(greaterThanOrEqualTo(Rational.ZERO), "[0, Infinity)"); } @Test public void testOf_Rational() { aeq(of(Rational.ZERO), "[0, 0]"); aeq(of(Rational.read("5/4").get()), "[5/4, 5/4]"); aeq(of(Rational.read("-2").get()), "[-2, -2]"); } @Test public void testIsFinitelyBounded() { assertTrue(ZERO.isFinitelyBounded()); assertTrue(ONE.isFinitelyBounded()); assertFalse(ALL.isFinitelyBounded()); assertTrue(read("[-2, 5/3]").get().isFinitelyBounded()); assertTrue(read("[4, 4]").get().isFinitelyBounded()); assertFalse(read("(-Infinity, 3/2]").get().isFinitelyBounded()); assertFalse(read("[-6, Infinity)").get().isFinitelyBounded()); } @Test public void testContains_Rational() { assertTrue(ZERO.contains(Rational.ZERO)); assertFalse(ZERO.contains(Rational.ONE)); assertTrue(ONE.contains(Rational.ONE)); assertFalse(ONE.contains(Rational.ZERO)); assertTrue(ALL.contains(Rational.ZERO)); assertTrue(ALL.contains(Rational.ONE)); assertTrue(ALL.contains(Rational.read("-4/3").get())); assertTrue(read("[-2, 5/3]").get().contains(Rational.read("-2").get())); assertTrue(read("[-2, 5/3]").get().contains(Rational.read("-1").get())); assertTrue(read("[-2, 5/3]").get().contains(Rational.ZERO)); assertTrue(read("[-2, 5/3]").get().contains(Rational.ONE)); assertTrue(read("[-2, 5/3]").get().contains(Rational.read("5/3").get())); assertFalse(read("[-2, 5/3]").get().contains(Rational.read("-3").get())); assertFalse(read("[-2, 5/3]").get().contains(Rational.read("2").get())); assertTrue(read("[4, 4]").get().contains(Rational.read("4").get())); assertFalse(read("[4, 4]").get().contains(Rational.read("3").get())); assertFalse(read("[4, 4]").get().contains(Rational.read("5").get())); assertTrue(read("(-Infinity, 3/2]").get().contains(Rational.ZERO)); assertTrue(read("(-Infinity, 3/2]").get().contains(Rational.ONE)); assertTrue(read("(-Infinity, 3/2]").get().contains(Rational.read("-10").get())); assertTrue(read("(-Infinity, 3/2]").get().contains(Rational.read("3/2").get())); assertFalse(read("(-Infinity, 3/2]").get().contains(Rational.read("2").get())); assertTrue(read("[-6, Infinity)").get().contains(Rational.ZERO)); assertTrue(read("[-6, Infinity)").get().contains(Rational.ONE)); assertTrue(read("[-6, Infinity)").get().contains(Rational.read("-4").get())); assertTrue(read("[-6, Infinity)").get().contains(Rational.read("5").get())); assertFalse(read("[-6, Infinity)").get().contains(Rational.read("-8").get())); } @Test public void testContains_Interval() { assertTrue(ZERO.contains(ZERO)); assertTrue(ONE.contains(ONE)); assertTrue(ALL.contains(ALL)); assertTrue(ALL.contains(ZERO)); assertTrue(ALL.contains(ONE)); assertFalse(ZERO.contains(ONE)); assertFalse(ZERO.contains(ALL)); assertFalse(ONE.contains(ZERO)); assertFalse(ONE.contains(ALL)); assertTrue(read("[1, 4]").get().contains(read("[2, 3]").get())); assertTrue(read("[1, 4]").get().contains(read("[1, 4]").get())); assertFalse(read("[1, 4]").get().contains(read("[0, 2]").get())); assertTrue(read("(-Infinity, 1/2]").get().contains(read("(-Infinity, 0]").get())); assertTrue(read("(-Infinity, 1/2]").get().contains(read("[0, 0]").get())); assertFalse(read("(-Infinity, 1/2]").get().contains(read("(-Infinity, 1]").get())); assertTrue(read("[1/2, Infinity)").get().contains(read("[1, Infinity)").get())); assertTrue(read("[1/2, Infinity)").get().contains(read("[1, 1]").get())); assertFalse(read("[1/2, Infinity)").get().contains(read("[0, Infinity)").get())); assertFalse(read("[1/2, Infinity)").get().contains(read("(-Infinity, 1/2]").get())); } @Test public void testDiameter() { aeq(ZERO.diameter().get(), "0"); aeq(ONE.diameter().get(), "0"); assertFalse(ALL.diameter().isPresent()); aeq(read("[-2, 5/3]").get().diameter().get(), "11/3"); aeq(read("[4, 4]").get().diameter().get(), "0"); assertFalse(read("(-Infinity, 3/2]").get().diameter().isPresent()); assertFalse(read("[-6, Infinity)").get().diameter().isPresent()); } @Test public void testConvexHull_Interval() { aeq(ZERO.convexHull(ZERO), "[0, 0]"); aeq(ZERO.convexHull(ONE), "[0, 1]"); aeq(ZERO.convexHull(ALL), "(-Infinity, Infinity)"); aeq(ZERO.convexHull(read("[-2, 5/3]").get()), "[-2, 5/3]"); aeq(ZERO.convexHull(read("[4, 4]").get()), "[0, 4]"); aeq(ZERO.convexHull(read("(-Infinity, 3/2]").get()), "(-Infinity, 3/2]"); aeq(ZERO.convexHull(read("[-6, Infinity)").get()), "[-6, Infinity)"); aeq(ONE.convexHull(ZERO), "[0, 1]"); aeq(ONE.convexHull(ONE), "[1, 1]"); aeq(ONE.convexHull(ALL), "(-Infinity, Infinity)"); aeq(ONE.convexHull(read("[-2, 5/3]").get()), "[-2, 5/3]"); aeq(ONE.convexHull(read("[4, 4]").get()), "[1, 4]"); aeq(ONE.convexHull(read("(-Infinity, 3/2]").get()), "(-Infinity, 3/2]"); aeq(ONE.convexHull(read("[-6, Infinity)").get()), "[-6, Infinity)"); aeq(ALL.convexHull(ZERO), "(-Infinity, Infinity)"); aeq(ALL.convexHull(ONE), "(-Infinity, Infinity)"); aeq(ALL.convexHull(ALL), "(-Infinity, Infinity)"); aeq(ALL.convexHull(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(ALL.convexHull(read("[4, 4]").get()), "(-Infinity, Infinity)"); aeq(ALL.convexHull(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(ALL.convexHull(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().convexHull(ZERO), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().convexHull(ONE), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().convexHull(ALL), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().convexHull(read("[-2, 5/3]").get()), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().convexHull(read("[4, 4]").get()), "[-2, 4]"); aeq(read("[-2, 5/3]").get().convexHull(read("(-Infinity, 3/2]").get()), "(-Infinity, 5/3]"); aeq(read("[-2, 5/3]").get().convexHull(read("[-6, Infinity)").get()), "[-6, Infinity)"); aeq(read("[4, 4]").get().convexHull(ZERO), "[0, 4]"); aeq(read("[4, 4]").get().convexHull(ONE), "[1, 4]"); aeq(read("[4, 4]").get().convexHull(ALL), "(-Infinity, Infinity)"); aeq(read("[4, 4]").get().convexHull(read("[-2, 5/3]").get()), "[-2, 4]"); aeq(read("[4, 4]").get().convexHull(read("[4, 4]").get()), "[4, 4]"); aeq(read("[4, 4]").get().convexHull(read("(-Infinity, 3/2]").get()), "(-Infinity, 4]"); aeq(read("[4, 4]").get().convexHull(read("[-6, Infinity)").get()), "[-6, Infinity)"); aeq(read("(-Infinity, 3/2]").get().convexHull(ZERO), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().convexHull(ONE), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().convexHull(ALL), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().convexHull(read("[-2, 5/3]").get()), "(-Infinity, 5/3]"); aeq(read("(-Infinity, 3/2]").get().convexHull(read("[4, 4]").get()), "(-Infinity, 4]"); aeq(read("(-Infinity, 3/2]").get().convexHull(read("(-Infinity, 3/2]").get()), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().convexHull(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().convexHull(ZERO), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().convexHull(ONE), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().convexHull(ALL), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().convexHull(read("[-2, 5/3]").get()), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().convexHull(read("[4, 4]").get()), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().convexHull(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().convexHull(read("[-6, Infinity)").get()), "[-6, Infinity)"); } @Test public void testConvexHull_List_Interval() { aeq(convexHull(readIntervalList("[[0, 0]]")), "[0, 0]"); aeq(convexHull(readIntervalList("[[-1, 2]]")), "[-1, 2]"); aeq(convexHull(readIntervalList("[[-1, Infinity)]")), "[-1, Infinity)"); aeq(convexHull(readIntervalList("[(-Infinity, 4]]")), "(-Infinity, 4]"); aeq(convexHull(readIntervalList("[(-Infinity, Infinity)]")), "(-Infinity, Infinity)"); aeq(convexHull(readIntervalList("[[0, 0], [1, 1]]")), "[0, 1]"); aeq(convexHull(readIntervalList("[[1, 2], [3, 4]]")), "[1, 4]"); aeq(convexHull(readIntervalList("[[1, 3], [2, 4]]")), "[1, 4]"); aeq(convexHull(readIntervalList("[(-Infinity, Infinity), [3, 4]]")), "(-Infinity, Infinity)"); aeq(convexHull(readIntervalList("[[-1, Infinity), (-Infinity, 4]]")), "(-Infinity, Infinity)"); aeq(convexHull(readIntervalList("[[1, 2], [3, 4], [5, 6]]")), "[1, 6]"); aeq(convexHull(readIntervalList("[[1, 2], [2, 2], [3, Infinity)]")), "[1, Infinity)"); try { convexHull(readIntervalList("[]")); fail(); } catch (IllegalArgumentException ignored) {} try { convexHull(readIntervalListWithNulls("[[1, 2], null]")); fail(); } catch (NullPointerException ignored) {} } @Test public void testIntersection() { aeq(ZERO.intersection(ZERO).get(), "[0, 0]"); aeq(ONE.intersection(ONE).get(), "[1, 1]"); aeq(ALL.intersection(ALL).get(), "(-Infinity, Infinity)"); aeq(ALL.intersection(ZERO).get(), "[0, 0]"); aeq(ALL.intersection(ONE).get(), "[1, 1]"); assertFalse(ZERO.intersection(ONE).isPresent()); aeq(read("[1, 3]").get().intersection(read("[2, 4]").get()).get(), "[2, 3]"); aeq(read("[1, 2]").get().intersection(read("[2, 4]").get()).get(), "[2, 2]"); assertFalse(read("[1, 2]").get().intersection(read("[3, 4]").get()).isPresent()); aeq(ALL.intersection(read("[1, 2]").get()).get(), "[1, 2]"); aeq(read("(-Infinity, 2]").get().intersection(read("[1, 3]").get()).get(), "[1, 2]"); aeq(read("(-Infinity, 2]").get().intersection(read("(-Infinity, 3]").get()).get(), "(-Infinity, 2]"); aeq(read("[2, Infinity)").get().intersection(read("[1, 3]").get()).get(), "[2, 3]"); aeq(read("[2, Infinity)").get().intersection(read("[3, Infinity)").get()).get(), "[3, Infinity)"); aeq(read("[2, Infinity)").get().intersection(read("(-Infinity, 3]").get()).get(), "[2, 3]"); assertFalse(read("[2, Infinity)").get().intersection(read("(-Infinity, 1]").get()).isPresent()); } @Test public void testDisjoint() { assertFalse(ZERO.disjoint(ZERO)); assertFalse(ONE.disjoint(ONE)); assertFalse(ALL.disjoint(ALL)); assertFalse(ALL.disjoint(ZERO)); assertFalse(ALL.disjoint(ONE)); assertTrue(ZERO.disjoint(ONE)); assertFalse(read("[1, 3]").get().disjoint(read("[2, 4]").get())); assertTrue(read("[1, 2]").get().disjoint(read("[3, 4]").get())); assertFalse(read("(-Infinity, 2]").get().disjoint(read("[1, 3]").get())); assertTrue(read("(-Infinity, 2]").get().disjoint(read("[3, 4]").get())); assertFalse(read("[2, Infinity)").get().disjoint(read("[1, 3]").get())); assertTrue(read("[2, Infinity)").get().disjoint(read("[0, 1]").get())); assertTrue(read("[2, Infinity)").get().disjoint(read("(-Infinity, 1]").get())); assertFalse(read("[2, Infinity)").get().disjoint(read("(-Infinity, 3]").get())); } @Test public void testMakeDisjoint() { aeq(makeDisjoint(readIntervalList("[]")), "[]"); aeq(makeDisjoint(readIntervalList("[[0, 0]]")), "[[0, 0]]"); aeq(makeDisjoint(readIntervalList("[[1, 1]]")), "[[1, 1]]"); aeq(makeDisjoint(readIntervalList("[(-Infinity, Infinity)]")), "[(-Infinity, Infinity)]"); aeq(makeDisjoint(readIntervalList("[(-Infinity, 3]]")), "[(-Infinity, 3]]"); aeq(makeDisjoint(readIntervalList("[[2, Infinity)]")), "[[2, Infinity)]"); aeq(makeDisjoint(readIntervalList("[[2, 3]]")), "[[2, 3]]"); aeq( makeDisjoint(readIntervalList("[(-Infinity, 3], [4, 5], [6, 7]]")), "[(-Infinity, 3], [4, 5], [6, 7]]" ); aeq(makeDisjoint(readIntervalList("[(-Infinity, 3], [3, 5], [5, 7]]")), "[(-Infinity, 7]]"); aeq(makeDisjoint(readIntervalList("[(-Infinity, 3], [2, 5], [6, 7]]")), "[(-Infinity, 5], [6, 7]]"); aeq( makeDisjoint(readIntervalList("[[1, 2], [4, 6], [10, Infinity), [3, 7], [5, 9]]")), "[[1, 2], [3, 9], [10, Infinity)]" ); try { makeDisjoint(readIntervalListWithNulls("[[1, 3], null, [5, Infinity)]")); fail(); } catch (NullPointerException ignored) {} } @Test public void testComplement() { aeq(ZERO.complement(), "[(-Infinity, Infinity)]"); aeq(ONE.complement(), "[(-Infinity, Infinity)]"); aeq(ALL.complement(), "[]"); aeq(read("[-2, 5/3]").get().complement(), "[(-Infinity, -2], [5/3, Infinity)]"); aeq(read("[4, 4]").get().complement(), "[(-Infinity, Infinity)]"); aeq(read("(-Infinity, 3/2]").get().complement(), "[[3/2, Infinity)]"); aeq(read("[-6, Infinity)").get().complement(), "[(-Infinity, -6]]"); } @Test public void testMidpoint() { aeq(ZERO.midpoint(), "0"); aeq(ONE.midpoint(), "1"); aeq(read("[4, 4]").get().midpoint(), "4"); aeq(read("[1, 2]").get().midpoint(), "3/2"); aeq(read("[-2, 5/3]").get().midpoint(), "-1/6"); try { ALL.midpoint(); fail(); } catch (ArithmeticException ignored) {} try { read("(-Infinity, 1]").get().midpoint(); fail(); } catch (ArithmeticException ignored) {} try { read("[1, Infinity)").get().midpoint(); fail(); } catch (ArithmeticException ignored) {} } @Test public void testSplit() { aeq(ZERO.split(Rational.ZERO), "([0, 0], [0, 0])"); aeq(ONE.split(Rational.ONE), "([1, 1], [1, 1])"); aeq(ALL.split(Rational.ONE), "((-Infinity, 1], [1, Infinity))"); aeq(read("[4, 4]").get().split(Rational.read("4").get()), "([4, 4], [4, 4])"); aeq(read("[0, 1]").get().split(Rational.read("1/3").get()), "([0, 1/3], [1/3, 1])"); aeq(read("[0, 1]").get().split(Rational.ZERO), "([0, 0], [0, 1])"); aeq(read("[0, 1]").get().split(Rational.ONE), "([0, 1], [1, 1])"); aeq(read("[-2, 5/3]").get().split(Rational.read("1").get()), "([-2, 1], [1, 5/3])"); aeq(read("(-Infinity, 1]").get().split(Rational.read("-3").get()), "((-Infinity, -3], [-3, 1])"); aeq(read("[5/3, Infinity)").get().split(Rational.read("10").get()), "([5/3, 10], [10, Infinity))"); try { ZERO.split(Rational.ONE); fail(); } catch (ArithmeticException ignored) {} try { read("[-2, 5/3]").get().split(Rational.read("-4").get()); fail(); } catch (ArithmeticException ignored) {} try { read("(-Infinity, 1]").get().split(Rational.read("4").get()); fail(); } catch (ArithmeticException ignored) {} try { read("[1, Infinity)").get().split(Rational.read("-4").get()); fail(); } catch (ArithmeticException ignored) {} } @Test public void testBisect() { aeq(ZERO.bisect(), "([0, 0], [0, 0])"); aeq(ONE.bisect(), "([1, 1], [1, 1])"); aeq(read("[4, 4]").get().bisect(), "([4, 4], [4, 4])"); aeq(read("[1, 2]").get().bisect(), "([1, 3/2], [3/2, 2])"); aeq(read("[-2, 5/3]").get().bisect(), "([-2, -1/6], [-1/6, 5/3])"); try { ALL.bisect(); fail(); } catch (ArithmeticException ignored) {} try { read("(-Infinity, 1]").get().bisect(); fail(); } catch (ArithmeticException ignored) {} try { read("[1, Infinity)").get().bisect(); fail(); } catch (ArithmeticException ignored) {} } @Test public void testRoundingPreimage_float() { aeq( roundingPreimage(0.0f), "[-1/1427247692705959881058285969449495136382746624, 1/1427247692705959881058285969449495136382746624]" ); aeq( roundingPreimage(-0.0f), "[-1/1427247692705959881058285969449495136382746624, 1/1427247692705959881058285969449495136382746624]" ); aeq(roundingPreimage(Float.POSITIVE_INFINITY), "[340282346638528859811704183484516925440, Infinity)"); aeq(roundingPreimage(Float.NEGATIVE_INFINITY), "(-Infinity, -340282346638528859811704183484516925440]"); aeq(roundingPreimage(1.0f), "[33554431/33554432, 16777217/16777216]"); aeq(roundingPreimage(13.0f), "[27262975/2097152, 27262977/2097152]"); aeq(roundingPreimage(-5.0f), "[-20971521/4194304, -20971519/4194304]"); aeq(roundingPreimage(1.5f), "[25165823/16777216, 25165825/16777216]"); aeq(roundingPreimage(0.15625f), "[20971519/134217728, 20971521/134217728]"); aeq(roundingPreimage(0.1f), "[26843545/268435456, 26843547/268435456]"); aeq(roundingPreimage(1.0f / 3.0f), "[22369621/67108864, 22369623/67108864]"); aeq(roundingPreimage(1.0e10f), "[9999999488, 10000000512]"); aeq(roundingPreimage(1.0e30f), "[999999977268534356919527145472, 1000000052826398082833850564608]"); aeq(roundingPreimage((float) Math.PI), "[26353589/8388608, 26353591/8388608]"); aeq(roundingPreimage((float) Math.E), "[22802599/8388608, 22802601/8388608]"); aeq(roundingPreimage((float) Math.sqrt(2)), "[23726565/16777216, 23726567/16777216]"); aeq( roundingPreimage(Float.MIN_VALUE), "[1/1427247692705959881058285969449495136382746624, 3/1427247692705959881058285969449495136382746624]" ); aeq( roundingPreimage(-Float.MIN_VALUE), "[-3/1427247692705959881058285969449495136382746624," + " -1/1427247692705959881058285969449495136382746624]" ); aeq( roundingPreimage(Float.MIN_NORMAL), "[16777215/1427247692705959881058285969449495136382746624," + " 16777217/1427247692705959881058285969449495136382746624]" ); aeq( roundingPreimage(-Float.MIN_NORMAL), "[-16777217/1427247692705959881058285969449495136382746624," + " -16777215/1427247692705959881058285969449495136382746624]" ); aeq( roundingPreimage(Float.MAX_VALUE), "[340282336497324057985868971510891282432, 340282346638528859811704183484516925440]" ); aeq( roundingPreimage(-Float.MAX_VALUE), "[-340282346638528859811704183484516925440, -340282336497324057985868971510891282432]" ); try { roundingPreimage(Float.NaN); fail(); } catch (ArithmeticException ignored) {} } @Test public void testRoundingPreimage_double() { aeq( roundingPreimage(0.0), "[-1/40480450661462123670499069343783461409911329952828423671380271605486067913599069378392076740287" + "424899037415572863362382277961747477158695373402679988147701984303484855313272272893381548418643268" + "247953535694549013712401496684938539723620671129831911268162011302471753910466682923046100506437265" + "5017292012526615415482186989568," + " 1/404804506614621236704990693437834614099113299528284236713802716054860679135990693783920767402874" + "248990374155728633623822779617474771586953734026799881477019843034848553132722728933815484186432682" + "479535356945490137124014966849385397236206711298319112681620113024717539104666829230461005064372655" + "017292012526615415482186989568]" ); aeq( roundingPreimage(-0.0), "[-1/40480450661462123670499069343783461409911329952828423671380271605486067913599069378392076740287" + "424899037415572863362382277961747477158695373402679988147701984303484855313272272893381548418643268" + "247953535694549013712401496684938539723620671129831911268162011302471753910466682923046100506437265" + "5017292012526615415482186989568," + " 1/404804506614621236704990693437834614099113299528284236713802716054860679135990693783920767402874" + "248990374155728633623822779617474771586953734026799881477019843034848553132722728933815484186432682" + "479535356945490137124014966849385397236206711298319112681620113024717539104666829230461005064372655" + "017292012526615415482186989568]" ); aeq( roundingPreimage(Double.POSITIVE_INFINITY), "[17976931348623157081452742373170435679807056752584499659891747680315726078002853876058955863276687" + "817154045895351438246423432132688946418276846754670353751698604991057655128207624549009038932894407" + "586850845513394230458323690322294816580855933212334827479782620414472316873817718091929988125040402" + "6184124858368," + " Infinity)" ); aeq( roundingPreimage(Double.NEGATIVE_INFINITY), "(-Infinity," + " -1797693134862315708145274237317043567980705675258449965989174768031572607800285387605895586327668" + "781715404589535143824642343213268894641827684675467035375169860499105765512820762454900903893289440" + "758685084551339423045832369032229481658085593321233482747978262041447231687381771809192998812504040" + "26184124858368]" ); aeq(roundingPreimage(1.0), "[18014398509481983/18014398509481984, 9007199254740993/9007199254740992]"); aeq(roundingPreimage(13.0), "[14636698788954111/1125899906842624, 14636698788954113/1125899906842624]"); aeq(roundingPreimage(-5.0), "[-11258999068426241/2251799813685248, -11258999068426239/2251799813685248]"); aeq(roundingPreimage(1.5), "[13510798882111487/9007199254740992, 13510798882111489/9007199254740992]"); aeq(roundingPreimage(0.15625), "[11258999068426239/72057594037927936, 11258999068426241/72057594037927936]"); aeq(roundingPreimage(0.1), "[14411518807585587/144115188075855872, 14411518807585589/144115188075855872]"); aeq(roundingPreimage(1.0 / 3.0), "[12009599006321321/36028797018963968, 12009599006321323/36028797018963968]"); aeq(roundingPreimage(1.0e10), "[10485759999999999/1048576, 10485760000000001/1048576]"); aeq(roundingPreimage(1.0e30), "[999999999999999949515880660992, 1000000000000000090253369016320]"); aeq(roundingPreimage(Math.PI), "[14148475504056879/4503599627370496, 14148475504056881/4503599627370496]"); aeq(roundingPreimage(Math.E), "[12242053029736145/4503599627370496, 12242053029736147/4503599627370496]"); aeq(roundingPreimage(Math.sqrt(2)), "[12738103345051545/9007199254740992, 12738103345051547/9007199254740992]"); aeq( roundingPreimage(Double.MIN_VALUE), "[1/404804506614621236704990693437834614099113299528284236713802716054860679135990693783920767402874" + "248990374155728633623822779617474771586953734026799881477019843034848553132722728933815484186432682" + "479535356945490137124014966849385397236206711298319112681620113024717539104666829230461005064372655" + "017292012526615415482186989568," + " 3/404804506614621236704990693437834614099113299528284236713802716054860679135990693783920767402874" + "248990374155728633623822779617474771586953734026799881477019843034848553132722728933815484186432682" + "479535356945490137124014966849385397236206711298319112681620113024717539104666829230461005064372655" + "017292012526615415482186989568]" ); aeq( roundingPreimage(-Double.MIN_VALUE), "[-3/40480450661462123670499069343783461409911329952828423671380271605486067913599069378392076740287" + "424899037415572863362382277961747477158695373402679988147701984303484855313272272893381548418643268" + "247953535694549013712401496684938539723620671129831911268162011302471753910466682923046100506437265" + "5017292012526615415482186989568," + " -1/40480450661462123670499069343783461409911329952828423671380271605486067913599069378392076740287" + "424899037415572863362382277961747477158695373402679988147701984303484855313272272893381548418643268" + "247953535694549013712401496684938539723620671129831911268162011302471753910466682923046100506437265" + "5017292012526615415482186989568]" ); aeq( roundingPreimage(Double.MIN_NORMAL), "[9007199254740991/404804506614621236704990693437834614099113299528284236713802716054860679135990693" + "783920767402874248990374155728633623822779617474771586953734026799881477019843034848553132722728933" + "815484186432682479535356945490137124014966849385397236206711298319112681620113024717539104666829230" + "461005064372655017292012526615415482186989568," + " 9007199254740993/404804506614621236704990693437834614099113299528284236713802716054860679135990693" + "783920767402874248990374155728633623822779617474771586953734026799881477019843034848553132722728933" + "815484186432682479535356945490137124014966849385397236206711298319112681620113024717539104666829230" + "461005064372655017292012526615415482186989568]" ); aeq( roundingPreimage(-Double.MIN_NORMAL), "[-9007199254740993/40480450661462123670499069343783461409911329952828423671380271605486067913599069" + "378392076740287424899037415572863362382277961747477158695373402679988147701984303484855313272272893" + "381548418643268247953535694549013712401496684938539723620671129831911268162011302471753910466682923" + "0461005064372655017292012526615415482186989568," + " -9007199254740991/40480450661462123670499069343783461409911329952828423671380271605486067913599069" + "378392076740287424899037415572863362382277961747477158695373402679988147701984303484855313272272893" + "381548418643268247953535694549013712401496684938539723620671129831911268162011302471753910466682923" + "0461005064372655017292012526615415482186989568]" ); aeq( roundingPreimage(Double.MAX_VALUE), "[17976931348623156083532587605810529851620700234165216626166117462586955326729232657453009928794654" + "924675063149033587701752208710592698796290627760473556921329019091915239418047621712533496094635638" + "726128664019802903779951418360298151175628372777140383052148396392393563313364280213909166945792787" + "4464075218944," + " 17976931348623157081452742373170435679807056752584499659891747680315726078002853876058955863276687" + "817154045895351438246423432132688946418276846754670353751698604991057655128207624549009038932894407" + "586850845513394230458323690322294816580855933212334827479782620414472316873817718091929988125040402" + "6184124858368]" ); aeq( roundingPreimage(-Double.MAX_VALUE), "[-1797693134862315708145274237317043567980705675258449965989174768031572607800285387605895586327668" + "781715404589535143824642343213268894641827684675467035375169860499105765512820762454900903893289440" + "758685084551339423045832369032229481658085593321233482747978262041447231687381771809192998812504040" + "26184124858368," + " -1797693134862315608353258760581052985162070023416521662616611746258695532672923265745300992879465" + "492467506314903358770175220871059269879629062776047355692132901909191523941804762171253349609463563" + "872612866401980290377995141836029815117562837277714038305214839639239356331336428021390916694579278" + "74464075218944]" ); try { roundingPreimage(Double.NaN); fail(); } catch (ArithmeticException ignored) {} } @Test public void testRoundingPreimage_BigDecimal() { aeq(roundingPreimage(BigDecimal.ZERO), "[-1/2, 1/2]"); aeq(roundingPreimage(BigDecimal.ONE), "[1/2, 3/2]"); aeq(roundingPreimage(new BigDecimal("3")), "[5/2, 7/2]"); aeq(roundingPreimage(new BigDecimal("-5")), "[-11/2, -9/2]"); aeq(roundingPreimage(new BigDecimal("0.1")), "[1/20, 3/20]"); aeq(roundingPreimage(new BigDecimal("3.14159")), "[628317/200000, 628319/200000]"); aeq( roundingPreimage(new BigDecimal("-2.718281828459045")), "[-5436563656918091/2000000000000000, -5436563656918089/2000000000000000]" ); aeq(roundingPreimage(new BigDecimal("0.00000000000001")), "[1/200000000000000, 3/200000000000000]"); aeq(roundingPreimage(new BigDecimal("1000000000000000")), "[1999999999999999/2, 2000000000000001/2]"); aeq(roundingPreimage(new BigDecimal("1E15")), "[500000000000000, 1500000000000000]"); } @Test public void testFloatRange() { aeq(ZERO.floatRange(), "(0.0, 0.0)"); aeq(ONE.floatRange(), "(1.0, 1.0)"); aeq(ALL.floatRange(), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().floatRange(), "(-2.0, 1.6666667)"); aeq(read("[5/3, 4]").get().floatRange(), "(1.6666666, 4.0)"); aeq(read("[4, 4]").get().floatRange(), "(4.0, 4.0)"); aeq(read("[1/3, 1/3]").get().floatRange(), "(0.3333333, 0.33333334)"); aeq(read("(-Infinity, 3/2]").get().floatRange(), "(-Infinity, 1.5)"); aeq(read("[-6, Infinity)").get().floatRange(), "(-6.0, Infinity)"); aeq(of(Rational.of(10).pow(-100)).floatRange(), "(0.0, 1.4E-45)"); aeq(of(Rational.of(10).pow(-100).negate()).floatRange(), "(-1.4E-45, -0.0)"); aeq(of(Rational.of(10).pow(-100).negate(), Rational.of(10).pow(-100)).floatRange(), "(-1.4E-45, 1.4E-45)"); aeq(of(Rational.of(10).pow(100)).floatRange(), "(3.4028235E38, Infinity)"); aeq(of(Rational.of(10).pow(100).negate()).floatRange(), "(-Infinity, -3.4028235E38)"); aeq(of(Rational.of(10).pow(100).negate(), Rational.of(10).pow(100)).floatRange(), "(-Infinity, Infinity)"); } @Test public void testDoubleRange() { aeq(ZERO.doubleRange(), "(0.0, 0.0)"); aeq(ONE.doubleRange(), "(1.0, 1.0)"); aeq(ALL.doubleRange(), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().doubleRange(), "(-2.0, 1.6666666666666667)"); aeq(read("[5/3, 4]").get().doubleRange(), "(1.6666666666666665, 4.0)"); aeq(read("[4, 4]").get().doubleRange(), "(4.0, 4.0)"); aeq(read("[1/3, 1/3]").get().doubleRange(), "(0.3333333333333333, 0.33333333333333337)"); aeq(read("(-Infinity, 3/2]").get().doubleRange(), "(-Infinity, 1.5)"); aeq(read("[-6, Infinity)").get().doubleRange(), "(-6.0, Infinity)"); aeq(of(Rational.of(10).pow(-1000)).doubleRange(), "(0.0, 4.9E-324)"); aeq(of(Rational.of(10).pow(-1000).negate()).doubleRange(), "(-4.9E-324, -0.0)"); aeq( of(Rational.of(10).pow(-1000).negate(), Rational.of(10).pow(-1000)).doubleRange(), "(-4.9E-324, 4.9E-324)" ); aeq(of(Rational.of(10).pow(1000)).doubleRange(), "(1.7976931348623157E308, Infinity)"); aeq(of(Rational.of(10).pow(1000).negate()).doubleRange(), "(-Infinity, -1.7976931348623157E308)"); aeq(of(Rational.of(10).pow(1000).negate(), Rational.of(10).pow(1000)).doubleRange(), "(-Infinity, Infinity)"); } @Test public void testAdd() { aeq(ZERO.add(ZERO), "[0, 0]"); aeq(ZERO.add(ONE), "[1, 1]"); aeq(ZERO.add(ALL), "(-Infinity, Infinity)"); aeq(ZERO.add(read("[-2, 5/3]").get()), "[-2, 5/3]"); aeq(ZERO.add(read("[4, 4]").get()), "[4, 4]"); aeq(ZERO.add(read("(-Infinity, 3/2]").get()), "(-Infinity, 3/2]"); aeq(ZERO.add(read("[-6, Infinity)").get()), "[-6, Infinity)"); aeq(ONE.add(ZERO), "[1, 1]"); aeq(ONE.add(ONE), "[2, 2]"); aeq(ONE.add(ALL), "(-Infinity, Infinity)"); aeq(ONE.add(read("[-2, 5/3]").get()), "[-1, 8/3]"); aeq(ONE.add(read("[4, 4]").get()), "[5, 5]"); aeq(ONE.add(read("(-Infinity, 3/2]").get()), "(-Infinity, 5/2]"); aeq(ONE.add(read("[-6, Infinity)").get()), "[-5, Infinity)"); aeq(ALL.add(ZERO), "(-Infinity, Infinity)"); aeq(ALL.add(ONE), "(-Infinity, Infinity)"); aeq(ALL.add(ALL), "(-Infinity, Infinity)"); aeq(ALL.add(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(ALL.add(read("[4, 4]").get()), "(-Infinity, Infinity)"); aeq(ALL.add(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(ALL.add(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().add(ZERO), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().add(ONE), "[-1, 8/3]"); aeq(read("[-2, 5/3]").get().add(ALL), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().add(read("[-2, 5/3]").get()), "[-4, 10/3]"); aeq(read("[-2, 5/3]").get().add(read("[4, 4]").get()), "[2, 17/3]"); aeq(read("[-2, 5/3]").get().add(read("(-Infinity, 3/2]").get()), "(-Infinity, 19/6]"); aeq(read("[-2, 5/3]").get().add(read("[-6, Infinity)").get()), "[-8, Infinity)"); aeq(read("[4, 4]").get().add(ZERO), "[4, 4]"); aeq(read("[4, 4]").get().add(ONE), "[5, 5]"); aeq(read("[4, 4]").get().add(ALL), "(-Infinity, Infinity)"); aeq(read("[4, 4]").get().add(read("[-2, 5/3]").get()), "[2, 17/3]"); aeq(read("[4, 4]").get().add(read("[4, 4]").get()), "[8, 8]"); aeq(read("[4, 4]").get().add(read("(-Infinity, 3/2]").get()), "(-Infinity, 11/2]"); aeq(read("[4, 4]").get().add(read("[-6, Infinity)").get()), "[-2, Infinity)"); aeq(read("(-Infinity, 3/2]").get().add(ZERO), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().add(ONE), "(-Infinity, 5/2]"); aeq(read("(-Infinity, 3/2]").get().add(ALL), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().add(read("[-2, 5/3]").get()), "(-Infinity, 19/6]"); aeq(read("(-Infinity, 3/2]").get().add(read("[4, 4]").get()), "(-Infinity, 11/2]"); aeq(read("(-Infinity, 3/2]").get().add(read("(-Infinity, 3/2]").get()), "(-Infinity, 3]"); aeq(read("(-Infinity, 3/2]").get().add(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().add(ZERO), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().add(ONE), "[-5, Infinity)"); aeq(read("[-6, Infinity)").get().add(ALL), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().add(read("[-2, 5/3]").get()), "[-8, Infinity)"); aeq(read("[-6, Infinity)").get().add(read("[4, 4]").get()), "[-2, Infinity)"); aeq(read("[-6, Infinity)").get().add(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().add(read("[-6, Infinity)").get()), "[-12, Infinity)"); } @Test public void testNegate() { aeq(ZERO.negate(), "[0, 0]"); aeq(ONE.negate(), "[-1, -1]"); aeq(ALL.negate(), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().negate(), "[-5/3, 2]"); aeq(read("[4, 4]").get().negate(), "[-4, -4]"); aeq(read("(-Infinity, 3/2]").get().negate(), "[-3/2, Infinity)"); aeq(read("[-6, Infinity)").get().negate(), "(-Infinity, 6]"); } @Test public void testAbs() { aeq(ZERO.abs(), "[0, 0]"); aeq(ONE.abs(), "[1, 1]"); aeq(ALL.abs(), "[0, Infinity)"); aeq(read("[-2, 5/3]").get().abs(), "[0, 2]"); aeq(read("[4, 4]").get().abs(), "[4, 4]"); aeq(read("(-Infinity, 3/2]").get().abs(), "[0, Infinity)"); aeq(read("(-Infinity, -3/2]").get().abs(), "[3/2, Infinity)"); aeq(read("[-6, Infinity)").get().abs(), "[0, Infinity)"); aeq(read("[6, Infinity)").get().abs(), "[6, Infinity)"); } @Test public void testSignum() { aeq(ZERO.signum(), "Optional[0]"); aeq(ONE.signum(), "Optional[1]"); aeq(ALL.signum(), "Optional.empty"); aeq(read("[-2, 5/3]").get().signum(), "Optional.empty"); aeq(read("[4, 4]").get().signum(), "Optional[1]"); aeq(read("(-Infinity, 3/2]").get().signum(), "Optional.empty"); aeq(read("(-Infinity, -3/2]").get().signum(), "Optional[-1]"); aeq(read("[-6, Infinity)").get().signum(), "Optional.empty"); aeq(read("[6, Infinity)").get().signum(), "Optional[1]"); } @Test public void testSubtract() { aeq(ZERO.subtract(ZERO), "[0, 0]"); aeq(ZERO.subtract(ONE), "[-1, -1]"); aeq(ZERO.subtract(ALL), "(-Infinity, Infinity)"); aeq(ZERO.subtract(read("[-2, 5/3]").get()), "[-5/3, 2]"); aeq(ZERO.subtract(read("[4, 4]").get()), "[-4, -4]"); aeq(ZERO.subtract(read("(-Infinity, 3/2]").get()), "[-3/2, Infinity)"); aeq(ZERO.subtract(read("[-6, Infinity)").get()), "(-Infinity, 6]"); aeq(ONE.subtract(ZERO), "[1, 1]"); aeq(ONE.subtract(ONE), "[0, 0]"); aeq(ONE.subtract(ALL), "(-Infinity, Infinity)"); aeq(ONE.subtract(read("[-2, 5/3]").get()), "[-2/3, 3]"); aeq(ONE.subtract(read("[4, 4]").get()), "[-3, -3]"); aeq(ONE.subtract(read("(-Infinity, 3/2]").get()), "[-1/2, Infinity)"); aeq(ONE.subtract(read("[-6, Infinity)").get()), "(-Infinity, 7]"); aeq(ALL.subtract(ZERO), "(-Infinity, Infinity)"); aeq(ALL.subtract(ONE), "(-Infinity, Infinity)"); aeq(ALL.subtract(ALL), "(-Infinity, Infinity)"); aeq(ALL.subtract(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(ALL.subtract(read("[4, 4]").get()), "(-Infinity, Infinity)"); aeq(ALL.subtract(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(ALL.subtract(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().subtract(ZERO), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().subtract(ONE), "[-3, 2/3]"); aeq(read("[-2, 5/3]").get().subtract(ALL), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().subtract(read("[-2, 5/3]").get()), "[-11/3, 11/3]"); aeq(read("[-2, 5/3]").get().subtract(read("[4, 4]").get()), "[-6, -7/3]"); aeq(read("[-2, 5/3]").get().subtract(read("(-Infinity, 3/2]").get()), "[-7/2, Infinity)"); aeq(read("[-2, 5/3]").get().subtract(read("[-6, Infinity)").get()), "(-Infinity, 23/3]"); aeq(read("[4, 4]").get().subtract(ZERO), "[4, 4]"); aeq(read("[4, 4]").get().subtract(ONE), "[3, 3]"); aeq(read("[4, 4]").get().subtract(ALL), "(-Infinity, Infinity)"); aeq(read("[4, 4]").get().subtract(read("[-2, 5/3]").get()), "[7/3, 6]"); aeq(read("[4, 4]").get().subtract(read("[4, 4]").get()), "[0, 0]"); aeq(read("[4, 4]").get().subtract(read("(-Infinity, 3/2]").get()), "[5/2, Infinity)"); aeq(read("[4, 4]").get().subtract(read("[-6, Infinity)").get()), "(-Infinity, 10]"); aeq(read("(-Infinity, 3/2]").get().subtract(ZERO), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().subtract(ONE), "(-Infinity, 1/2]"); aeq(read("(-Infinity, 3/2]").get().subtract(ALL), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().subtract(read("[-2, 5/3]").get()), "(-Infinity, 7/2]"); aeq(read("(-Infinity, 3/2]").get().subtract(read("[4, 4]").get()), "(-Infinity, -5/2]"); aeq(read("(-Infinity, 3/2]").get().subtract(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().subtract(read("[-6, Infinity)").get()), "(-Infinity, 15/2]"); aeq(read("[-6, Infinity)").get().subtract(ZERO), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().subtract(ONE), "[-7, Infinity)"); aeq(read("[-6, Infinity)").get().subtract(ALL), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().subtract(read("[-2, 5/3]").get()), "[-23/3, Infinity)"); aeq(read("[-6, Infinity)").get().subtract(read("[4, 4]").get()), "[-10, Infinity)"); aeq(read("[-6, Infinity)").get().subtract(read("(-Infinity, 3/2]").get()), "[-15/2, Infinity)"); aeq(read("[-6, Infinity)").get().subtract(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); } @Test public void testMultiply_Interval() { aeq(ZERO.multiply(ZERO), "[0, 0]"); aeq(ZERO.multiply(ONE), "[0, 0]"); aeq(ZERO.multiply(ALL), "[0, 0]"); aeq(ZERO.multiply(read("[-2, 5/3]").get()), "[0, 0]"); aeq(ZERO.multiply(read("[4, 4]").get()), "[0, 0]"); aeq(ZERO.multiply(read("(-Infinity, 3/2]").get()), "[0, 0]"); aeq(ZERO.multiply(read("[-6, Infinity)").get()), "[0, 0]"); aeq(ONE.multiply(ZERO), "[0, 0]"); aeq(ONE.multiply(ONE), "[1, 1]"); aeq(ONE.multiply(ALL), "(-Infinity, Infinity)"); aeq(ONE.multiply(read("[-2, 5/3]").get()), "[-2, 5/3]"); aeq(ONE.multiply(read("[4, 4]").get()), "[4, 4]"); aeq(ONE.multiply(read("(-Infinity, 3/2]").get()), "(-Infinity, 3/2]"); aeq(ONE.multiply(read("[-6, Infinity)").get()), "[-6, Infinity)"); aeq(ALL.multiply(ZERO), "[0, 0]"); aeq(ALL.multiply(ONE), "(-Infinity, Infinity)"); aeq(ALL.multiply(ALL), "(-Infinity, Infinity)"); aeq(ALL.multiply(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(ALL.multiply(read("[4, 4]").get()), "(-Infinity, Infinity)"); aeq(ALL.multiply(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(ALL.multiply(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().multiply(ZERO), "[0, 0]"); aeq(read("[-2, 5/3]").get().multiply(ONE), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().multiply(ALL), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().multiply(read("[-2, 5/3]").get()), "[-10/3, 4]"); aeq(read("[-2, 5/3]").get().multiply(read("[4, 4]").get()), "[-8, 20/3]"); aeq(read("[-2, 5/3]").get().multiply(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().multiply(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[4, 4]").get().multiply(ZERO), "[0, 0]"); aeq(read("[4, 4]").get().multiply(ONE), "[4, 4]"); aeq(read("[4, 4]").get().multiply(ALL), "(-Infinity, Infinity)"); aeq(read("[4, 4]").get().multiply(read("[-2, 5/3]").get()), "[-8, 20/3]"); aeq(read("[4, 4]").get().multiply(read("[4, 4]").get()), "[16, 16]"); aeq(read("[4, 4]").get().multiply(read("(-Infinity, 3/2]").get()), "(-Infinity, 6]"); aeq(read("[4, 4]").get().multiply(read("[-6, Infinity)").get()), "[-24, Infinity)"); aeq(read("(-Infinity, 3/2]").get().multiply(ZERO), "[0, 0]"); aeq(read("(-Infinity, 3/2]").get().multiply(ONE), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().multiply(ALL), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().multiply(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().multiply(read("[4, 4]").get()), "(-Infinity, 6]"); aeq(read("(-Infinity, 3/2]").get().multiply(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().multiply(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(ZERO), "[0, 0]"); aeq(read("[-6, Infinity)").get().multiply(ONE), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(ALL), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(read("[4, 4]").get()), "[-24, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 0]").get().multiply(read("(-Infinity, 0]").get()), "[0, Infinity)"); } @Test public void testMultiply_Rational() { aeq(ZERO.multiply(Rational.ZERO), "[0, 0]"); aeq(ZERO.multiply(Rational.ONE), "[0, 0]"); aeq(ZERO.multiply(Rational.read("2/3").get()), "[0, 0]"); aeq(ZERO.multiply(Rational.read("-7").get()), "[0, 0]"); aeq(ONE.multiply(Rational.ZERO), "[0, 0]"); aeq(ONE.multiply(Rational.ONE), "[1, 1]"); aeq(ONE.multiply(Rational.read("2/3").get()), "[2/3, 2/3]"); aeq(ONE.multiply(Rational.read("-7").get()), "[-7, -7]"); aeq(ALL.multiply(Rational.ZERO), "[0, 0]"); aeq(ALL.multiply(Rational.ONE), "(-Infinity, Infinity)"); aeq(ALL.multiply(Rational.read("2/3").get()), "(-Infinity, Infinity)"); aeq(ALL.multiply(Rational.read("-7").get()), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().multiply(Rational.ZERO), "[0, 0]"); aeq(read("[-2, 5/3]").get().multiply(Rational.ONE), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().multiply(Rational.read("2/3").get()), "[-4/3, 10/9]"); aeq(read("[-2, 5/3]").get().multiply(Rational.read("-7").get()), "[-35/3, 14]"); aeq(read("[4, 4]").get().multiply(Rational.ZERO), "[0, 0]"); aeq(read("[4, 4]").get().multiply(Rational.ONE), "[4, 4]"); aeq(read("[4, 4]").get().multiply(Rational.read("2/3").get()), "[8/3, 8/3]"); aeq(read("[4, 4]").get().multiply(Rational.read("-7").get()), "[-28, -28]"); aeq(read("(-Infinity, 3/2]").get().multiply(Rational.ZERO), "[0, 0]"); aeq(read("(-Infinity, 3/2]").get().multiply(Rational.ONE), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().multiply(Rational.read("2/3").get()), "(-Infinity, 1]"); aeq(read("(-Infinity, 3/2]").get().multiply(Rational.read("-7").get()), "[-21/2, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(Rational.ZERO), "[0, 0]"); aeq(read("[-6, Infinity)").get().multiply(Rational.ONE), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(Rational.read("2/3").get()), "[-4, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(Rational.read("-7").get()), "(-Infinity, 42]"); } @Test public void testMultiply_BigInteger() { aeq(ZERO.multiply(BigInteger.ZERO), "[0, 0]"); aeq(ZERO.multiply(BigInteger.ONE), "[0, 0]"); aeq(ZERO.multiply(BigInteger.valueOf(5)), "[0, 0]"); aeq(ZERO.multiply(BigInteger.valueOf(-7)), "[0, 0]"); aeq(ONE.multiply(BigInteger.ZERO), "[0, 0]"); aeq(ONE.multiply(BigInteger.ONE), "[1, 1]"); aeq(ONE.multiply(BigInteger.valueOf(5)), "[5, 5]"); aeq(ONE.multiply(BigInteger.valueOf(-7)), "[-7, -7]"); aeq(ALL.multiply(BigInteger.ZERO), "[0, 0]"); aeq(ALL.multiply(BigInteger.ONE), "(-Infinity, Infinity)"); aeq(ALL.multiply(BigInteger.valueOf(5)), "(-Infinity, Infinity)"); aeq(ALL.multiply(BigInteger.valueOf(-7)), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().multiply(BigInteger.ZERO), "[0, 0]"); aeq(read("[-2, 5/3]").get().multiply(BigInteger.ONE), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().multiply(BigInteger.valueOf(5)), "[-10, 25/3]"); aeq(read("[-2, 5/3]").get().multiply(BigInteger.valueOf(-7)), "[-35/3, 14]"); aeq(read("[4, 4]").get().multiply(BigInteger.ZERO), "[0, 0]"); aeq(read("[4, 4]").get().multiply(BigInteger.ONE), "[4, 4]"); aeq(read("[4, 4]").get().multiply(BigInteger.valueOf(5)), "[20, 20]"); aeq(read("[4, 4]").get().multiply(BigInteger.valueOf(-7)), "[-28, -28]"); aeq(read("(-Infinity, 3/2]").get().multiply(BigInteger.ZERO), "[0, 0]"); aeq(read("(-Infinity, 3/2]").get().multiply(BigInteger.ONE), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().multiply(BigInteger.valueOf(5)), "(-Infinity, 15/2]"); aeq(read("(-Infinity, 3/2]").get().multiply(BigInteger.valueOf(-7)), "[-21/2, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(BigInteger.ZERO), "[0, 0]"); aeq(read("[-6, Infinity)").get().multiply(BigInteger.ONE), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(BigInteger.valueOf(5)), "[-30, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(BigInteger.valueOf(-7)), "(-Infinity, 42]"); } @Test public void testMultiply_int() { aeq(ZERO.multiply(0), "[0, 0]"); aeq(ZERO.multiply(1), "[0, 0]"); aeq(ZERO.multiply(5), "[0, 0]"); aeq(ZERO.multiply(-7), "[0, 0]"); aeq(ONE.multiply(0), "[0, 0]"); aeq(ONE.multiply(1), "[1, 1]"); aeq(ONE.multiply(5), "[5, 5]"); aeq(ONE.multiply(-7), "[-7, -7]"); aeq(ALL.multiply(0), "[0, 0]"); aeq(ALL.multiply(1), "(-Infinity, Infinity)"); aeq(ALL.multiply(5), "(-Infinity, Infinity)"); aeq(ALL.multiply(-7), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().multiply(0), "[0, 0]"); aeq(read("[-2, 5/3]").get().multiply(1), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().multiply(5), "[-10, 25/3]"); aeq(read("[-2, 5/3]").get().multiply(-7), "[-35/3, 14]"); aeq(read("[4, 4]").get().multiply(0), "[0, 0]"); aeq(read("[4, 4]").get().multiply(1), "[4, 4]"); aeq(read("[4, 4]").get().multiply(5), "[20, 20]"); aeq(read("[4, 4]").get().multiply(-7), "[-28, -28]"); aeq(read("(-Infinity, 3/2]").get().multiply(0), "[0, 0]"); aeq(read("(-Infinity, 3/2]").get().multiply(1), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().multiply(5), "(-Infinity, 15/2]"); aeq(read("(-Infinity, 3/2]").get().multiply(-7), "[-21/2, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(0), "[0, 0]"); aeq(read("[-6, Infinity)").get().multiply(1), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(5), "[-30, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(-7), "(-Infinity, 42]"); } @Test public void testInvert() { aeq(ZERO.invert(), "[]"); aeq(ONE.invert(), "[[1, 1]]"); aeq(ALL.invert(), "[(-Infinity, Infinity)]"); aeq(read("[-2, 5/3]").get().invert(), "[(-Infinity, -1/2], [3/5, Infinity)]"); aeq(read("[4, 4]").get().invert(), "[[1/4, 1/4]]"); aeq(read("[0, 4]").get().invert(), "[[1/4, Infinity)]"); aeq(read("[-4, 0]").get().invert(), "[(-Infinity, -1/4]]"); aeq(read("(-Infinity, -3/2]").get().invert(), "[[-2/3, 0]]"); aeq(read("(-Infinity, 3/2]").get().invert(), "[(-Infinity, 0], [2/3, Infinity)]"); aeq(read("(-Infinity, 0]").get().invert(), "[(-Infinity, 0]]"); aeq(read("[-6, Infinity)").get().invert(), "[(-Infinity, -1/6], [0, Infinity)]"); aeq(read("[6, Infinity)").get().invert(), "[[0, 1/6]]"); aeq(read("[0, Infinity)").get().invert(), "[[0, Infinity)]"); aeq(read("(-Infinity, 0]").get().invert(), "[(-Infinity, 0]]"); } @Test public void testInvertHull() { aeq(ONE.invertHull(), "[1, 1]"); aeq(ALL.invertHull(), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().invertHull(), "(-Infinity, Infinity)"); aeq(read("[4, 4]").get().invertHull(), "[1/4, 1/4]"); aeq(read("[0, 4]").get().invertHull(), "[1/4, Infinity)"); aeq(read("[-4, 0]").get().invertHull(), "(-Infinity, -1/4]"); aeq(read("(-Infinity, -3/2]").get().invertHull(), "[-2/3, 0]"); aeq(read("(-Infinity, 3/2]").get().invertHull(), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 0]").get().invertHull(), "(-Infinity, 0]"); aeq(read("[-6, Infinity)").get().invertHull(), "(-Infinity, Infinity)"); aeq(read("[6, Infinity)").get().invertHull(), "[0, 1/6]"); aeq(read("[0, Infinity)").get().invertHull(), "[0, Infinity)"); aeq(read("(-Infinity, 0]").get().invertHull(), "(-Infinity, 0]"); try { ZERO.invertHull(); fail(); } catch (ArithmeticException ignored) {} } @Test public void testDivide_Interval() { aeq(ZERO.divide(ZERO), "[]"); aeq(ZERO.divide(ONE), "[[0, 0]]"); aeq(ZERO.divide(ALL), "[[0, 0]]"); aeq(ZERO.divide(read("[-2, 5/3]").get()), "[[0, 0]]"); aeq(ZERO.divide(read("[4, 4]").get()), "[[0, 0]]"); aeq(ZERO.divide(read("(-Infinity, 3/2]").get()), "[[0, 0]]"); aeq(ZERO.divide(read("[-6, Infinity)").get()), "[[0, 0]]"); aeq(ONE.divide(ZERO), "[]"); aeq(ONE.divide(ONE), "[[1, 1]]"); aeq(ONE.divide(ALL), "[(-Infinity, Infinity)]"); aeq(ONE.divide(read("[-2, 5/3]").get()), "[(-Infinity, -1/2], [3/5, Infinity)]"); aeq(ONE.divide(read("[4, 4]").get()), "[[1/4, 1/4]]"); aeq(ONE.divide(read("(-Infinity, 3/2]").get()), "[(-Infinity, 0], [2/3, Infinity)]"); aeq(ONE.divide(read("[-6, Infinity)").get()), "[(-Infinity, -1/6], [0, Infinity)]"); aeq(ALL.divide(ZERO), "[]"); aeq(ALL.divide(ONE), "[(-Infinity, Infinity)]"); aeq(ALL.divide(ALL), "[(-Infinity, Infinity)]"); aeq(ALL.divide(read("[-2, 5/3]").get()), "[(-Infinity, Infinity)]"); aeq(ALL.divide(read("[4, 4]").get()), "[(-Infinity, Infinity)]"); aeq(ALL.divide(read("(-Infinity, 3/2]").get()), "[(-Infinity, Infinity)]"); aeq(ALL.divide(read("[-6, Infinity)").get()), "[(-Infinity, Infinity)]"); aeq(read("[-2, 5/3]").get().divide(ZERO), "[]"); aeq(read("[-2, 5/3]").get().divide(ONE), "[[-2, 5/3]]"); aeq(read("[-2, 5/3]").get().divide(ALL), "[(-Infinity, Infinity)]"); aeq(read("[-2, 5/3]").get().divide(read("[-2, 5/3]").get()), "[(-Infinity, Infinity)]"); aeq(read("[-2, 5/3]").get().divide(read("[4, 4]").get()), "[[-1/2, 5/12]]"); aeq(read("[-2, 5/3]").get().divide(read("(-Infinity, 3/2]").get()), "[(-Infinity, Infinity)]"); aeq(read("[-2, 5/3]").get().divide(read("[-6, Infinity)").get()), "[(-Infinity, Infinity)]"); aeq(read("[4, 4]").get().divide(ZERO), "[]"); aeq(read("[4, 4]").get().divide(ONE), "[[4, 4]]"); aeq(read("[4, 4]").get().divide(ALL), "[(-Infinity, Infinity)]"); aeq(read("[4, 4]").get().divide(read("[-2, 5/3]").get()), "[(-Infinity, -2], [12/5, Infinity)]"); aeq(read("[4, 4]").get().divide(read("[4, 4]").get()), "[[1, 1]]"); aeq(read("[4, 4]").get().divide(read("(-Infinity, 3/2]").get()), "[(-Infinity, 0], [8/3, Infinity)]"); aeq(read("[4, 4]").get().divide(read("[-6, Infinity)").get()), "[(-Infinity, -2/3], [0, Infinity)]"); aeq(read("(-Infinity, 3/2]").get().divide(ZERO), "[]"); aeq(read("(-Infinity, 3/2]").get().divide(ONE), "[(-Infinity, 3/2]]"); aeq(read("(-Infinity, 3/2]").get().divide(ALL), "[(-Infinity, Infinity)]"); aeq(read("(-Infinity, 3/2]").get().divide(read("[-2, 5/3]").get()), "[(-Infinity, Infinity)]"); aeq(read("(-Infinity, 3/2]").get().divide(read("[4, 4]").get()), "[(-Infinity, 3/8]]"); aeq(read("(-Infinity, 3/2]").get().divide(read("(-Infinity, 3/2]").get()), "[(-Infinity, Infinity)]"); aeq(read("(-Infinity, 3/2]").get().divide(read("[-6, Infinity)").get()), "[(-Infinity, Infinity)]"); aeq(read("[-6, Infinity)").get().divide(ZERO), "[]"); aeq(read("[-6, Infinity)").get().divide(ONE), "[[-6, Infinity)]"); aeq(read("[-6, Infinity)").get().divide(ALL), "[(-Infinity, Infinity)]"); aeq(read("[-6, Infinity)").get().divide(read("[-2, 5/3]").get()), "[(-Infinity, Infinity)]"); aeq(read("[-6, Infinity)").get().divide(read("[4, 4]").get()), "[[-3/2, Infinity)]"); aeq(read("[-6, Infinity)").get().divide(read("(-Infinity, 3/2]").get()), "[(-Infinity, Infinity)]"); aeq(read("[-6, Infinity)").get().divide(read("[-6, Infinity)").get()), "[(-Infinity, Infinity)]"); aeq(read("(-Infinity, 0]").get().divide(read("(-Infinity, 0]").get()), "[[0, Infinity)]"); } @Test public void testDivideHull() { aeq(ZERO.divideHull(ONE), "[0, 0]"); aeq(ZERO.divideHull(ALL), "[0, 0]"); aeq(ZERO.divideHull(read("[-2, 5/3]").get()), "[0, 0]"); aeq(ZERO.divideHull(read("[4, 4]").get()), "[0, 0]"); aeq(ZERO.divideHull(read("(-Infinity, 3/2]").get()), "[0, 0]"); aeq(ZERO.divideHull(read("[-6, Infinity)").get()), "[0, 0]"); aeq(ONE.divideHull(ONE), "[1, 1]"); aeq(ONE.divideHull(ALL), "(-Infinity, Infinity)"); aeq(ONE.divideHull(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(ONE.divideHull(read("[4, 4]").get()), "[1/4, 1/4]"); aeq(ONE.divideHull(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(ONE.divideHull(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(ALL.divideHull(ONE), "(-Infinity, Infinity)"); aeq(ALL.divideHull(ALL), "(-Infinity, Infinity)"); aeq(ALL.divideHull(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(ALL.divideHull(read("[4, 4]").get()), "(-Infinity, Infinity)"); aeq(ALL.divideHull(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(ALL.divideHull(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().divideHull(ONE), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().divideHull(ALL), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().divideHull(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().divideHull(read("[4, 4]").get()), "[-1/2, 5/12]"); aeq(read("[-2, 5/3]").get().divideHull(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().divideHull(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[4, 4]").get().divideHull(ONE), "[4, 4]"); aeq(read("[4, 4]").get().divideHull(ALL), "(-Infinity, Infinity)"); aeq(read("[4, 4]").get().divideHull(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(read("[4, 4]").get().divideHull(read("[4, 4]").get()), "[1, 1]"); aeq(read("[4, 4]").get().divideHull(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(read("[4, 4]").get().divideHull(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().divideHull(ONE), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().divideHull(ALL), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().divideHull(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().divideHull(read("[4, 4]").get()), "(-Infinity, 3/8]"); aeq(read("(-Infinity, 3/2]").get().divideHull(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().divideHull(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().divideHull(ONE), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().divideHull(ALL), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().divideHull(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().divideHull(read("[4, 4]").get()), "[-3/2, Infinity)"); aeq(read("[-6, Infinity)").get().divideHull(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().divideHull(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 0]").get().divideHull(read("(-Infinity, 0]").get()), "[0, Infinity)"); try { ZERO.divideHull(ZERO); fail(); } catch (ArithmeticException ignored) {} try { read("[-2, 5/3]").get().divideHull(ZERO); fail(); } catch (ArithmeticException ignored) {} } @Test public void testDivide_Rational() { aeq(ZERO.divide(Rational.ONE), "[0, 0]"); aeq(ZERO.divide(Rational.read("2/3").get()), "[0, 0]"); aeq(ZERO.divide(Rational.read("-7").get()), "[0, 0]"); aeq(ONE.divide(Rational.ONE), "[1, 1]"); aeq(ONE.divide(Rational.read("2/3").get()), "[3/2, 3/2]"); aeq(ONE.divide(Rational.read("-7").get()), "[-1/7, -1/7]"); aeq(ALL.divide(Rational.ONE), "(-Infinity, Infinity)"); aeq(ALL.divide(Rational.read("2/3").get()), "(-Infinity, Infinity)"); aeq(ALL.divide(Rational.read("-7").get()), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().divide(Rational.ONE), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().divide(Rational.read("2/3").get()), "[-3, 5/2]"); aeq(read("[-2, 5/3]").get().divide(Rational.read("-7").get()), "[-5/21, 2/7]"); aeq(read("[4, 4]").get().divide(Rational.ONE), "[4, 4]"); aeq(read("[4, 4]").get().divide(Rational.read("2/3").get()), "[6, 6]"); aeq(read("[4, 4]").get().divide(Rational.read("-7").get()), "[-4/7, -4/7]"); aeq(read("(-Infinity, 3/2]").get().divide(Rational.ONE), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().divide(Rational.read("2/3").get()), "(-Infinity, 9/4]"); aeq(read("(-Infinity, 3/2]").get().divide(Rational.read("-7").get()), "[-3/14, Infinity)"); aeq(read("[-6, Infinity)").get().divide(Rational.ONE), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().divide(Rational.read("2/3").get()), "[-9, Infinity)"); aeq(read("[-6, Infinity)").get().divide(Rational.read("-7").get()), "(-Infinity, 6/7]"); try { read("[-2, 5/3]").get().divide(Rational.ZERO); } catch (ArithmeticException ignored) {} } @Test public void testDivide_BigInteger() { aeq(ZERO.divide(BigInteger.ONE), "[0, 0]"); aeq(ZERO.divide(BigInteger.valueOf(5)), "[0, 0]"); aeq(ZERO.divide(BigInteger.valueOf(-7)), "[0, 0]"); aeq(ONE.divide(BigInteger.ONE), "[1, 1]"); aeq(ONE.divide(BigInteger.valueOf(5)), "[1/5, 1/5]"); aeq(ONE.divide(BigInteger.valueOf(-7)), "[-1/7, -1/7]"); aeq(ALL.divide(BigInteger.ONE), "(-Infinity, Infinity)"); aeq(ALL.divide(BigInteger.valueOf(5)), "(-Infinity, Infinity)"); aeq(ALL.divide(BigInteger.valueOf(-7)), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().divide(BigInteger.ONE), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().divide(BigInteger.valueOf(5)), "[-2/5, 1/3]"); aeq(read("[-2, 5/3]").get().divide(BigInteger.valueOf(-7)), "[-5/21, 2/7]"); aeq(read("[4, 4]").get().divide(BigInteger.ONE), "[4, 4]"); aeq(read("[4, 4]").get().divide(BigInteger.valueOf(5)), "[4/5, 4/5]"); aeq(read("[4, 4]").get().divide(BigInteger.valueOf(-7)), "[-4/7, -4/7]"); aeq(read("(-Infinity, 3/2]").get().divide(BigInteger.ONE), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().divide(BigInteger.valueOf(5)), "(-Infinity, 3/10]"); aeq(read("(-Infinity, 3/2]").get().divide(BigInteger.valueOf(-7)), "[-3/14, Infinity)"); aeq(read("[-6, Infinity)").get().divide(BigInteger.ONE), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().divide(BigInteger.valueOf(5)), "[-6/5, Infinity)"); aeq(read("[-6, Infinity)").get().divide(BigInteger.valueOf(-7)), "(-Infinity, 6/7]"); try { read("[-2, 5/3]").get().divide(BigInteger.ZERO); } catch (ArithmeticException ignored) {} } @Test public void testDivide_int() { aeq(ZERO.divide(1), "[0, 0]"); aeq(ZERO.divide(5), "[0, 0]"); aeq(ZERO.divide(-7), "[0, 0]"); aeq(ONE.divide(1), "[1, 1]"); aeq(ONE.divide(5), "[1/5, 1/5]"); aeq(ONE.divide(-7), "[-1/7, -1/7]"); aeq(ALL.divide(1), "(-Infinity, Infinity)"); aeq(ALL.divide(5), "(-Infinity, Infinity)"); aeq(ALL.divide(-7), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().divide(1), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().divide(5), "[-2/5, 1/3]"); aeq(read("[-2, 5/3]").get().divide(-7), "[-5/21, 2/7]"); aeq(read("[4, 4]").get().divide(1), "[4, 4]"); aeq(read("[4, 4]").get().divide(5), "[4/5, 4/5]"); aeq(read("[4, 4]").get().divide(-7), "[-4/7, -4/7]"); aeq(read("(-Infinity, 3/2]").get().divide(1), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().divide(5), "(-Infinity, 3/10]"); aeq(read("(-Infinity, 3/2]").get().divide(-7), "[-3/14, Infinity)"); aeq(read("[-6, Infinity)").get().divide(1), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().divide(5), "[-6/5, Infinity)"); aeq(read("[-6, Infinity)").get().divide(-7), "(-Infinity, 6/7]"); try { read("[-2, 5/3]").get().divide(0); } catch (ArithmeticException ignored) {} } @Test public void testShiftLeft() { aeq(ZERO.shiftLeft(0), "[0, 0]"); aeq(ZERO.shiftLeft(1), "[0, 0]"); aeq(ZERO.shiftLeft(2), "[0, 0]"); aeq(ZERO.shiftLeft(3), "[0, 0]"); aeq(ZERO.shiftLeft(4), "[0, 0]"); aeq(ZERO.shiftLeft(-1), "[0, 0]"); aeq(ZERO.shiftLeft(-2), "[0, 0]"); aeq(ZERO.shiftLeft(-3), "[0, 0]"); aeq(ZERO.shiftLeft(-4), "[0, 0]"); aeq(ONE.shiftLeft(0), "[1, 1]"); aeq(ONE.shiftLeft(1), "[2, 2]"); aeq(ONE.shiftLeft(2), "[4, 4]"); aeq(ONE.shiftLeft(3), "[8, 8]"); aeq(ONE.shiftLeft(4), "[16, 16]"); aeq(ONE.shiftLeft(-1), "[1/2, 1/2]"); aeq(ONE.shiftLeft(-2), "[1/4, 1/4]"); aeq(ONE.shiftLeft(-3), "[1/8, 1/8]"); aeq(ONE.shiftLeft(-4), "[1/16, 1/16]"); aeq(ALL.shiftLeft(0), "(-Infinity, Infinity)"); aeq(ALL.shiftLeft(1), "(-Infinity, Infinity)"); aeq(ALL.shiftLeft(2), "(-Infinity, Infinity)"); aeq(ALL.shiftLeft(3), "(-Infinity, Infinity)"); aeq(ALL.shiftLeft(4), "(-Infinity, Infinity)"); aeq(ALL.shiftLeft(-1), "(-Infinity, Infinity)"); aeq(ALL.shiftLeft(-2), "(-Infinity, Infinity)"); aeq(ALL.shiftLeft(-3), "(-Infinity, Infinity)"); aeq(ALL.shiftLeft(-4), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().shiftLeft(0), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().shiftLeft(1), "[-4, 10/3]"); aeq(read("[-2, 5/3]").get().shiftLeft(2), "[-8, 20/3]"); aeq(read("[-2, 5/3]").get().shiftLeft(3), "[-16, 40/3]"); aeq(read("[-2, 5/3]").get().shiftLeft(4), "[-32, 80/3]"); aeq(read("[-2, 5/3]").get().shiftLeft(-1), "[-1, 5/6]"); aeq(read("[-2, 5/3]").get().shiftLeft(-2), "[-1/2, 5/12]"); aeq(read("[-2, 5/3]").get().shiftLeft(-3), "[-1/4, 5/24]"); aeq(read("[-2, 5/3]").get().shiftLeft(-4), "[-1/8, 5/48]"); aeq(read("[4, 4]").get().shiftLeft(0), "[4, 4]"); aeq(read("[4, 4]").get().shiftLeft(1), "[8, 8]"); aeq(read("[4, 4]").get().shiftLeft(2), "[16, 16]"); aeq(read("[4, 4]").get().shiftLeft(3), "[32, 32]"); aeq(read("[4, 4]").get().shiftLeft(4), "[64, 64]"); aeq(read("[4, 4]").get().shiftLeft(-1), "[2, 2]"); aeq(read("[4, 4]").get().shiftLeft(-2), "[1, 1]"); aeq(read("[4, 4]").get().shiftLeft(-3), "[1/2, 1/2]"); aeq(read("[4, 4]").get().shiftLeft(-4), "[1/4, 1/4]"); aeq(read("(-Infinity, -3/2]").get().shiftLeft(0), "(-Infinity, -3/2]"); aeq(read("(-Infinity, -3/2]").get().shiftLeft(1), "(-Infinity, -3]"); aeq(read("(-Infinity, -3/2]").get().shiftLeft(2), "(-Infinity, -6]"); aeq(read("(-Infinity, -3/2]").get().shiftLeft(3), "(-Infinity, -12]"); aeq(read("(-Infinity, -3/2]").get().shiftLeft(4), "(-Infinity, -24]"); aeq(read("(-Infinity, -3/2]").get().shiftLeft(-1), "(-Infinity, -3/4]"); aeq(read("(-Infinity, -3/2]").get().shiftLeft(-2), "(-Infinity, -3/8]"); aeq(read("(-Infinity, -3/2]").get().shiftLeft(-3), "(-Infinity, -3/16]"); aeq(read("(-Infinity, -3/2]").get().shiftLeft(-4), "(-Infinity, -3/32]"); aeq(read("[-6, Infinity)").get().shiftLeft(0), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().shiftLeft(1), "[-12, Infinity)"); aeq(read("[-6, Infinity)").get().shiftLeft(2), "[-24, Infinity)"); aeq(read("[-6, Infinity)").get().shiftLeft(3), "[-48, Infinity)"); aeq(read("[-6, Infinity)").get().shiftLeft(4), "[-96, Infinity)"); aeq(read("[-6, Infinity)").get().shiftLeft(-1), "[-3, Infinity)"); aeq(read("[-6, Infinity)").get().shiftLeft(-2), "[-3/2, Infinity)"); aeq(read("[-6, Infinity)").get().shiftLeft(-3), "[-3/4, Infinity)"); aeq(read("[-6, Infinity)").get().shiftLeft(-4), "[-3/8, Infinity)"); } @Test public void testShiftRight() { aeq(ZERO.shiftRight(0), "[0, 0]"); aeq(ZERO.shiftRight(1), "[0, 0]"); aeq(ZERO.shiftRight(2), "[0, 0]"); aeq(ZERO.shiftRight(3), "[0, 0]"); aeq(ZERO.shiftRight(4), "[0, 0]"); aeq(ZERO.shiftRight(-1), "[0, 0]"); aeq(ZERO.shiftRight(-2), "[0, 0]"); aeq(ZERO.shiftRight(-3), "[0, 0]"); aeq(ZERO.shiftRight(-4), "[0, 0]"); aeq(ONE.shiftRight(0), "[1, 1]"); aeq(ONE.shiftRight(1), "[1/2, 1/2]"); aeq(ONE.shiftRight(2), "[1/4, 1/4]"); aeq(ONE.shiftRight(3), "[1/8, 1/8]"); aeq(ONE.shiftRight(4), "[1/16, 1/16]"); aeq(ONE.shiftRight(-1), "[2, 2]"); aeq(ONE.shiftRight(-2), "[4, 4]"); aeq(ONE.shiftRight(-3), "[8, 8]"); aeq(ONE.shiftRight(-4), "[16, 16]"); aeq(ALL.shiftRight(0), "(-Infinity, Infinity)"); aeq(ALL.shiftRight(1), "(-Infinity, Infinity)"); aeq(ALL.shiftRight(2), "(-Infinity, Infinity)"); aeq(ALL.shiftRight(3), "(-Infinity, Infinity)"); aeq(ALL.shiftRight(4), "(-Infinity, Infinity)"); aeq(ALL.shiftRight(-1), "(-Infinity, Infinity)"); aeq(ALL.shiftRight(-2), "(-Infinity, Infinity)"); aeq(ALL.shiftRight(-3), "(-Infinity, Infinity)"); aeq(ALL.shiftRight(-4), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().shiftRight(0), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().shiftRight(1), "[-1, 5/6]"); aeq(read("[-2, 5/3]").get().shiftRight(2), "[-1/2, 5/12]"); aeq(read("[-2, 5/3]").get().shiftRight(3), "[-1/4, 5/24]"); aeq(read("[-2, 5/3]").get().shiftRight(4), "[-1/8, 5/48]"); aeq(read("[-2, 5/3]").get().shiftRight(-1), "[-4, 10/3]"); aeq(read("[-2, 5/3]").get().shiftRight(-2), "[-8, 20/3]"); aeq(read("[-2, 5/3]").get().shiftRight(-3), "[-16, 40/3]"); aeq(read("[-2, 5/3]").get().shiftRight(-4), "[-32, 80/3]"); aeq(read("[4, 4]").get().shiftRight(0), "[4, 4]"); aeq(read("[4, 4]").get().shiftRight(1), "[2, 2]"); aeq(read("[4, 4]").get().shiftRight(2), "[1, 1]"); aeq(read("[4, 4]").get().shiftRight(3), "[1/2, 1/2]"); aeq(read("[4, 4]").get().shiftRight(4), "[1/4, 1/4]"); aeq(read("[4, 4]").get().shiftRight(-1), "[8, 8]"); aeq(read("[4, 4]").get().shiftRight(-2), "[16, 16]"); aeq(read("[4, 4]").get().shiftRight(-3), "[32, 32]"); aeq(read("[4, 4]").get().shiftRight(-4), "[64, 64]"); aeq(read("(-Infinity, -3/2]").get().shiftRight(0), "(-Infinity, -3/2]"); aeq(read("(-Infinity, -3/2]").get().shiftRight(1), "(-Infinity, -3/4]"); aeq(read("(-Infinity, -3/2]").get().shiftRight(2), "(-Infinity, -3/8]"); aeq(read("(-Infinity, -3/2]").get().shiftRight(3), "(-Infinity, -3/16]"); aeq(read("(-Infinity, -3/2]").get().shiftRight(4), "(-Infinity, -3/32]"); aeq(read("(-Infinity, -3/2]").get().shiftRight(-1), "(-Infinity, -3]"); aeq(read("(-Infinity, -3/2]").get().shiftRight(-2), "(-Infinity, -6]"); aeq(read("(-Infinity, -3/2]").get().shiftRight(-3), "(-Infinity, -12]"); aeq(read("(-Infinity, -3/2]").get().shiftRight(-4), "(-Infinity, -24]"); aeq(read("[-6, Infinity)").get().shiftRight(0), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().shiftRight(1), "[-3, Infinity)"); aeq(read("[-6, Infinity)").get().shiftRight(2), "[-3/2, Infinity)"); aeq(read("[-6, Infinity)").get().shiftRight(3), "[-3/4, Infinity)"); aeq(read("[-6, Infinity)").get().shiftRight(4), "[-3/8, Infinity)"); aeq(read("[-6, Infinity)").get().shiftRight(-1), "[-12, Infinity)"); aeq(read("[-6, Infinity)").get().shiftRight(-2), "[-24, Infinity)"); aeq(read("[-6, Infinity)").get().shiftRight(-3), "[-48, Infinity)"); aeq(read("[-6, Infinity)").get().shiftRight(-4), "[-96, Infinity)"); } @Test public void testSum() { aeq(sum(readIntervalList("[]")), "[0, 0]"); aeq(sum(readIntervalList("[[-2, 5/3], (-Infinity, 6], [4, 4]]")), "(-Infinity, 35/3]"); try { sum(readIntervalListWithNulls("[[-2, 5/3], null, [4, 4]]")); fail(); } catch (NullPointerException ignored) {} } @Test public void testProduct() { aeq(product(readIntervalList("[]")), "[1, 1]"); aeq(product(readIntervalList("[[-2, 5/3], [0, 6], [4, 4]]")), "[-48, 40]"); aeq(product(readIntervalList("[[-2, 5/3], (-Infinity, 6], [4, 4]]")), "(-Infinity, Infinity)"); try { product(readIntervalListWithNulls("[[-2, 5/3], null, [4, 4]]")); fail(); } catch (NullPointerException ignored) {} } @Test public void testDelta() { aeq(delta(readIntervalList("[[1/3, 2]]")), "[]"); aeq(delta(readIntervalList("[[-2, 5/3], (-Infinity, 6], [4, 4]]")), "[(-Infinity, 8], [-2, Infinity)]"); try { delta(readIntervalListWithNulls("[]")); fail(); } catch (IllegalArgumentException ignored) {} try { IterableUtils.toList(delta(readIntervalListWithNulls("[[-2, 5/3], null, [4, 4]]"))); fail(); } catch (NullPointerException ignored) {} } @Test public void testPow() { aeq(ZERO.pow(0), "[[1, 1]]"); aeq(ZERO.pow(1), "[[0, 0]]"); aeq(ZERO.pow(2), "[[0, 0]]"); aeq(ZERO.pow(3), "[[0, 0]]"); aeq(ONE.pow(0), "[[1, 1]]"); aeq(ONE.pow(1), "[[1, 1]]"); aeq(ONE.pow(2), "[[1, 1]]"); aeq(ONE.pow(3), "[[1, 1]]"); aeq(ONE.pow(-1), "[[1, 1]]"); aeq(ONE.pow(-2), "[[1, 1]]"); aeq(ONE.pow(-3), "[[1, 1]]"); aeq(ALL.pow(0), "[[1, 1]]"); aeq(ALL.pow(1), "[(-Infinity, Infinity)]"); aeq(ALL.pow(2), "[[0, Infinity)]"); aeq(ALL.pow(3), "[(-Infinity, Infinity)]"); aeq(ALL.pow(-1), "[(-Infinity, Infinity)]"); aeq(ALL.pow(-2), "[[0, Infinity)]"); aeq(ALL.pow(-3), "[(-Infinity, Infinity)]"); aeq(read("[-2, 5/3]").get().pow(0), "[[1, 1]]"); aeq(read("[-2, 5/3]").get().pow(1), "[[-2, 5/3]]"); aeq(read("[-2, 5/3]").get().pow(2), "[[0, 4]]"); aeq(read("[-2, 5/3]").get().pow(3), "[[-8, 125/27]]"); aeq(read("[-2, 5/3]").get().pow(-1), "[(-Infinity, -1/2], [3/5, Infinity)]"); aeq(read("[-2, 5/3]").get().pow(-2), "[[1/4, Infinity)]"); aeq(read("[-2, 5/3]").get().pow(-3), "[(-Infinity, -1/8], [27/125, Infinity)]"); aeq(read("[4, 4]").get().pow(0), "[[1, 1]]"); aeq(read("[4, 4]").get().pow(1), "[[4, 4]]"); aeq(read("[4, 4]").get().pow(2), "[[16, 16]]"); aeq(read("[4, 4]").get().pow(3), "[[64, 64]]"); aeq(read("[4, 4]").get().pow(-1), "[[1/4, 1/4]]"); aeq(read("[4, 4]").get().pow(-2), "[[1/16, 1/16]]"); aeq(read("[4, 4]").get().pow(-3), "[[1/64, 1/64]]"); aeq(read("(-Infinity, 3/2]").get().pow(0), "[[1, 1]]"); aeq(read("(-Infinity, 3/2]").get().pow(1), "[(-Infinity, 3/2]]"); aeq(read("(-Infinity, 3/2]").get().pow(2), "[[0, Infinity)]"); aeq(read("(-Infinity, 3/2]").get().pow(3), "[(-Infinity, 27/8]]"); aeq(read("(-Infinity, 3/2]").get().pow(-1), "[(-Infinity, 0], [2/3, Infinity)]"); aeq(read("(-Infinity, 3/2]").get().pow(-2), "[[0, Infinity)]"); aeq(read("(-Infinity, 3/2]").get().pow(-3), "[(-Infinity, 0], [8/27, Infinity)]"); aeq(read("[-6, Infinity)").get().pow(0), "[[1, 1]]"); aeq(read("[-6, Infinity)").get().pow(1), "[[-6, Infinity)]"); aeq(read("[-6, Infinity)").get().pow(2), "[[0, Infinity)]"); aeq(read("[-6, Infinity)").get().pow(3), "[[-216, Infinity)]"); aeq(read("[-6, Infinity)").get().pow(-1), "[(-Infinity, -1/6], [0, Infinity)]"); aeq(read("[-6, Infinity)").get().pow(-2), "[[0, Infinity)]"); aeq(read("[-6, Infinity)").get().pow(-3), "[(-Infinity, -1/216], [0, Infinity)]"); } @Test public void testPowHull() { aeq(ZERO.powHull(0), "[1, 1]"); aeq(ZERO.powHull(1), "[0, 0]"); aeq(ZERO.powHull(2), "[0, 0]"); aeq(ZERO.powHull(3), "[0, 0]"); aeq(ONE.powHull(0), "[1, 1]"); aeq(ONE.powHull(1), "[1, 1]"); aeq(ONE.powHull(2), "[1, 1]"); aeq(ONE.powHull(3), "[1, 1]"); aeq(ONE.powHull(-1), "[1, 1]"); aeq(ONE.powHull(-2), "[1, 1]"); aeq(ONE.powHull(-3), "[1, 1]"); aeq(ALL.powHull(0), "[1, 1]"); aeq(ALL.powHull(1), "(-Infinity, Infinity)"); aeq(ALL.powHull(2), "[0, Infinity)"); aeq(ALL.powHull(3), "(-Infinity, Infinity)"); aeq(ALL.powHull(-1), "(-Infinity, Infinity)"); aeq(ALL.powHull(-2), "[0, Infinity)"); aeq(ALL.powHull(-3), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().powHull(0), "[1, 1]"); aeq(read("[-2, 5/3]").get().powHull(1), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().powHull(2), "[0, 4]"); aeq(read("[-2, 5/3]").get().powHull(3), "[-8, 125/27]"); aeq(read("[-2, 5/3]").get().powHull(-1), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().powHull(-2), "[1/4, Infinity)"); aeq(read("[-2, 5/3]").get().powHull(-3), "(-Infinity, Infinity)"); aeq(read("[4, 4]").get().powHull(0), "[1, 1]"); aeq(read("[4, 4]").get().powHull(1), "[4, 4]"); aeq(read("[4, 4]").get().powHull(2), "[16, 16]"); aeq(read("[4, 4]").get().powHull(3), "[64, 64]"); aeq(read("[4, 4]").get().powHull(-1), "[1/4, 1/4]"); aeq(read("[4, 4]").get().powHull(-2), "[1/16, 1/16]"); aeq(read("[4, 4]").get().powHull(-3), "[1/64, 1/64]"); aeq(read("(-Infinity, 3/2]").get().powHull(0), "[1, 1]"); aeq(read("(-Infinity, 3/2]").get().powHull(1), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().powHull(2), "[0, Infinity)"); aeq(read("(-Infinity, 3/2]").get().powHull(3), "(-Infinity, 27/8]"); aeq(read("(-Infinity, 3/2]").get().powHull(-1), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().powHull(-2), "[0, Infinity)"); aeq(read("(-Infinity, 3/2]").get().powHull(-3), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().powHull(0), "[1, 1]"); aeq(read("[-6, Infinity)").get().powHull(1), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().powHull(2), "[0, Infinity)"); aeq(read("[-6, Infinity)").get().powHull(3), "[-216, Infinity)"); aeq(read("[-6, Infinity)").get().powHull(-1), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().powHull(-2), "[0, Infinity)"); aeq(read("[-6, Infinity)").get().powHull(-3), "(-Infinity, Infinity)"); try { ZERO.powHull(-1); fail(); } catch (ArithmeticException ignored) {} try { ZERO.powHull(-2); fail(); } catch (ArithmeticException ignored) {} try { ZERO.powHull(-3); fail(); } catch (ArithmeticException ignored) {} } @Test public void testElementCompare() { aeq(ZERO.elementCompare(ZERO), "Optional[EQ]"); aeq(ZERO.elementCompare(ONE), "Optional[LT]"); aeq(ZERO.elementCompare(ALL), "Optional.empty"); aeq(ZERO.elementCompare(read("[-2, 5/3]").get()), "Optional.empty"); aeq(ZERO.elementCompare(read("[4, 4]").get()), "Optional[LT]"); aeq(ZERO.elementCompare(read("(-Infinity, 3/2]").get()), "Optional.empty"); aeq(ZERO.elementCompare(read("[-6, Infinity)").get()), "Optional.empty"); aeq(ONE.elementCompare(ZERO), "Optional[GT]"); aeq(ONE.elementCompare(ONE), "Optional[EQ]"); aeq(ONE.elementCompare(ALL), "Optional.empty"); aeq(ONE.elementCompare(read("[-2, 5/3]").get()), "Optional.empty"); aeq(ONE.elementCompare(read("[4, 4]").get()), "Optional[LT]"); aeq(ONE.elementCompare(read("(-Infinity, 3/2]").get()), "Optional.empty"); aeq(ONE.elementCompare(read("[-6, Infinity)").get()), "Optional.empty"); aeq(ALL.elementCompare(ZERO), "Optional.empty"); aeq(ALL.elementCompare(ONE), "Optional.empty"); aeq(ALL.elementCompare(ALL), "Optional.empty"); aeq(ALL.elementCompare(read("[-2, 5/3]").get()), "Optional.empty"); aeq(ALL.elementCompare(read("[4, 4]").get()), "Optional.empty"); aeq(ALL.elementCompare(read("(-Infinity, 3/2]").get()), "Optional.empty"); aeq(ALL.elementCompare(read("[-6, Infinity)").get()), "Optional.empty"); aeq(read("[-2, 5/3]").get().elementCompare(ZERO), "Optional.empty"); aeq(read("[-2, 5/3]").get().elementCompare(ONE), "Optional.empty"); aeq(read("[-2, 5/3]").get().elementCompare(ALL), "Optional.empty"); aeq(read("[-2, 5/3]").get().elementCompare(read("[-2, 5/3]").get()), "Optional.empty"); aeq(read("[-2, 5/3]").get().elementCompare(read("[4, 4]").get()), "Optional[LT]"); aeq(read("[-2, 5/3]").get().elementCompare(read("(-Infinity, 3/2]").get()), "Optional.empty"); aeq(read("[-2, 5/3]").get().elementCompare(read("[-6, Infinity)").get()), "Optional.empty"); aeq(read("[4, 4]").get().elementCompare(ZERO), "Optional[GT]"); aeq(read("[4, 4]").get().elementCompare(ONE), "Optional[GT]"); aeq(read("[4, 4]").get().elementCompare(ALL), "Optional.empty"); aeq(read("[4, 4]").get().elementCompare(read("[-2, 5/3]").get()), "Optional[GT]"); aeq(read("[4, 4]").get().elementCompare(read("[4, 4]").get()), "Optional[EQ]"); aeq(read("[4, 4]").get().elementCompare(read("(-Infinity, 3/2]").get()), "Optional[GT]"); aeq(read("[4, 4]").get().elementCompare(read("[-6, Infinity)").get()), "Optional.empty"); aeq(read("(-Infinity, 3/2]").get().elementCompare(ZERO), "Optional.empty"); aeq(read("(-Infinity, 3/2]").get().elementCompare(ONE), "Optional.empty"); aeq(read("(-Infinity, 3/2]").get().elementCompare(ALL), "Optional.empty"); aeq(read("(-Infinity, 3/2]").get().elementCompare(read("[-2, 5/3]").get()), "Optional.empty"); aeq(read("(-Infinity, 3/2]").get().elementCompare(read("[4, 4]").get()), "Optional[LT]"); aeq(read("(-Infinity, 3/2]").get().elementCompare(read("(-Infinity, 3/2]").get()), "Optional.empty"); aeq(read("(-Infinity, 3/2]").get().elementCompare(read("[-6, Infinity)").get()), "Optional.empty"); aeq(read("[-6, Infinity)").get().elementCompare(ZERO), "Optional.empty"); aeq(read("[-6, Infinity)").get().elementCompare(ONE), "Optional.empty"); aeq(read("[-6, Infinity)").get().elementCompare(ALL), "Optional.empty"); aeq(read("[-6, Infinity)").get().elementCompare(read("[-2, 5/3]").get()), "Optional.empty"); aeq(read("[-6, Infinity)").get().elementCompare(read("[4, 4]").get()), "Optional.empty"); aeq(read("[-6, Infinity)").get().elementCompare(read("(-Infinity, 3/2]").get()), "Optional.empty"); aeq(read("[-6, Infinity)").get().elementCompare(read("[-6, Infinity)").get()), "Optional.empty"); } @Test public void testEquals() { //noinspection EqualsWithItself assertTrue(ZERO.equals(ZERO)); //noinspection EqualsWithItself assertTrue(ONE.equals(ONE)); //noinspection EqualsWithItself assertTrue(ALL.equals(ALL)); assertTrue(read("[-2, 5/3]").equals(read("[-2, 5/3]"))); assertTrue(read("[4, 4]").equals(read("[4, 4]"))); assertTrue(read("(-Infinity, 3/2]").equals(read("(-Infinity, 3/2]"))); assertTrue(read("[-6, Infinity)").equals(read("[-6, Infinity)"))); assertFalse(ZERO.equals(ONE)); assertFalse(ZERO.equals(ALL)); assertFalse(ZERO.equals(read("[-2, 5/3]").get())); assertFalse(ZERO.equals(read("[4, 4]").get())); assertFalse(ZERO.equals(read("(-Infinity, 3/2]").get())); assertFalse(ZERO.equals(read("[-6, Infinity)").get())); assertFalse(ONE.equals(ZERO)); assertFalse(ONE.equals(ALL)); assertFalse(ONE.equals(read("[-2, 5/3]").get())); assertFalse(ONE.equals(read("[4, 4]").get())); assertFalse(ONE.equals(read("(-Infinity, 3/2]").get())); assertFalse(ONE.equals(read("[-6, Infinity)").get())); assertFalse(ALL.equals(ZERO)); assertFalse(ALL.equals(ONE)); assertFalse(ALL.equals(read("[-2, 5/3]").get())); assertFalse(ALL.equals(read("[4, 4]").get())); assertFalse(ALL.equals(read("(-Infinity, 3/2]").get())); assertFalse(ALL.equals(read("[-6, Infinity)").get())); assertFalse(read("[-2, 5/3]").get().equals(ZERO)); assertFalse(read("[-2, 5/3]").get().equals(ONE)); assertFalse(read("[-2, 5/3]").get().equals(ALL)); assertFalse(read("[-2, 5/3]").get().equals(read("[4, 4]").get())); assertFalse(read("[-2, 5/3]").get().equals(read("(-Infinity, 3/2]").get())); assertFalse(read("[-2, 5/3]").get().equals(read("[-6, Infinity)").get())); assertFalse(read("[4, 4]").get().equals(ZERO)); assertFalse(read("[4, 4]").get().equals(ONE)); assertFalse(read("[4, 4]").get().equals(ALL)); assertFalse(read("[4, 4]").get().equals(read("[-2, 5/3]").get())); assertFalse(read("[4, 4]").get().equals(read("(-Infinity, 3/2]").get())); assertFalse(read("[4, 4]").get().equals(read("[-6, Infinity)").get())); assertFalse(read("(-Infinity, 3/2]").get().equals(ZERO)); assertFalse(read("(-Infinity, 3/2]").get().equals(ONE)); assertFalse(read("(-Infinity, 3/2]").get().equals(ALL)); assertFalse(read("(-Infinity, 3/2]").get().equals(read("[-2, 5/3]").get())); assertFalse(read("(-Infinity, 3/2]").get().equals(read("[4, 4]").get())); assertFalse(read("(-Infinity, 3/2]").get().equals(read("[-6, Infinity)").get())); assertFalse(read("[-6, Infinity)").get().equals(ZERO)); assertFalse(read("[-6, Infinity)").get().equals(ONE)); assertFalse(read("[-6, Infinity)").get().equals(ALL)); assertFalse(read("[-6, Infinity)").get().equals(read("[-2, 5/3]").get())); assertFalse(read("[-6, Infinity)").get().equals(read("[4, 4]").get())); assertFalse(read("[-6, Infinity)").get().equals(read("(-Infinity, 3/2]").get())); //noinspection ObjectEqualsNull assertFalse(ZERO.equals(null)); //noinspection ObjectEqualsNull assertFalse(ONE.equals(null)); //noinspection ObjectEqualsNull assertFalse(ALL.equals(null)); assertTrue(read("[-2, 5/3]").isPresent()); assertTrue(read("[4, 4]").isPresent()); assertTrue(read("(-Infinity, 3/2]").isPresent()); assertTrue(read("[-6, Infinity)").isPresent()); } @Test public void testHashCode() { aeq(ZERO.hashCode(), 32); aeq(ONE.hashCode(), 1024); aeq(ALL.hashCode(), 0); aeq(read("[-2, 5/3]").hashCode(), -1733); aeq(read("[4, 4]").hashCode(), 4000); aeq(read("(-Infinity, 3/2]").hashCode(), 95); aeq(read("[-6, Infinity)").hashCode(), -5735); } @Test public void testCompareTo() { assertTrue(eq(ZERO, ZERO)); assertTrue(eq(ONE, ONE)); assertTrue(eq(ALL, ALL)); assertTrue(eq(read("[-2, 5/3]").get(), read("[-2, 5/3]").get())); assertTrue(eq(read("[4, 4]").get(), read("[4, 4]").get())); assertTrue(eq(read("(-Infinity, 3/2]").get(), read("(-Infinity, 3/2]").get())); assertTrue(eq(read("[-6, Infinity)").get(), read("[-6, Infinity)").get())); assertTrue(lt(ZERO, ONE)); assertTrue(gt(ZERO, ALL)); assertTrue(gt(ZERO, read("[-2, 5/3]").get())); assertTrue(lt(ZERO, read("[4, 4]").get())); assertTrue(gt(ZERO, read("(-Infinity, 3/2]").get())); assertTrue(gt(ZERO, read("[-6, Infinity)").get())); assertTrue(gt(ONE, ZERO)); assertTrue(gt(ONE, ALL)); assertTrue(gt(ONE, read("[-2, 5/3]").get())); assertTrue(lt(ONE, read("[4, 4]").get())); assertTrue(gt(ONE, read("(-Infinity, 3/2]").get())); assertTrue(gt(ONE, read("[-6, Infinity)").get())); assertTrue(lt(ALL, ZERO)); assertTrue(lt(ALL, ONE)); assertTrue(lt(ALL, read("[-2, 5/3]").get())); assertTrue(lt(ALL, read("[4, 4]").get())); assertTrue(gt(ALL, read("(-Infinity, 3/2]").get())); assertTrue(lt(ALL, read("[-6, Infinity)").get())); assertTrue(lt(read("[-2, 5/3]").get(), ZERO)); assertTrue(lt(read("[-2, 5/3]").get(), ONE)); assertTrue(gt(read("[-2, 5/3]").get(), ALL)); assertTrue(lt(read("[-2, 5/3]").get(), read("[4, 4]").get())); assertTrue(gt(read("[-2, 5/3]").get(), read("(-Infinity, 3/2]").get())); assertTrue(gt(read("[-2, 5/3]").get(), read("[-6, Infinity)").get())); assertTrue(gt(read("[4, 4]").get(), ZERO)); assertTrue(gt(read("[4, 4]").get(), ONE)); assertTrue(gt(read("[4, 4]").get(), ALL)); assertTrue(gt(read("[4, 4]").get(), read("[-2, 5/3]").get())); assertTrue(gt(read("[4, 4]").get(), read("(-Infinity, 3/2]").get())); assertTrue(gt(read("[4, 4]").get(), read("[-6, Infinity)").get())); assertTrue(lt(read("(-Infinity, 3/2]").get(), ZERO)); assertTrue(lt(read("(-Infinity, 3/2]").get(), ONE)); assertTrue(lt(read("(-Infinity, 3/2]").get(), ALL)); assertTrue(lt(read("(-Infinity, 3/2]").get(), read("[-2, 5/3]").get())); assertTrue(lt(read("(-Infinity, 3/2]").get(), read("[4, 4]").get())); assertTrue(lt(read("(-Infinity, 3/2]").get(), read("[-6, Infinity)").get())); assertTrue(lt(read("[-6, Infinity)").get(), ZERO)); assertTrue(lt(read("[-6, Infinity)").get(), ONE)); assertTrue(gt(read("[-6, Infinity)").get(), ALL)); assertTrue(lt(read("[-6, Infinity)").get(), read("[-2, 5/3]").get())); assertTrue(lt(read("[-6, Infinity)").get(), read("[4, 4]").get())); assertTrue(gt(read("[-6, Infinity)").get(), read("(-Infinity, 3/2]").get())); } @Test public void testRead() { aeq(read("[0, 0]").get(), ZERO); aeq(read("[1, 1]").get(), ONE); aeq(read("(-Infinity, Infinity)").get(), ALL); aeq(read("[-2, 5/3]").get(), "[-2, 5/3]"); aeq(read("[4, 4]").get(), "[4, 4]"); aeq(read("(-Infinity, 3/2]").get(), "(-Infinity, 3/2]"); aeq(read("[-6, Infinity)").get(), "[-6, Infinity)"); assertFalse(read("").isPresent()); assertFalse(read("[").isPresent()); assertFalse(read("[]").isPresent()); assertFalse(read("[,]").isPresent()); assertFalse(read("[1, 1").isPresent()); assertFalse(read("[12]").isPresent()); assertFalse(read("[1 1]").isPresent()); assertFalse(read("[1, 1]").isPresent()); assertFalse(read("[ 1, 1]").isPresent()); assertFalse(read("[1, 1 ]").isPresent()); assertFalse(read("[1, 1] ").isPresent()); assertFalse(read("[-Infinity, Infinity]").isPresent()); assertFalse(read("(-Infinity, 4)").isPresent()); assertFalse(read("[4, Infinity]").isPresent()); assertFalse(read("(Infinity, -Infinity)").isPresent()); assertFalse(read("[2, 3-]").isPresent()); assertFalse(read("[2.0, 4]").isPresent()); assertFalse(read("[2,4]").isPresent()); assertFalse(read("[5, 4]").isPresent()); assertFalse(read("[5, 4/0]").isPresent()); } @Test public void testFindIn() { aeq(findIn("abcd[-5, 2/3]xyz").get(), "([-5, 2/3], 4)"); aeq(findIn("vdfvdf(-Infinity, 3]cds").get(), "((-Infinity, 3], 6)"); aeq(findIn("gvrgw49((-Infinity, Infinity)Infinity)").get(), "((-Infinity, Infinity), 8)"); assertFalse(findIn("").isPresent()); assertFalse(findIn("hello").isPresent()); assertFalse(findIn("vdfsvfbf").isPresent()); assertFalse(findIn("vdfvds[-Infinity, 2]vsd").isPresent()); assertFalse(findIn("vdfvds(Infinity, 2]vsd").isPresent()); assertFalse(findIn("abcd[5, 4]xyz").isPresent()); assertFalse(findIn("abcd[5, 4/0]xyz").isPresent()); } @Test public void testToString() { aeq(ZERO, "[0, 0]"); aeq(ONE, "[1, 1]"); aeq(ALL, "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get(), "[-2, 5/3]"); aeq(read("[4, 4]").get(), "[4, 4]"); aeq(read("(-Infinity, 3/2]").get(), "(-Infinity, 3/2]"); aeq(read("[-6, Infinity)").get(), "[-6, Infinity)"); } private static void aeq(Iterable<?> a, Object b) { assertEquals(IterableUtils.toString(a), b.toString()); } private static void aeq(Object a, Object b) { assertEquals(a.toString(), b.toString()); } private static @NotNull List<Interval> readIntervalList(@NotNull String s) { return Readers.readList(Interval::read).apply(s).get(); } private static @NotNull List<Interval> readIntervalListWithNulls(@NotNull String s) { return Readers.readListWithNulls(Interval::read).apply(s).get(); } }
src/test/java/mho/qbar/objects/IntervalTest.java
package mho.qbar.objects; import mho.wheels.iterables.IterableUtils; import mho.wheels.misc.Readers; import org.jetbrains.annotations.NotNull; import org.junit.Test; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import java.util.Optional; import static mho.qbar.objects.Interval.*; import static mho.qbar.objects.Interval.greaterThanOrEqualTo; import static mho.qbar.objects.Interval.lessThanOrEqualTo; import static mho.wheels.ordering.Ordering.*; import static org.junit.Assert.*; public class IntervalTest { @Test public void testConstants() { aeq(ZERO, "[0, 0]"); aeq(ONE, "[1, 1]"); aeq(ALL, "(-Infinity, Infinity)"); } @Test public void testGetLower() { aeq(ZERO.getLower().get(), "0"); aeq(ONE.getLower().get(), "1"); aeq(read("[-2, 5/3]").get().getLower().get(), "-2"); assertFalse(ALL.getLower().isPresent()); } @Test public void testGetUpper() { aeq(ZERO.getUpper().get(), "0"); aeq(ONE.getUpper().get(), "1"); aeq(read("[-2, 5/3]").get().getUpper().get(), "5/3"); assertFalse(ALL.getUpper().isPresent()); } @Test public void testOf_Rational_Rational() { aeq(of(Rational.read("1/3").get(), Rational.read("1/2").get()), "[1/3, 1/2]"); aeq(of(Rational.read("-5").get(), Rational.ZERO), "[-5, 0]"); aeq(of(Rational.read("2").get(), Rational.read("2").get()), "[2, 2]"); try { of(Rational.read("3").get(), Rational.read("2").get()); fail(); } catch (IllegalArgumentException ignored) {} } @Test public void testLessThanOrEqualTo() { aeq(lessThanOrEqualTo(Rational.read("1/3").get()), "(-Infinity, 1/3]"); aeq(lessThanOrEqualTo(Rational.ZERO), "(-Infinity, 0]"); } @Test public void testGreaterThanOrEqualTo() { aeq(greaterThanOrEqualTo(Rational.read("1/3").get()), "[1/3, Infinity)"); aeq(greaterThanOrEqualTo(Rational.ZERO), "[0, Infinity)"); } @Test public void testOf_Rational() { aeq(of(Rational.ZERO), "[0, 0]"); aeq(of(Rational.read("5/4").get()), "[5/4, 5/4]"); aeq(of(Rational.read("-2").get()), "[-2, -2]"); } @Test public void testIsFinitelyBounded() { assertTrue(ZERO.isFinitelyBounded()); assertTrue(ONE.isFinitelyBounded()); assertFalse(ALL.isFinitelyBounded()); assertTrue(read("[-2, 5/3]").get().isFinitelyBounded()); assertTrue(read("[4, 4]").get().isFinitelyBounded()); assertFalse(read("(-Infinity, 3/2]").get().isFinitelyBounded()); assertFalse(read("[-6, Infinity)").get().isFinitelyBounded()); } @Test public void testContains_Rational() { assertTrue(ZERO.contains(Rational.ZERO)); assertFalse(ZERO.contains(Rational.ONE)); assertTrue(ONE.contains(Rational.ONE)); assertFalse(ONE.contains(Rational.ZERO)); assertTrue(ALL.contains(Rational.ZERO)); assertTrue(ALL.contains(Rational.ONE)); assertTrue(ALL.contains(Rational.read("-4/3").get())); assertTrue(read("[-2, 5/3]").get().contains(Rational.read("-2").get())); assertTrue(read("[-2, 5/3]").get().contains(Rational.read("-1").get())); assertTrue(read("[-2, 5/3]").get().contains(Rational.ZERO)); assertTrue(read("[-2, 5/3]").get().contains(Rational.ONE)); assertTrue(read("[-2, 5/3]").get().contains(Rational.read("5/3").get())); assertFalse(read("[-2, 5/3]").get().contains(Rational.read("-3").get())); assertFalse(read("[-2, 5/3]").get().contains(Rational.read("2").get())); assertTrue(read("[4, 4]").get().contains(Rational.read("4").get())); assertFalse(read("[4, 4]").get().contains(Rational.read("3").get())); assertFalse(read("[4, 4]").get().contains(Rational.read("5").get())); assertTrue(read("(-Infinity, 3/2]").get().contains(Rational.ZERO)); assertTrue(read("(-Infinity, 3/2]").get().contains(Rational.ONE)); assertTrue(read("(-Infinity, 3/2]").get().contains(Rational.read("-10").get())); assertTrue(read("(-Infinity, 3/2]").get().contains(Rational.read("3/2").get())); assertFalse(read("(-Infinity, 3/2]").get().contains(Rational.read("2").get())); assertTrue(read("[-6, Infinity)").get().contains(Rational.ZERO)); assertTrue(read("[-6, Infinity)").get().contains(Rational.ONE)); assertTrue(read("[-6, Infinity)").get().contains(Rational.read("-4").get())); assertTrue(read("[-6, Infinity)").get().contains(Rational.read("5").get())); assertFalse(read("[-6, Infinity)").get().contains(Rational.read("-8").get())); } @Test public void testContains_Interval() { assertTrue(ZERO.contains(ZERO)); assertTrue(ONE.contains(ONE)); assertTrue(ALL.contains(ALL)); assertTrue(ALL.contains(ZERO)); assertTrue(ALL.contains(ONE)); assertFalse(ZERO.contains(ONE)); assertFalse(ZERO.contains(ALL)); assertFalse(ONE.contains(ZERO)); assertFalse(ONE.contains(ALL)); assertTrue(read("[1, 4]").get().contains(read("[2, 3]").get())); assertTrue(read("[1, 4]").get().contains(read("[1, 4]").get())); assertFalse(read("[1, 4]").get().contains(read("[0, 2]").get())); assertTrue(read("(-Infinity, 1/2]").get().contains(read("(-Infinity, 0]").get())); assertTrue(read("(-Infinity, 1/2]").get().contains(read("[0, 0]").get())); assertFalse(read("(-Infinity, 1/2]").get().contains(read("(-Infinity, 1]").get())); assertTrue(read("[1/2, Infinity)").get().contains(read("[1, Infinity)").get())); assertTrue(read("[1/2, Infinity)").get().contains(read("[1, 1]").get())); assertFalse(read("[1/2, Infinity)").get().contains(read("[0, Infinity)").get())); assertFalse(read("[1/2, Infinity)").get().contains(read("(-Infinity, 1/2]").get())); } @Test public void testDiameter() { aeq(ZERO.diameter().get(), "0"); aeq(ONE.diameter().get(), "0"); assertFalse(ALL.diameter().isPresent()); aeq(read("[-2, 5/3]").get().diameter().get(), "11/3"); aeq(read("[4, 4]").get().diameter().get(), "0"); assertFalse(read("(-Infinity, 3/2]").get().diameter().isPresent()); assertFalse(read("[-6, Infinity)").get().diameter().isPresent()); } @Test public void testConvexHull_Interval() { aeq(ZERO.convexHull(ZERO), "[0, 0]"); aeq(ZERO.convexHull(ONE), "[0, 1]"); aeq(ZERO.convexHull(ALL), "(-Infinity, Infinity)"); aeq(ZERO.convexHull(read("[-2, 5/3]").get()), "[-2, 5/3]"); aeq(ZERO.convexHull(read("[4, 4]").get()), "[0, 4]"); aeq(ZERO.convexHull(read("(-Infinity, 3/2]").get()), "(-Infinity, 3/2]"); aeq(ZERO.convexHull(read("[-6, Infinity)").get()), "[-6, Infinity)"); aeq(ONE.convexHull(ZERO), "[0, 1]"); aeq(ONE.convexHull(ONE), "[1, 1]"); aeq(ONE.convexHull(ALL), "(-Infinity, Infinity)"); aeq(ONE.convexHull(read("[-2, 5/3]").get()), "[-2, 5/3]"); aeq(ONE.convexHull(read("[4, 4]").get()), "[1, 4]"); aeq(ONE.convexHull(read("(-Infinity, 3/2]").get()), "(-Infinity, 3/2]"); aeq(ONE.convexHull(read("[-6, Infinity)").get()), "[-6, Infinity)"); aeq(ALL.convexHull(ZERO), "(-Infinity, Infinity)"); aeq(ALL.convexHull(ONE), "(-Infinity, Infinity)"); aeq(ALL.convexHull(ALL), "(-Infinity, Infinity)"); aeq(ALL.convexHull(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(ALL.convexHull(read("[4, 4]").get()), "(-Infinity, Infinity)"); aeq(ALL.convexHull(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(ALL.convexHull(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().convexHull(ZERO), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().convexHull(ONE), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().convexHull(ALL), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().convexHull(read("[-2, 5/3]").get()), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().convexHull(read("[4, 4]").get()), "[-2, 4]"); aeq(read("[-2, 5/3]").get().convexHull(read("(-Infinity, 3/2]").get()), "(-Infinity, 5/3]"); aeq(read("[-2, 5/3]").get().convexHull(read("[-6, Infinity)").get()), "[-6, Infinity)"); aeq(read("[4, 4]").get().convexHull(ZERO), "[0, 4]"); aeq(read("[4, 4]").get().convexHull(ONE), "[1, 4]"); aeq(read("[4, 4]").get().convexHull(ALL), "(-Infinity, Infinity)"); aeq(read("[4, 4]").get().convexHull(read("[-2, 5/3]").get()), "[-2, 4]"); aeq(read("[4, 4]").get().convexHull(read("[4, 4]").get()), "[4, 4]"); aeq(read("[4, 4]").get().convexHull(read("(-Infinity, 3/2]").get()), "(-Infinity, 4]"); aeq(read("[4, 4]").get().convexHull(read("[-6, Infinity)").get()), "[-6, Infinity)"); aeq(read("(-Infinity, 3/2]").get().convexHull(ZERO), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().convexHull(ONE), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().convexHull(ALL), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().convexHull(read("[-2, 5/3]").get()), "(-Infinity, 5/3]"); aeq(read("(-Infinity, 3/2]").get().convexHull(read("[4, 4]").get()), "(-Infinity, 4]"); aeq(read("(-Infinity, 3/2]").get().convexHull(read("(-Infinity, 3/2]").get()), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().convexHull(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().convexHull(ZERO), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().convexHull(ONE), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().convexHull(ALL), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().convexHull(read("[-2, 5/3]").get()), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().convexHull(read("[4, 4]").get()), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().convexHull(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().convexHull(read("[-6, Infinity)").get()), "[-6, Infinity)"); } @Test public void testConvexHull_List_Interval() { aeq(convexHull(readIntervalList("[[0, 0]]")), "[0, 0]"); aeq(convexHull(readIntervalList("[[-1, 2]]")), "[-1, 2]"); aeq(convexHull(readIntervalList("[[-1, Infinity)]")), "[-1, Infinity)"); aeq(convexHull(readIntervalList("[(-Infinity, 4]]")), "(-Infinity, 4]"); aeq(convexHull(readIntervalList("[(-Infinity, Infinity)]")), "(-Infinity, Infinity)"); aeq(convexHull(readIntervalList("[[0, 0], [1, 1]]")), "[0, 1]"); aeq(convexHull(readIntervalList("[[1, 2], [3, 4]]")), "[1, 4]"); aeq(convexHull(readIntervalList("[[1, 3], [2, 4]]")), "[1, 4]"); aeq(convexHull(readIntervalList("[(-Infinity, Infinity), [3, 4]]")), "(-Infinity, Infinity)"); aeq(convexHull(readIntervalList("[[-1, Infinity), (-Infinity, 4]]")), "(-Infinity, Infinity)"); aeq(convexHull(readIntervalList("[[1, 2], [3, 4], [5, 6]]")), "[1, 6]"); aeq(convexHull(readIntervalList("[[1, 2], [2, 2], [3, Infinity)]")), "[1, Infinity)"); try { convexHull(readIntervalList("[]")); fail(); } catch (IllegalArgumentException ignored) {} try { convexHull(readIntervalListWithNulls("[[1, 2], null]")); fail(); } catch (NullPointerException ignored) {} } @Test public void testIntersection() { aeq(ZERO.intersection(ZERO).get(), "[0, 0]"); aeq(ONE.intersection(ONE).get(), "[1, 1]"); aeq(ALL.intersection(ALL).get(), "(-Infinity, Infinity)"); aeq(ALL.intersection(ZERO).get(), "[0, 0]"); aeq(ALL.intersection(ONE).get(), "[1, 1]"); assertFalse(ZERO.intersection(ONE).isPresent()); aeq(read("[1, 3]").get().intersection(read("[2, 4]").get()).get(), "[2, 3]"); aeq(read("[1, 2]").get().intersection(read("[2, 4]").get()).get(), "[2, 2]"); assertFalse(read("[1, 2]").get().intersection(read("[3, 4]").get()).isPresent()); aeq(ALL.intersection(read("[1, 2]").get()).get(), "[1, 2]"); aeq(read("(-Infinity, 2]").get().intersection(read("[1, 3]").get()).get(), "[1, 2]"); aeq(read("(-Infinity, 2]").get().intersection(read("(-Infinity, 3]").get()).get(), "(-Infinity, 2]"); aeq(read("[2, Infinity)").get().intersection(read("[1, 3]").get()).get(), "[2, 3]"); aeq(read("[2, Infinity)").get().intersection(read("[3, Infinity)").get()).get(), "[3, Infinity)"); aeq(read("[2, Infinity)").get().intersection(read("(-Infinity, 3]").get()).get(), "[2, 3]"); assertFalse(read("[2, Infinity)").get().intersection(read("(-Infinity, 1]").get()).isPresent()); } @Test public void testDisjoint() { assertFalse(ZERO.disjoint(ZERO)); assertFalse(ONE.disjoint(ONE)); assertFalse(ALL.disjoint(ALL)); assertFalse(ALL.disjoint(ZERO)); assertFalse(ALL.disjoint(ONE)); assertTrue(ZERO.disjoint(ONE)); assertFalse(read("[1, 3]").get().disjoint(read("[2, 4]").get())); assertTrue(read("[1, 2]").get().disjoint(read("[3, 4]").get())); assertFalse(read("(-Infinity, 2]").get().disjoint(read("[1, 3]").get())); assertTrue(read("(-Infinity, 2]").get().disjoint(read("[3, 4]").get())); assertFalse(read("[2, Infinity)").get().disjoint(read("[1, 3]").get())); assertTrue(read("[2, Infinity)").get().disjoint(read("[0, 1]").get())); assertTrue(read("[2, Infinity)").get().disjoint(read("(-Infinity, 1]").get())); assertFalse(read("[2, Infinity)").get().disjoint(read("(-Infinity, 3]").get())); } @Test public void testMakeDisjoint() { aeq(makeDisjoint(readIntervalList("[]")), "[]"); aeq(makeDisjoint(readIntervalList("[[0, 0]]")), "[[0, 0]]"); aeq(makeDisjoint(readIntervalList("[[1, 1]]")), "[[1, 1]]"); aeq(makeDisjoint(readIntervalList("[(-Infinity, Infinity)]")), "[(-Infinity, Infinity)]"); aeq(makeDisjoint(readIntervalList("[(-Infinity, 3]]")), "[(-Infinity, 3]]"); aeq(makeDisjoint(readIntervalList("[[2, Infinity)]")), "[[2, Infinity)]"); aeq(makeDisjoint(readIntervalList("[[2, 3]]")), "[[2, 3]]"); aeq( makeDisjoint(readIntervalList("[(-Infinity, 3], [4, 5], [6, 7]]")), "[(-Infinity, 3], [4, 5], [6, 7]]" ); aeq(makeDisjoint(readIntervalList("[(-Infinity, 3], [3, 5], [5, 7]]")), "[(-Infinity, 7]]"); aeq(makeDisjoint(readIntervalList("[(-Infinity, 3], [2, 5], [6, 7]]")), "[(-Infinity, 5], [6, 7]]"); aeq( makeDisjoint(readIntervalList("[[1, 2], [4, 6], [10, Infinity), [3, 7], [5, 9]]")), "[[1, 2], [3, 9], [10, Infinity)]" ); try { makeDisjoint(readIntervalListWithNulls("[[1, 3], null, [5, Infinity)]")); fail(); } catch (NullPointerException ignored) {} } @Test public void testComplement() { aeq(ZERO.complement(), "[(-Infinity, Infinity)]"); aeq(ONE.complement(), "[(-Infinity, Infinity)]"); aeq(ALL.complement(), "[]"); aeq(read("[-2, 5/3]").get().complement(), "[(-Infinity, -2], [5/3, Infinity)]"); aeq(read("[4, 4]").get().complement(), "[(-Infinity, Infinity)]"); aeq(read("(-Infinity, 3/2]").get().complement(), "[[3/2, Infinity)]"); aeq(read("[-6, Infinity)").get().complement(), "[(-Infinity, -6]]"); } @Test public void testMidpoint() { aeq(ZERO.midpoint(), "0"); aeq(ONE.midpoint(), "1"); aeq(read("[4, 4]").get().midpoint(), "4"); aeq(read("[1, 2]").get().midpoint(), "3/2"); aeq(read("[-2, 5/3]").get().midpoint(), "-1/6"); try { ALL.midpoint(); fail(); } catch (ArithmeticException ignored) {} try { read("(-Infinity, 1]").get().midpoint(); fail(); } catch (ArithmeticException ignored) {} try { read("[1, Infinity)").get().midpoint(); fail(); } catch (ArithmeticException ignored) {} } @Test public void testSplit() { aeq(ZERO.split(Rational.ZERO), "([0, 0], [0, 0])"); aeq(ONE.split(Rational.ONE), "([1, 1], [1, 1])"); aeq(ALL.split(Rational.ONE), "((-Infinity, 1], [1, Infinity))"); aeq(read("[4, 4]").get().split(Rational.read("4").get()), "([4, 4], [4, 4])"); aeq(read("[0, 1]").get().split(Rational.read("1/3").get()), "([0, 1/3], [1/3, 1])"); aeq(read("[0, 1]").get().split(Rational.ZERO), "([0, 0], [0, 1])"); aeq(read("[0, 1]").get().split(Rational.ONE), "([0, 1], [1, 1])"); aeq(read("[-2, 5/3]").get().split(Rational.read("1").get()), "([-2, 1], [1, 5/3])"); aeq(read("(-Infinity, 1]").get().split(Rational.read("-3").get()), "((-Infinity, -3], [-3, 1])"); aeq(read("[5/3, Infinity)").get().split(Rational.read("10").get()), "([5/3, 10], [10, Infinity))"); try { ZERO.split(Rational.ONE); fail(); } catch (ArithmeticException ignored) {} try { read("[-2, 5/3]").get().split(Rational.read("-4").get()); fail(); } catch (ArithmeticException ignored) {} try { read("(-Infinity, 1]").get().split(Rational.read("4").get()); fail(); } catch (ArithmeticException ignored) {} try { read("[1, Infinity)").get().split(Rational.read("-4").get()); fail(); } catch (ArithmeticException ignored) {} } @Test public void testBisect() { aeq(ZERO.bisect(), "([0, 0], [0, 0])"); aeq(ONE.bisect(), "([1, 1], [1, 1])"); aeq(read("[4, 4]").get().bisect(), "([4, 4], [4, 4])"); aeq(read("[1, 2]").get().bisect(), "([1, 3/2], [3/2, 2])"); aeq(read("[-2, 5/3]").get().bisect(), "([-2, -1/6], [-1/6, 5/3])"); try { ALL.bisect(); fail(); } catch (ArithmeticException ignored) {} try { read("(-Infinity, 1]").get().bisect(); fail(); } catch (ArithmeticException ignored) {} try { read("[1, Infinity)").get().bisect(); fail(); } catch (ArithmeticException ignored) {} } @Test public void testRoundingPreimage_float() { aeq( roundingPreimage(0.0f), "[-1/1427247692705959881058285969449495136382746624, 1/1427247692705959881058285969449495136382746624]" ); aeq( roundingPreimage(-0.0f), "[-1/1427247692705959881058285969449495136382746624, 1/1427247692705959881058285969449495136382746624]" ); aeq(roundingPreimage(Float.POSITIVE_INFINITY), "[340282346638528859811704183484516925440, Infinity)"); aeq(roundingPreimage(Float.NEGATIVE_INFINITY), "(-Infinity, -340282346638528859811704183484516925440]"); aeq(roundingPreimage(1.0f), "[33554431/33554432, 16777217/16777216]"); aeq(roundingPreimage(13.0f), "[27262975/2097152, 27262977/2097152]"); aeq(roundingPreimage(-5.0f), "[-20971521/4194304, -20971519/4194304]"); aeq(roundingPreimage(1.5f), "[25165823/16777216, 25165825/16777216]"); aeq(roundingPreimage(0.15625f), "[20971519/134217728, 20971521/134217728]"); aeq(roundingPreimage(0.1f), "[26843545/268435456, 26843547/268435456]"); aeq(roundingPreimage(1.0f / 3.0f), "[22369621/67108864, 22369623/67108864]"); aeq(roundingPreimage(1.0e10f), "[9999999488, 10000000512]"); aeq(roundingPreimage(1.0e30f), "[999999977268534356919527145472, 1000000052826398082833850564608]"); aeq(roundingPreimage((float) Math.PI), "[26353589/8388608, 26353591/8388608]"); aeq(roundingPreimage((float) Math.E), "[22802599/8388608, 22802601/8388608]"); aeq(roundingPreimage((float) Math.sqrt(2)), "[23726565/16777216, 23726567/16777216]"); aeq( roundingPreimage(Float.MIN_VALUE), "[1/1427247692705959881058285969449495136382746624, 3/1427247692705959881058285969449495136382746624]" ); aeq( roundingPreimage(-Float.MIN_VALUE), "[-3/1427247692705959881058285969449495136382746624," + " -1/1427247692705959881058285969449495136382746624]" ); aeq( roundingPreimage(Float.MIN_NORMAL), "[16777215/1427247692705959881058285969449495136382746624," + " 16777217/1427247692705959881058285969449495136382746624]" ); aeq( roundingPreimage(-Float.MIN_NORMAL), "[-16777217/1427247692705959881058285969449495136382746624," + " -16777215/1427247692705959881058285969449495136382746624]" ); aeq( roundingPreimage(Float.MAX_VALUE), "[340282336497324057985868971510891282432, 340282346638528859811704183484516925440]" ); aeq( roundingPreimage(-Float.MAX_VALUE), "[-340282346638528859811704183484516925440, -340282336497324057985868971510891282432]" ); try { roundingPreimage(Float.NaN); fail(); } catch (ArithmeticException ignored) {} } @Test public void testRoundingPreimage_double() { aeq( roundingPreimage(0.0), "[-1/40480450661462123670499069343783461409911329952828423671380271605486067913599069378392076740287" + "424899037415572863362382277961747477158695373402679988147701984303484855313272272893381548418643268" + "247953535694549013712401496684938539723620671129831911268162011302471753910466682923046100506437265" + "5017292012526615415482186989568," + " 1/404804506614621236704990693437834614099113299528284236713802716054860679135990693783920767402874" + "248990374155728633623822779617474771586953734026799881477019843034848553132722728933815484186432682" + "479535356945490137124014966849385397236206711298319112681620113024717539104666829230461005064372655" + "017292012526615415482186989568]" ); aeq( roundingPreimage(-0.0), "[-1/40480450661462123670499069343783461409911329952828423671380271605486067913599069378392076740287" + "424899037415572863362382277961747477158695373402679988147701984303484855313272272893381548418643268" + "247953535694549013712401496684938539723620671129831911268162011302471753910466682923046100506437265" + "5017292012526615415482186989568," + " 1/404804506614621236704990693437834614099113299528284236713802716054860679135990693783920767402874" + "248990374155728633623822779617474771586953734026799881477019843034848553132722728933815484186432682" + "479535356945490137124014966849385397236206711298319112681620113024717539104666829230461005064372655" + "017292012526615415482186989568]" ); aeq( roundingPreimage(Double.POSITIVE_INFINITY), "[17976931348623157081452742373170435679807056752584499659891747680315726078002853876058955863276687" + "817154045895351438246423432132688946418276846754670353751698604991057655128207624549009038932894407" + "586850845513394230458323690322294816580855933212334827479782620414472316873817718091929988125040402" + "6184124858368," + " Infinity)" ); aeq( roundingPreimage(Double.NEGATIVE_INFINITY), "(-Infinity," + " -1797693134862315708145274237317043567980705675258449965989174768031572607800285387605895586327668" + "781715404589535143824642343213268894641827684675467035375169860499105765512820762454900903893289440" + "758685084551339423045832369032229481658085593321233482747978262041447231687381771809192998812504040" + "26184124858368]" ); aeq(roundingPreimage(1.0), "[18014398509481983/18014398509481984, 9007199254740993/9007199254740992]"); aeq(roundingPreimage(13.0), "[14636698788954111/1125899906842624, 14636698788954113/1125899906842624]"); aeq(roundingPreimage(-5.0), "[-11258999068426241/2251799813685248, -11258999068426239/2251799813685248]"); aeq(roundingPreimage(1.5), "[13510798882111487/9007199254740992, 13510798882111489/9007199254740992]"); aeq(roundingPreimage(0.15625), "[11258999068426239/72057594037927936, 11258999068426241/72057594037927936]"); aeq(roundingPreimage(0.1), "[14411518807585587/144115188075855872, 14411518807585589/144115188075855872]"); aeq(roundingPreimage(1.0 / 3.0), "[12009599006321321/36028797018963968, 12009599006321323/36028797018963968]"); aeq(roundingPreimage(1.0e10), "[10485759999999999/1048576, 10485760000000001/1048576]"); aeq(roundingPreimage(1.0e30), "[999999999999999949515880660992, 1000000000000000090253369016320]"); aeq(roundingPreimage(Math.PI), "[14148475504056879/4503599627370496, 14148475504056881/4503599627370496]"); aeq(roundingPreimage(Math.E), "[12242053029736145/4503599627370496, 12242053029736147/4503599627370496]"); aeq(roundingPreimage(Math.sqrt(2)), "[12738103345051545/9007199254740992, 12738103345051547/9007199254740992]"); aeq( roundingPreimage(Double.MIN_VALUE), "[1/404804506614621236704990693437834614099113299528284236713802716054860679135990693783920767402874" + "248990374155728633623822779617474771586953734026799881477019843034848553132722728933815484186432682" + "479535356945490137124014966849385397236206711298319112681620113024717539104666829230461005064372655" + "017292012526615415482186989568," + " 3/404804506614621236704990693437834614099113299528284236713802716054860679135990693783920767402874" + "248990374155728633623822779617474771586953734026799881477019843034848553132722728933815484186432682" + "479535356945490137124014966849385397236206711298319112681620113024717539104666829230461005064372655" + "017292012526615415482186989568]" ); aeq( roundingPreimage(-Double.MIN_VALUE), "[-3/40480450661462123670499069343783461409911329952828423671380271605486067913599069378392076740287" + "424899037415572863362382277961747477158695373402679988147701984303484855313272272893381548418643268" + "247953535694549013712401496684938539723620671129831911268162011302471753910466682923046100506437265" + "5017292012526615415482186989568," + " -1/40480450661462123670499069343783461409911329952828423671380271605486067913599069378392076740287" + "424899037415572863362382277961747477158695373402679988147701984303484855313272272893381548418643268" + "247953535694549013712401496684938539723620671129831911268162011302471753910466682923046100506437265" + "5017292012526615415482186989568]" ); aeq( roundingPreimage(Double.MIN_NORMAL), "[9007199254740991/404804506614621236704990693437834614099113299528284236713802716054860679135990693" + "783920767402874248990374155728633623822779617474771586953734026799881477019843034848553132722728933" + "815484186432682479535356945490137124014966849385397236206711298319112681620113024717539104666829230" + "461005064372655017292012526615415482186989568," + " 9007199254740993/404804506614621236704990693437834614099113299528284236713802716054860679135990693" + "783920767402874248990374155728633623822779617474771586953734026799881477019843034848553132722728933" + "815484186432682479535356945490137124014966849385397236206711298319112681620113024717539104666829230" + "461005064372655017292012526615415482186989568]" ); aeq( roundingPreimage(-Double.MIN_NORMAL), "[-9007199254740993/40480450661462123670499069343783461409911329952828423671380271605486067913599069" + "378392076740287424899037415572863362382277961747477158695373402679988147701984303484855313272272893" + "381548418643268247953535694549013712401496684938539723620671129831911268162011302471753910466682923" + "0461005064372655017292012526615415482186989568," + " -9007199254740991/40480450661462123670499069343783461409911329952828423671380271605486067913599069" + "378392076740287424899037415572863362382277961747477158695373402679988147701984303484855313272272893" + "381548418643268247953535694549013712401496684938539723620671129831911268162011302471753910466682923" + "0461005064372655017292012526615415482186989568]" ); aeq( roundingPreimage(Double.MAX_VALUE), "[17976931348623156083532587605810529851620700234165216626166117462586955326729232657453009928794654" + "924675063149033587701752208710592698796290627760473556921329019091915239418047621712533496094635638" + "726128664019802903779951418360298151175628372777140383052148396392393563313364280213909166945792787" + "4464075218944," + " 17976931348623157081452742373170435679807056752584499659891747680315726078002853876058955863276687" + "817154045895351438246423432132688946418276846754670353751698604991057655128207624549009038932894407" + "586850845513394230458323690322294816580855933212334827479782620414472316873817718091929988125040402" + "6184124858368]" ); aeq( roundingPreimage(-Double.MAX_VALUE), "[-1797693134862315708145274237317043567980705675258449965989174768031572607800285387605895586327668" + "781715404589535143824642343213268894641827684675467035375169860499105765512820762454900903893289440" + "758685084551339423045832369032229481658085593321233482747978262041447231687381771809192998812504040" + "26184124858368," + " -1797693134862315608353258760581052985162070023416521662616611746258695532672923265745300992879465" + "492467506314903358770175220871059269879629062776047355692132901909191523941804762171253349609463563" + "872612866401980290377995141836029815117562837277714038305214839639239356331336428021390916694579278" + "74464075218944]" ); try { roundingPreimage(Double.NaN); fail(); } catch (ArithmeticException ignored) {} } @Test public void testRoundingPreimage_BigDecimal() { aeq(roundingPreimage(BigDecimal.ZERO), "[-1/2, 1/2]"); aeq(roundingPreimage(BigDecimal.ONE), "[1/2, 3/2]"); aeq(roundingPreimage(new BigDecimal("3")), "[5/2, 7/2]"); aeq(roundingPreimage(new BigDecimal("-5")), "[-11/2, -9/2]"); aeq(roundingPreimage(new BigDecimal("0.1")), "[1/20, 3/20]"); aeq(roundingPreimage(new BigDecimal("3.14159")), "[628317/200000, 628319/200000]"); aeq( roundingPreimage(new BigDecimal("-2.718281828459045")), "[-5436563656918091/2000000000000000, -5436563656918089/2000000000000000]" ); aeq(roundingPreimage(new BigDecimal("0.00000000000001")), "[1/200000000000000, 3/200000000000000]"); aeq(roundingPreimage(new BigDecimal("1000000000000000")), "[1999999999999999/2, 2000000000000001/2]"); aeq(roundingPreimage(new BigDecimal("1E15")), "[500000000000000, 1500000000000000]"); } @Test public void testFloatRange() { aeq(ZERO.floatRange(), "(0.0, 0.0)"); aeq(ONE.floatRange(), "(1.0, 1.0)"); aeq(ALL.floatRange(), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().floatRange(), "(-2.0, 1.6666667)"); aeq(read("[5/3, 4]").get().floatRange(), "(1.6666666, 4.0)"); aeq(read("[4, 4]").get().floatRange(), "(4.0, 4.0)"); aeq(read("[1/3, 1/3]").get().floatRange(), "(0.3333333, 0.33333334)"); aeq(read("(-Infinity, 3/2]").get().floatRange(), "(-Infinity, 1.5)"); aeq(read("[-6, Infinity)").get().floatRange(), "(-6.0, Infinity)"); aeq(of(Rational.of(10).pow(-100)).floatRange(), "(0.0, 1.4E-45)"); aeq(of(Rational.of(10).pow(-100).negate()).floatRange(), "(-1.4E-45, -0.0)"); aeq(of(Rational.of(10).pow(-100).negate(), Rational.of(10).pow(-100)).floatRange(), "(-1.4E-45, 1.4E-45)"); aeq(of(Rational.of(10).pow(100)).floatRange(), "(3.4028235E38, Infinity)"); aeq(of(Rational.of(10).pow(100).negate()).floatRange(), "(-Infinity, -3.4028235E38)"); aeq(of(Rational.of(10).pow(100).negate(), Rational.of(10).pow(100)).floatRange(), "(-Infinity, Infinity)"); } @Test public void testDoubleRange() { aeq(ZERO.doubleRange(), "(0.0, 0.0)"); aeq(ONE.doubleRange(), "(1.0, 1.0)"); aeq(ALL.doubleRange(), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().doubleRange(), "(-2.0, 1.6666666666666667)"); aeq(read("[5/3, 4]").get().doubleRange(), "(1.6666666666666665, 4.0)"); aeq(read("[4, 4]").get().doubleRange(), "(4.0, 4.0)"); aeq(read("[1/3, 1/3]").get().doubleRange(), "(0.3333333333333333, 0.33333333333333337)"); aeq(read("(-Infinity, 3/2]").get().doubleRange(), "(-Infinity, 1.5)"); aeq(read("[-6, Infinity)").get().doubleRange(), "(-6.0, Infinity)"); aeq(of(Rational.of(10).pow(-1000)).doubleRange(), "(0.0, 4.9E-324)"); aeq(of(Rational.of(10).pow(-1000).negate()).doubleRange(), "(-4.9E-324, -0.0)"); aeq( of(Rational.of(10).pow(-1000).negate(), Rational.of(10).pow(-1000)).doubleRange(), "(-4.9E-324, 4.9E-324)" ); aeq(of(Rational.of(10).pow(1000)).doubleRange(), "(1.7976931348623157E308, Infinity)"); aeq(of(Rational.of(10).pow(1000).negate()).doubleRange(), "(-Infinity, -1.7976931348623157E308)"); aeq(of(Rational.of(10).pow(1000).negate(), Rational.of(10).pow(1000)).doubleRange(), "(-Infinity, Infinity)"); } @Test public void testAdd() { aeq(ZERO.add(ZERO), "[0, 0]"); aeq(ZERO.add(ONE), "[1, 1]"); aeq(ZERO.add(ALL), "(-Infinity, Infinity)"); aeq(ZERO.add(read("[-2, 5/3]").get()), "[-2, 5/3]"); aeq(ZERO.add(read("[4, 4]").get()), "[4, 4]"); aeq(ZERO.add(read("(-Infinity, 3/2]").get()), "(-Infinity, 3/2]"); aeq(ZERO.add(read("[-6, Infinity)").get()), "[-6, Infinity)"); aeq(ONE.add(ZERO), "[1, 1]"); aeq(ONE.add(ONE), "[2, 2]"); aeq(ONE.add(ALL), "(-Infinity, Infinity)"); aeq(ONE.add(read("[-2, 5/3]").get()), "[-1, 8/3]"); aeq(ONE.add(read("[4, 4]").get()), "[5, 5]"); aeq(ONE.add(read("(-Infinity, 3/2]").get()), "(-Infinity, 5/2]"); aeq(ONE.add(read("[-6, Infinity)").get()), "[-5, Infinity)"); aeq(ALL.add(ZERO), "(-Infinity, Infinity)"); aeq(ALL.add(ONE), "(-Infinity, Infinity)"); aeq(ALL.add(ALL), "(-Infinity, Infinity)"); aeq(ALL.add(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(ALL.add(read("[4, 4]").get()), "(-Infinity, Infinity)"); aeq(ALL.add(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(ALL.add(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().add(ZERO), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().add(ONE), "[-1, 8/3]"); aeq(read("[-2, 5/3]").get().add(ALL), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().add(read("[-2, 5/3]").get()), "[-4, 10/3]"); aeq(read("[-2, 5/3]").get().add(read("[4, 4]").get()), "[2, 17/3]"); aeq(read("[-2, 5/3]").get().add(read("(-Infinity, 3/2]").get()), "(-Infinity, 19/6]"); aeq(read("[-2, 5/3]").get().add(read("[-6, Infinity)").get()), "[-8, Infinity)"); aeq(read("[4, 4]").get().add(ZERO), "[4, 4]"); aeq(read("[4, 4]").get().add(ONE), "[5, 5]"); aeq(read("[4, 4]").get().add(ALL), "(-Infinity, Infinity)"); aeq(read("[4, 4]").get().add(read("[-2, 5/3]").get()), "[2, 17/3]"); aeq(read("[4, 4]").get().add(read("[4, 4]").get()), "[8, 8]"); aeq(read("[4, 4]").get().add(read("(-Infinity, 3/2]").get()), "(-Infinity, 11/2]"); aeq(read("[4, 4]").get().add(read("[-6, Infinity)").get()), "[-2, Infinity)"); aeq(read("(-Infinity, 3/2]").get().add(ZERO), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().add(ONE), "(-Infinity, 5/2]"); aeq(read("(-Infinity, 3/2]").get().add(ALL), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().add(read("[-2, 5/3]").get()), "(-Infinity, 19/6]"); aeq(read("(-Infinity, 3/2]").get().add(read("[4, 4]").get()), "(-Infinity, 11/2]"); aeq(read("(-Infinity, 3/2]").get().add(read("(-Infinity, 3/2]").get()), "(-Infinity, 3]"); aeq(read("(-Infinity, 3/2]").get().add(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().add(ZERO), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().add(ONE), "[-5, Infinity)"); aeq(read("[-6, Infinity)").get().add(ALL), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().add(read("[-2, 5/3]").get()), "[-8, Infinity)"); aeq(read("[-6, Infinity)").get().add(read("[4, 4]").get()), "[-2, Infinity)"); aeq(read("[-6, Infinity)").get().add(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().add(read("[-6, Infinity)").get()), "[-12, Infinity)"); } @Test public void testNegate() { aeq(ZERO.negate(), "[0, 0]"); aeq(ONE.negate(), "[-1, -1]"); aeq(ALL.negate(), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().negate(), "[-5/3, 2]"); aeq(read("[4, 4]").get().negate(), "[-4, -4]"); aeq(read("(-Infinity, 3/2]").get().negate(), "[-3/2, Infinity)"); aeq(read("[-6, Infinity)").get().negate(), "(-Infinity, 6]"); } @Test public void testAbs() { aeq(ZERO.abs(), "[0, 0]"); aeq(ONE.abs(), "[1, 1]"); aeq(ALL.abs(), "[0, Infinity)"); aeq(read("[-2, 5/3]").get().abs(), "[0, 2]"); aeq(read("[4, 4]").get().abs(), "[4, 4]"); aeq(read("(-Infinity, 3/2]").get().abs(), "[0, Infinity)"); aeq(read("(-Infinity, -3/2]").get().abs(), "[3/2, Infinity)"); aeq(read("[-6, Infinity)").get().abs(), "[0, Infinity)"); aeq(read("[6, Infinity)").get().abs(), "[6, Infinity)"); } @Test public void testSignum() { aeq(ZERO.signum(), "Optional[0]"); aeq(ONE.signum(), "Optional[1]"); aeq(ALL.signum(), "Optional.empty"); aeq(read("[-2, 5/3]").get().signum(), "Optional.empty"); aeq(read("[4, 4]").get().signum(), "Optional[1]"); aeq(read("(-Infinity, 3/2]").get().signum(), "Optional.empty"); aeq(read("(-Infinity, -3/2]").get().signum(), "Optional[-1]"); aeq(read("[-6, Infinity)").get().signum(), "Optional.empty"); aeq(read("[6, Infinity)").get().signum(), "Optional[1]"); } @Test public void testSubtract() { aeq(ZERO.subtract(ZERO), "[0, 0]"); aeq(ZERO.subtract(ONE), "[-1, -1]"); aeq(ZERO.subtract(ALL), "(-Infinity, Infinity)"); aeq(ZERO.subtract(read("[-2, 5/3]").get()), "[-5/3, 2]"); aeq(ZERO.subtract(read("[4, 4]").get()), "[-4, -4]"); aeq(ZERO.subtract(read("(-Infinity, 3/2]").get()), "[-3/2, Infinity)"); aeq(ZERO.subtract(read("[-6, Infinity)").get()), "(-Infinity, 6]"); aeq(ONE.subtract(ZERO), "[1, 1]"); aeq(ONE.subtract(ONE), "[0, 0]"); aeq(ONE.subtract(ALL), "(-Infinity, Infinity)"); aeq(ONE.subtract(read("[-2, 5/3]").get()), "[-2/3, 3]"); aeq(ONE.subtract(read("[4, 4]").get()), "[-3, -3]"); aeq(ONE.subtract(read("(-Infinity, 3/2]").get()), "[-1/2, Infinity)"); aeq(ONE.subtract(read("[-6, Infinity)").get()), "(-Infinity, 7]"); aeq(ALL.subtract(ZERO), "(-Infinity, Infinity)"); aeq(ALL.subtract(ONE), "(-Infinity, Infinity)"); aeq(ALL.subtract(ALL), "(-Infinity, Infinity)"); aeq(ALL.subtract(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(ALL.subtract(read("[4, 4]").get()), "(-Infinity, Infinity)"); aeq(ALL.subtract(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(ALL.subtract(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().subtract(ZERO), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().subtract(ONE), "[-3, 2/3]"); aeq(read("[-2, 5/3]").get().subtract(ALL), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().subtract(read("[-2, 5/3]").get()), "[-11/3, 11/3]"); aeq(read("[-2, 5/3]").get().subtract(read("[4, 4]").get()), "[-6, -7/3]"); aeq(read("[-2, 5/3]").get().subtract(read("(-Infinity, 3/2]").get()), "[-7/2, Infinity)"); aeq(read("[-2, 5/3]").get().subtract(read("[-6, Infinity)").get()), "(-Infinity, 23/3]"); aeq(read("[4, 4]").get().subtract(ZERO), "[4, 4]"); aeq(read("[4, 4]").get().subtract(ONE), "[3, 3]"); aeq(read("[4, 4]").get().subtract(ALL), "(-Infinity, Infinity)"); aeq(read("[4, 4]").get().subtract(read("[-2, 5/3]").get()), "[7/3, 6]"); aeq(read("[4, 4]").get().subtract(read("[4, 4]").get()), "[0, 0]"); aeq(read("[4, 4]").get().subtract(read("(-Infinity, 3/2]").get()), "[5/2, Infinity)"); aeq(read("[4, 4]").get().subtract(read("[-6, Infinity)").get()), "(-Infinity, 10]"); aeq(read("(-Infinity, 3/2]").get().subtract(ZERO), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().subtract(ONE), "(-Infinity, 1/2]"); aeq(read("(-Infinity, 3/2]").get().subtract(ALL), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().subtract(read("[-2, 5/3]").get()), "(-Infinity, 7/2]"); aeq(read("(-Infinity, 3/2]").get().subtract(read("[4, 4]").get()), "(-Infinity, -5/2]"); aeq(read("(-Infinity, 3/2]").get().subtract(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().subtract(read("[-6, Infinity)").get()), "(-Infinity, 15/2]"); aeq(read("[-6, Infinity)").get().subtract(ZERO), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().subtract(ONE), "[-7, Infinity)"); aeq(read("[-6, Infinity)").get().subtract(ALL), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().subtract(read("[-2, 5/3]").get()), "[-23/3, Infinity)"); aeq(read("[-6, Infinity)").get().subtract(read("[4, 4]").get()), "[-10, Infinity)"); aeq(read("[-6, Infinity)").get().subtract(read("(-Infinity, 3/2]").get()), "[-15/2, Infinity)"); aeq(read("[-6, Infinity)").get().subtract(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); } @Test public void testMultiply_Interval() { aeq(ZERO.multiply(ZERO), "[0, 0]"); aeq(ZERO.multiply(ONE), "[0, 0]"); aeq(ZERO.multiply(ALL), "[0, 0]"); aeq(ZERO.multiply(read("[-2, 5/3]").get()), "[0, 0]"); aeq(ZERO.multiply(read("[4, 4]").get()), "[0, 0]"); aeq(ZERO.multiply(read("(-Infinity, 3/2]").get()), "[0, 0]"); aeq(ZERO.multiply(read("[-6, Infinity)").get()), "[0, 0]"); aeq(ONE.multiply(ZERO), "[0, 0]"); aeq(ONE.multiply(ONE), "[1, 1]"); aeq(ONE.multiply(ALL), "(-Infinity, Infinity)"); aeq(ONE.multiply(read("[-2, 5/3]").get()), "[-2, 5/3]"); aeq(ONE.multiply(read("[4, 4]").get()), "[4, 4]"); aeq(ONE.multiply(read("(-Infinity, 3/2]").get()), "(-Infinity, 3/2]"); aeq(ONE.multiply(read("[-6, Infinity)").get()), "[-6, Infinity)"); aeq(ALL.multiply(ZERO), "[0, 0]"); aeq(ALL.multiply(ONE), "(-Infinity, Infinity)"); aeq(ALL.multiply(ALL), "(-Infinity, Infinity)"); aeq(ALL.multiply(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(ALL.multiply(read("[4, 4]").get()), "(-Infinity, Infinity)"); aeq(ALL.multiply(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(ALL.multiply(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().multiply(ZERO), "[0, 0]"); aeq(read("[-2, 5/3]").get().multiply(ONE), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().multiply(ALL), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().multiply(read("[-2, 5/3]").get()), "[-10/3, 4]"); aeq(read("[-2, 5/3]").get().multiply(read("[4, 4]").get()), "[-8, 20/3]"); aeq(read("[-2, 5/3]").get().multiply(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().multiply(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[4, 4]").get().multiply(ZERO), "[0, 0]"); aeq(read("[4, 4]").get().multiply(ONE), "[4, 4]"); aeq(read("[4, 4]").get().multiply(ALL), "(-Infinity, Infinity)"); aeq(read("[4, 4]").get().multiply(read("[-2, 5/3]").get()), "[-8, 20/3]"); aeq(read("[4, 4]").get().multiply(read("[4, 4]").get()), "[16, 16]"); aeq(read("[4, 4]").get().multiply(read("(-Infinity, 3/2]").get()), "(-Infinity, 6]"); aeq(read("[4, 4]").get().multiply(read("[-6, Infinity)").get()), "[-24, Infinity)"); aeq(read("(-Infinity, 3/2]").get().multiply(ZERO), "[0, 0]"); aeq(read("(-Infinity, 3/2]").get().multiply(ONE), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().multiply(ALL), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().multiply(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().multiply(read("[4, 4]").get()), "(-Infinity, 6]"); aeq(read("(-Infinity, 3/2]").get().multiply(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().multiply(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(ZERO), "[0, 0]"); aeq(read("[-6, Infinity)").get().multiply(ONE), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(ALL), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(read("[4, 4]").get()), "[-24, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 0]").get().multiply(read("(-Infinity, 0]").get()), "[0, Infinity)"); } @Test public void testMultiply_Rational() { aeq(ZERO.multiply(Rational.ZERO), "[0, 0]"); aeq(ZERO.multiply(Rational.ONE), "[0, 0]"); aeq(ZERO.multiply(Rational.read("2/3").get()), "[0, 0]"); aeq(ZERO.multiply(Rational.read("-7").get()), "[0, 0]"); aeq(ONE.multiply(Rational.ZERO), "[0, 0]"); aeq(ONE.multiply(Rational.ONE), "[1, 1]"); aeq(ONE.multiply(Rational.read("2/3").get()), "[2/3, 2/3]"); aeq(ONE.multiply(Rational.read("-7").get()), "[-7, -7]"); aeq(ALL.multiply(Rational.ZERO), "[0, 0]"); aeq(ALL.multiply(Rational.ONE), "(-Infinity, Infinity)"); aeq(ALL.multiply(Rational.read("2/3").get()), "(-Infinity, Infinity)"); aeq(ALL.multiply(Rational.read("-7").get()), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().multiply(Rational.ZERO), "[0, 0]"); aeq(read("[-2, 5/3]").get().multiply(Rational.ONE), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().multiply(Rational.read("2/3").get()), "[-4/3, 10/9]"); aeq(read("[-2, 5/3]").get().multiply(Rational.read("-7").get()), "[-35/3, 14]"); aeq(read("[4, 4]").get().multiply(Rational.ZERO), "[0, 0]"); aeq(read("[4, 4]").get().multiply(Rational.ONE), "[4, 4]"); aeq(read("[4, 4]").get().multiply(Rational.read("2/3").get()), "[8/3, 8/3]"); aeq(read("[4, 4]").get().multiply(Rational.read("-7").get()), "[-28, -28]"); aeq(read("(-Infinity, 3/2]").get().multiply(Rational.ZERO), "[0, 0]"); aeq(read("(-Infinity, 3/2]").get().multiply(Rational.ONE), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().multiply(Rational.read("2/3").get()), "(-Infinity, 1]"); aeq(read("(-Infinity, 3/2]").get().multiply(Rational.read("-7").get()), "[-21/2, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(Rational.ZERO), "[0, 0]"); aeq(read("[-6, Infinity)").get().multiply(Rational.ONE), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(Rational.read("2/3").get()), "[-4, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(Rational.read("-7").get()), "(-Infinity, 42]"); } @Test public void testMultiply_BigInteger() { aeq(ZERO.multiply(BigInteger.ZERO), "[0, 0]"); aeq(ZERO.multiply(BigInteger.ONE), "[0, 0]"); aeq(ZERO.multiply(BigInteger.valueOf(5)), "[0, 0]"); aeq(ZERO.multiply(BigInteger.valueOf(-7)), "[0, 0]"); aeq(ONE.multiply(BigInteger.ZERO), "[0, 0]"); aeq(ONE.multiply(BigInteger.ONE), "[1, 1]"); aeq(ONE.multiply(BigInteger.valueOf(5)), "[5, 5]"); aeq(ONE.multiply(BigInteger.valueOf(-7)), "[-7, -7]"); aeq(ALL.multiply(BigInteger.ZERO), "[0, 0]"); aeq(ALL.multiply(BigInteger.ONE), "(-Infinity, Infinity)"); aeq(ALL.multiply(BigInteger.valueOf(5)), "(-Infinity, Infinity)"); aeq(ALL.multiply(BigInteger.valueOf(-7)), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().multiply(BigInteger.ZERO), "[0, 0]"); aeq(read("[-2, 5/3]").get().multiply(BigInteger.ONE), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().multiply(BigInteger.valueOf(5)), "[-10, 25/3]"); aeq(read("[-2, 5/3]").get().multiply(BigInteger.valueOf(-7)), "[-35/3, 14]"); aeq(read("[4, 4]").get().multiply(BigInteger.ZERO), "[0, 0]"); aeq(read("[4, 4]").get().multiply(BigInteger.ONE), "[4, 4]"); aeq(read("[4, 4]").get().multiply(BigInteger.valueOf(5)), "[20, 20]"); aeq(read("[4, 4]").get().multiply(BigInteger.valueOf(-7)), "[-28, -28]"); aeq(read("(-Infinity, 3/2]").get().multiply(BigInteger.ZERO), "[0, 0]"); aeq(read("(-Infinity, 3/2]").get().multiply(BigInteger.ONE), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().multiply(BigInteger.valueOf(5)), "(-Infinity, 15/2]"); aeq(read("(-Infinity, 3/2]").get().multiply(BigInteger.valueOf(-7)), "[-21/2, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(BigInteger.ZERO), "[0, 0]"); aeq(read("[-6, Infinity)").get().multiply(BigInteger.ONE), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(BigInteger.valueOf(5)), "[-30, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(BigInteger.valueOf(-7)), "(-Infinity, 42]"); } @Test public void testMultiply_int() { aeq(ZERO.multiply(0), "[0, 0]"); aeq(ZERO.multiply(1), "[0, 0]"); aeq(ZERO.multiply(5), "[0, 0]"); aeq(ZERO.multiply(-7), "[0, 0]"); aeq(ONE.multiply(0), "[0, 0]"); aeq(ONE.multiply(1), "[1, 1]"); aeq(ONE.multiply(5), "[5, 5]"); aeq(ONE.multiply(-7), "[-7, -7]"); aeq(ALL.multiply(0), "[0, 0]"); aeq(ALL.multiply(1), "(-Infinity, Infinity)"); aeq(ALL.multiply(5), "(-Infinity, Infinity)"); aeq(ALL.multiply(-7), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().multiply(0), "[0, 0]"); aeq(read("[-2, 5/3]").get().multiply(1), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().multiply(5), "[-10, 25/3]"); aeq(read("[-2, 5/3]").get().multiply(-7), "[-35/3, 14]"); aeq(read("[4, 4]").get().multiply(0), "[0, 0]"); aeq(read("[4, 4]").get().multiply(1), "[4, 4]"); aeq(read("[4, 4]").get().multiply(5), "[20, 20]"); aeq(read("[4, 4]").get().multiply(-7), "[-28, -28]"); aeq(read("(-Infinity, 3/2]").get().multiply(0), "[0, 0]"); aeq(read("(-Infinity, 3/2]").get().multiply(1), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().multiply(5), "(-Infinity, 15/2]"); aeq(read("(-Infinity, 3/2]").get().multiply(-7), "[-21/2, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(0), "[0, 0]"); aeq(read("[-6, Infinity)").get().multiply(1), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(5), "[-30, Infinity)"); aeq(read("[-6, Infinity)").get().multiply(-7), "(-Infinity, 42]"); } @Test public void testInvert() { aeq(ZERO.invert(), "[]"); aeq(ONE.invert(), "[[1, 1]]"); aeq(ALL.invert(), "[(-Infinity, Infinity)]"); aeq(read("[-2, 5/3]").get().invert(), "[(-Infinity, -1/2], [3/5, Infinity)]"); aeq(read("[4, 4]").get().invert(), "[[1/4, 1/4]]"); aeq(read("[0, 4]").get().invert(), "[[1/4, Infinity)]"); aeq(read("[-4, 0]").get().invert(), "[(-Infinity, -1/4]]"); aeq(read("(-Infinity, -3/2]").get().invert(), "[[-2/3, 0]]"); aeq(read("(-Infinity, 3/2]").get().invert(), "[(-Infinity, 0], [2/3, Infinity)]"); aeq(read("(-Infinity, 0]").get().invert(), "[(-Infinity, 0]]"); aeq(read("[-6, Infinity)").get().invert(), "[(-Infinity, -1/6], [0, Infinity)]"); aeq(read("[6, Infinity)").get().invert(), "[[0, 1/6]]"); aeq(read("[0, Infinity)").get().invert(), "[[0, Infinity)]"); aeq(read("(-Infinity, 0]").get().invert(), "[(-Infinity, 0]]"); } @Test public void testInvertHull() { aeq(ONE.invertHull(), "[1, 1]"); aeq(ALL.invertHull(), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().invertHull(), "(-Infinity, Infinity)"); aeq(read("[4, 4]").get().invertHull(), "[1/4, 1/4]"); aeq(read("[0, 4]").get().invertHull(), "[1/4, Infinity)"); aeq(read("[-4, 0]").get().invertHull(), "(-Infinity, -1/4]"); aeq(read("(-Infinity, -3/2]").get().invertHull(), "[-2/3, 0]"); aeq(read("(-Infinity, 3/2]").get().invertHull(), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 0]").get().invertHull(), "(-Infinity, 0]"); aeq(read("[-6, Infinity)").get().invertHull(), "(-Infinity, Infinity)"); aeq(read("[6, Infinity)").get().invertHull(), "[0, 1/6]"); aeq(read("[0, Infinity)").get().invertHull(), "[0, Infinity)"); aeq(read("(-Infinity, 0]").get().invertHull(), "(-Infinity, 0]"); try { ZERO.invertHull(); fail(); } catch (ArithmeticException ignored) {} } @Test public void testDivide_Interval() { aeq(ZERO.divide(ZERO), "[]"); aeq(ZERO.divide(ONE), "[[0, 0]]"); aeq(ZERO.divide(ALL), "[[0, 0]]"); aeq(ZERO.divide(read("[-2, 5/3]").get()), "[[0, 0]]"); aeq(ZERO.divide(read("[4, 4]").get()), "[[0, 0]]"); aeq(ZERO.divide(read("(-Infinity, 3/2]").get()), "[[0, 0]]"); aeq(ZERO.divide(read("[-6, Infinity)").get()), "[[0, 0]]"); aeq(ONE.divide(ZERO), "[]"); aeq(ONE.divide(ONE), "[[1, 1]]"); aeq(ONE.divide(ALL), "[(-Infinity, Infinity)]"); aeq(ONE.divide(read("[-2, 5/3]").get()), "[(-Infinity, -1/2], [3/5, Infinity)]"); aeq(ONE.divide(read("[4, 4]").get()), "[[1/4, 1/4]]"); aeq(ONE.divide(read("(-Infinity, 3/2]").get()), "[(-Infinity, 0], [2/3, Infinity)]"); aeq(ONE.divide(read("[-6, Infinity)").get()), "[(-Infinity, -1/6], [0, Infinity)]"); aeq(ALL.divide(ZERO), "[]"); aeq(ALL.divide(ONE), "[(-Infinity, Infinity)]"); aeq(ALL.divide(ALL), "[(-Infinity, Infinity)]"); aeq(ALL.divide(read("[-2, 5/3]").get()), "[(-Infinity, Infinity)]"); aeq(ALL.divide(read("[4, 4]").get()), "[(-Infinity, Infinity)]"); aeq(ALL.divide(read("(-Infinity, 3/2]").get()), "[(-Infinity, Infinity)]"); aeq(ALL.divide(read("[-6, Infinity)").get()), "[(-Infinity, Infinity)]"); aeq(read("[-2, 5/3]").get().divide(ZERO), "[]"); aeq(read("[-2, 5/3]").get().divide(ONE), "[[-2, 5/3]]"); aeq(read("[-2, 5/3]").get().divide(ALL), "[(-Infinity, Infinity)]"); aeq(read("[-2, 5/3]").get().divide(read("[-2, 5/3]").get()), "[(-Infinity, Infinity)]"); aeq(read("[-2, 5/3]").get().divide(read("[4, 4]").get()), "[[-1/2, 5/12]]"); aeq(read("[-2, 5/3]").get().divide(read("(-Infinity, 3/2]").get()), "[(-Infinity, Infinity)]"); aeq(read("[-2, 5/3]").get().divide(read("[-6, Infinity)").get()), "[(-Infinity, Infinity)]"); aeq(read("[4, 4]").get().divide(ZERO), "[]"); aeq(read("[4, 4]").get().divide(ONE), "[[4, 4]]"); aeq(read("[4, 4]").get().divide(ALL), "[(-Infinity, Infinity)]"); aeq(read("[4, 4]").get().divide(read("[-2, 5/3]").get()), "[(-Infinity, -2], [12/5, Infinity)]"); aeq(read("[4, 4]").get().divide(read("[4, 4]").get()), "[[1, 1]]"); aeq(read("[4, 4]").get().divide(read("(-Infinity, 3/2]").get()), "[(-Infinity, 0], [8/3, Infinity)]"); aeq(read("[4, 4]").get().divide(read("[-6, Infinity)").get()), "[(-Infinity, -2/3], [0, Infinity)]"); aeq(read("(-Infinity, 3/2]").get().divide(ZERO), "[]"); aeq(read("(-Infinity, 3/2]").get().divide(ONE), "[(-Infinity, 3/2]]"); aeq(read("(-Infinity, 3/2]").get().divide(ALL), "[(-Infinity, Infinity)]"); aeq(read("(-Infinity, 3/2]").get().divide(read("[-2, 5/3]").get()), "[(-Infinity, Infinity)]"); aeq(read("(-Infinity, 3/2]").get().divide(read("[4, 4]").get()), "[(-Infinity, 3/8]]"); aeq(read("(-Infinity, 3/2]").get().divide(read("(-Infinity, 3/2]").get()), "[(-Infinity, Infinity)]"); aeq(read("(-Infinity, 3/2]").get().divide(read("[-6, Infinity)").get()), "[(-Infinity, Infinity)]"); aeq(read("[-6, Infinity)").get().divide(ZERO), "[]"); aeq(read("[-6, Infinity)").get().divide(ONE), "[[-6, Infinity)]"); aeq(read("[-6, Infinity)").get().divide(ALL), "[(-Infinity, Infinity)]"); aeq(read("[-6, Infinity)").get().divide(read("[-2, 5/3]").get()), "[(-Infinity, Infinity)]"); aeq(read("[-6, Infinity)").get().divide(read("[4, 4]").get()), "[[-3/2, Infinity)]"); aeq(read("[-6, Infinity)").get().divide(read("(-Infinity, 3/2]").get()), "[(-Infinity, Infinity)]"); aeq(read("[-6, Infinity)").get().divide(read("[-6, Infinity)").get()), "[(-Infinity, Infinity)]"); aeq(read("(-Infinity, 0]").get().divide(read("(-Infinity, 0]").get()), "[[0, Infinity)]"); } @Test public void testDivideHull() { aeq(ZERO.divideHull(ONE), "[0, 0]"); aeq(ZERO.divideHull(ALL), "[0, 0]"); aeq(ZERO.divideHull(read("[-2, 5/3]").get()), "[0, 0]"); aeq(ZERO.divideHull(read("[4, 4]").get()), "[0, 0]"); aeq(ZERO.divideHull(read("(-Infinity, 3/2]").get()), "[0, 0]"); aeq(ZERO.divideHull(read("[-6, Infinity)").get()), "[0, 0]"); aeq(ONE.divideHull(ONE), "[1, 1]"); aeq(ONE.divideHull(ALL), "(-Infinity, Infinity)"); aeq(ONE.divideHull(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(ONE.divideHull(read("[4, 4]").get()), "[1/4, 1/4]"); aeq(ONE.divideHull(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(ONE.divideHull(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(ALL.divideHull(ONE), "(-Infinity, Infinity)"); aeq(ALL.divideHull(ALL), "(-Infinity, Infinity)"); aeq(ALL.divideHull(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(ALL.divideHull(read("[4, 4]").get()), "(-Infinity, Infinity)"); aeq(ALL.divideHull(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(ALL.divideHull(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().divideHull(ONE), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().divideHull(ALL), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().divideHull(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().divideHull(read("[4, 4]").get()), "[-1/2, 5/12]"); aeq(read("[-2, 5/3]").get().divideHull(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().divideHull(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[4, 4]").get().divideHull(ONE), "[4, 4]"); aeq(read("[4, 4]").get().divideHull(ALL), "(-Infinity, Infinity)"); aeq(read("[4, 4]").get().divideHull(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(read("[4, 4]").get().divideHull(read("[4, 4]").get()), "[1, 1]"); aeq(read("[4, 4]").get().divideHull(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(read("[4, 4]").get().divideHull(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().divideHull(ONE), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().divideHull(ALL), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().divideHull(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().divideHull(read("[4, 4]").get()), "(-Infinity, 3/8]"); aeq(read("(-Infinity, 3/2]").get().divideHull(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().divideHull(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().divideHull(ONE), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().divideHull(ALL), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().divideHull(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().divideHull(read("[4, 4]").get()), "[-3/2, Infinity)"); aeq(read("[-6, Infinity)").get().divideHull(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().divideHull(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 0]").get().divideHull(read("(-Infinity, 0]").get()), "[0, Infinity)"); try { ZERO.divideHull(ZERO); fail(); } catch (ArithmeticException ignored) {} try { read("[-2, 5/3]").get().divideHull(ZERO); fail(); } catch (ArithmeticException ignored) {} } @Test public void testDivide_Rational() { aeq(ZERO.divide(Rational.ONE), "[0, 0]"); aeq(ZERO.divide(Rational.read("2/3").get()), "[0, 0]"); aeq(ZERO.divide(Rational.read("-7").get()), "[0, 0]"); aeq(ONE.divide(Rational.ONE), "[1, 1]"); aeq(ONE.divide(Rational.read("2/3").get()), "[3/2, 3/2]"); aeq(ONE.divide(Rational.read("-7").get()), "[-1/7, -1/7]"); aeq(ALL.divide(Rational.ONE), "(-Infinity, Infinity)"); aeq(ALL.divide(Rational.read("2/3").get()), "(-Infinity, Infinity)"); aeq(ALL.divide(Rational.read("-7").get()), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().divide(Rational.ONE), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().divide(Rational.read("2/3").get()), "[-3, 5/2]"); aeq(read("[-2, 5/3]").get().divide(Rational.read("-7").get()), "[-5/21, 2/7]"); aeq(read("[4, 4]").get().divide(Rational.ONE), "[4, 4]"); aeq(read("[4, 4]").get().divide(Rational.read("2/3").get()), "[6, 6]"); aeq(read("[4, 4]").get().divide(Rational.read("-7").get()), "[-4/7, -4/7]"); aeq(read("(-Infinity, 3/2]").get().divide(Rational.ONE), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().divide(Rational.read("2/3").get()), "(-Infinity, 9/4]"); aeq(read("(-Infinity, 3/2]").get().divide(Rational.read("-7").get()), "[-3/14, Infinity)"); aeq(read("[-6, Infinity)").get().divide(Rational.ONE), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().divide(Rational.read("2/3").get()), "[-9, Infinity)"); aeq(read("[-6, Infinity)").get().divide(Rational.read("-7").get()), "(-Infinity, 6/7]"); try { read("[-2, 5/3]").get().divide(Rational.ZERO); } catch (ArithmeticException ignored) {} } @Test public void testDivide_BigInteger() { aeq(ZERO.divide(BigInteger.ONE), "[0, 0]"); aeq(ZERO.divide(BigInteger.valueOf(5)), "[0, 0]"); aeq(ZERO.divide(BigInteger.valueOf(-7)), "[0, 0]"); aeq(ONE.divide(BigInteger.ONE), "[1, 1]"); aeq(ONE.divide(BigInteger.valueOf(5)), "[1/5, 1/5]"); aeq(ONE.divide(BigInteger.valueOf(-7)), "[-1/7, -1/7]"); aeq(ALL.divide(BigInteger.ONE), "(-Infinity, Infinity)"); aeq(ALL.divide(BigInteger.valueOf(5)), "(-Infinity, Infinity)"); aeq(ALL.divide(BigInteger.valueOf(-7)), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().divide(BigInteger.ONE), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().divide(BigInteger.valueOf(5)), "[-2/5, 1/3]"); aeq(read("[-2, 5/3]").get().divide(BigInteger.valueOf(-7)), "[-5/21, 2/7]"); aeq(read("[4, 4]").get().divide(BigInteger.ONE), "[4, 4]"); aeq(read("[4, 4]").get().divide(BigInteger.valueOf(5)), "[4/5, 4/5]"); aeq(read("[4, 4]").get().divide(BigInteger.valueOf(-7)), "[-4/7, -4/7]"); aeq(read("(-Infinity, 3/2]").get().divide(BigInteger.ONE), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().divide(BigInteger.valueOf(5)), "(-Infinity, 3/10]"); aeq(read("(-Infinity, 3/2]").get().divide(BigInteger.valueOf(-7)), "[-3/14, Infinity)"); aeq(read("[-6, Infinity)").get().divide(BigInteger.ONE), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().divide(BigInteger.valueOf(5)), "[-6/5, Infinity)"); aeq(read("[-6, Infinity)").get().divide(BigInteger.valueOf(-7)), "(-Infinity, 6/7]"); try { read("[-2, 5/3]").get().divide(BigInteger.ZERO); } catch (ArithmeticException ignored) {} } @Test public void testDivide_int() { aeq(ZERO.divide(1), "[0, 0]"); aeq(ZERO.divide(5), "[0, 0]"); aeq(ZERO.divide(-7), "[0, 0]"); aeq(ONE.divide(1), "[1, 1]"); aeq(ONE.divide(5), "[1/5, 1/5]"); aeq(ONE.divide(-7), "[-1/7, -1/7]"); aeq(ALL.divide(1), "(-Infinity, Infinity)"); aeq(ALL.divide(5), "(-Infinity, Infinity)"); aeq(ALL.divide(-7), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().divide(1), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().divide(5), "[-2/5, 1/3]"); aeq(read("[-2, 5/3]").get().divide(-7), "[-5/21, 2/7]"); aeq(read("[4, 4]").get().divide(1), "[4, 4]"); aeq(read("[4, 4]").get().divide(5), "[4/5, 4/5]"); aeq(read("[4, 4]").get().divide(-7), "[-4/7, -4/7]"); aeq(read("(-Infinity, 3/2]").get().divide(1), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().divide(5), "(-Infinity, 3/10]"); aeq(read("(-Infinity, 3/2]").get().divide(-7), "[-3/14, Infinity)"); aeq(read("[-6, Infinity)").get().divide(1), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().divide(5), "[-6/5, Infinity)"); aeq(read("[-6, Infinity)").get().divide(-7), "(-Infinity, 6/7]"); try { read("[-2, 5/3]").get().divide(0); } catch (ArithmeticException ignored) {} } @Test public void testShiftLeft() { aeq(ZERO.shiftLeft(0), "[0, 0]"); aeq(ZERO.shiftLeft(1), "[0, 0]"); aeq(ZERO.shiftLeft(2), "[0, 0]"); aeq(ZERO.shiftLeft(3), "[0, 0]"); aeq(ZERO.shiftLeft(4), "[0, 0]"); aeq(ZERO.shiftLeft(-1), "[0, 0]"); aeq(ZERO.shiftLeft(-2), "[0, 0]"); aeq(ZERO.shiftLeft(-3), "[0, 0]"); aeq(ZERO.shiftLeft(-4), "[0, 0]"); aeq(ONE.shiftLeft(0), "[1, 1]"); aeq(ONE.shiftLeft(1), "[2, 2]"); aeq(ONE.shiftLeft(2), "[4, 4]"); aeq(ONE.shiftLeft(3), "[8, 8]"); aeq(ONE.shiftLeft(4), "[16, 16]"); aeq(ONE.shiftLeft(-1), "[1/2, 1/2]"); aeq(ONE.shiftLeft(-2), "[1/4, 1/4]"); aeq(ONE.shiftLeft(-3), "[1/8, 1/8]"); aeq(ONE.shiftLeft(-4), "[1/16, 1/16]"); aeq(ALL.shiftLeft(0), "(-Infinity, Infinity)"); aeq(ALL.shiftLeft(1), "(-Infinity, Infinity)"); aeq(ALL.shiftLeft(2), "(-Infinity, Infinity)"); aeq(ALL.shiftLeft(3), "(-Infinity, Infinity)"); aeq(ALL.shiftLeft(4), "(-Infinity, Infinity)"); aeq(ALL.shiftLeft(-1), "(-Infinity, Infinity)"); aeq(ALL.shiftLeft(-2), "(-Infinity, Infinity)"); aeq(ALL.shiftLeft(-3), "(-Infinity, Infinity)"); aeq(ALL.shiftLeft(-4), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().shiftLeft(0), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().shiftLeft(1), "[-4, 10/3]"); aeq(read("[-2, 5/3]").get().shiftLeft(2), "[-8, 20/3]"); aeq(read("[-2, 5/3]").get().shiftLeft(3), "[-16, 40/3]"); aeq(read("[-2, 5/3]").get().shiftLeft(4), "[-32, 80/3]"); aeq(read("[-2, 5/3]").get().shiftLeft(-1), "[-1, 5/6]"); aeq(read("[-2, 5/3]").get().shiftLeft(-2), "[-1/2, 5/12]"); aeq(read("[-2, 5/3]").get().shiftLeft(-3), "[-1/4, 5/24]"); aeq(read("[-2, 5/3]").get().shiftLeft(-4), "[-1/8, 5/48]"); aeq(read("[4, 4]").get().shiftLeft(0), "[4, 4]"); aeq(read("[4, 4]").get().shiftLeft(1), "[8, 8]"); aeq(read("[4, 4]").get().shiftLeft(2), "[16, 16]"); aeq(read("[4, 4]").get().shiftLeft(3), "[32, 32]"); aeq(read("[4, 4]").get().shiftLeft(4), "[64, 64]"); aeq(read("[4, 4]").get().shiftLeft(-1), "[2, 2]"); aeq(read("[4, 4]").get().shiftLeft(-2), "[1, 1]"); aeq(read("[4, 4]").get().shiftLeft(-3), "[1/2, 1/2]"); aeq(read("[4, 4]").get().shiftLeft(-4), "[1/4, 1/4]"); aeq(read("(-Infinity, -3/2]").get().shiftLeft(0), "(-Infinity, -3/2]"); aeq(read("(-Infinity, -3/2]").get().shiftLeft(1), "(-Infinity, -3]"); aeq(read("(-Infinity, -3/2]").get().shiftLeft(2), "(-Infinity, -6]"); aeq(read("(-Infinity, -3/2]").get().shiftLeft(3), "(-Infinity, -12]"); aeq(read("(-Infinity, -3/2]").get().shiftLeft(4), "(-Infinity, -24]"); aeq(read("(-Infinity, -3/2]").get().shiftLeft(-1), "(-Infinity, -3/4]"); aeq(read("(-Infinity, -3/2]").get().shiftLeft(-2), "(-Infinity, -3/8]"); aeq(read("(-Infinity, -3/2]").get().shiftLeft(-3), "(-Infinity, -3/16]"); aeq(read("(-Infinity, -3/2]").get().shiftLeft(-4), "(-Infinity, -3/32]"); aeq(read("[-6, Infinity)").get().shiftLeft(0), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().shiftLeft(1), "[-12, Infinity)"); aeq(read("[-6, Infinity)").get().shiftLeft(2), "[-24, Infinity)"); aeq(read("[-6, Infinity)").get().shiftLeft(3), "[-48, Infinity)"); aeq(read("[-6, Infinity)").get().shiftLeft(4), "[-96, Infinity)"); aeq(read("[-6, Infinity)").get().shiftLeft(-1), "[-3, Infinity)"); aeq(read("[-6, Infinity)").get().shiftLeft(-2), "[-3/2, Infinity)"); aeq(read("[-6, Infinity)").get().shiftLeft(-3), "[-3/4, Infinity)"); aeq(read("[-6, Infinity)").get().shiftLeft(-4), "[-3/8, Infinity)"); } @Test public void testShiftRight() { aeq(ZERO.shiftRight(0), "[0, 0]"); aeq(ZERO.shiftRight(1), "[0, 0]"); aeq(ZERO.shiftRight(2), "[0, 0]"); aeq(ZERO.shiftRight(3), "[0, 0]"); aeq(ZERO.shiftRight(4), "[0, 0]"); aeq(ZERO.shiftRight(-1), "[0, 0]"); aeq(ZERO.shiftRight(-2), "[0, 0]"); aeq(ZERO.shiftRight(-3), "[0, 0]"); aeq(ZERO.shiftRight(-4), "[0, 0]"); aeq(ONE.shiftRight(0), "[1, 1]"); aeq(ONE.shiftRight(1), "[1/2, 1/2]"); aeq(ONE.shiftRight(2), "[1/4, 1/4]"); aeq(ONE.shiftRight(3), "[1/8, 1/8]"); aeq(ONE.shiftRight(4), "[1/16, 1/16]"); aeq(ONE.shiftRight(-1), "[2, 2]"); aeq(ONE.shiftRight(-2), "[4, 4]"); aeq(ONE.shiftRight(-3), "[8, 8]"); aeq(ONE.shiftRight(-4), "[16, 16]"); aeq(ALL.shiftRight(0), "(-Infinity, Infinity)"); aeq(ALL.shiftRight(1), "(-Infinity, Infinity)"); aeq(ALL.shiftRight(2), "(-Infinity, Infinity)"); aeq(ALL.shiftRight(3), "(-Infinity, Infinity)"); aeq(ALL.shiftRight(4), "(-Infinity, Infinity)"); aeq(ALL.shiftRight(-1), "(-Infinity, Infinity)"); aeq(ALL.shiftRight(-2), "(-Infinity, Infinity)"); aeq(ALL.shiftRight(-3), "(-Infinity, Infinity)"); aeq(ALL.shiftRight(-4), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().shiftRight(0), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().shiftRight(1), "[-1, 5/6]"); aeq(read("[-2, 5/3]").get().shiftRight(2), "[-1/2, 5/12]"); aeq(read("[-2, 5/3]").get().shiftRight(3), "[-1/4, 5/24]"); aeq(read("[-2, 5/3]").get().shiftRight(4), "[-1/8, 5/48]"); aeq(read("[-2, 5/3]").get().shiftRight(-1), "[-4, 10/3]"); aeq(read("[-2, 5/3]").get().shiftRight(-2), "[-8, 20/3]"); aeq(read("[-2, 5/3]").get().shiftRight(-3), "[-16, 40/3]"); aeq(read("[-2, 5/3]").get().shiftRight(-4), "[-32, 80/3]"); aeq(read("[4, 4]").get().shiftRight(0), "[4, 4]"); aeq(read("[4, 4]").get().shiftRight(1), "[2, 2]"); aeq(read("[4, 4]").get().shiftRight(2), "[1, 1]"); aeq(read("[4, 4]").get().shiftRight(3), "[1/2, 1/2]"); aeq(read("[4, 4]").get().shiftRight(4), "[1/4, 1/4]"); aeq(read("[4, 4]").get().shiftRight(-1), "[8, 8]"); aeq(read("[4, 4]").get().shiftRight(-2), "[16, 16]"); aeq(read("[4, 4]").get().shiftRight(-3), "[32, 32]"); aeq(read("[4, 4]").get().shiftRight(-4), "[64, 64]"); aeq(read("(-Infinity, -3/2]").get().shiftRight(0), "(-Infinity, -3/2]"); aeq(read("(-Infinity, -3/2]").get().shiftRight(1), "(-Infinity, -3/4]"); aeq(read("(-Infinity, -3/2]").get().shiftRight(2), "(-Infinity, -3/8]"); aeq(read("(-Infinity, -3/2]").get().shiftRight(3), "(-Infinity, -3/16]"); aeq(read("(-Infinity, -3/2]").get().shiftRight(4), "(-Infinity, -3/32]"); aeq(read("(-Infinity, -3/2]").get().shiftRight(-1), "(-Infinity, -3]"); aeq(read("(-Infinity, -3/2]").get().shiftRight(-2), "(-Infinity, -6]"); aeq(read("(-Infinity, -3/2]").get().shiftRight(-3), "(-Infinity, -12]"); aeq(read("(-Infinity, -3/2]").get().shiftRight(-4), "(-Infinity, -24]"); aeq(read("[-6, Infinity)").get().shiftRight(0), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().shiftRight(1), "[-3, Infinity)"); aeq(read("[-6, Infinity)").get().shiftRight(2), "[-3/2, Infinity)"); aeq(read("[-6, Infinity)").get().shiftRight(3), "[-3/4, Infinity)"); aeq(read("[-6, Infinity)").get().shiftRight(4), "[-3/8, Infinity)"); aeq(read("[-6, Infinity)").get().shiftRight(-1), "[-12, Infinity)"); aeq(read("[-6, Infinity)").get().shiftRight(-2), "[-24, Infinity)"); aeq(read("[-6, Infinity)").get().shiftRight(-3), "[-48, Infinity)"); aeq(read("[-6, Infinity)").get().shiftRight(-4), "[-96, Infinity)"); } @Test public void testSum() { aeq(sum(readIntervalList("[]")), "[0, 0]"); aeq(sum(readIntervalList("[[-2, 5/3], (-Infinity, 6], [4, 4]]")), "(-Infinity, 35/3]"); try { sum(readIntervalListWithNulls("[[-2, 5/3], null, [4, 4]]")); fail(); } catch (NullPointerException ignored) {} } @Test public void testProduct() { aeq(product(readIntervalList("[]")), "[1, 1]"); aeq(product(readIntervalList("[[-2, 5/3], [0, 6], [4, 4]]")), "[-48, 40]"); aeq(product(readIntervalList("[[-2, 5/3], (-Infinity, 6], [4, 4]]")), "(-Infinity, Infinity)"); try { product(readIntervalListWithNulls("[[-2, 5/3], null, [4, 4]]")); fail(); } catch (IllegalArgumentException ignored) {} } @Test public void testDelta() { aeq(delta(readIntervalList("[[1/3, 2]]")), "[]"); aeq(delta(readIntervalList("[[-2, 5/3], (-Infinity, 6], [4, 4]]")), "[(-Infinity, 8], [-2, Infinity)]"); try { delta(readIntervalListWithNulls("[]")); fail(); } catch (IllegalArgumentException ignored) {} try { IterableUtils.toList(delta(readIntervalListWithNulls("[[-2, 5/3], null, [4, 4]]"))); fail(); } catch (NullPointerException ignored) {} } @Test public void testPow() { aeq(ZERO.pow(0), "[[1, 1]]"); aeq(ZERO.pow(1), "[[0, 0]]"); aeq(ZERO.pow(2), "[[0, 0]]"); aeq(ZERO.pow(3), "[[0, 0]]"); aeq(ONE.pow(0), "[[1, 1]]"); aeq(ONE.pow(1), "[[1, 1]]"); aeq(ONE.pow(2), "[[1, 1]]"); aeq(ONE.pow(3), "[[1, 1]]"); aeq(ONE.pow(-1), "[[1, 1]]"); aeq(ONE.pow(-2), "[[1, 1]]"); aeq(ONE.pow(-3), "[[1, 1]]"); aeq(ALL.pow(0), "[[1, 1]]"); aeq(ALL.pow(1), "[(-Infinity, Infinity)]"); aeq(ALL.pow(2), "[[0, Infinity)]"); aeq(ALL.pow(3), "[(-Infinity, Infinity)]"); aeq(ALL.pow(-1), "[(-Infinity, Infinity)]"); aeq(ALL.pow(-2), "[[0, Infinity)]"); aeq(ALL.pow(-3), "[(-Infinity, Infinity)]"); aeq(read("[-2, 5/3]").get().pow(0), "[[1, 1]]"); aeq(read("[-2, 5/3]").get().pow(1), "[[-2, 5/3]]"); aeq(read("[-2, 5/3]").get().pow(2), "[[0, 4]]"); aeq(read("[-2, 5/3]").get().pow(3), "[[-8, 125/27]]"); aeq(read("[-2, 5/3]").get().pow(-1), "[(-Infinity, -1/2], [3/5, Infinity)]"); aeq(read("[-2, 5/3]").get().pow(-2), "[[1/4, Infinity)]"); aeq(read("[-2, 5/3]").get().pow(-3), "[(-Infinity, -1/8], [27/125, Infinity)]"); aeq(read("[4, 4]").get().pow(0), "[[1, 1]]"); aeq(read("[4, 4]").get().pow(1), "[[4, 4]]"); aeq(read("[4, 4]").get().pow(2), "[[16, 16]]"); aeq(read("[4, 4]").get().pow(3), "[[64, 64]]"); aeq(read("[4, 4]").get().pow(-1), "[[1/4, 1/4]]"); aeq(read("[4, 4]").get().pow(-2), "[[1/16, 1/16]]"); aeq(read("[4, 4]").get().pow(-3), "[[1/64, 1/64]]"); aeq(read("(-Infinity, 3/2]").get().pow(0), "[[1, 1]]"); aeq(read("(-Infinity, 3/2]").get().pow(1), "[(-Infinity, 3/2]]"); aeq(read("(-Infinity, 3/2]").get().pow(2), "[[0, Infinity)]"); aeq(read("(-Infinity, 3/2]").get().pow(3), "[(-Infinity, 27/8]]"); aeq(read("(-Infinity, 3/2]").get().pow(-1), "[(-Infinity, 0], [2/3, Infinity)]"); aeq(read("(-Infinity, 3/2]").get().pow(-2), "[[0, Infinity)]"); aeq(read("(-Infinity, 3/2]").get().pow(-3), "[(-Infinity, 0], [8/27, Infinity)]"); aeq(read("[-6, Infinity)").get().pow(0), "[[1, 1]]"); aeq(read("[-6, Infinity)").get().pow(1), "[[-6, Infinity)]"); aeq(read("[-6, Infinity)").get().pow(2), "[[0, Infinity)]"); aeq(read("[-6, Infinity)").get().pow(3), "[[-216, Infinity)]"); aeq(read("[-6, Infinity)").get().pow(-1), "[(-Infinity, -1/6], [0, Infinity)]"); aeq(read("[-6, Infinity)").get().pow(-2), "[[0, Infinity)]"); aeq(read("[-6, Infinity)").get().pow(-3), "[(-Infinity, -1/216], [0, Infinity)]"); } @Test public void testPowHull() { aeq(ZERO.powHull(0), "[1, 1]"); aeq(ZERO.powHull(1), "[0, 0]"); aeq(ZERO.powHull(2), "[0, 0]"); aeq(ZERO.powHull(3), "[0, 0]"); aeq(ONE.powHull(0), "[1, 1]"); aeq(ONE.powHull(1), "[1, 1]"); aeq(ONE.powHull(2), "[1, 1]"); aeq(ONE.powHull(3), "[1, 1]"); aeq(ONE.powHull(-1), "[1, 1]"); aeq(ONE.powHull(-2), "[1, 1]"); aeq(ONE.powHull(-3), "[1, 1]"); aeq(ALL.powHull(0), "[1, 1]"); aeq(ALL.powHull(1), "(-Infinity, Infinity)"); aeq(ALL.powHull(2), "[0, Infinity)"); aeq(ALL.powHull(3), "(-Infinity, Infinity)"); aeq(ALL.powHull(-1), "(-Infinity, Infinity)"); aeq(ALL.powHull(-2), "[0, Infinity)"); aeq(ALL.powHull(-3), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().powHull(0), "[1, 1]"); aeq(read("[-2, 5/3]").get().powHull(1), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().powHull(2), "[0, 4]"); aeq(read("[-2, 5/3]").get().powHull(3), "[-8, 125/27]"); aeq(read("[-2, 5/3]").get().powHull(-1), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().powHull(-2), "[1/4, Infinity)"); aeq(read("[-2, 5/3]").get().powHull(-3), "(-Infinity, Infinity)"); aeq(read("[4, 4]").get().powHull(0), "[1, 1]"); aeq(read("[4, 4]").get().powHull(1), "[4, 4]"); aeq(read("[4, 4]").get().powHull(2), "[16, 16]"); aeq(read("[4, 4]").get().powHull(3), "[64, 64]"); aeq(read("[4, 4]").get().powHull(-1), "[1/4, 1/4]"); aeq(read("[4, 4]").get().powHull(-2), "[1/16, 1/16]"); aeq(read("[4, 4]").get().powHull(-3), "[1/64, 1/64]"); aeq(read("(-Infinity, 3/2]").get().powHull(0), "[1, 1]"); aeq(read("(-Infinity, 3/2]").get().powHull(1), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().powHull(2), "[0, Infinity)"); aeq(read("(-Infinity, 3/2]").get().powHull(3), "(-Infinity, 27/8]"); aeq(read("(-Infinity, 3/2]").get().powHull(-1), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().powHull(-2), "[0, Infinity)"); aeq(read("(-Infinity, 3/2]").get().powHull(-3), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().powHull(0), "[1, 1]"); aeq(read("[-6, Infinity)").get().powHull(1), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().powHull(2), "[0, Infinity)"); aeq(read("[-6, Infinity)").get().powHull(3), "[-216, Infinity)"); aeq(read("[-6, Infinity)").get().powHull(-1), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().powHull(-2), "[0, Infinity)"); aeq(read("[-6, Infinity)").get().powHull(-3), "(-Infinity, Infinity)"); try { ZERO.powHull(-1); fail(); } catch (ArithmeticException ignored) {} try { ZERO.powHull(-2); fail(); } catch (ArithmeticException ignored) {} try { ZERO.powHull(-3); fail(); } catch (ArithmeticException ignored) {} } @Test public void testElementCompare() { aeq(ZERO.elementCompare(ZERO), "Optional[EQ]"); aeq(ZERO.elementCompare(ONE), "Optional[LT]"); aeq(ZERO.elementCompare(ALL), "Optional.empty"); aeq(ZERO.elementCompare(read("[-2, 5/3]").get()), "Optional.empty"); aeq(ZERO.elementCompare(read("[4, 4]").get()), "Optional[LT]"); aeq(ZERO.elementCompare(read("(-Infinity, 3/2]").get()), "Optional.empty"); aeq(ZERO.elementCompare(read("[-6, Infinity)").get()), "Optional.empty"); aeq(ONE.elementCompare(ZERO), "Optional[GT]"); aeq(ONE.elementCompare(ONE), "Optional[EQ]"); aeq(ONE.elementCompare(ALL), "Optional.empty"); aeq(ONE.elementCompare(read("[-2, 5/3]").get()), "Optional.empty"); aeq(ONE.elementCompare(read("[4, 4]").get()), "Optional[LT]"); aeq(ONE.elementCompare(read("(-Infinity, 3/2]").get()), "Optional.empty"); aeq(ONE.elementCompare(read("[-6, Infinity)").get()), "Optional.empty"); aeq(ALL.elementCompare(ZERO), "Optional.empty"); aeq(ALL.elementCompare(ONE), "Optional.empty"); aeq(ALL.elementCompare(ALL), "Optional.empty"); aeq(ALL.elementCompare(read("[-2, 5/3]").get()), "Optional.empty"); aeq(ALL.elementCompare(read("[4, 4]").get()), "Optional.empty"); aeq(ALL.elementCompare(read("(-Infinity, 3/2]").get()), "Optional.empty"); aeq(ALL.elementCompare(read("[-6, Infinity)").get()), "Optional.empty"); aeq(read("[-2, 5/3]").get().elementCompare(ZERO), "Optional.empty"); aeq(read("[-2, 5/3]").get().elementCompare(ONE), "Optional.empty"); aeq(read("[-2, 5/3]").get().elementCompare(ALL), "Optional.empty"); aeq(read("[-2, 5/3]").get().elementCompare(read("[-2, 5/3]").get()), "Optional.empty"); aeq(read("[-2, 5/3]").get().elementCompare(read("[4, 4]").get()), "Optional[LT]"); aeq(read("[-2, 5/3]").get().elementCompare(read("(-Infinity, 3/2]").get()), "Optional.empty"); aeq(read("[-2, 5/3]").get().elementCompare(read("[-6, Infinity)").get()), "Optional.empty"); aeq(read("[4, 4]").get().elementCompare(ZERO), "Optional[GT]"); aeq(read("[4, 4]").get().elementCompare(ONE), "Optional[GT]"); aeq(read("[4, 4]").get().elementCompare(ALL), "Optional.empty"); aeq(read("[4, 4]").get().elementCompare(read("[-2, 5/3]").get()), "Optional[GT]"); aeq(read("[4, 4]").get().elementCompare(read("[4, 4]").get()), "Optional[EQ]"); aeq(read("[4, 4]").get().elementCompare(read("(-Infinity, 3/2]").get()), "Optional[GT]"); aeq(read("[4, 4]").get().elementCompare(read("[-6, Infinity)").get()), "Optional.empty"); aeq(read("(-Infinity, 3/2]").get().elementCompare(ZERO), "Optional.empty"); aeq(read("(-Infinity, 3/2]").get().elementCompare(ONE), "Optional.empty"); aeq(read("(-Infinity, 3/2]").get().elementCompare(ALL), "Optional.empty"); aeq(read("(-Infinity, 3/2]").get().elementCompare(read("[-2, 5/3]").get()), "Optional.empty"); aeq(read("(-Infinity, 3/2]").get().elementCompare(read("[4, 4]").get()), "Optional[LT]"); aeq(read("(-Infinity, 3/2]").get().elementCompare(read("(-Infinity, 3/2]").get()), "Optional.empty"); aeq(read("(-Infinity, 3/2]").get().elementCompare(read("[-6, Infinity)").get()), "Optional.empty"); aeq(read("[-6, Infinity)").get().elementCompare(ZERO), "Optional.empty"); aeq(read("[-6, Infinity)").get().elementCompare(ONE), "Optional.empty"); aeq(read("[-6, Infinity)").get().elementCompare(ALL), "Optional.empty"); aeq(read("[-6, Infinity)").get().elementCompare(read("[-2, 5/3]").get()), "Optional.empty"); aeq(read("[-6, Infinity)").get().elementCompare(read("[4, 4]").get()), "Optional.empty"); aeq(read("[-6, Infinity)").get().elementCompare(read("(-Infinity, 3/2]").get()), "Optional.empty"); aeq(read("[-6, Infinity)").get().elementCompare(read("[-6, Infinity)").get()), "Optional.empty"); } @Test public void testEquals() { //noinspection EqualsWithItself assertTrue(ZERO.equals(ZERO)); //noinspection EqualsWithItself assertTrue(ONE.equals(ONE)); //noinspection EqualsWithItself assertTrue(ALL.equals(ALL)); assertTrue(read("[-2, 5/3]").equals(read("[-2, 5/3]"))); assertTrue(read("[4, 4]").equals(read("[4, 4]"))); assertTrue(read("(-Infinity, 3/2]").equals(read("(-Infinity, 3/2]"))); assertTrue(read("[-6, Infinity)").equals(read("[-6, Infinity)"))); assertFalse(ZERO.equals(ONE)); assertFalse(ZERO.equals(ALL)); assertFalse(ZERO.equals(read("[-2, 5/3]").get())); assertFalse(ZERO.equals(read("[4, 4]").get())); assertFalse(ZERO.equals(read("(-Infinity, 3/2]").get())); assertFalse(ZERO.equals(read("[-6, Infinity)").get())); assertFalse(ONE.equals(ZERO)); assertFalse(ONE.equals(ALL)); assertFalse(ONE.equals(read("[-2, 5/3]").get())); assertFalse(ONE.equals(read("[4, 4]").get())); assertFalse(ONE.equals(read("(-Infinity, 3/2]").get())); assertFalse(ONE.equals(read("[-6, Infinity)").get())); assertFalse(ALL.equals(ZERO)); assertFalse(ALL.equals(ONE)); assertFalse(ALL.equals(read("[-2, 5/3]").get())); assertFalse(ALL.equals(read("[4, 4]").get())); assertFalse(ALL.equals(read("(-Infinity, 3/2]").get())); assertFalse(ALL.equals(read("[-6, Infinity)").get())); assertFalse(read("[-2, 5/3]").get().equals(ZERO)); assertFalse(read("[-2, 5/3]").get().equals(ONE)); assertFalse(read("[-2, 5/3]").get().equals(ALL)); assertFalse(read("[-2, 5/3]").get().equals(read("[4, 4]").get())); assertFalse(read("[-2, 5/3]").get().equals(read("(-Infinity, 3/2]").get())); assertFalse(read("[-2, 5/3]").get().equals(read("[-6, Infinity)").get())); assertFalse(read("[4, 4]").get().equals(ZERO)); assertFalse(read("[4, 4]").get().equals(ONE)); assertFalse(read("[4, 4]").get().equals(ALL)); assertFalse(read("[4, 4]").get().equals(read("[-2, 5/3]").get())); assertFalse(read("[4, 4]").get().equals(read("(-Infinity, 3/2]").get())); assertFalse(read("[4, 4]").get().equals(read("[-6, Infinity)").get())); assertFalse(read("(-Infinity, 3/2]").get().equals(ZERO)); assertFalse(read("(-Infinity, 3/2]").get().equals(ONE)); assertFalse(read("(-Infinity, 3/2]").get().equals(ALL)); assertFalse(read("(-Infinity, 3/2]").get().equals(read("[-2, 5/3]").get())); assertFalse(read("(-Infinity, 3/2]").get().equals(read("[4, 4]").get())); assertFalse(read("(-Infinity, 3/2]").get().equals(read("[-6, Infinity)").get())); assertFalse(read("[-6, Infinity)").get().equals(ZERO)); assertFalse(read("[-6, Infinity)").get().equals(ONE)); assertFalse(read("[-6, Infinity)").get().equals(ALL)); assertFalse(read("[-6, Infinity)").get().equals(read("[-2, 5/3]").get())); assertFalse(read("[-6, Infinity)").get().equals(read("[4, 4]").get())); assertFalse(read("[-6, Infinity)").get().equals(read("(-Infinity, 3/2]").get())); //noinspection ObjectEqualsNull assertFalse(ZERO.equals(null)); //noinspection ObjectEqualsNull assertFalse(ONE.equals(null)); //noinspection ObjectEqualsNull assertFalse(ALL.equals(null)); assertTrue(read("[-2, 5/3]").isPresent()); assertTrue(read("[4, 4]").isPresent()); assertTrue(read("(-Infinity, 3/2]").isPresent()); assertTrue(read("[-6, Infinity)").isPresent()); } @Test public void testHashCode() { aeq(ZERO.hashCode(), 32); aeq(ONE.hashCode(), 1024); aeq(ALL.hashCode(), 0); aeq(read("[-2, 5/3]").hashCode(), -1733); aeq(read("[4, 4]").hashCode(), 4000); aeq(read("(-Infinity, 3/2]").hashCode(), 95); aeq(read("[-6, Infinity)").hashCode(), -5735); } @Test public void testCompareTo() { assertTrue(eq(ZERO, ZERO)); assertTrue(eq(ONE, ONE)); assertTrue(eq(ALL, ALL)); assertTrue(eq(read("[-2, 5/3]").get(), read("[-2, 5/3]").get())); assertTrue(eq(read("[4, 4]").get(), read("[4, 4]").get())); assertTrue(eq(read("(-Infinity, 3/2]").get(), read("(-Infinity, 3/2]").get())); assertTrue(eq(read("[-6, Infinity)").get(), read("[-6, Infinity)").get())); assertTrue(lt(ZERO, ONE)); assertTrue(gt(ZERO, ALL)); assertTrue(gt(ZERO, read("[-2, 5/3]").get())); assertTrue(lt(ZERO, read("[4, 4]").get())); assertTrue(gt(ZERO, read("(-Infinity, 3/2]").get())); assertTrue(gt(ZERO, read("[-6, Infinity)").get())); assertTrue(gt(ONE, ZERO)); assertTrue(gt(ONE, ALL)); assertTrue(gt(ONE, read("[-2, 5/3]").get())); assertTrue(lt(ONE, read("[4, 4]").get())); assertTrue(gt(ONE, read("(-Infinity, 3/2]").get())); assertTrue(gt(ONE, read("[-6, Infinity)").get())); assertTrue(lt(ALL, ZERO)); assertTrue(lt(ALL, ONE)); assertTrue(lt(ALL, read("[-2, 5/3]").get())); assertTrue(lt(ALL, read("[4, 4]").get())); assertTrue(gt(ALL, read("(-Infinity, 3/2]").get())); assertTrue(lt(ALL, read("[-6, Infinity)").get())); assertTrue(lt(read("[-2, 5/3]").get(), ZERO)); assertTrue(lt(read("[-2, 5/3]").get(), ONE)); assertTrue(gt(read("[-2, 5/3]").get(), ALL)); assertTrue(lt(read("[-2, 5/3]").get(), read("[4, 4]").get())); assertTrue(gt(read("[-2, 5/3]").get(), read("(-Infinity, 3/2]").get())); assertTrue(gt(read("[-2, 5/3]").get(), read("[-6, Infinity)").get())); assertTrue(gt(read("[4, 4]").get(), ZERO)); assertTrue(gt(read("[4, 4]").get(), ONE)); assertTrue(gt(read("[4, 4]").get(), ALL)); assertTrue(gt(read("[4, 4]").get(), read("[-2, 5/3]").get())); assertTrue(gt(read("[4, 4]").get(), read("(-Infinity, 3/2]").get())); assertTrue(gt(read("[4, 4]").get(), read("[-6, Infinity)").get())); assertTrue(lt(read("(-Infinity, 3/2]").get(), ZERO)); assertTrue(lt(read("(-Infinity, 3/2]").get(), ONE)); assertTrue(lt(read("(-Infinity, 3/2]").get(), ALL)); assertTrue(lt(read("(-Infinity, 3/2]").get(), read("[-2, 5/3]").get())); assertTrue(lt(read("(-Infinity, 3/2]").get(), read("[4, 4]").get())); assertTrue(lt(read("(-Infinity, 3/2]").get(), read("[-6, Infinity)").get())); assertTrue(lt(read("[-6, Infinity)").get(), ZERO)); assertTrue(lt(read("[-6, Infinity)").get(), ONE)); assertTrue(gt(read("[-6, Infinity)").get(), ALL)); assertTrue(lt(read("[-6, Infinity)").get(), read("[-2, 5/3]").get())); assertTrue(lt(read("[-6, Infinity)").get(), read("[4, 4]").get())); assertTrue(gt(read("[-6, Infinity)").get(), read("(-Infinity, 3/2]").get())); } @Test public void testRead() { aeq(read("[0, 0]").get(), ZERO); aeq(read("[1, 1]").get(), ONE); aeq(read("(-Infinity, Infinity)").get(), ALL); aeq(read("[-2, 5/3]").get(), "[-2, 5/3]"); aeq(read("[4, 4]").get(), "[4, 4]"); aeq(read("(-Infinity, 3/2]").get(), "(-Infinity, 3/2]"); aeq(read("[-6, Infinity)").get(), "[-6, Infinity)"); assertFalse(read("").isPresent()); assertFalse(read("[").isPresent()); assertFalse(read("[]").isPresent()); assertFalse(read("[,]").isPresent()); assertFalse(read("[1, 1").isPresent()); assertFalse(read("[12]").isPresent()); assertFalse(read("[1 1]").isPresent()); assertFalse(read("[1, 1]").isPresent()); assertFalse(read("[ 1, 1]").isPresent()); assertFalse(read("[1, 1 ]").isPresent()); assertFalse(read("[1, 1] ").isPresent()); assertFalse(read("[-Infinity, Infinity]").isPresent()); assertFalse(read("(-Infinity, 4)").isPresent()); assertFalse(read("[4, Infinity]").isPresent()); assertFalse(read("(Infinity, -Infinity)").isPresent()); assertFalse(read("[2, 3-]").isPresent()); assertFalse(read("[2.0, 4]").isPresent()); assertFalse(read("[2,4]").isPresent()); assertFalse(read("[5, 4]").isPresent()); assertFalse(read("[5, 4/0]").isPresent()); } @Test public void testFindIn() { aeq(findIn("abcd[-5, 2/3]xyz").get(), "([-5, 2/3], 4)"); aeq(findIn("vdfvdf(-Infinity, 3]cds").get(), "((-Infinity, 3], 6)"); aeq(findIn("gvrgw49((-Infinity, Infinity)Infinity)").get(), "((-Infinity, Infinity), 8)"); assertFalse(findIn("").isPresent()); assertFalse(findIn("hello").isPresent()); assertFalse(findIn("vdfsvfbf").isPresent()); assertFalse(findIn("vdfvds[-Infinity, 2]vsd").isPresent()); assertFalse(findIn("vdfvds(Infinity, 2]vsd").isPresent()); assertFalse(findIn("abcd[5, 4]xyz").isPresent()); assertFalse(findIn("abcd[5, 4/0]xyz").isPresent()); } @Test public void testToString() { aeq(ZERO, "[0, 0]"); aeq(ONE, "[1, 1]"); aeq(ALL, "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get(), "[-2, 5/3]"); aeq(read("[4, 4]").get(), "[4, 4]"); aeq(read("(-Infinity, 3/2]").get(), "(-Infinity, 3/2]"); aeq(read("[-6, Infinity)").get(), "[-6, Infinity)"); } private static void aeq(Iterable<?> a, Object b) { assertEquals(IterableUtils.toString(a), b.toString()); } private static void aeq(Object a, Object b) { assertEquals(a.toString(), b.toString()); } private static @NotNull List<Interval> readIntervalList(@NotNull String s) { return Readers.readList(Interval::read).apply(s).get(); } private static @NotNull List<Interval> readIntervalListWithNulls(@NotNull String s) { return Readers.readListWithNulls(Interval::read).apply(s).get(); } }
fix exception type
src/test/java/mho/qbar/objects/IntervalTest.java
fix exception type
Java
mit
46bf1aad4292666c492849b75f06a1dfb660f0ec
0
mickleness/pumpernickel,mickleness/pumpernickel,mickleness/pumpernickel
package com.pump.geom; import java.awt.Rectangle; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Path2D; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.Serializable; import java.util.Objects; /** * A simple wrapper for a shape that makes it immutable and serializable. * <p> * If we simply stored data as a Path2D or GeneralPath then other entities may * invoke <code>reset()</code>, <code>transform(..)</code> or other methods to * modify the shape data. * <p> * This is similar (or identical?) to <code>sun.font.DelegateShape</code>. */ public class ImmutableShape implements Shape, Serializable { private static final long serialVersionUID = 1L; protected Shape shape; public ImmutableShape(Shape shape) { Objects.requireNonNull(shape); this.shape = shape; } @Override public Rectangle getBounds() { return shape.getBounds(); } @Override public Rectangle2D getBounds2D() { return shape.getBounds2D(); } @Override public boolean contains(double x, double y) { return shape.contains(x, y); } @Override public boolean contains(Point2D p) { return shape.contains(p); } @Override public boolean intersects(double x, double y, double w, double h) { return shape.intersects(x, y, w, h); } @Override public boolean intersects(Rectangle2D r) { return shape.intersects(r); } @Override public boolean contains(double x, double y, double w, double h) { return shape.contains(x, y, w, h); } @Override public boolean contains(Rectangle2D r) { return shape.contains(r); } @Override public PathIterator getPathIterator(AffineTransform at) { return shape.getPathIterator(at); } @Override public PathIterator getPathIterator(AffineTransform at, double flatness) { return shape.getPathIterator(at, flatness); } private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.writeInt(0); if (shape instanceof Serializable) { out.writeObject(shape); } else { PathIterator pi = shape.getPathIterator(null); String str = ShapeStringUtils.toString(pi); out.writeObject(str); out.writeInt(pi.getWindingRule()); } } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { int internalVersion = in.readInt(); if (internalVersion == 0) { Object v = in.readObject(); if (v instanceof Shape) { shape = (Shape) v; } else { String str = (String) v; PathIterator pi = ShapeStringUtils.createPathIterator(str); int windingRule = in.readInt(); Path2D p = new Path2D.Float(windingRule); p.append(pi, false); shape = p; } } else { throw new IOException( "Unsupported internal version: " + internalVersion); } } }
src/main/java/com/pump/geom/ImmutableShape.java
package com.pump.geom; import java.awt.Rectangle; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Path2D; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.Serializable; import java.util.Objects; /** * A simple wrapper for a shape that makes it immutable and serializable. * <p> * If we simply stored data as a Path2D or GeneralPath then other entities may * invoke <code>reset()</code>, <code>transform(..)</code> or other methods to * modify the shape data. */ public class ImmutableShape implements Shape, Serializable { private static final long serialVersionUID = 1L; protected Shape shape; public ImmutableShape(Shape shape) { Objects.requireNonNull(shape); this.shape = shape; } @Override public Rectangle getBounds() { return shape.getBounds(); } @Override public Rectangle2D getBounds2D() { return shape.getBounds2D(); } @Override public boolean contains(double x, double y) { return shape.contains(x, y); } @Override public boolean contains(Point2D p) { return shape.contains(p); } @Override public boolean intersects(double x, double y, double w, double h) { return shape.intersects(x, y, w, h); } @Override public boolean intersects(Rectangle2D r) { return shape.intersects(r); } @Override public boolean contains(double x, double y, double w, double h) { return shape.contains(x, y, w, h); } @Override public boolean contains(Rectangle2D r) { return shape.contains(r); } @Override public PathIterator getPathIterator(AffineTransform at) { return shape.getPathIterator(at); } @Override public PathIterator getPathIterator(AffineTransform at, double flatness) { return shape.getPathIterator(at, flatness); } private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.writeInt(0); if (shape instanceof Serializable) { out.writeObject(shape); } else { PathIterator pi = shape.getPathIterator(null); String str = ShapeStringUtils.toString(pi); out.writeObject(str); out.writeInt(pi.getWindingRule()); } } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { int internalVersion = in.readInt(); if (internalVersion == 0) { Object v = in.readObject(); if (v instanceof Shape) { shape = (Shape) v; } else { String str = (String) v; PathIterator pi = ShapeStringUtils.createPathIterator(str); int windingRule = in.readInt(); Path2D p = new Path2D.Float(windingRule); p.append(pi, false); shape = p; } } else { throw new IOException( "Unsupported internal version: " + internalVersion); } } }
Adding trivial javadoc comment
src/main/java/com/pump/geom/ImmutableShape.java
Adding trivial javadoc comment
Java
mit
59b6efdc61004ded0d492d42dc6e1c0410676f5f
0
tlaplus/tlaplus,tlaplus/tlaplus,tlaplus/tlaplus,tlaplus/tlaplus
// Copyright (c) 2003 Compaq Corporation. All rights reserved. // Portions Copyright (c) 2003 Microsoft Corporation. All rights reserved. // Last modified on Thu 10 April 2008 at 14:31:23 PST by lamport // modified on Wed Dec 5 22:37:20 PST 2001 by yuanyu package tlc2; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; import model.InJarFilenameToStream; import model.ModelInJar; import tlc2.debug.TLCDebugger; import tlc2.output.EC; import tlc2.output.ErrorTraceMessagePrinterRecorder; import tlc2.output.MP; import tlc2.output.Messages; import tlc2.tool.DFIDModelChecker; import tlc2.tool.ITool; import tlc2.tool.ModelChecker; import tlc2.tool.Simulator; import tlc2.tool.SingleThreadedSimulator; import tlc2.tool.fp.FPSet; import tlc2.tool.fp.FPSetConfiguration; import tlc2.tool.fp.FPSetFactory; import tlc2.tool.impl.DebugTool; import tlc2.tool.impl.FastTool; import tlc2.tool.impl.ParameterizedSpecObj; import tlc2.tool.impl.ParameterizedSpecObj.PostCondition; import tlc2.tool.impl.Tool; import tlc2.tool.management.ModelCheckerMXWrapper; import tlc2.tool.management.TLCStandardMBean; import tlc2.util.DotStateWriter; import tlc2.util.FP64; import tlc2.util.IStateWriter; import tlc2.util.NoopStateWriter; import tlc2.util.RandomGenerator; import tlc2.util.StateWriter; import tlc2.value.RandomEnumerableValues; import util.Assert.TLCRuntimeException; import util.DebugPrinter; import util.ExecutionStatisticsCollector; import util.FileUtil; import util.FilenameToStream; import util.MailSender; import util.SimpleFilenameToStream; import util.TLAConstants; import util.TLCRuntime; import util.ToolIO; import util.UniqueString; import util.UsageGenerator; /** * Main TLC starter class. * * <b>Note:</b> If you are using a new instance of this class in an already existant JVM which has done processing with * tlc2 parsers, please see the class javadocs for {@link TLCRunner} * * @author Yuan Yu * @author Leslie Lamport * @author Simon Zambrovski */ public class TLC { /** * Whether the TLA+ spec is encoded in a .jar file, not a TLA+ text file. */ private static boolean MODEL_PART_OF_JAR = false; /** * Possible TLC run modes: either model checking or simulation. */ public enum RunMode { MODEL_CHECK, SIMULATE; } // SZ Feb 20, 2009: the class has been // transformed from static to dynamic /** * Whether to run in model checking or simulation mode. * Defaults to model checking. */ private RunMode runMode; /** * Whether to clean up the states directory. */ private boolean cleanup; /** * Whether to check for deadlock. */ private boolean deadlock; /** * Whether a seed for the random number generator was provided. */ private boolean noSeed; /** * The seed for the random number generator. */ private long seed; /** * Adjustment for random number generator seed. */ private long aril; /** * TLC processing start time. */ private long startTime; /** * Name of main TLA+ specification file. */ private String mainFile; private String configFile; private String metadir; /** * If instantiated with a non-Noop* instance, the trace will be written to the * user provided file (-dump parameter). * <p> * Contrary to plain -dump, -dot will also write out transitions from state s to * s' if s' is already known. Thus, the resulting graph shows all successors of * s instead of just s's unexplored ones. * <p> * Off (NoopStateWriter) by default. */ private IStateWriter stateWriter = new NoopStateWriter(); /** * Name of checkpoint from which TLC should recover. */ private String fromChkpt; /** * Fingerprint set function index to use. * By default one is picked at random. */ private int fpIndex; /** * The number of traces/behaviors to generate in simulation mode */ private static long traceNum = Long.MAX_VALUE; /** * Name of the file to which to write state traces. */ private String traceFile = null; private String traceActions = null; /** * Maximum state trace depth. Set to 100 by default. */ private int traceDepth; private FilenameToStream resolver; /** * Whether welcome message has already been printed. */ private boolean welcomePrinted; /** * Fingerprint set configuration. */ private FPSetConfiguration fpSetConfiguration; private final Map<String, Object> params; private int debugPort = -1; private boolean suspend = true; private boolean halt = true; /** * Interface to retrieve model properties. */ private volatile ITool tool; /** * Records errors as TLC runs. */ private final ErrorTraceMessagePrinterRecorder recorder = new ErrorTraceMessagePrinterRecorder(); /** * Trace exploration spec generator. */ private TraceExplorationSpec teSpec; /** * Initialization */ public TLC() { welcomePrinted = false; runMode = RunMode.MODEL_CHECK; cleanup = false; deadlock = true; noSeed = true; seed = 0; aril = 0; mainFile = null; configFile = null; fromChkpt = null; resolver = null; fpIndex = new Random().nextInt(FP64.Polys.length); traceDepth = 100; fpSetConfiguration = new FPSetConfiguration(); params = new HashMap<>(); } /* * This TLA checker (TLC) provides the following functionalities: * 1. Simulation of TLA+ specs: * java tlc2.TLC -simulate spec[.tla] * 2. Model checking of TLA+ specs: * java tlc2.TLC [-modelcheck] spec[.tla] * * The command line also provides the following options observed for functionalities 1. & 2.: * o -config file: provide the config file. * Defaults to spec.cfg if not provided * o -deadlock: do not check for deadlock. * Defaults to checking deadlock if not specified * o -depth num: specify the depth of random simulation * Defaults to 100 if not specified * o -seed num: provide the seed for random simulation * Defaults to a random seed if not specified * o -aril num: Adjust the seed for random simulation * Defaults to 0 if not specified * o -recover path: recover from the checkpoint at path * Defaults to scratch run if not specified * o -metadir path: store metadata in the directory at path * Defaults to specdir/states if not specified * o -userFile file: A full qualified/absolute path to a file to log user * output (Print/PrintT/...) to * o -workers num: the number of TLC worker threads * Defaults to 1 * o -dfid num: use depth-first iterative deepening with initial depth num * o -cleanup: clean up the states directory * o -dumpTrace format file: dump all counter-examples into file in the given format. * o -dump [dot] file: dump all the states into file. If "dot" as sub-parameter * is given, the output will be in dot notation. * o -postCondition mod!op: Evaluate the operator op in module mod after state-space exploration. * o -difftrace: when printing trace, show only * the differences between successive states * Defaults to printing full state descriptions if not specified * (Added by Rajeev Joshi) * o -terse: do not expand values in Print statement * Defaults to expand value if not specified * o -coverage minutes: collect coverage information on the spec, * print out the information every minutes. * Defaults to no coverage if not specified * o -continue: continue running even when invariant is violated * Defaults to stop at the first violation if not specified * o -lncheck: Check liveness properties at different times * of model checking. * Defaults to false increasing the overall model checking time. * o -nowarning: disable all the warnings * Defaults to report warnings if not specified * o -fp num: use the num'th irreducible polynomial from the list * stored in the class FP64. * o -view: apply VIEW (if provided) when printing out states. * o -gzip: control if gzip is applied to value input/output stream. * Defaults to off if not specified * o -debug: debbuging information (non-production use) * o -debugger: Activate TLC debugger * o -tool: tool mode (put output codes on console) * o -generateSpecTE: will generate SpecTE assets if error-states are * encountered during model checking; this will change * to tool mode regardless of whether '-tool' was * explicitly specified; add on 'nomonolith' to not * embed the dependencies in the SpecTE * o -checkpoint num: interval for check pointing (in minutes) * Defaults to 30 * o -fpmem num: a value between 0 and 1, exclusive, representing the ratio * of total system memory used to store the fingerprints of * found states. * Defaults to 1/4 physical memory. (Added 6 Apr 2010 by Yuan Yu.) * o -fpbits num: the number of msb used by MultiFPSet to create nested FPSets. * Defaults to 1 * o -maxSetSize num: the size of the largest set TLC will enumerate. * Defaults to 1000000 * */ public static void main(String[] args) throws Exception { final TLC tlc = new TLC(); // Try to parse parameters. if (!tlc.handleParameters(args)) { // This is a tool failure. We must exit with a non-zero exit // code or else we will mislead system tools and scripts into // thinking everything went smoothly. // // FIXME: handleParameters should return an error object (or // null), where the error object contains an error message. // This makes handleParameters a function we can test. System.exit(1); } if (!tlc.checkEnvironment()) { System.exit(1); } final MailSender ms = new MailSender(); // Setup how spec files will be resolved in the filesystem. if (MODEL_PART_OF_JAR) { // There was not spec file given, it instead exists in the // .jar file being executed. So we need to use a special file // resolver to parse it. tlc.setResolver(new InJarFilenameToStream(ModelInJar.PATH)); } else { // The user passed us a spec file directly. To ensure we can // recover it during semantic parsing, we must include its // parent directory as a library path in the file resolver. // // If the spec file has no parent directory, use the "standard" // library paths provided by SimpleFilenameToStream. final String dir = FileUtil.parseDirname(tlc.getMainFile()); if (!dir.isEmpty()) { tlc.setResolver(new SimpleFilenameToStream(dir)); } else { tlc.setResolver(new SimpleFilenameToStream()); } } // Setup MailSender *before* calling tlc.process. The MailSender's task it to // write the MC.out file. The MC.out file is e.g. used by CloudTLC to feed // progress back to the Toolbox (see CloudDistributedTLCJob). ms.setModelName(tlc.getModelName()); ms.setSpecName(tlc.getSpecName()); // Execute TLC. final int errorCode = tlc.process(); // Send logged output by email. // // This is needed when TLC runs on another host and email is // the only means for the user to get access to the model // checking results. boolean mailSent = ms.send(tlc.getModuleFiles()); // Treat failure to send mail as a tool failure. // // With distributed TLC and CloudDistributedTLCJob in particular, // the cloud node is immediately turned off once the TLC process // has finished. If we were to shutdown the node even when sending // out the email has failed, the result would be lost. if (!mailSent) { System.exit(1); } // Be explicit about tool success. System.exit(EC.ExitStatus.errorConstantToExitStatus(errorCode)); } // false if the environment (JVM, OS, ...) makes model checking impossible. // Might also result in warnings. private boolean checkEnvironment() { // Not a reasons to refuse startup but warn about non-ideal garbage collector. // See https://twitter.com/lemmster/status/1089656514892070912 for actual // performance penalty. if (!TLCRuntime.getInstance().isThroughputOptimizedGC()) { MP.printWarning(EC.TLC_ENVIRONMENT_JVM_GC); } return true; } public static void setTraceNum(long aTraceNum) { traceNum = aTraceNum; } /** * This method handles parameter arguments and prepares the actual call * <strong>Note:</strong> This method set ups the static TLCGlobals variables * @return status of parsing: true iff parameter check was ok, false otherwise * @throws IOException */ // SZ Feb 23, 2009: added return status to indicate the error in parsing @SuppressWarnings("deprecation") // we're emitting a warning to the user, but still accepting fpmem values > 1 public boolean handleParameters(String[] args) { String dumpFile = null; boolean asDot = false; boolean colorize = false; boolean actionLabels = false; boolean snapshot = false; boolean generateTESpec = true; boolean forceGenerateTESpec = false; Path teSpecOut = null; // SZ Feb 20, 2009: extracted this method to separate the // parameter handling from the actual processing int index = 0; while (index < args.length) { if (args[index].equals("-simulate") || args[index].equals("-generate")) { if (args[index].equals("-generate")) { System.setProperty(Tool.class.getName() + ".probabilistic", Boolean.TRUE.toString()); } runMode = RunMode.SIMULATE; index++; // Simulation args can be: // file=/path/to/file,num=4711 or num=4711,file=/path/to/file or num=4711 or // file=/path/to/file // "file=..." and "num=..." are only relevant for simulation which is why they // are args to "-simulate". if ((index < args.length) && (args[index].contains("stats=") || args[index].contains("file=") || args[index].contains("num="))) { final String[] simArgs = args[index].split(","); index++; // consume simulate args for (String arg : simArgs) { if (arg.startsWith("num=")) { traceNum = Long.parseLong(arg.replace("num=", "")); } else if (arg.startsWith("file=")) { traceFile = arg.replace("file=", ""); } else if (arg.equals("stats=basic")) { traceActions = "BASIC"; } else if (arg.equals("stats=full")) { traceActions = "FULL"; } } } } else if (args[index].equals("-modelcheck")) { index++; } else if (args[index].equals("-difftrace")) { index++; TLCGlobals.printDiffsOnly = true; } else if (args[index].equals("-deadlock")) { index++; deadlock = false; } else if (args[index].equals("-cleanup")) { index++; cleanup = true; } else if (args[index].equals("-nowarning")) { index++; TLCGlobals.warn = false; } else if (args[index].equals("-gzip")) { index++; TLCGlobals.useGZIP = true; } else if (args[index].equals("-terse")) { index++; TLCGlobals.expand = false; } else if (args[index].equals("-continue")) { index++; TLCGlobals.continuation = true; } else if (args[index].equals("-view")) { index++; TLCGlobals.useView = true; } else if (args[index].equals("-debug")) { index++; TLCGlobals.debug = true; } else if (args[index].equals("-debugger")) { index++; debugPort = 4712; //standard port. if ((index < args.length) && (args[index].contains("port=") || args[index].contains("nosuspend") || args[index].contains("nohalt"))) { suspend = !args[index].toLowerCase().contains("nosuspend"); halt = !args[index].toLowerCase().contains("nohalt"); final Matcher matcher = Pattern.compile(".*port=([0-9]{1,5}).*").matcher(args[index]); if (matcher.find()) { debugPort = Integer.parseInt(matcher.group(1)); } index++; } } else if (args[index].equals("-tool")) { index++; TLCGlobals.tool = true; } else if (args[index].equals("-generateSpecTE")) { index++; forceGenerateTESpec = true; if ((index < args.length) && args[index].equals("nomonolith")) { index++; } } else if (args[index].equals("-noGenerateSpecTE") || args[index].equalsIgnoreCase("-noTE")) { index++; generateTESpec = false; } else if (args[index].equals("-teSpecOutDir")) { index++; if (index < args.length) { String path = args[index]; try { teSpecOut = Paths.get(path); } catch (InvalidPathException e) { printErrorMsg("Error: invalid path for -teSpecOutDir option: " + path); return false; } index++; } else { printErrorMsg("Error: expected a path for -teSpecOutDir option."); return false; } } else if (args[index].equals("-help") || args[index].equals("-h")) { // See note referring to "-help" in MP#getMessage0 for EC.WRONG_COMMANDLINE_PARAMS_TLC. printUsage(); return false; } else if (args[index].equals("-lncheck")) { index++; if (index < args.length) { TLCGlobals.lnCheck = args[index].toLowerCase(); index++; } else { printErrorMsg("Error: expect a strategy such as final for -lncheck option."); return false; } } else if (args[index].equals("-config")) { index++; if (index < args.length) { configFile = args[index]; if (configFile.endsWith(TLAConstants.Files.CONFIG_EXTENSION)) { configFile = configFile.substring(0, (configFile.length() - TLAConstants.Files.CONFIG_EXTENSION.length())); } index++; } else { printErrorMsg("Error: expect a file name for -config option."); return false; } } else if (args[index].equals("-dump")) { index++; // consume "-dump". if (((index + 1) < args.length) && args[index].startsWith("dot")) { final String dotArgs = args[index].toLowerCase(); index++; // consume "dot...". asDot = true; colorize = dotArgs.contains("colorize"); actionLabels = dotArgs.contains("actionlabels"); snapshot = dotArgs.contains("snapshot"); dumpFile = getDumpFile(args[index++], ".dot"); } else if (index < args.length) { dumpFile = getDumpFile(args[index++], ".dump"); } else { printErrorMsg("Error: A file name for dumping states required."); return false; } } else if (args[index].equalsIgnoreCase("-dumpTrace")) { index++; // consume "-dumpTrace". if ((index + 1) < args.length) { final String fmt = args[index++]; if ("json".equalsIgnoreCase(fmt)) { @SuppressWarnings("unchecked") final List<PostCondition> pcs = (List<PostCondition>) params.computeIfAbsent( ParameterizedSpecObj.POST_CONDITIONS, k -> new ArrayList<PostCondition>()); pcs.add(new PostCondition("_JsonTrace", "_JsonTrace", "_JsonTraceFile", args[index++])); } else if ("tla".equalsIgnoreCase(fmt)) { @SuppressWarnings("unchecked") final List<PostCondition> pcs = (List<PostCondition>) params.computeIfAbsent( ParameterizedSpecObj.POST_CONDITIONS, k -> new ArrayList<PostCondition>()); pcs.add(new PostCondition("_TLAPlusCounterExample", "_TLAPlusCounterExample", "_TLAPlusCounterExampleFile", args[index++])); } else if ("Tomorrow's most favorite format".equalsIgnoreCase(fmt)) { //Add your new dumpTrace formats here! } else { printErrorMsg("Error: Unknown format " + fmt + " given to -dumpTrace."); return false; } } else { printErrorMsg("Error: A format and a file name for dumping traces required."); return false; } } else if (args[index].equalsIgnoreCase("-postCondition")) { index++; // consume "-postCondition". if (index < args.length) { @SuppressWarnings("unchecked") final List<PostCondition> pcs = (List<PostCondition>) params .computeIfAbsent(ParameterizedSpecObj.POST_CONDITIONS, k -> new ArrayList<PostCondition>()); // TODO: Add input validation! pcs.add(new PostCondition(args[index++])); } else { printErrorMsg("Error: Module!Operator for postCondition required."); return false; } } else if (args[index].equals("-coverage")) { index++; if (index < args.length) { try { TLCGlobals.coverageInterval = Integer.parseInt(args[index]) * 60 * 1000; if (TLCGlobals.coverageInterval < 0) { printErrorMsg("Error: expect a nonnegative integer for -coverage option."); return false; } index++; } catch (NumberFormatException e) { printErrorMsg("Error: An integer for coverage report interval required." + " But encountered " + args[index]); return false; } } else { printErrorMsg("Error: coverage report interval required."); return false; } } else if (args[index].equals("-checkpoint")) { index++; if (index < args.length) { try { TLCGlobals.chkptDuration = Integer.parseInt(args[index]) * 1000 * 60; if (TLCGlobals.chkptDuration < 0) { printErrorMsg("Error: expect a nonnegative integer for -checkpoint option."); return false; } index++; } catch (Exception e) { printErrorMsg("Error: An integer for checkpoint interval is required. But encountered " + args[index]); return false; } } else { printErrorMsg("Error: checkpoint interval required."); return false; } } else if (args[index].equals("-depth")) { index++; if (index < args.length) { try { traceDepth = Integer.parseInt(args[index]); index++; } catch (Exception e) { printErrorMsg("Error: An integer for trace length required. But encountered " + args[index]); return false; } } else { printErrorMsg("Error: trace length required."); return false; } } else if (args[index].equals("-seed")) { index++; if (index < args.length) { try { seed = Long.parseLong(args[index]); index++; noSeed = false; } catch (Exception e) { printErrorMsg("Error: An integer for seed required. But encountered " + args[index]); return false; } } else { printErrorMsg("Error: seed required."); return false; } } else if (args[index].equals("-aril")) { index++; if (index < args.length) { try { aril = Long.parseLong(args[index]); index++; } catch (Exception e) { printErrorMsg("Error: An integer for aril required. But encountered " + args[index]); return false; } } else { printErrorMsg("Error: aril required."); return false; } } else if (args[index].equals("-maxSetSize")) { index++; if (index < args.length) { try { int bound = Integer.parseInt(args[index]); // make sure it's in valid range if (!TLCGlobals.isValidSetSize(bound)) { int maxValue = Integer.MAX_VALUE; printErrorMsg("Error: Value in interval [0, " + maxValue + "] for maxSetSize required. But encountered " + args[index]); return false; } TLCGlobals.setBound = bound; index++; } catch (Exception e) { printErrorMsg("Error: An integer for maxSetSize required. But encountered " + args[index]); return false; } } else { printErrorMsg("Error: maxSetSize required."); return false; } } else if (args[index].equals("-recover")) { index++; if (index < args.length) { fromChkpt = args[index++] + FileUtil.separator; } else { printErrorMsg("Error: need to specify the metadata directory for recovery."); return false; } } else if (args[index].equals("-metadir")) { index++; if (index < args.length) { TLCGlobals.metaDir = args[index++] + FileUtil.separator; } else { printErrorMsg("Error: need to specify the metadata directory."); return false; } } else if (args[index].equals("-userFile")) { index++; if (index < args.length) { try { // Most problems will only show when TLC eventually tries // to write to the file. tlc2.module.TLC.OUTPUT = new BufferedWriter(new FileWriter(new File(args[index++]))); } catch (IOException e) { printErrorMsg("Error: Failed to create user output log file."); return false; } } else { printErrorMsg("Error: need to specify the full qualified file."); return false; } } else if (args[index].equals("-workers")) { index++; if (index < args.length) { try { int num = args[index].trim().toLowerCase().equals("auto") ? Runtime.getRuntime().availableProcessors() : Integer.parseInt(args[index]); if (num < 1) { printErrorMsg("Error: at least one worker required."); return false; } TLCGlobals.setNumWorkers(num); index++; } catch (Exception e) { printErrorMsg("Error: worker number or 'auto' required. But encountered " + args[index]); return false; } } else { printErrorMsg("Error: expect an integer or 'auto' for -workers option."); return false; } } else if (args[index].equals("-dfid")) { index++; if (index < args.length) { try { TLCGlobals.DFIDMax = Integer.parseInt(args[index]); if (TLCGlobals.DFIDMax < 0) { printErrorMsg("Error: expect a nonnegative integer for -dfid option."); return false; } index++; } catch (Exception e) { printErrorMsg("Error: expect a nonnegative integer for -dfid option. " + "But encountered " + args[index]); return false; } } else { printErrorMsg("Error: expect a nonnegative integer for -dfid option."); return false; } } else if (args[index].equals("-fp")) { index++; if (index < args.length) { try { fpIndex = Integer.parseInt(args[index]); if (fpIndex < 0 || fpIndex >= FP64.Polys.length) { printErrorMsg("Error: The number for -fp must be between 0 and " + (FP64.Polys.length - 1) + " (inclusive)."); return false; } index++; } catch (Exception e) { printErrorMsg("Error: A number for -fp is required. But encountered " + args[index]); return false; } } else { printErrorMsg("Error: expect an integer for -fp option."); return false; } } else if (args[index].equals("-fpmem")) { index++; if (index < args.length) { try { // -fpmem can be used in two ways: // a) to set the relative memory to be used for fingerprints (being machine independent) // b) to set the absolute memory to be used for fingerprints // // In order to set memory relatively, a value in the domain [0.0, 1.0] is interpreted as a fraction. // A value in the [2, Double.MaxValue] domain allocates memory absolutely. // // Independently of relative or absolute mem allocation, // a user cannot allocate more than JVM heap space // available. Conversely there is the lower hard limit TLC#MinFpMemSize. double fpMemSize = Double.parseDouble(args[index]); if (fpMemSize < 0) { printErrorMsg("Error: An positive integer or a fraction for fpset memory size/percentage required. But encountered " + args[index]); return false; } else if (fpMemSize > 1) { // For legacy reasons we allow users to set the // absolute amount of memory. If this is the case, // we know the user intends to allocate all 100% of // the absolute memory to the fpset. ToolIO.out .println("Using -fpmem with an abolute memory value has been deprecated. " + "Please allocate memory for the TLC process via the JVM mechanisms " + "and use -fpmem to set the fraction to be used for fingerprint storage."); fpSetConfiguration.setMemory((long) fpMemSize); fpSetConfiguration.setRatio(1.0d); } else { fpSetConfiguration.setRatio(fpMemSize); } index++; } catch (Exception e) { printErrorMsg("Error: An positive integer or a fraction for fpset memory size/percentage required. But encountered " + args[index]); return false; } } else { printErrorMsg("Error: fpset memory size required."); return false; } } else if (args[index].equals("-fpbits")) { index++; if (index < args.length) { try { int fpBits = Integer.parseInt(args[index]); // make sure it's in valid range if (!FPSet.isValid(fpBits)) { printErrorMsg("Error: Value in interval [0, 30] for fpbits required. But encountered " + args[index]); return false; } fpSetConfiguration.setFpBits(fpBits); index++; } catch (Exception e) { printErrorMsg("Error: An integer for fpbits required. But encountered " + args[index]); return false; } } else { printErrorMsg("Error: fpbits required."); return false; } } else { if (args[index].charAt(0) == '-') { printErrorMsg("Error: unrecognized option: " + args[index]); return false; } if (mainFile != null) { printErrorMsg("Error: more than one input files: " + mainFile + " and " + args[index]); return false; } mainFile = args[index++]; if (mainFile.endsWith(TLAConstants.Files.TLA_EXTENSION)) { mainFile = mainFile.substring(0, (mainFile.length() - TLAConstants.Files.TLA_EXTENSION.length())); } } } if (TLCGlobals.getNumWorkers() != 1 && debugPort >= 0) { printErrorMsg("Error: TLA+ Debugger does not support running with multiple workers."); return false; } startTime = System.currentTimeMillis(); if (mainFile == null) { // command line omitted name of spec file, take this as an // indicator to check the in-jar model/ folder for a spec. // If a spec is found, use it instead. if (ModelInJar.hasModel()) { MODEL_PART_OF_JAR = true; ModelInJar.loadProperties(); TLCGlobals.tool = true; // always run in Tool mode (to parse output by Toolbox later) TLCGlobals.chkptDuration = 0; // never use checkpoints with distributed TLC (highly inefficient) mainFile = TLAConstants.Files.MODEL_CHECK_FILE_BASENAME; } else { printErrorMsg("Error: Missing input TLA+ module."); return false; } } generateTESpec = // Let -generateSpecTE force the generation of a trace spec even in e.g. -tool // mode. Eventually, we trace spec generation should even be the default with // -tool mode to make trace specs broadly available to VSCode TLA+ extension // users. However, the Eclipse Toolbox should not generate trace specs unless it // migrates from its (legacy) trace exploration to trace specs. forceGenerateTESpec || (generateTESpec // TODO Drop forceGen... and replace .tool with check of system property // tlc2.TLC.ide=toolbox to prevent trace spec generation when running from // Toolbox. && !TLCGlobals.tool && !TLCGlobals.continuation && !TraceExplorationSpec.isTESpecFile(mainFile)); if (generateTESpec) { if (teSpecOut == null) { this.teSpec = new TraceExplorationSpec(getTlaFileParentDir(mainFile), new Date(startTime), mainFile, this.recorder); } else { if (teSpecOut.toString().toLowerCase().endsWith(TLAConstants.Files.TLA_EXTENSION)) { this.teSpec = new TraceExplorationSpec(teSpecOut.getParent(), teSpecOut.getFileName().toFile() .getName().replaceFirst(TLAConstants.Files.TLA_EXTENSION + "$", ""), mainFile, this.recorder); } else { this.teSpec = new TraceExplorationSpec(teSpecOut, new Date(startTime), mainFile, this.recorder); } } } // The functionality to start TLC from an (absolute) path /path/to/spec/file.tla // seems to have eroded over the years which is why this block of code is a // clutch. It essentially massages the variable values for mainFile, specDir and // the user dir to make the code below - as well as the FilenameToStream // resolver - // work. Original issues was https://github.com/tlaplus/tlaplus/issues/24. final File f = new File(mainFile); String specDir = ""; if (f.isAbsolute()) { specDir = f.getParent() + FileUtil.separator; mainFile = f.getName(); // Not setting user dir causes a ConfigFileException when the resolver // tries to read the .cfg file later in the game. ToolIO.setUserDir(specDir); } if (configFile == null) { configFile = mainFile; } if (cleanup && (fromChkpt == null)) { // clean up the states directory only when not recovering FileUtil.deleteDir(TLCGlobals.metaRoot, true); } // Check if mainFile is an absolute or relative file system path. If it is // absolute, the parent gets used as TLC's meta directory (where it stores // states...). Otherwise, no meta dir is set causing states etc. to be stored in // the current directory. metadir = FileUtil.makeMetaDir(new Date(startTime), specDir, fromChkpt); if (dumpFile != null) { if (dumpFile.startsWith("${metadir}")) { // prefix dumpfile with the known value of this.metadir. There // is no way to determine the actual value of this.metadir // before TLC startup and thus it's impossible to make the // dumpfile end up in the metadir if desired. dumpFile = dumpFile.replace("${metadir}", metadir); } try { if (asDot) { this.stateWriter = new DotStateWriter(dumpFile, colorize, actionLabels, snapshot); } else { this.stateWriter = new StateWriter(dumpFile); } } catch (IOException e) { printErrorMsg(String.format("Error: Given file name %s for dumping states invalid.", dumpFile)); return false; } } if (TLCGlobals.debug) { final StringBuilder buffer = new StringBuilder("TLC arguments:"); for (int i = 0; i < args.length; i++) { buffer.append(args[i]); if (i < args.length - 1) { buffer.append(" "); } } buffer.append("\n"); DebugPrinter.print(buffer.toString()); } // if no errors, print welcome message printWelcome(); return true; } /** * Require a $suffix file extension unless already given. It is not clear why * this is enforced. */ private static String getDumpFile(String dumpFile, String suffix) { if (dumpFile.endsWith(suffix)) { return dumpFile; } return dumpFile + suffix; } /** * The processing method */ public int process() { MP.setRecorder(this.recorder); // UniqueString.initialize(); // a JMX wrapper that exposes runtime statistics TLCStandardMBean modelCheckerMXWrapper = TLCStandardMBean.getNullTLCStandardMBean(); // SZ Feb 20, 2009: extracted this method to separate the // parameter handling from the actual processing try { // Initialize: if (fromChkpt != null) { // We must recover the intern var table as early as possible UniqueString.internTbl.recover(fromChkpt); } FP64.Init(fpIndex); final RandomGenerator rng = new RandomGenerator(); // Start checking: final int result; if (RunMode.SIMULATE.equals(runMode)) { // random simulation if (noSeed) { seed = rng.nextLong(); rng.setSeed(seed); } else { rng.setSeed(seed, aril); } RandomEnumerableValues.setSeed(seed); printStartupBanner(EC.TLC_MODE_SIMU, getSimulationRuntime(seed)); Simulator simulator; if (debugPort >= 0) { assert TLCGlobals.getNumWorkers() == 1 : "TLCDebugger does not support running with multiple workers."; final TLCDebugger instance = TLCDebugger.Factory.getInstance(debugPort, suspend, halt); synchronized (instance) { tool = new DebugTool(mainFile, configFile, resolver, Tool.Mode.Simulation, params, instance); } simulator = new SingleThreadedSimulator(tool, metadir, traceFile, deadlock, traceDepth, traceNum, traceActions, rng, seed, resolver); } else { tool = new FastTool(mainFile, configFile, resolver, Tool.Mode.Simulation, params); simulator = new Simulator(tool, metadir, traceFile, deadlock, traceDepth, traceNum, traceActions, rng, seed, resolver, TLCGlobals.getNumWorkers()); } TLCGlobals.simulator = simulator; result = simulator.simulate(); } else { // RunMode.MODEL_CHECK if (noSeed) { seed = rng.nextLong(); } // Replace seed with tlc2.util.FP64.Polys[fpIndex]? // + No need to print seed in startup-banner for BFS and DFS // - Only 131 different seeds // RandomEnumerableValues.setSeed(tlc2.util.FP64.Polys[fpIndex]); RandomEnumerableValues.setSeed(seed); // Print startup banner before SANY writes its output. printStartupBanner(isBFS() ? EC.TLC_MODE_MC : EC.TLC_MODE_MC_DFS, getModelCheckingRuntime(fpIndex, fpSetConfiguration)); // model checking if (debugPort >= 0) { assert TLCGlobals.getNumWorkers() == 1 : "TLCDebugger does not support running with multiple workers."; final TLCDebugger instance = TLCDebugger.Factory.getInstance(debugPort, suspend, halt); synchronized (instance) { tool = new DebugTool(mainFile, configFile, resolver, params, instance); } } else { tool = new FastTool(mainFile, configFile, resolver, params); } deadlock = deadlock && tool.getModelConfig().getCheckDeadlock(); if (isBFS()) { TLCGlobals.mainChecker = new ModelChecker(tool, metadir, stateWriter, deadlock, fromChkpt, FPSetFactory.getFPSetInitialized(fpSetConfiguration, metadir, new File(mainFile).getName()), startTime); modelCheckerMXWrapper = new ModelCheckerMXWrapper((ModelChecker) TLCGlobals.mainChecker, this); result = TLCGlobals.mainChecker.modelCheck(); } else { TLCGlobals.mainChecker = new DFIDModelChecker(tool, metadir, stateWriter, deadlock, fromChkpt, startTime); result = TLCGlobals.mainChecker.modelCheck(); } } return result; } catch (Throwable e) { if (e instanceof StackOverflowError) { System.gc(); return MP.printError(EC.SYSTEM_STACK_OVERFLOW, e); } else if (e instanceof OutOfMemoryError) { System.gc(); return MP.printError(EC.SYSTEM_OUT_OF_MEMORY, e); } else if (e instanceof TLCRuntimeException) { return MP.printTLCRuntimeException((TLCRuntimeException) e); } else if (e instanceof RuntimeException) { // SZ 29.07.2009 // printing the stack trace of the runtime exceptions return MP.printError(EC.GENERAL, e); // e.printStackTrace(); } else { return MP.printError(EC.GENERAL, e); } } finally { if (tlc2.module.TLC.OUTPUT != null) { try { tlc2.module.TLC.OUTPUT.flush(); tlc2.module.TLC.OUTPUT.close(); } catch (IOException e) { } } modelCheckerMXWrapper.unregister(); // In tool mode print runtime in milliseconds, in non-tool mode print human // readable runtime (days, hours, minutes, ...). final long runtime = System.currentTimeMillis() - startTime; MP.printMessage(EC.TLC_FINISHED, // If TLC runs without -tool output it might still be useful to // report overall runtime in a machine-readable format (milliseconds) // instead of in a human-readable one. TLCGlobals.tool || Boolean.getBoolean(TLC.class.getName() + ".asMilliSeconds") ? Long.toString(runtime) + "ms" : convertRuntimeToHumanReadable(runtime)); // Generate trace exploration spec if error occurred. if (teSpec != null) { teSpec.generate(this.tool); } MP.unsubscribeRecorder(this.recorder); MP.flush(); } } private static boolean isBFS() { return TLCGlobals.DFIDMax == -1; } public static Map<String, String> getSimulationRuntime(final long seed) { final Runtime runtime = Runtime.getRuntime(); final long heapMemory = runtime.maxMemory() / 1024L / 1024L; final TLCRuntime tlcRuntime = TLCRuntime.getInstance(); final long offHeapMemory = tlcRuntime.getNonHeapPhysicalMemory() / 1024L / 1024L; final long pid = tlcRuntime.pid(); final Map<String, String> result = new LinkedHashMap<>(); result.put("seed", String.valueOf(seed)); result.put("workers", String.valueOf(TLCGlobals.getNumWorkers())); result.put("plural", TLCGlobals.getNumWorkers() == 1 ? "" : "s"); result.put("cores", Integer.toString(runtime.availableProcessors())); result.put("osName", System.getProperty("os.name")); result.put("osVersion", System.getProperty("os.version")); result.put("osArch", System.getProperty("os.arch")); result.put("jvmVendor", System.getProperty("java.vendor")); result.put("jvmVersion", System.getProperty("java.version")); result.put("jvmArch", tlcRuntime.getArchitecture().name()); result.put("jvmHeapMem", Long.toString(heapMemory)); result.put("jvmOffHeapMem", Long.toString(offHeapMemory)); result.put("jvmPid", pid == -1 ? "" : String.valueOf(pid)); return result; } public static Map<String, String> getModelCheckingRuntime(final int fpIndex, final FPSetConfiguration fpSetConfig) { final Runtime runtime = Runtime.getRuntime(); final long heapMemory = runtime.maxMemory() / 1024L / 1024L; final TLCRuntime tlcRuntime = TLCRuntime.getInstance(); final long offHeapMemory = tlcRuntime.getNonHeapPhysicalMemory() / 1024L / 1024L; final long pid = tlcRuntime.pid(); // TODO Better to use Class#getSimpleName provided we would have access to the // Class instance instead of just its name. However, loading the class here is // overkill and might interfere if other parts of TLC pull off class-loading // tricks. final String fpSetClassSimpleName = fpSetConfig.getImplementation() .substring(fpSetConfig.getImplementation().lastIndexOf(".") + 1); final String stateQueueClassSimpleName = ModelChecker.getStateQueueName(); // fpSetClassSimpleName and stateQueueClassSimpleName ignored in DFS mode. final Map<String, String> result = new LinkedHashMap<>(); result.put("workers", String.valueOf(TLCGlobals.getNumWorkers())); result.put("plural", TLCGlobals.getNumWorkers() == 1 ? "" : "s"); result.put("cores", Integer.toString(runtime.availableProcessors())); result.put("osName", System.getProperty("os.name")); result.put("osVersion", System.getProperty("os.version")); result.put("osArch", System.getProperty("os.arch")); result.put("jvmVendor", System.getProperty("java.vendor")); result.put("jvmVersion", System.getProperty("java.version")); result.put("jvmArch", tlcRuntime.getArchitecture().name()); result.put("jvmHeapMem", Long.toString(heapMemory)); result.put("jvmOffHeapMem", Long.toString(offHeapMemory)); result.put("seed", Long.toString(RandomEnumerableValues.getSeed())); result.put("fpidx", Integer.toString(fpIndex)); result.put("jvmPid", pid == -1 ? "" : String.valueOf(pid)); result.put("fpset", fpSetClassSimpleName); result.put("queue", stateQueueClassSimpleName); return result; } /** * @return The given milliseconds runtime converted into human readable form * with SI unit and insignificant parts stripped (when runtime is * days, nobody cares for minutes or seconds). */ public static String convertRuntimeToHumanReadable(long runtime) { SimpleDateFormat df = null; if (runtime > (60 * 60 * 24 * 1000L)) { df = new SimpleDateFormat("D'd' HH'h'"); runtime -= 86400000L; } else if (runtime > (60 * 60 * 24 * 1000L)) { df = new SimpleDateFormat("D'd' HH'h'"); runtime -= 86400000L; } else if (runtime > (60 * 60 * 1000L)) { df = new SimpleDateFormat("HH'h' mm'min'"); } else if (runtime > (60 * 1000L)) { df = new SimpleDateFormat("mm'min' ss's'"); } else { df = new SimpleDateFormat("ss's'"); } df.setTimeZone(TimeZone.getTimeZone("UTC")); return df.format(runtime); } public List<File> getModuleFiles() { final List<File> result = new ArrayList<File>(); if (TLCGlobals.mainChecker instanceof ModelChecker) { final ModelChecker mc = (ModelChecker) TLCGlobals.mainChecker; result.addAll(mc.getModuleFiles(resolver)); if (ModelInJar.hasCfg()) { result.add(ModelInJar.getCfg()); } // It might be desirable to include tlc.jfr - a flight recording aka profiling // at the JVM level here. This doesn't work though as the recording get created // after the termination of the JVM. A recording can also be several hundred // MBs large. } return result; } /** * Sets resolver for the file names * @param resolver a resolver for the names, if <code>null</code> is used, * the standard resolver {@link SimpleFilenameToStream} is used */ public void setResolver(FilenameToStream resolver) { this.resolver = resolver; ToolIO.setDefaultResolver(resolver); } public FilenameToStream getResolver() { return this.resolver; } public void setStateWriter(IStateWriter sw) { this.stateWriter = sw; } /** * Print out an error message, with usage hint * @param msg, message to print * TODO remove this method and replace the calls */ private void printErrorMsg(String msg) { printWelcome(); MP.printError(EC.WRONG_COMMANDLINE_PARAMS_TLC, msg); } /** * Prints the welcome message once per instance */ private void printWelcome() { if (!this.welcomePrinted) { this.welcomePrinted = true; if (TLCGlobals.getRevision() == null) { MP.printMessage(EC.TLC_VERSION, TLCGlobals.versionOfTLC); } else { MP.printMessage(EC.TLC_VERSION, TLCGlobals.versionOfTLC + " (rev: " + TLCGlobals.getRevision() + ")"); } } } private void printStartupBanner(final int mode, final Map<String, String> parameters) { MP.printMessage(mode, parameters.values().toArray(new String[parameters.size()])); final Map<String, String> udc = new LinkedHashMap<>(); // First indicate the version (to make parsing forward compatible) udc.put("ver", TLCGlobals.getRevisionOrDev()); // Simulation, DFS or BFS mode. udc.put("mode", mode2String(mode)); parameters.remove("plural"); // damn hack! // "pid", "seed", and "fpidx" have no relevance for us. parameters.remove("jvmPid"); parameters.remove("fpidx"); parameters.remove("seed"); udc.putAll(parameters); // True if TLC is run from within the Toolbox. Derive ide name from .tool too // unless set explicitly. Eventually, we can probably remove the toolbox // parameter. udc.put("toolbox", Boolean.toString(TLCGlobals.tool)); udc.put("ide", System.getProperty(TLC.class.getName() + ".ide", TLCGlobals.tool ? "toolbox" : "cli")); new ExecutionStatisticsCollector().collect(udc); } /** * Gets the parent directory of the TLA file. * @param tlaFilePath Path to a TLA file. * @return Path to the parent directory of the TLA file. */ private static Path getTlaFileParentDir(String tlaFilePath) { if (null == tlaFilePath) { return Paths.get("."); } try { Path tlaDirPath = Paths.get(tlaFilePath).getParent(); return null == tlaDirPath ? Paths.get(".") : tlaDirPath; } catch (InvalidPathException e) { return Paths.get("."); } } private static String mode2String(final int mode) { switch (mode) { case EC.TLC_MODE_MC: return "bfs"; case EC.TLC_MODE_MC_DFS: return "dfs"; case EC.TLC_MODE_SIMU: return "simulation"; default: return "unknown"; } } /** * */ private void printUsage() { final List<List<UsageGenerator.Argument>> commandVariants = new ArrayList<>(); final List<UsageGenerator.Argument> sharedArguments = new ArrayList<>(); // N.B. alphabetical ordering is not required by the UsageGenerator, but introduced here to more easily // find options when reading the code sharedArguments.add(new UsageGenerator.Argument("-checkpoint", "minutes", "interval between check point; defaults to 30", true)); sharedArguments.add(new UsageGenerator.Argument("-cleanup", "clean up the states directory", true)); sharedArguments.add(new UsageGenerator.Argument("-config", "file", "provide the configuration file; defaults to SPEC.cfg", true)); sharedArguments.add(new UsageGenerator.Argument("-continue", "continue running even when an invariant is violated; default\n" + "behavior is to halt on first violation", true)); sharedArguments.add(new UsageGenerator.Argument("-coverage", "minutes", "interval between the collection of coverage information;\n" + "if not specified, no coverage will be collected", true)); sharedArguments.add(new UsageGenerator.Argument("-deadlock", "if specified DO NOT CHECK FOR DEADLOCK. Setting the flag is\n" + "the same as setting CHECK_DEADLOCK to FALSE in config\n" + "file. When -deadlock is specified, config entry is\n" + "ignored; default behavior is to check for deadlocks", true)); sharedArguments.add(new UsageGenerator.Argument("-postCondition", "mod!oper", "evaluate the given (constant-level) operator oper in the TLA+\n" + "module mod at the end of model-checking.", true)); sharedArguments.add(new UsageGenerator.Argument("-difftrace", "show only the differences between successive states when\n" + "printing trace information; defaults to printing\n" + "full state descriptions", true)); sharedArguments.add(new UsageGenerator.Argument("-dumpTrace", "format file", "in case of a property violation, formats the TLA+ error trace\n" + "as the given format and dumps the output to the specified\n" + "file. The file is relative to the same directory as the\n" + "main spec. At the time of writing, TLC supports the \"tla\"\n" + "and the \"json\" formats. To dump to multiple formats, the\n" + "-dumpTrace parameter may appear multiple times.\n" + "The git commits 1eb815620 and 386eaa19f show that adding new\n" + "formats is easy.\n", true)); sharedArguments.add(new UsageGenerator.Argument("-debug", "print various debugging information - not for production use\n", true)); sharedArguments.add(new UsageGenerator.Argument("-dump", "file", "dump all states into the specified file; this parameter takes\n" + "optional parameters for dot graph generation. Specifying\n" + "'dot' allows further options, comma delimited, of zero\n" + "or more of 'actionlabels', 'colorize', 'snapshot' to be\n" + "specified before the '.dot'-suffixed filename", true, "dot actionlabels,colorize,snapshot")); sharedArguments.add(new UsageGenerator.Argument("-fp", "N", "use the Nth irreducible polynomial from the list stored\n" + "in the class FP64", true)); sharedArguments.add(new UsageGenerator.Argument("-fpbits", "num", "the number of MSB used by MultiFPSet to create nested\n" + "FPSets; defaults to 1", true)); sharedArguments.add(new UsageGenerator.Argument("-fpmem", "num", "a value in (0.0,1.0) representing the ratio of total\n" + "physical memory to devote to storing the fingerprints\n" + "of found states; defaults to 0.25", true)); sharedArguments.add(new UsageGenerator.Argument("-noGenerateSpecTE", "Whether to skip generating a trace exploration (TE) spec in\n" + "the event of TLC finding a state or behavior that does\n" + "not satisfy the invariants; TLC's default behavior is to\n" + "generate this spec.", true)); sharedArguments.add(new UsageGenerator.Argument("-teSpecOutDir", "some-dir-name", "Directory to which to output the TE spec if TLC generates\n" + "an error trace. Can be a relative (to root spec dir)\n" + "or absolute path. By default the TE spec is output\n" + "to the same directory as the main spec.", true)); sharedArguments.add(new UsageGenerator.Argument("-gzip", "control if gzip is applied to value input/output streams;\n" + "defaults to 'off'", true)); sharedArguments.add(new UsageGenerator.Argument("-h", "display these help instructions", true)); sharedArguments.add(new UsageGenerator.Argument("-maxSetSize", "num", "the size of the largest set which TLC will enumerate; defaults\n" + "to 1000000 (10^6)", true)); sharedArguments.add(new UsageGenerator.Argument("-metadir", "path", "specify the directory in which to store metadata; defaults to\n" + "SPEC-directory/states if not specified", true)); sharedArguments.add(new UsageGenerator.Argument("-nowarning", "disable all warnings; defaults to reporting warnings", true)); sharedArguments.add(new UsageGenerator.Argument("-recover", "id", "recover from the checkpoint with the specified id", true)); sharedArguments.add(new UsageGenerator.Argument("-terse", "do not expand values in Print statements; defaults to\n" + "expanding values", true)); sharedArguments.add(new UsageGenerator.Argument("-tool", "run in 'tool' mode, surrounding output with message codes;\n" + "if '-generateSpecTE' is specified, this is enabled\n" + "automatically", true)); sharedArguments.add(new UsageGenerator.Argument("-userFile", "file", "an absolute path to a file in which to log user output (for\n" + "example, that which is produced by Print)", true)); sharedArguments.add(new UsageGenerator.Argument("-workers", "num", "the number of TLC worker threads; defaults to 1. Use 'auto'\n" + "to automatically select the number of threads based on the\n" + "number of available cores.", true)); sharedArguments.add(new UsageGenerator.Argument("-debugger", "nosuspend", "run simulation or model-checking in debug mode such that TLC's\n" + "state-space exploration can be temporarily halted and variables\n" + "be inspected. The only debug front-end so far is the TLA+\n" + "VSCode extension, which has to be downloaded and configured\n" + "separately, though other front-ends could be implemeted via the\n" + "debug-adapter-protocol.\n" + "Specifying the optional parameter 'nosuspend' causes\n" + "TLC to start state-space exploration without waiting for a\n" + "debugger front-end to connect. Without 'nosuspend', TLC\n" + "suspends state-space exploration before the first ASSUME is\n" + "evaluated (but after constants are processed). With 'nohalt',\n" + "TLC does not halt state-space exploration when an evaluation\n" + "or runtime error is caught. Without 'nohalt', evaluation or\n" + "runtime errors can be inspected in the debugger before TLC\n" + "terminates. The optional parameter 'port=1274' makes the\n" + "debugger listen on port 1274 instead of on the standard\n" + "port 4712, and 'port=0' lets the debugger choose a port.\n" + "Multiple optional parameters must be comma-separated.\n" + "Specifying '-debugger' implies '-workers 1'." + "", false, "nosuspend")); sharedArguments.add(new UsageGenerator.Argument("SPEC", null)); final List<UsageGenerator.Argument> modelCheckVariant = new ArrayList<>(sharedArguments); modelCheckVariant.add(new UsageGenerator.Argument("-dfid", "num", "run the model check in depth-first iterative deepening\n" + "starting with an initial depth of 'num'", true)); modelCheckVariant.add(new UsageGenerator.Argument("-view", "apply VIEW (if provided) when printing out states", true)); commandVariants.add(modelCheckVariant); final List<UsageGenerator.Argument> simulateVariant = new ArrayList<>(sharedArguments); simulateVariant.add(new UsageGenerator.Argument("-depth", "num", "specifies the depth of random simulation; defaults to 100", true)); simulateVariant.add(new UsageGenerator.Argument("-seed", "num", "provide the seed for random simulation; defaults to a\n" + "random long pulled from a pseudo-RNG", true)); simulateVariant.add(new UsageGenerator.Argument("-aril", "num", "adjust the seed for random simulation; defaults to 0", true)); simulateVariant.add(new UsageGenerator.Argument("-simulate", null, "run in simulation mode; optional parameters may be specified\n" + "comma delimited: 'num=X' where X is the maximum number of\n" + "total traces to generate and/or 'file=Y' where Y is the\n" + "absolute-pathed prefix for trace file modules to be written\n" + "by the simulation workers; for example Y='/a/b/c/tr' would\n" + "produce, e.g, '/a/b/c/tr_1_15'", false, "file=X,num=Y")); // implies workers 1 // bfs and simulation only (no iddfs) commandVariants.add(simulateVariant); final List<String> tips = new ArrayList<String>(); tips.add("When using the '-generateSpecTE' you can version the generated specification by doing:\n\t" + "./tla2tools.jar -generateSpecTE MySpec.tla && NAME=\"SpecTE-$(date +%s)\" && sed -e \"s/MODULE" + " SpecTE/MODULE $NAME/g\" SpecTE.tla > $NAME.tla"); tips.add("If, while checking a SpecTE created via '-generateSpecTE', you get an error message concerning\n" + "CONSTANT declaration and you've previous used 'integers' as model values, rename your\n" + "model values to start with a non-numeral and rerun the model check to generate a new SpecTE."); tips.add("If, while checking a SpecTE created via '-generateSpecTE', you get a warning concerning\n" + "duplicate operator definitions, this is likely due to the 'monolith' specification\n" + "creation. Try re-running TLC adding the 'nomonolith' option to the '-generateSpecTE'\n" + "parameter."); UsageGenerator.displayUsage(ToolIO.out, "TLC", TLCGlobals.versionOfTLC, "provides model checking and simulation of TLA+ specifications", Messages.getString("TLCDescription"), commandVariants, tips, ' '); } FPSetConfiguration getFPSetConfiguration() { return fpSetConfiguration; } public RunMode getRunMode() { return runMode; } public String getMainFile() { return mainFile; } public long getStartTime() { return startTime; } public String getModelName() { return System.getProperty(MailSender.MODEL_NAME, this.mainFile); } public String getSpecName() { return System.getProperty(MailSender.SPEC_NAME, this.mainFile); } }
tlatools/org.lamport.tlatools/src/tlc2/TLC.java
// Copyright (c) 2003 Compaq Corporation. All rights reserved. // Portions Copyright (c) 2003 Microsoft Corporation. All rights reserved. // Last modified on Thu 10 April 2008 at 14:31:23 PST by lamport // modified on Wed Dec 5 22:37:20 PST 2001 by yuanyu package tlc2; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; import model.InJarFilenameToStream; import model.ModelInJar; import tlc2.debug.TLCDebugger; import tlc2.output.EC; import tlc2.output.ErrorTraceMessagePrinterRecorder; import tlc2.output.MP; import tlc2.output.Messages; import tlc2.tool.DFIDModelChecker; import tlc2.tool.ITool; import tlc2.tool.ModelChecker; import tlc2.tool.Simulator; import tlc2.tool.SingleThreadedSimulator; import tlc2.tool.fp.FPSet; import tlc2.tool.fp.FPSetConfiguration; import tlc2.tool.fp.FPSetFactory; import tlc2.tool.impl.DebugTool; import tlc2.tool.impl.FastTool; import tlc2.tool.impl.ParameterizedSpecObj; import tlc2.tool.impl.ParameterizedSpecObj.PostCondition; import tlc2.tool.impl.Tool; import tlc2.tool.management.ModelCheckerMXWrapper; import tlc2.tool.management.TLCStandardMBean; import tlc2.util.DotStateWriter; import tlc2.util.FP64; import tlc2.util.IStateWriter; import tlc2.util.NoopStateWriter; import tlc2.util.RandomGenerator; import tlc2.util.StateWriter; import tlc2.value.RandomEnumerableValues; import util.Assert.TLCRuntimeException; import util.DebugPrinter; import util.ExecutionStatisticsCollector; import util.FileUtil; import util.FilenameToStream; import util.MailSender; import util.SimpleFilenameToStream; import util.TLAConstants; import util.TLCRuntime; import util.ToolIO; import util.UniqueString; import util.UsageGenerator; /** * Main TLC starter class. * * <b>Note:</b> If you are using a new instance of this class in an already existant JVM which has done processing with * tlc2 parsers, please see the class javadocs for {@link TLCRunner} * * @author Yuan Yu * @author Leslie Lamport * @author Simon Zambrovski */ public class TLC { /** * Whether the TLA+ spec is encoded in a .jar file, not a TLA+ text file. */ private static boolean MODEL_PART_OF_JAR = false; /** * Possible TLC run modes: either model checking or simulation. */ public enum RunMode { MODEL_CHECK, SIMULATE; } // SZ Feb 20, 2009: the class has been // transformed from static to dynamic /** * Whether to run in model checking or simulation mode. * Defaults to model checking. */ private RunMode runMode; /** * Whether to clean up the states directory. */ private boolean cleanup; /** * Whether to check for deadlock. */ private boolean deadlock; /** * Whether a seed for the random number generator was provided. */ private boolean noSeed; /** * The seed for the random number generator. */ private long seed; /** * Adjustment for random number generator seed. */ private long aril; /** * TLC processing start time. */ private long startTime; /** * Name of main TLA+ specification file. */ private String mainFile; private String configFile; private String metadir; /** * If instantiated with a non-Noop* instance, the trace will be written to the * user provided file (-dump parameter). * <p> * Contrary to plain -dump, -dot will also write out transitions from state s to * s' if s' is already known. Thus, the resulting graph shows all successors of * s instead of just s's unexplored ones. * <p> * Off (NoopStateWriter) by default. */ private IStateWriter stateWriter = new NoopStateWriter(); /** * Name of checkpoint from which TLC should recover. */ private String fromChkpt; /** * Fingerprint set function index to use. * By default one is picked at random. */ private int fpIndex; /** * The number of traces/behaviors to generate in simulation mode */ private static long traceNum = Long.MAX_VALUE; /** * Name of the file to which to write state traces. */ private String traceFile = null; private String traceActions = null; /** * Maximum state trace depth. Set to 100 by default. */ private int traceDepth; private FilenameToStream resolver; /** * Whether welcome message has already been printed. */ private boolean welcomePrinted; /** * Fingerprint set configuration. */ private FPSetConfiguration fpSetConfiguration; private final Map<String, Object> params; private int debugPort = -1; private boolean suspend = true; private boolean halt = true; /** * Interface to retrieve model properties. */ private volatile ITool tool; /** * Records errors as TLC runs. */ private final ErrorTraceMessagePrinterRecorder recorder = new ErrorTraceMessagePrinterRecorder(); /** * Trace exploration spec generator. */ private TraceExplorationSpec teSpec; /** * Initialization */ public TLC() { welcomePrinted = false; runMode = RunMode.MODEL_CHECK; cleanup = false; deadlock = true; noSeed = true; seed = 0; aril = 0; mainFile = null; configFile = null; fromChkpt = null; resolver = null; fpIndex = new Random().nextInt(FP64.Polys.length); traceDepth = 100; fpSetConfiguration = new FPSetConfiguration(); params = new HashMap<>(); } /* * This TLA checker (TLC) provides the following functionalities: * 1. Simulation of TLA+ specs: * java tlc2.TLC -simulate spec[.tla] * 2. Model checking of TLA+ specs: * java tlc2.TLC [-modelcheck] spec[.tla] * * The command line also provides the following options observed for functionalities 1. & 2.: * o -config file: provide the config file. * Defaults to spec.cfg if not provided * o -deadlock: do not check for deadlock. * Defaults to checking deadlock if not specified * o -depth num: specify the depth of random simulation * Defaults to 100 if not specified * o -seed num: provide the seed for random simulation * Defaults to a random seed if not specified * o -aril num: Adjust the seed for random simulation * Defaults to 0 if not specified * o -recover path: recover from the checkpoint at path * Defaults to scratch run if not specified * o -metadir path: store metadata in the directory at path * Defaults to specdir/states if not specified * o -userFile file: A full qualified/absolute path to a file to log user * output (Print/PrintT/...) to * o -workers num: the number of TLC worker threads * Defaults to 1 * o -dfid num: use depth-first iterative deepening with initial depth num * o -cleanup: clean up the states directory * o -dumpTrace format file: dump all counter-examples into file in the given format. * o -dump [dot] file: dump all the states into file. If "dot" as sub-parameter * is given, the output will be in dot notation. * o -postCondition mod!op: Evaluate the operator op in module mod after state-space exploration. * o -difftrace: when printing trace, show only * the differences between successive states * Defaults to printing full state descriptions if not specified * (Added by Rajeev Joshi) * o -terse: do not expand values in Print statement * Defaults to expand value if not specified * o -coverage minutes: collect coverage information on the spec, * print out the information every minutes. * Defaults to no coverage if not specified * o -continue: continue running even when invariant is violated * Defaults to stop at the first violation if not specified * o -lncheck: Check liveness properties at different times * of model checking. * Defaults to false increasing the overall model checking time. * o -nowarning: disable all the warnings * Defaults to report warnings if not specified * o -fp num: use the num'th irreducible polynomial from the list * stored in the class FP64. * o -view: apply VIEW (if provided) when printing out states. * o -gzip: control if gzip is applied to value input/output stream. * Defaults to off if not specified * o -debug: debbuging information (non-production use) * o -debugger: Activate TLC debugger * o -tool: tool mode (put output codes on console) * o -generateSpecTE: will generate SpecTE assets if error-states are * encountered during model checking; this will change * to tool mode regardless of whether '-tool' was * explicitly specified; add on 'nomonolith' to not * embed the dependencies in the SpecTE * o -checkpoint num: interval for check pointing (in minutes) * Defaults to 30 * o -fpmem num: a value between 0 and 1, exclusive, representing the ratio * of total system memory used to store the fingerprints of * found states. * Defaults to 1/4 physical memory. (Added 6 Apr 2010 by Yuan Yu.) * o -fpbits num: the number of msb used by MultiFPSet to create nested FPSets. * Defaults to 1 * o -maxSetSize num: the size of the largest set TLC will enumerate. * Defaults to 1000000 * */ public static void main(String[] args) throws Exception { final TLC tlc = new TLC(); // Try to parse parameters. if (!tlc.handleParameters(args)) { // This is a tool failure. We must exit with a non-zero exit // code or else we will mislead system tools and scripts into // thinking everything went smoothly. // // FIXME: handleParameters should return an error object (or // null), where the error object contains an error message. // This makes handleParameters a function we can test. System.exit(1); } if (!tlc.checkEnvironment()) { System.exit(1); } final MailSender ms = new MailSender(); // Setup how spec files will be resolved in the filesystem. if (MODEL_PART_OF_JAR) { // There was not spec file given, it instead exists in the // .jar file being executed. So we need to use a special file // resolver to parse it. tlc.setResolver(new InJarFilenameToStream(ModelInJar.PATH)); } else { // The user passed us a spec file directly. To ensure we can // recover it during semantic parsing, we must include its // parent directory as a library path in the file resolver. // // If the spec file has no parent directory, use the "standard" // library paths provided by SimpleFilenameToStream. final String dir = FileUtil.parseDirname(tlc.getMainFile()); if (!dir.isEmpty()) { tlc.setResolver(new SimpleFilenameToStream(dir)); } else { tlc.setResolver(new SimpleFilenameToStream()); } } // Setup MailSender *before* calling tlc.process. The MailSender's task it to // write the MC.out file. The MC.out file is e.g. used by CloudTLC to feed // progress back to the Toolbox (see CloudDistributedTLCJob). ms.setModelName(tlc.getModelName()); ms.setSpecName(tlc.getSpecName()); // Execute TLC. final int errorCode = tlc.process(); // Send logged output by email. // // This is needed when TLC runs on another host and email is // the only means for the user to get access to the model // checking results. boolean mailSent = ms.send(tlc.getModuleFiles()); // Treat failure to send mail as a tool failure. // // With distributed TLC and CloudDistributedTLCJob in particular, // the cloud node is immediately turned off once the TLC process // has finished. If we were to shutdown the node even when sending // out the email has failed, the result would be lost. if (!mailSent) { System.exit(1); } // Be explicit about tool success. System.exit(EC.ExitStatus.errorConstantToExitStatus(errorCode)); } // false if the environment (JVM, OS, ...) makes model checking impossible. // Might also result in warnings. private boolean checkEnvironment() { // Not a reasons to refuse startup but warn about non-ideal garbage collector. // See https://twitter.com/lemmster/status/1089656514892070912 for actual // performance penalty. if (!TLCRuntime.getInstance().isThroughputOptimizedGC()) { MP.printWarning(EC.TLC_ENVIRONMENT_JVM_GC); } return true; } public static void setTraceNum(long aTraceNum) { traceNum = aTraceNum; } /** * This method handles parameter arguments and prepares the actual call * <strong>Note:</strong> This method set ups the static TLCGlobals variables * @return status of parsing: true iff parameter check was ok, false otherwise * @throws IOException */ // SZ Feb 23, 2009: added return status to indicate the error in parsing @SuppressWarnings("deprecation") // we're emitting a warning to the user, but still accepting fpmem values > 1 public boolean handleParameters(String[] args) { String dumpFile = null; boolean asDot = false; boolean colorize = false; boolean actionLabels = false; boolean snapshot = false; boolean generateTESpec = true; boolean forceGenerateTESpec = false; Path teSpecOut = null; // SZ Feb 20, 2009: extracted this method to separate the // parameter handling from the actual processing int index = 0; while (index < args.length) { if (args[index].equals("-simulate") || args[index].equals("-generate")) { if (args[index].equals("-generate")) { System.setProperty(Tool.class.getName() + ".probabilistic", Boolean.TRUE.toString()); } runMode = RunMode.SIMULATE; index++; // Simulation args can be: // file=/path/to/file,num=4711 or num=4711,file=/path/to/file or num=4711 or // file=/path/to/file // "file=..." and "num=..." are only relevant for simulation which is why they // are args to "-simulate". if ((index < args.length) && (args[index].contains("stats=") || args[index].contains("file=") || args[index].contains("num="))) { final String[] simArgs = args[index].split(","); index++; // consume simulate args for (String arg : simArgs) { if (arg.startsWith("num=")) { traceNum = Long.parseLong(arg.replace("num=", "")); } else if (arg.startsWith("file=")) { traceFile = arg.replace("file=", ""); } else if (arg.equals("stats=basic")) { traceActions = "BASIC"; } else if (arg.equals("stats=full")) { traceActions = "FULL"; } } } } else if (args[index].equals("-modelcheck")) { index++; } else if (args[index].equals("-difftrace")) { index++; TLCGlobals.printDiffsOnly = true; } else if (args[index].equals("-deadlock")) { index++; deadlock = false; } else if (args[index].equals("-cleanup")) { index++; cleanup = true; } else if (args[index].equals("-nowarning")) { index++; TLCGlobals.warn = false; } else if (args[index].equals("-gzip")) { index++; TLCGlobals.useGZIP = true; } else if (args[index].equals("-terse")) { index++; TLCGlobals.expand = false; } else if (args[index].equals("-continue")) { index++; TLCGlobals.continuation = true; } else if (args[index].equals("-view")) { index++; TLCGlobals.useView = true; } else if (args[index].equals("-debug")) { index++; TLCGlobals.debug = true; } else if (args[index].equals("-debugger")) { index++; debugPort = 4712; //standard port. if ((index < args.length) && (args[index].contains("port=") || args[index].contains("nosuspend") || args[index].contains("nohalt"))) { suspend = !args[index].toLowerCase().contains("nosuspend"); halt = !args[index].toLowerCase().contains("nohalt"); final Matcher matcher = Pattern.compile(".*port=([0-9]{1,5}).*").matcher(args[index]); if (matcher.find()) { debugPort = Integer.parseInt(matcher.group(1)); } index++; } } else if (args[index].equals("-tool")) { index++; TLCGlobals.tool = true; } else if (args[index].equals("-generateSpecTE")) { index++; forceGenerateTESpec = true; if ((index < args.length) && args[index].equals("nomonolith")) { index++; } } else if (args[index].equals("-noGenerateSpecTE") || args[index].equalsIgnoreCase("-noTE")) { index++; generateTESpec = false; } else if (args[index].equals("-teSpecOutDir")) { index++; if (index < args.length) { String path = args[index]; try { teSpecOut = Paths.get(path); } catch (InvalidPathException e) { printErrorMsg("Error: invalid path for -teSpecOutDir option: " + path); return false; } index++; } else { printErrorMsg("Error: expected a path for -teSpecOutDir option."); return false; } } else if (args[index].equals("-help") || args[index].equals("-h")) { // See note referring to "-help" in MP#getMessage0 for EC.WRONG_COMMANDLINE_PARAMS_TLC. printUsage(); return false; } else if (args[index].equals("-lncheck")) { index++; if (index < args.length) { TLCGlobals.lnCheck = args[index].toLowerCase(); index++; } else { printErrorMsg("Error: expect a strategy such as final for -lncheck option."); return false; } } else if (args[index].equals("-config")) { index++; if (index < args.length) { configFile = args[index]; if (configFile.endsWith(TLAConstants.Files.CONFIG_EXTENSION)) { configFile = configFile.substring(0, (configFile.length() - TLAConstants.Files.CONFIG_EXTENSION.length())); } index++; } else { printErrorMsg("Error: expect a file name for -config option."); return false; } } else if (args[index].equals("-dump")) { index++; // consume "-dump". if (((index + 1) < args.length) && args[index].startsWith("dot")) { final String dotArgs = args[index].toLowerCase(); index++; // consume "dot...". asDot = true; colorize = dotArgs.contains("colorize"); actionLabels = dotArgs.contains("actionlabels"); snapshot = dotArgs.contains("snapshot"); dumpFile = getDumpFile(args[index++], ".dot"); } else if (index < args.length) { dumpFile = getDumpFile(args[index++], ".dump"); } else { printErrorMsg("Error: A file name for dumping states required."); return false; } } else if (args[index].equalsIgnoreCase("-dumpTrace")) { index++; // consume "-dumpTrace". if ((index + 1) < args.length) { final String fmt = args[index++]; if ("json".equalsIgnoreCase(fmt)) { @SuppressWarnings("unchecked") final List<PostCondition> pcs = (List<PostCondition>) params.computeIfAbsent( ParameterizedSpecObj.POST_CONDITIONS, k -> new ArrayList<PostCondition>()); pcs.add(new PostCondition("_JsonTrace", "_JsonTrace", "_JsonTraceFile", args[index++])); } else if ("tla".equalsIgnoreCase(fmt)) { @SuppressWarnings("unchecked") final List<PostCondition> pcs = (List<PostCondition>) params.computeIfAbsent( ParameterizedSpecObj.POST_CONDITIONS, k -> new ArrayList<PostCondition>()); pcs.add(new PostCondition("_TLAPlusCounterExample", "_TLAPlusCounterExample", "_TLAPlusCounterExampleFile", args[index++])); } else if ("Tomorrow's most favorite format".equalsIgnoreCase(fmt)) { //Add your new dumpTrace formats here! } else { printErrorMsg("Error: Unknown format " + fmt + " given to -dumpTrace."); return false; } } else { printErrorMsg("Error: A format and a file name for dumping traces required."); return false; } } else if (args[index].equalsIgnoreCase("-postCondition")) { index++; // consume "-postCondition". if (index < args.length) { @SuppressWarnings("unchecked") final List<PostCondition> pcs = (List<PostCondition>) params .computeIfAbsent(ParameterizedSpecObj.POST_CONDITIONS, k -> new ArrayList<PostCondition>()); // TODO: Add input validation! pcs.add(new PostCondition(args[index++])); } else { printErrorMsg("Error: Module!Operator for postCondition required."); return false; } } else if (args[index].equals("-coverage")) { index++; if (index < args.length) { try { TLCGlobals.coverageInterval = Integer.parseInt(args[index]) * 60 * 1000; if (TLCGlobals.coverageInterval < 0) { printErrorMsg("Error: expect a nonnegative integer for -coverage option."); return false; } index++; } catch (NumberFormatException e) { printErrorMsg("Error: An integer for coverage report interval required." + " But encountered " + args[index]); return false; } } else { printErrorMsg("Error: coverage report interval required."); return false; } } else if (args[index].equals("-checkpoint")) { index++; if (index < args.length) { try { TLCGlobals.chkptDuration = Integer.parseInt(args[index]) * 1000 * 60; if (TLCGlobals.chkptDuration < 0) { printErrorMsg("Error: expect a nonnegative integer for -checkpoint option."); return false; } index++; } catch (Exception e) { printErrorMsg("Error: An integer for checkpoint interval is required. But encountered " + args[index]); return false; } } else { printErrorMsg("Error: checkpoint interval required."); return false; } } else if (args[index].equals("-depth")) { index++; if (index < args.length) { try { traceDepth = Integer.parseInt(args[index]); index++; } catch (Exception e) { printErrorMsg("Error: An integer for trace length required. But encountered " + args[index]); return false; } } else { printErrorMsg("Error: trace length required."); return false; } } else if (args[index].equals("-seed")) { index++; if (index < args.length) { try { seed = Long.parseLong(args[index]); index++; noSeed = false; } catch (Exception e) { printErrorMsg("Error: An integer for seed required. But encountered " + args[index]); return false; } } else { printErrorMsg("Error: seed required."); return false; } } else if (args[index].equals("-aril")) { index++; if (index < args.length) { try { aril = Long.parseLong(args[index]); index++; } catch (Exception e) { printErrorMsg("Error: An integer for aril required. But encountered " + args[index]); return false; } } else { printErrorMsg("Error: aril required."); return false; } } else if (args[index].equals("-maxSetSize")) { index++; if (index < args.length) { try { int bound = Integer.parseInt(args[index]); // make sure it's in valid range if (!TLCGlobals.isValidSetSize(bound)) { int maxValue = Integer.MAX_VALUE; printErrorMsg("Error: Value in interval [0, " + maxValue + "] for maxSetSize required. But encountered " + args[index]); return false; } TLCGlobals.setBound = bound; index++; } catch (Exception e) { printErrorMsg("Error: An integer for maxSetSize required. But encountered " + args[index]); return false; } } else { printErrorMsg("Error: maxSetSize required."); return false; } } else if (args[index].equals("-recover")) { index++; if (index < args.length) { fromChkpt = args[index++] + FileUtil.separator; } else { printErrorMsg("Error: need to specify the metadata directory for recovery."); return false; } } else if (args[index].equals("-metadir")) { index++; if (index < args.length) { TLCGlobals.metaDir = args[index++] + FileUtil.separator; } else { printErrorMsg("Error: need to specify the metadata directory."); return false; } } else if (args[index].equals("-userFile")) { index++; if (index < args.length) { try { // Most problems will only show when TLC eventually tries // to write to the file. tlc2.module.TLC.OUTPUT = new BufferedWriter(new FileWriter(new File(args[index++]))); } catch (IOException e) { printErrorMsg("Error: Failed to create user output log file."); return false; } } else { printErrorMsg("Error: need to specify the full qualified file."); return false; } } else if (args[index].equals("-workers")) { index++; if (index < args.length) { try { int num = args[index].trim().toLowerCase().equals("auto") ? Runtime.getRuntime().availableProcessors() : Integer.parseInt(args[index]); if (num < 1) { printErrorMsg("Error: at least one worker required."); return false; } TLCGlobals.setNumWorkers(num); index++; } catch (Exception e) { printErrorMsg("Error: worker number or 'auto' required. But encountered " + args[index]); return false; } } else { printErrorMsg("Error: expect an integer or 'auto' for -workers option."); return false; } } else if (args[index].equals("-dfid")) { index++; if (index < args.length) { try { TLCGlobals.DFIDMax = Integer.parseInt(args[index]); if (TLCGlobals.DFIDMax < 0) { printErrorMsg("Error: expect a nonnegative integer for -dfid option."); return false; } index++; } catch (Exception e) { printErrorMsg("Error: expect a nonnegative integer for -dfid option. " + "But encountered " + args[index]); return false; } } else { printErrorMsg("Error: expect a nonnegative integer for -dfid option."); return false; } } else if (args[index].equals("-fp")) { index++; if (index < args.length) { try { fpIndex = Integer.parseInt(args[index]); if (fpIndex < 0 || fpIndex >= FP64.Polys.length) { printErrorMsg("Error: The number for -fp must be between 0 and " + (FP64.Polys.length - 1) + " (inclusive)."); return false; } index++; } catch (Exception e) { printErrorMsg("Error: A number for -fp is required. But encountered " + args[index]); return false; } } else { printErrorMsg("Error: expect an integer for -fp option."); return false; } } else if (args[index].equals("-fpmem")) { index++; if (index < args.length) { try { // -fpmem can be used in two ways: // a) to set the relative memory to be used for fingerprints (being machine independent) // b) to set the absolute memory to be used for fingerprints // // In order to set memory relatively, a value in the domain [0.0, 1.0] is interpreted as a fraction. // A value in the [2, Double.MaxValue] domain allocates memory absolutely. // // Independently of relative or absolute mem allocation, // a user cannot allocate more than JVM heap space // available. Conversely there is the lower hard limit TLC#MinFpMemSize. double fpMemSize = Double.parseDouble(args[index]); if (fpMemSize < 0) { printErrorMsg("Error: An positive integer or a fraction for fpset memory size/percentage required. But encountered " + args[index]); return false; } else if (fpMemSize > 1) { // For legacy reasons we allow users to set the // absolute amount of memory. If this is the case, // we know the user intends to allocate all 100% of // the absolute memory to the fpset. ToolIO.out .println("Using -fpmem with an abolute memory value has been deprecated. " + "Please allocate memory for the TLC process via the JVM mechanisms " + "and use -fpmem to set the fraction to be used for fingerprint storage."); fpSetConfiguration.setMemory((long) fpMemSize); fpSetConfiguration.setRatio(1.0d); } else { fpSetConfiguration.setRatio(fpMemSize); } index++; } catch (Exception e) { printErrorMsg("Error: An positive integer or a fraction for fpset memory size/percentage required. But encountered " + args[index]); return false; } } else { printErrorMsg("Error: fpset memory size required."); return false; } } else if (args[index].equals("-fpbits")) { index++; if (index < args.length) { try { int fpBits = Integer.parseInt(args[index]); // make sure it's in valid range if (!FPSet.isValid(fpBits)) { printErrorMsg("Error: Value in interval [0, 30] for fpbits required. But encountered " + args[index]); return false; } fpSetConfiguration.setFpBits(fpBits); index++; } catch (Exception e) { printErrorMsg("Error: An integer for fpbits required. But encountered " + args[index]); return false; } } else { printErrorMsg("Error: fpbits required."); return false; } } else { if (args[index].charAt(0) == '-') { printErrorMsg("Error: unrecognized option: " + args[index]); return false; } if (mainFile != null) { printErrorMsg("Error: more than one input files: " + mainFile + " and " + args[index]); return false; } mainFile = args[index++]; if (mainFile.endsWith(TLAConstants.Files.TLA_EXTENSION)) { mainFile = mainFile.substring(0, (mainFile.length() - TLAConstants.Files.TLA_EXTENSION.length())); } } } startTime = System.currentTimeMillis(); if (mainFile == null) { // command line omitted name of spec file, take this as an // indicator to check the in-jar model/ folder for a spec. // If a spec is found, use it instead. if (ModelInJar.hasModel()) { MODEL_PART_OF_JAR = true; ModelInJar.loadProperties(); TLCGlobals.tool = true; // always run in Tool mode (to parse output by Toolbox later) TLCGlobals.chkptDuration = 0; // never use checkpoints with distributed TLC (highly inefficient) mainFile = TLAConstants.Files.MODEL_CHECK_FILE_BASENAME; } else { printErrorMsg("Error: Missing input TLA+ module."); return false; } } generateTESpec = // Let -generateSpecTE force the generation of a trace spec even in e.g. -tool // mode. Eventually, we trace spec generation should even be the default with // -tool mode to make trace specs broadly available to VSCode TLA+ extension // users. However, the Eclipse Toolbox should not generate trace specs unless it // migrates from its (legacy) trace exploration to trace specs. forceGenerateTESpec || (generateTESpec // TODO Drop forceGen... and replace .tool with check of system property // tlc2.TLC.ide=toolbox to prevent trace spec generation when running from // Toolbox. && !TLCGlobals.tool && !TLCGlobals.continuation && !TraceExplorationSpec.isTESpecFile(mainFile)); if (generateTESpec) { if (teSpecOut == null) { this.teSpec = new TraceExplorationSpec(getTlaFileParentDir(mainFile), new Date(startTime), mainFile, this.recorder); } else { if (teSpecOut.toString().toLowerCase().endsWith(TLAConstants.Files.TLA_EXTENSION)) { this.teSpec = new TraceExplorationSpec(teSpecOut.getParent(), teSpecOut.getFileName().toFile() .getName().replaceFirst(TLAConstants.Files.TLA_EXTENSION + "$", ""), mainFile, this.recorder); } else { this.teSpec = new TraceExplorationSpec(teSpecOut, new Date(startTime), mainFile, this.recorder); } } } // The functionality to start TLC from an (absolute) path /path/to/spec/file.tla // seems to have eroded over the years which is why this block of code is a // clutch. It essentially massages the variable values for mainFile, specDir and // the user dir to make the code below - as well as the FilenameToStream // resolver - // work. Original issues was https://github.com/tlaplus/tlaplus/issues/24. final File f = new File(mainFile); String specDir = ""; if (f.isAbsolute()) { specDir = f.getParent() + FileUtil.separator; mainFile = f.getName(); // Not setting user dir causes a ConfigFileException when the resolver // tries to read the .cfg file later in the game. ToolIO.setUserDir(specDir); } if (configFile == null) { configFile = mainFile; } if (cleanup && (fromChkpt == null)) { // clean up the states directory only when not recovering FileUtil.deleteDir(TLCGlobals.metaRoot, true); } // Check if mainFile is an absolute or relative file system path. If it is // absolute, the parent gets used as TLC's meta directory (where it stores // states...). Otherwise, no meta dir is set causing states etc. to be stored in // the current directory. metadir = FileUtil.makeMetaDir(new Date(startTime), specDir, fromChkpt); if (dumpFile != null) { if (dumpFile.startsWith("${metadir}")) { // prefix dumpfile with the known value of this.metadir. There // is no way to determine the actual value of this.metadir // before TLC startup and thus it's impossible to make the // dumpfile end up in the metadir if desired. dumpFile = dumpFile.replace("${metadir}", metadir); } try { if (asDot) { this.stateWriter = new DotStateWriter(dumpFile, colorize, actionLabels, snapshot); } else { this.stateWriter = new StateWriter(dumpFile); } } catch (IOException e) { printErrorMsg(String.format("Error: Given file name %s for dumping states invalid.", dumpFile)); return false; } } if (TLCGlobals.debug) { final StringBuilder buffer = new StringBuilder("TLC arguments:"); for (int i = 0; i < args.length; i++) { buffer.append(args[i]); if (i < args.length - 1) { buffer.append(" "); } } buffer.append("\n"); DebugPrinter.print(buffer.toString()); } // if no errors, print welcome message printWelcome(); return true; } /** * Require a $suffix file extension unless already given. It is not clear why * this is enforced. */ private static String getDumpFile(String dumpFile, String suffix) { if (dumpFile.endsWith(suffix)) { return dumpFile; } return dumpFile + suffix; } /** * The processing method */ public int process() { MP.setRecorder(this.recorder); // UniqueString.initialize(); // a JMX wrapper that exposes runtime statistics TLCStandardMBean modelCheckerMXWrapper = TLCStandardMBean.getNullTLCStandardMBean(); // SZ Feb 20, 2009: extracted this method to separate the // parameter handling from the actual processing try { // Initialize: if (fromChkpt != null) { // We must recover the intern var table as early as possible UniqueString.internTbl.recover(fromChkpt); } FP64.Init(fpIndex); final RandomGenerator rng = new RandomGenerator(); // Start checking: final int result; if (RunMode.SIMULATE.equals(runMode)) { // random simulation if (noSeed) { seed = rng.nextLong(); rng.setSeed(seed); } else { rng.setSeed(seed, aril); } RandomEnumerableValues.setSeed(seed); printStartupBanner(EC.TLC_MODE_SIMU, getSimulationRuntime(seed)); Simulator simulator; if (debugPort >= 0) { assert TLCGlobals.getNumWorkers() == 1 : "TLCDebugger does not support running with multiple workers."; final TLCDebugger instance = TLCDebugger.Factory.getInstance(debugPort, suspend, halt); synchronized (instance) { tool = new DebugTool(mainFile, configFile, resolver, Tool.Mode.Simulation, params, instance); } simulator = new SingleThreadedSimulator(tool, metadir, traceFile, deadlock, traceDepth, traceNum, traceActions, rng, seed, resolver); } else { tool = new FastTool(mainFile, configFile, resolver, Tool.Mode.Simulation, params); simulator = new Simulator(tool, metadir, traceFile, deadlock, traceDepth, traceNum, traceActions, rng, seed, resolver, TLCGlobals.getNumWorkers()); } TLCGlobals.simulator = simulator; result = simulator.simulate(); } else { // RunMode.MODEL_CHECK if (noSeed) { seed = rng.nextLong(); } // Replace seed with tlc2.util.FP64.Polys[fpIndex]? // + No need to print seed in startup-banner for BFS and DFS // - Only 131 different seeds // RandomEnumerableValues.setSeed(tlc2.util.FP64.Polys[fpIndex]); RandomEnumerableValues.setSeed(seed); // Print startup banner before SANY writes its output. printStartupBanner(isBFS() ? EC.TLC_MODE_MC : EC.TLC_MODE_MC_DFS, getModelCheckingRuntime(fpIndex, fpSetConfiguration)); // model checking if (debugPort >= 0) { assert TLCGlobals.getNumWorkers() == 1 : "TLCDebugger does not support running with multiple workers."; final TLCDebugger instance = TLCDebugger.Factory.getInstance(debugPort, suspend, halt); synchronized (instance) { tool = new DebugTool(mainFile, configFile, resolver, params, instance); } } else { tool = new FastTool(mainFile, configFile, resolver, params); } deadlock = deadlock && tool.getModelConfig().getCheckDeadlock(); if (isBFS()) { TLCGlobals.mainChecker = new ModelChecker(tool, metadir, stateWriter, deadlock, fromChkpt, FPSetFactory.getFPSetInitialized(fpSetConfiguration, metadir, new File(mainFile).getName()), startTime); modelCheckerMXWrapper = new ModelCheckerMXWrapper((ModelChecker) TLCGlobals.mainChecker, this); result = TLCGlobals.mainChecker.modelCheck(); } else { TLCGlobals.mainChecker = new DFIDModelChecker(tool, metadir, stateWriter, deadlock, fromChkpt, startTime); result = TLCGlobals.mainChecker.modelCheck(); } } return result; } catch (Throwable e) { if (e instanceof StackOverflowError) { System.gc(); return MP.printError(EC.SYSTEM_STACK_OVERFLOW, e); } else if (e instanceof OutOfMemoryError) { System.gc(); return MP.printError(EC.SYSTEM_OUT_OF_MEMORY, e); } else if (e instanceof TLCRuntimeException) { return MP.printTLCRuntimeException((TLCRuntimeException) e); } else if (e instanceof RuntimeException) { // SZ 29.07.2009 // printing the stack trace of the runtime exceptions return MP.printError(EC.GENERAL, e); // e.printStackTrace(); } else { return MP.printError(EC.GENERAL, e); } } finally { if (tlc2.module.TLC.OUTPUT != null) { try { tlc2.module.TLC.OUTPUT.flush(); tlc2.module.TLC.OUTPUT.close(); } catch (IOException e) { } } modelCheckerMXWrapper.unregister(); // In tool mode print runtime in milliseconds, in non-tool mode print human // readable runtime (days, hours, minutes, ...). final long runtime = System.currentTimeMillis() - startTime; MP.printMessage(EC.TLC_FINISHED, // If TLC runs without -tool output it might still be useful to // report overall runtime in a machine-readable format (milliseconds) // instead of in a human-readable one. TLCGlobals.tool || Boolean.getBoolean(TLC.class.getName() + ".asMilliSeconds") ? Long.toString(runtime) + "ms" : convertRuntimeToHumanReadable(runtime)); // Generate trace exploration spec if error occurred. if (teSpec != null) { teSpec.generate(this.tool); } MP.unsubscribeRecorder(this.recorder); MP.flush(); } } private static boolean isBFS() { return TLCGlobals.DFIDMax == -1; } public static Map<String, String> getSimulationRuntime(final long seed) { final Runtime runtime = Runtime.getRuntime(); final long heapMemory = runtime.maxMemory() / 1024L / 1024L; final TLCRuntime tlcRuntime = TLCRuntime.getInstance(); final long offHeapMemory = tlcRuntime.getNonHeapPhysicalMemory() / 1024L / 1024L; final long pid = tlcRuntime.pid(); final Map<String, String> result = new LinkedHashMap<>(); result.put("seed", String.valueOf(seed)); result.put("workers", String.valueOf(TLCGlobals.getNumWorkers())); result.put("plural", TLCGlobals.getNumWorkers() == 1 ? "" : "s"); result.put("cores", Integer.toString(runtime.availableProcessors())); result.put("osName", System.getProperty("os.name")); result.put("osVersion", System.getProperty("os.version")); result.put("osArch", System.getProperty("os.arch")); result.put("jvmVendor", System.getProperty("java.vendor")); result.put("jvmVersion", System.getProperty("java.version")); result.put("jvmArch", tlcRuntime.getArchitecture().name()); result.put("jvmHeapMem", Long.toString(heapMemory)); result.put("jvmOffHeapMem", Long.toString(offHeapMemory)); result.put("jvmPid", pid == -1 ? "" : String.valueOf(pid)); return result; } public static Map<String, String> getModelCheckingRuntime(final int fpIndex, final FPSetConfiguration fpSetConfig) { final Runtime runtime = Runtime.getRuntime(); final long heapMemory = runtime.maxMemory() / 1024L / 1024L; final TLCRuntime tlcRuntime = TLCRuntime.getInstance(); final long offHeapMemory = tlcRuntime.getNonHeapPhysicalMemory() / 1024L / 1024L; final long pid = tlcRuntime.pid(); // TODO Better to use Class#getSimpleName provided we would have access to the // Class instance instead of just its name. However, loading the class here is // overkill and might interfere if other parts of TLC pull off class-loading // tricks. final String fpSetClassSimpleName = fpSetConfig.getImplementation() .substring(fpSetConfig.getImplementation().lastIndexOf(".") + 1); final String stateQueueClassSimpleName = ModelChecker.getStateQueueName(); // fpSetClassSimpleName and stateQueueClassSimpleName ignored in DFS mode. final Map<String, String> result = new LinkedHashMap<>(); result.put("workers", String.valueOf(TLCGlobals.getNumWorkers())); result.put("plural", TLCGlobals.getNumWorkers() == 1 ? "" : "s"); result.put("cores", Integer.toString(runtime.availableProcessors())); result.put("osName", System.getProperty("os.name")); result.put("osVersion", System.getProperty("os.version")); result.put("osArch", System.getProperty("os.arch")); result.put("jvmVendor", System.getProperty("java.vendor")); result.put("jvmVersion", System.getProperty("java.version")); result.put("jvmArch", tlcRuntime.getArchitecture().name()); result.put("jvmHeapMem", Long.toString(heapMemory)); result.put("jvmOffHeapMem", Long.toString(offHeapMemory)); result.put("seed", Long.toString(RandomEnumerableValues.getSeed())); result.put("fpidx", Integer.toString(fpIndex)); result.put("jvmPid", pid == -1 ? "" : String.valueOf(pid)); result.put("fpset", fpSetClassSimpleName); result.put("queue", stateQueueClassSimpleName); return result; } /** * @return The given milliseconds runtime converted into human readable form * with SI unit and insignificant parts stripped (when runtime is * days, nobody cares for minutes or seconds). */ public static String convertRuntimeToHumanReadable(long runtime) { SimpleDateFormat df = null; if (runtime > (60 * 60 * 24 * 1000L)) { df = new SimpleDateFormat("D'd' HH'h'"); runtime -= 86400000L; } else if (runtime > (60 * 60 * 24 * 1000L)) { df = new SimpleDateFormat("D'd' HH'h'"); runtime -= 86400000L; } else if (runtime > (60 * 60 * 1000L)) { df = new SimpleDateFormat("HH'h' mm'min'"); } else if (runtime > (60 * 1000L)) { df = new SimpleDateFormat("mm'min' ss's'"); } else { df = new SimpleDateFormat("ss's'"); } df.setTimeZone(TimeZone.getTimeZone("UTC")); return df.format(runtime); } public List<File> getModuleFiles() { final List<File> result = new ArrayList<File>(); if (TLCGlobals.mainChecker instanceof ModelChecker) { final ModelChecker mc = (ModelChecker) TLCGlobals.mainChecker; result.addAll(mc.getModuleFiles(resolver)); if (ModelInJar.hasCfg()) { result.add(ModelInJar.getCfg()); } // It might be desirable to include tlc.jfr - a flight recording aka profiling // at the JVM level here. This doesn't work though as the recording get created // after the termination of the JVM. A recording can also be several hundred // MBs large. } return result; } /** * Sets resolver for the file names * @param resolver a resolver for the names, if <code>null</code> is used, * the standard resolver {@link SimpleFilenameToStream} is used */ public void setResolver(FilenameToStream resolver) { this.resolver = resolver; ToolIO.setDefaultResolver(resolver); } public FilenameToStream getResolver() { return this.resolver; } public void setStateWriter(IStateWriter sw) { this.stateWriter = sw; } /** * Print out an error message, with usage hint * @param msg, message to print * TODO remove this method and replace the calls */ private void printErrorMsg(String msg) { printWelcome(); MP.printError(EC.WRONG_COMMANDLINE_PARAMS_TLC, msg); } /** * Prints the welcome message once per instance */ private void printWelcome() { if (!this.welcomePrinted) { this.welcomePrinted = true; if (TLCGlobals.getRevision() == null) { MP.printMessage(EC.TLC_VERSION, TLCGlobals.versionOfTLC); } else { MP.printMessage(EC.TLC_VERSION, TLCGlobals.versionOfTLC + " (rev: " + TLCGlobals.getRevision() + ")"); } } } private void printStartupBanner(final int mode, final Map<String, String> parameters) { MP.printMessage(mode, parameters.values().toArray(new String[parameters.size()])); final Map<String, String> udc = new LinkedHashMap<>(); // First indicate the version (to make parsing forward compatible) udc.put("ver", TLCGlobals.getRevisionOrDev()); // Simulation, DFS or BFS mode. udc.put("mode", mode2String(mode)); parameters.remove("plural"); // damn hack! // "pid", "seed", and "fpidx" have no relevance for us. parameters.remove("jvmPid"); parameters.remove("fpidx"); parameters.remove("seed"); udc.putAll(parameters); // True if TLC is run from within the Toolbox. Derive ide name from .tool too // unless set explicitly. Eventually, we can probably remove the toolbox // parameter. udc.put("toolbox", Boolean.toString(TLCGlobals.tool)); udc.put("ide", System.getProperty(TLC.class.getName() + ".ide", TLCGlobals.tool ? "toolbox" : "cli")); new ExecutionStatisticsCollector().collect(udc); } /** * Gets the parent directory of the TLA file. * @param tlaFilePath Path to a TLA file. * @return Path to the parent directory of the TLA file. */ private static Path getTlaFileParentDir(String tlaFilePath) { if (null == tlaFilePath) { return Paths.get("."); } try { Path tlaDirPath = Paths.get(tlaFilePath).getParent(); return null == tlaDirPath ? Paths.get(".") : tlaDirPath; } catch (InvalidPathException e) { return Paths.get("."); } } private static String mode2String(final int mode) { switch (mode) { case EC.TLC_MODE_MC: return "bfs"; case EC.TLC_MODE_MC_DFS: return "dfs"; case EC.TLC_MODE_SIMU: return "simulation"; default: return "unknown"; } } /** * */ private void printUsage() { final List<List<UsageGenerator.Argument>> commandVariants = new ArrayList<>(); final List<UsageGenerator.Argument> sharedArguments = new ArrayList<>(); // N.B. alphabetical ordering is not required by the UsageGenerator, but introduced here to more easily // find options when reading the code sharedArguments.add(new UsageGenerator.Argument("-checkpoint", "minutes", "interval between check point; defaults to 30", true)); sharedArguments.add(new UsageGenerator.Argument("-cleanup", "clean up the states directory", true)); sharedArguments.add(new UsageGenerator.Argument("-config", "file", "provide the configuration file; defaults to SPEC.cfg", true)); sharedArguments.add(new UsageGenerator.Argument("-continue", "continue running even when an invariant is violated; default\n" + "behavior is to halt on first violation", true)); sharedArguments.add(new UsageGenerator.Argument("-coverage", "minutes", "interval between the collection of coverage information;\n" + "if not specified, no coverage will be collected", true)); sharedArguments.add(new UsageGenerator.Argument("-deadlock", "if specified DO NOT CHECK FOR DEADLOCK. Setting the flag is\n" + "the same as setting CHECK_DEADLOCK to FALSE in config\n" + "file. When -deadlock is specified, config entry is\n" + "ignored; default behavior is to check for deadlocks", true)); sharedArguments.add(new UsageGenerator.Argument("-postCondition", "mod!oper", "evaluate the given (constant-level) operator oper in the TLA+\n" + "module mod at the end of model-checking.", true)); sharedArguments.add(new UsageGenerator.Argument("-difftrace", "show only the differences between successive states when\n" + "printing trace information; defaults to printing\n" + "full state descriptions", true)); sharedArguments.add(new UsageGenerator.Argument("-dumpTrace", "format file", "in case of a property violation, formats the TLA+ error trace\n" + "as the given format and dumps the output to the specified\n" + "file. The file is relative to the same directory as the\n" + "main spec. At the time of writing, TLC supports the \"tla\"\n" + "and the \"json\" formats. To dump to multiple formats, the\n" + "-dumpTrace parameter may appear multiple times.\n" + "The git commits 1eb815620 and 386eaa19f show that adding new\n" + "formats is easy.\n", true)); sharedArguments.add(new UsageGenerator.Argument("-debug", "print various debugging information - not for production use\n", true)); sharedArguments.add(new UsageGenerator.Argument("-dump", "file", "dump all states into the specified file; this parameter takes\n" + "optional parameters for dot graph generation. Specifying\n" + "'dot' allows further options, comma delimited, of zero\n" + "or more of 'actionlabels', 'colorize', 'snapshot' to be\n" + "specified before the '.dot'-suffixed filename", true, "dot actionlabels,colorize,snapshot")); sharedArguments.add(new UsageGenerator.Argument("-fp", "N", "use the Nth irreducible polynomial from the list stored\n" + "in the class FP64", true)); sharedArguments.add(new UsageGenerator.Argument("-fpbits", "num", "the number of MSB used by MultiFPSet to create nested\n" + "FPSets; defaults to 1", true)); sharedArguments.add(new UsageGenerator.Argument("-fpmem", "num", "a value in (0.0,1.0) representing the ratio of total\n" + "physical memory to devote to storing the fingerprints\n" + "of found states; defaults to 0.25", true)); sharedArguments.add(new UsageGenerator.Argument("-noGenerateSpecTE", "Whether to skip generating a trace exploration (TE) spec in\n" + "the event of TLC finding a state or behavior that does\n" + "not satisfy the invariants; TLC's default behavior is to\n" + "generate this spec.", true)); sharedArguments.add(new UsageGenerator.Argument("-teSpecOutDir", "some-dir-name", "Directory to which to output the TE spec if TLC generates\n" + "an error trace. Can be a relative (to root spec dir)\n" + "or absolute path. By default the TE spec is output\n" + "to the same directory as the main spec.", true)); sharedArguments.add(new UsageGenerator.Argument("-gzip", "control if gzip is applied to value input/output streams;\n" + "defaults to 'off'", true)); sharedArguments.add(new UsageGenerator.Argument("-h", "display these help instructions", true)); sharedArguments.add(new UsageGenerator.Argument("-maxSetSize", "num", "the size of the largest set which TLC will enumerate; defaults\n" + "to 1000000 (10^6)", true)); sharedArguments.add(new UsageGenerator.Argument("-metadir", "path", "specify the directory in which to store metadata; defaults to\n" + "SPEC-directory/states if not specified", true)); sharedArguments.add(new UsageGenerator.Argument("-nowarning", "disable all warnings; defaults to reporting warnings", true)); sharedArguments.add(new UsageGenerator.Argument("-recover", "id", "recover from the checkpoint with the specified id", true)); sharedArguments.add(new UsageGenerator.Argument("-terse", "do not expand values in Print statements; defaults to\n" + "expanding values", true)); sharedArguments.add(new UsageGenerator.Argument("-tool", "run in 'tool' mode, surrounding output with message codes;\n" + "if '-generateSpecTE' is specified, this is enabled\n" + "automatically", true)); sharedArguments.add(new UsageGenerator.Argument("-userFile", "file", "an absolute path to a file in which to log user output (for\n" + "example, that which is produced by Print)", true)); sharedArguments.add(new UsageGenerator.Argument("-workers", "num", "the number of TLC worker threads; defaults to 1. Use 'auto'\n" + "to automatically select the number of threads based on the\n" + "number of available cores.", true)); sharedArguments.add(new UsageGenerator.Argument("-debugger", "nosuspend", "run simulation or model-checking in debug mode such that TLC's\n" + "state-space exploration can be temporarily halted and variables\n" + "be inspected. The only debug front-end so far is the TLA+\n" + "VSCode extension, which has to be downloaded and configured\n" + "separately, though other front-ends could be implemeted via the\n" + "debug-adapter-protocol.\n" + "Specifying the optional parameter 'nosuspend' causes\n" + "TLC to start state-space exploration without waiting for a\n" + "debugger front-end to connect. Without 'nosuspend', TLC\n" + "suspends state-space exploration before the first ASSUME is\n" + "evaluated (but after constants are processed). With 'nohalt',\n" + "TLC does not halt state-space exploration when an evaluation\n" + "or runtime error is caught. Without 'nohalt', evaluation or\n" + "runtime errors can be inspected in the debugger before TLC\n" + "terminates. The optional parameter 'port=1274' makes the\n" + "debugger listen on port 1274 instead of on the standard\n" + "port 4712, and 'port=0' lets the debugger choose a port.\n" + "Multiple optional parameters must be comma-separated.\n" + "Specifying '-debugger' implies '-workers 1'." + "", false, "nosuspend")); sharedArguments.add(new UsageGenerator.Argument("SPEC", null)); final List<UsageGenerator.Argument> modelCheckVariant = new ArrayList<>(sharedArguments); modelCheckVariant.add(new UsageGenerator.Argument("-dfid", "num", "run the model check in depth-first iterative deepening\n" + "starting with an initial depth of 'num'", true)); modelCheckVariant.add(new UsageGenerator.Argument("-view", "apply VIEW (if provided) when printing out states", true)); commandVariants.add(modelCheckVariant); final List<UsageGenerator.Argument> simulateVariant = new ArrayList<>(sharedArguments); simulateVariant.add(new UsageGenerator.Argument("-depth", "num", "specifies the depth of random simulation; defaults to 100", true)); simulateVariant.add(new UsageGenerator.Argument("-seed", "num", "provide the seed for random simulation; defaults to a\n" + "random long pulled from a pseudo-RNG", true)); simulateVariant.add(new UsageGenerator.Argument("-aril", "num", "adjust the seed for random simulation; defaults to 0", true)); simulateVariant.add(new UsageGenerator.Argument("-simulate", null, "run in simulation mode; optional parameters may be specified\n" + "comma delimited: 'num=X' where X is the maximum number of\n" + "total traces to generate and/or 'file=Y' where Y is the\n" + "absolute-pathed prefix for trace file modules to be written\n" + "by the simulation workers; for example Y='/a/b/c/tr' would\n" + "produce, e.g, '/a/b/c/tr_1_15'", false, "file=X,num=Y")); // implies workers 1 // bfs and simulation only (no iddfs) commandVariants.add(simulateVariant); final List<String> tips = new ArrayList<String>(); tips.add("When using the '-generateSpecTE' you can version the generated specification by doing:\n\t" + "./tla2tools.jar -generateSpecTE MySpec.tla && NAME=\"SpecTE-$(date +%s)\" && sed -e \"s/MODULE" + " SpecTE/MODULE $NAME/g\" SpecTE.tla > $NAME.tla"); tips.add("If, while checking a SpecTE created via '-generateSpecTE', you get an error message concerning\n" + "CONSTANT declaration and you've previous used 'integers' as model values, rename your\n" + "model values to start with a non-numeral and rerun the model check to generate a new SpecTE."); tips.add("If, while checking a SpecTE created via '-generateSpecTE', you get a warning concerning\n" + "duplicate operator definitions, this is likely due to the 'monolith' specification\n" + "creation. Try re-running TLC adding the 'nomonolith' option to the '-generateSpecTE'\n" + "parameter."); UsageGenerator.displayUsage(ToolIO.out, "TLC", TLCGlobals.versionOfTLC, "provides model checking and simulation of TLA+ specifications", Messages.getString("TLCDescription"), commandVariants, tips, ' '); } FPSetConfiguration getFPSetConfiguration() { return fpSetConfiguration; } public RunMode getRunMode() { return runMode; } public String getMainFile() { return mainFile; } public long getStartTime() { return startTime; } public String getModelName() { return System.getProperty(MailSender.MODEL_NAME, this.mainFile); } public String getSpecName() { return System.getProperty(MailSender.SPEC_NAME, this.mainFile); } }
Print error at startup when user combined the debugger with multiple workers. [Feature][TLC][Debugger]
tlatools/org.lamport.tlatools/src/tlc2/TLC.java
Print error at startup when user combined the debugger with multiple workers.
Java
mit
5ee51d2b3901fcd05aff20f208c31232832989dd
0
napstr/FredBoat,OrangeFlare/FredBoat-CreamyMemers,Disputes/FredBoat,Frederikam/FredBoat,Frederikam/FredBoat,Frederikam/FredBoat,OrangeFlare/FredBoat-CreamyMemers,Frederikam/FredBoat,napstr/FredBoat,Disputes/FredBoat
/* * MIT License * * Copyright (c) 2017 Frederik Ar. Mikkelsen * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package fredboat.feature; import fredboat.db.DatabaseManager; import fredboat.db.EntityReader; import fredboat.db.EntityWriter; import fredboat.db.entities.GuildConfig; import net.dv8tion.jda.core.entities.Guild; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; public class I18n { private static final Logger log = LoggerFactory.getLogger(I18n.class); public static FredBoatLocale DEFAULT = new FredBoatLocale(new Locale("en","US"), "en_US", "English"); public static final HashMap<String, FredBoatLocale> LANGS = new HashMap<>(); public static void start() { LANGS.put("en_US", DEFAULT); LANGS.put("bg_BG", new FredBoatLocale(new Locale("bg", "BG"), "bg_BG", "български език")); LANGS.put("zh_TW", new FredBoatLocale(new Locale("zh", "TW"), "zh_TW", "文言")); LANGS.put("cs_CZ", new FredBoatLocale(new Locale("cs", "CZ"), "cs_CZ", "Čeština")); LANGS.put("da_DK", new FredBoatLocale(new Locale("da", "DK"), "da_DK", "Dansk")); LANGS.put("nl_NL", new FredBoatLocale(new Locale("nl", "NL"), "nl_NL", "Nederlands")); LANGS.put("fr_FR", new FredBoatLocale(new Locale("fr", "FR"), "fr_FR", "Français")); LANGS.put("de_DE", new FredBoatLocale(new Locale("de", "DE"), "de_DE", "Deutsch")); LANGS.put("he_IL", new FredBoatLocale(new Locale("he", "IL"), "he_IL", "עברית")); LANGS.put("id_ID", new FredBoatLocale(new Locale("id", "ID"), "id_ID", "Bahasa Indonesia")); LANGS.put("it_IT", new FredBoatLocale(new Locale("it", "IT"), "it_IT", "Italiano")); LANGS.put("ko_KR", new FredBoatLocale(new Locale("ko", "KR"), "ko_KR", "한국어")); LANGS.put("pt_BR", new FredBoatLocale(new Locale("pt", "BR"), "pt_BR", "Português (Brazil)")); LANGS.put("pt_PT", new FredBoatLocale(new Locale("pt", "PT"), "pt_PT", "Português")); LANGS.put("ro_RO", new FredBoatLocale(new Locale("ro", "RO"), "ro_RO", "Română")); LANGS.put("ru_RU", new FredBoatLocale(new Locale("ru", "RU"), "ru_RU", "Русский")); LANGS.put("es_ES", new FredBoatLocale(new Locale("es", "ES"), "es_ES", "Español")); LANGS.put("tr_TR", new FredBoatLocale(new Locale("tr", "TR"), "tr_TR", "Türkçe")); LANGS.put("vi_VN", new FredBoatLocale(new Locale("vi", "VN"), "vi_VN", "Tiếng Việt")); LANGS.put("en_PT", new FredBoatLocale(new Locale("en", "PT"), "en_PT", "Pirate English")); LANGS.put("en_TS", new FredBoatLocale(new Locale("en", "TS"), "en_TS", "Tsundere English")); log.info("Loaded " + LANGS.size() + " languages: " + LANGS); } public static ResourceBundle get(Guild guild) { if(DatabaseManager.state != DatabaseManager.DatabaseState.READY){ return DEFAULT.getProps(); } GuildConfig config; try { config = EntityReader.getGuildConfig(guild.getId()); } catch (Exception e) { log.error("Error when reading entity", e); return DEFAULT.getProps(); } return LANGS.getOrDefault(config.getLang(), DEFAULT).getProps(); } public static FredBoatLocale getLocale(Guild guild) { if(DatabaseManager.state != DatabaseManager.DatabaseState.READY){ return DEFAULT; } GuildConfig config; try { config = EntityReader.getGuildConfig(guild.getId()); } catch (Exception e) { log.error("Errpr when reading entity", e); return DEFAULT; } return LANGS.getOrDefault(config.getLang(), DEFAULT); } public static void set(Guild guild, String lang) throws LanguageNotSupportedException { GuildConfig config = EntityReader.getGuildConfig(guild.getId()); if(!LANGS.containsKey(lang)) throw new LanguageNotSupportedException("Language not found"); config.setLang(lang); EntityWriter.mergeGuildConfig(config); } public static class FredBoatLocale { private final Locale locale; private final String code; private final ResourceBundle props; private final String nativeName; FredBoatLocale(Locale locale, String code, String nativeName) throws MissingResourceException { this.locale = locale; this.code = code; props = ResourceBundle.getBundle("lang." + code, locale); this.nativeName = nativeName; } public Locale getLocale() { return locale; } public String getCode() { return code; } public ResourceBundle getProps() { return props; } public String getNativeName() { return nativeName; } @Override public String toString() { return "[" + nativeName + '}'; } } public static class LanguageNotSupportedException extends Exception { public LanguageNotSupportedException(String message) { super(message); } } }
FredBoat/src/main/java/fredboat/feature/I18n.java
/* * MIT License * * Copyright (c) 2017 Frederik Ar. Mikkelsen * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package fredboat.feature; import fredboat.db.DatabaseManager; import fredboat.db.EntityReader; import fredboat.db.EntityWriter; import fredboat.db.entities.GuildConfig; import net.dv8tion.jda.core.entities.Guild; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; public class I18n { private static final Logger log = LoggerFactory.getLogger(I18n.class); public static FredBoatLocale DEFAULT = new FredBoatLocale(new Locale("en","US"), "en_US", "English"); public static final HashMap<String, FredBoatLocale> LANGS = new HashMap<>(); public static void start() { LANGS.put("en_US", DEFAULT); LANGS.put("da_DK", new FredBoatLocale(new Locale("da", "DK"), "da_DK", "Dansk")); LANGS.put("nl_NL", new FredBoatLocale(new Locale("nl", "NL"), "nl_NL", "Nederlands")); LANGS.put("fr_FR", new FredBoatLocale(new Locale("fr", "FR"), "fr_FR", "Français")); LANGS.put("de_DE", new FredBoatLocale(new Locale("de", "DE"), "de_DE", "Deutsch")); LANGS.put("id_ID", new FredBoatLocale(new Locale("id", "ID"), "id_ID", "Bahasa Indonesia")); LANGS.put("it_IT", new FredBoatLocale(new Locale("it", "IT"), "it_IT", "Italiano")); LANGS.put("pt_BR", new FredBoatLocale(new Locale("pt", "BR"), "pt_BR", "Português (Brazil)")); LANGS.put("pt_PT", new FredBoatLocale(new Locale("pt", "PT"), "pt_PT", "Português")); LANGS.put("ro_RO", new FredBoatLocale(new Locale("ro", "RO"), "ro_RO", "Română")); LANGS.put("ru_RU", new FredBoatLocale(new Locale("ru", "RU"), "ru_RU", "Русский")); LANGS.put("tr_TR", new FredBoatLocale(new Locale("tr", "TR"), "tr_TR", "Türkçe")); LANGS.put("en_TS", new FredBoatLocale(new Locale("en", "TS"), "en_TS", "Tsundere English")); log.info("Loaded " + LANGS.size() + " languages: " + LANGS); } public static ResourceBundle get(Guild guild) { if(DatabaseManager.state != DatabaseManager.DatabaseState.READY){ return DEFAULT.getProps(); } GuildConfig config; try { config = EntityReader.getGuildConfig(guild.getId()); } catch (Exception e) { log.error("Error when reading entity", e); return DEFAULT.getProps(); } return LANGS.getOrDefault(config.getLang(), DEFAULT).getProps(); } public static FredBoatLocale getLocale(Guild guild) { if(DatabaseManager.state != DatabaseManager.DatabaseState.READY){ return DEFAULT; } GuildConfig config; try { config = EntityReader.getGuildConfig(guild.getId()); } catch (Exception e) { log.error("Errpr when reading entity", e); return DEFAULT; } return LANGS.getOrDefault(config.getLang(), DEFAULT); } public static void set(Guild guild, String lang) throws LanguageNotSupportedException { GuildConfig config = EntityReader.getGuildConfig(guild.getId()); if(!LANGS.containsKey(lang)) throw new LanguageNotSupportedException("Language not found"); config.setLang(lang); EntityWriter.mergeGuildConfig(config); } public static class FredBoatLocale { private final Locale locale; private final String code; private final ResourceBundle props; private final String nativeName; FredBoatLocale(Locale locale, String code, String nativeName) throws MissingResourceException { this.locale = locale; this.code = code; props = ResourceBundle.getBundle("lang." + code, locale); this.nativeName = nativeName; } public Locale getLocale() { return locale; } public String getCode() { return code; } public ResourceBundle getProps() { return props; } public String getNativeName() { return nativeName; } @Override public String toString() { return "[" + nativeName + '}'; } } public static class LanguageNotSupportedException extends Exception { public LanguageNotSupportedException(String message) { super(message); } } }
Added български език, 文言, Čeština, עברית, 한국어, Español, Tiếng Việt, and Pirate English
FredBoat/src/main/java/fredboat/feature/I18n.java
Added български език, 文言, Čeština, עברית, 한국어, Español, Tiếng Việt, and Pirate English
Java
mit
0e2d22e7c118fcbe9e95e3e247d49fedd06f5745
0
groupon/DotCi,suryagaddipati/DotCi,TheJumpCloud/DotCi,groupon/DotCi,TheJumpCloud/DotCi,dimacus/DotCi,michaelstandley/DotCi,bschmeck/DotCi,jkrems/DotCi,jkrems/DotCi,bschmeck/DotCi,suryagaddipati/DotCi,erikdw/DotCi,michaelstandley/DotCi,michaelstandley/DotCi,groupon/DotCi,erikdw/DotCi,DotCi/DotCi,erikdw/DotCi,TheJumpCloud/DotCi,DotCi/DotCi,DotCi/DotCi,jkrems/DotCi,dimacus/DotCi,bschmeck/DotCi,suryagaddipati/DotCi,dimacus/DotCi
/* The MIT License (MIT) Copyright (c) 2014, Groupon, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.groupon.jenkins.dynamic.build; import com.google.common.base.Objects; import com.google.common.collect.Iterables; import com.groupon.jenkins.dynamic.build.cause.BuildCause; import com.groupon.jenkins.dynamic.build.execution.BuildEnvironment; import com.groupon.jenkins.dynamic.build.execution.BuildExecutionContext; import com.groupon.jenkins.dynamic.build.execution.BuildType; import com.groupon.jenkins.dynamic.build.execution.DotCiPluginRunner; import com.groupon.jenkins.dynamic.build.execution.DynamicBuildExection; import com.groupon.jenkins.dynamic.buildconfiguration.BuildConfiguration; import com.groupon.jenkins.dynamic.buildconfiguration.EffectiveBuildConfigurationCalculator; import com.groupon.jenkins.dynamic.buildconfiguration.InvalidDotCiYmlException; import com.groupon.jenkins.github.services.GithubRepositoryService; import hudson.EnvVars; import hudson.Functions; import hudson.matrix.Combination; import hudson.model.AbstractProject; import hudson.model.Build; import hudson.model.BuildListener; import hudson.model.Cause; import hudson.model.CauseAction; import hudson.model.Executor; import hudson.model.Result; import hudson.tasks.BuildStep; import hudson.util.HttpResponses; import hudson.util.VersionNumber; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; import jenkins.model.Jenkins; import org.kohsuke.stapler.HttpResponse; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.interceptor.RequirePOST; import javax.servlet.ServletException; public class DynamicBuild extends DbBackedBuild<DynamicProject, DynamicBuild> { private transient BuildConfiguration buildConfiguration; private transient DynamicBuildModel model; public DynamicBuild(DynamicProject project) throws IOException { super(project); this.model = new DynamicBuildModel(this); } public DynamicBuild(DynamicProject project, File buildDir) throws IOException { super(project, buildDir); this.model = new DynamicBuildModel(this); } @SuppressWarnings("unchecked") @Override public void run() { this.model.run(); execute(new DynamicRunExecution()); } public boolean isNewJenkins() { VersionNumber matrixBreakOutVersion = new VersionNumber("1.560"); return Jenkins.getVersion().isNewerThan(matrixBreakOutVersion); } public DynamicBuildLayouter getLayouter() { return DynamicBuildLayouter.get(this); } // This needs to be overriden here to override @RequirePOST annotation, // which seems like a bug in the version were are using. @Override public synchronized HttpResponse doStop() throws IOException, ServletException { return super.doStop(); } @Override public void restoreFromDb(AbstractProject project, Map<String, Object> input) { super.restoreFromDb(project, input); if (input.containsKey("build_configuration")) { String buildConfigYml = (String) input.get("build_configuration"); this.buildConfiguration = BuildConfiguration.restoreFromYaml(buildConfigYml); } this.model = new DynamicBuildModel(this); } @Override protected Map<String, Object> getBuildAttributesForDb() { Map<String, Object> buildAttributes = super.getBuildAttributesForDb(); if (isConfigurationCalculated()) { buildAttributes.put("build_configuration", buildConfiguration.toYaml()); } buildAttributes.put("main_build", true); return buildAttributes; } @Override @RequirePOST public void doDoDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { checkPermission(DELETE); model.deleteBuild(); rsp.sendRedirect2(req.getContextPath() + '/' + getParent().getUrl()); } @Override public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) { try { Build item = getRun(Combination.fromString(token)); if (item != null) { if (item.getNumber() == this.getNumber()) { return item; } else { // redirect the user to the correct URL String url = Functions.joinPath(item.getUrl(), req.getRestOfPath()); String qs = req.getQueryString(); if (qs != null) { url += '?' + qs; } throw HttpResponses.redirectViaContextPath(url); } } } catch (IllegalArgumentException e) { // failed to parse the token as Combination. Must be something else } return super.getDynamic(token, req, rsp); } @Override public Map<String, String> getDotCiEnvVars(EnvVars jenkinsEnvVars) { Map<String, String> vars = super.getDotCiEnvVars(jenkinsEnvVars); Map<String, String> dotCiEnvVars = model.getDotCiEnvVars(); vars.putAll(dotCiEnvVars); return vars; } protected class DynamicRunExecution extends BuildExecution implements BuildExecutionContext { public boolean executeShell(BuildStep buildStep, BuildListener listener) throws InterruptedException, IOException { return performStep(buildStep, listener); } @Override public boolean performStep(BuildStep execution, BuildListener listener) throws IOException, InterruptedException { return perform(execution, listener); } @Override public void setResult(Result r) { DynamicBuild.this.setResult(r); } @Override protected Result doRun(BuildListener listener) throws Exception, hudson.model.Run.RunnerAbortedException { try { DynamicBuild.this.setBuildConfiguration(calculateBuildConfiguration(listener)); BuildEnvironment buildEnvironment = new BuildEnvironment(DynamicBuild.this, launcher, listener); DotCiPluginRunner dotCiPluginRunner = new DotCiPluginRunner(DynamicBuild.this, launcher, getBuildConfiguration()); DynamicBuildExection dynamicBuildExecution = new DynamicBuildExection(DynamicBuild.this, buildEnvironment, this, dotCiPluginRunner, getBuildType()); Result buildRunResult = dynamicBuildExecution.doRun(listener); setResult(buildRunResult); return buildRunResult; } catch (InvalidDotCiYmlException invalidDotCiYmlException) { for (String error : invalidDotCiYmlException.getValidationErrors()) { listener.error(error); } return Result.FAILURE; } } public BuildType getBuildType() throws IOException { if (getBuildConfiguration().isDocker()) { return BuildType.DockerImage; } if (new GithubRepositoryService(getGithubRepoUrl()).hasDockerFile(getSha())) { return BuildType.DockerLocal; } return BuildType.BareMetal; } private BuildConfiguration calculateBuildConfiguration(BuildListener listener) throws IOException, InterruptedException, InvalidDotCiYmlException { return new EffectiveBuildConfigurationCalculator().calculateBuildConfiguration(getGithubRepoUrl(), getSha(), getEnvironment(listener)); } @Override public BuildConfiguration getBuildConfiguration() { return DynamicBuild.this.getBuildConfiguration(); } } @Override @Exported public Executor getExecutor() { return super.getExecutor() == null ? getOneOffExecutor() : super.getExecutor(); } private DynamicProject getConductor() { return this.getParent(); } public Iterable<DynamicSubProject> getRunSubProjects() { return getConductor().getSubProjects(model.getMainRunCombinations(getAxisList())); } public Iterable<Combination> getAxisList() { return DynamicBuildLayouter.calculateAxisList(this).list(); } public Iterable<DynamicSubProject> getAllSubProjects() { return Iterables.concat(getRunSubProjects(), getPostBuildSubProjects()); } public Iterable<DynamicSubProject> getPostBuildSubProjects() { Combination postBuildCombination = model.getPostBuildCombination(getAxisList()); return postBuildCombination == null ? new ArrayList<DynamicSubProject>() : getConductor().getSubProjects(Arrays.asList(postBuildCombination)); } public Build getRun(Combination combination) { for (DynamicSubProject subProject : getAllSubProjects()) { if (subProject.getCombination().equals(combination)) { return getRunForConfiguration(subProject); } } return null; } @Override public DynamicProject getParent() { return super.getParent(); } private DynamicSubBuild getRunForConfiguration(DynamicSubProject c) { DynamicSubBuild r = c.getBuildByNumber(getNumber()); return r != null ? r : null; } public BuildConfiguration getBuildConfiguration() { return buildConfiguration; } public void setBuildConfiguration(BuildConfiguration buildConfiguration) throws IOException { this.buildConfiguration = buildConfiguration; this.save(); // make sure it get saved into the db } @Override public boolean equals(Object other) { if (other instanceof DynamicBuild) { DbBackedBuild<DynamicProject, DynamicBuild> otherBuild = (DbBackedBuild<DynamicProject, DynamicBuild>) other; if (otherBuild.getName().equals(this.getName()) && otherBuild.getNumber() == this.getNumber()) { return true; } } return false; } @Override public int hashCode() { return Objects.hashCode(getName(), getNumber()); } @Override public String getSha() { return this.getCause() == null ? "" : getCause().getSha(); } public boolean isConfigurationCalculated() { return buildConfiguration != null; } @Override public BuildCause getCause() { return model.getBuildCause(); } public String getGithubRepoUrl() { return getProject().getGithubRepoUrl(); } public void addCause(Cause manualCause) { this.getAction(CauseAction.class).getCauses().add(manualCause); } /* * Jenkins method is final cannot be mocked. Work around to make this * mockable without powermock */ public String getFullUrl() { return this.getAbsoluteUrl(); } public Map<String, String> getDotCiEnvVars() { return model.getDotCiEnvVars(); } public void skip() { addAction(new SkippedBuildAction()); } }
src/main/java/com/groupon/jenkins/dynamic/build/DynamicBuild.java
/* The MIT License (MIT) Copyright (c) 2014, Groupon, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.groupon.jenkins.dynamic.build; import com.google.common.base.Objects; import com.google.common.collect.Iterables; import com.groupon.jenkins.dynamic.build.cause.BuildCause; import com.groupon.jenkins.dynamic.build.execution.BuildEnvironment; import com.groupon.jenkins.dynamic.build.execution.BuildExecutionContext; import com.groupon.jenkins.dynamic.build.execution.BuildType; import com.groupon.jenkins.dynamic.build.execution.DotCiPluginRunner; import com.groupon.jenkins.dynamic.build.execution.DynamicBuildExection; import com.groupon.jenkins.dynamic.buildconfiguration.BuildConfiguration; import com.groupon.jenkins.dynamic.buildconfiguration.EffectiveBuildConfigurationCalculator; import com.groupon.jenkins.dynamic.buildconfiguration.InvalidDotCiYmlException; import com.groupon.jenkins.github.services.GithubRepositoryService; import hudson.EnvVars; import hudson.Functions; import hudson.matrix.Combination; import hudson.model.AbstractProject; import hudson.model.Build; import hudson.model.BuildListener; import hudson.model.Cause; import hudson.model.CauseAction; import hudson.model.Executor; import hudson.model.Result; import hudson.tasks.BuildStep; import hudson.util.HttpResponses; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; import org.kohsuke.stapler.HttpResponse; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.interceptor.RequirePOST; import javax.servlet.ServletException; public class DynamicBuild extends DbBackedBuild<DynamicProject, DynamicBuild> { private transient BuildConfiguration buildConfiguration; private transient DynamicBuildModel model; public DynamicBuild(DynamicProject project) throws IOException { super(project); this.model = new DynamicBuildModel(this); } public DynamicBuild(DynamicProject project, File buildDir) throws IOException { super(project, buildDir); this.model = new DynamicBuildModel(this); } @SuppressWarnings("unchecked") @Override public void run() { this.model.run(); execute(new DynamicRunExecution()); } public DynamicBuildLayouter getLayouter() { return DynamicBuildLayouter.get(this); } // This needs to be overriden here to override @RequirePOST annotation, // which seems like a bug in the version were are using. @Override public synchronized HttpResponse doStop() throws IOException, ServletException { return super.doStop(); } @Override public void restoreFromDb(AbstractProject project, Map<String, Object> input) { super.restoreFromDb(project, input); if (input.containsKey("build_configuration")) { String buildConfigYml = (String) input.get("build_configuration"); this.buildConfiguration = BuildConfiguration.restoreFromYaml(buildConfigYml); } this.model = new DynamicBuildModel(this); } @Override protected Map<String, Object> getBuildAttributesForDb() { Map<String, Object> buildAttributes = super.getBuildAttributesForDb(); if (isConfigurationCalculated()) { buildAttributes.put("build_configuration", buildConfiguration.toYaml()); } buildAttributes.put("main_build", true); return buildAttributes; } @Override @RequirePOST public void doDoDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { checkPermission(DELETE); model.deleteBuild(); rsp.sendRedirect2(req.getContextPath() + '/' + getParent().getUrl()); } @Override public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) { try { Build item = getRun(Combination.fromString(token)); if (item != null) { if (item.getNumber() == this.getNumber()) { return item; } else { // redirect the user to the correct URL String url = Functions.joinPath(item.getUrl(), req.getRestOfPath()); String qs = req.getQueryString(); if (qs != null) { url += '?' + qs; } throw HttpResponses.redirectViaContextPath(url); } } } catch (IllegalArgumentException e) { // failed to parse the token as Combination. Must be something else } return super.getDynamic(token, req, rsp); } @Override public Map<String, String> getDotCiEnvVars(EnvVars jenkinsEnvVars) { Map<String, String> vars = super.getDotCiEnvVars(jenkinsEnvVars); Map<String, String> dotCiEnvVars = model.getDotCiEnvVars(); vars.putAll(dotCiEnvVars); return vars; } protected class DynamicRunExecution extends BuildExecution implements BuildExecutionContext { public boolean executeShell(BuildStep buildStep, BuildListener listener) throws InterruptedException, IOException { return performStep(buildStep, listener); } @Override public boolean performStep(BuildStep execution, BuildListener listener) throws IOException, InterruptedException { return perform(execution, listener); } @Override public void setResult(Result r) { DynamicBuild.this.setResult(r); } @Override protected Result doRun(BuildListener listener) throws Exception, hudson.model.Run.RunnerAbortedException { try { DynamicBuild.this.setBuildConfiguration(calculateBuildConfiguration(listener)); BuildEnvironment buildEnvironment = new BuildEnvironment(DynamicBuild.this, launcher, listener); DotCiPluginRunner dotCiPluginRunner = new DotCiPluginRunner(DynamicBuild.this, launcher, getBuildConfiguration()); DynamicBuildExection dynamicBuildExecution = new DynamicBuildExection(DynamicBuild.this, buildEnvironment, this, dotCiPluginRunner, getBuildType()); Result buildRunResult = dynamicBuildExecution.doRun(listener); setResult(buildRunResult); return buildRunResult; } catch (InvalidDotCiYmlException invalidDotCiYmlException) { for (String error : invalidDotCiYmlException.getValidationErrors()) { listener.error(error); } return Result.FAILURE; } } public BuildType getBuildType() throws IOException { if (getBuildConfiguration().isDocker()) { return BuildType.DockerImage; } if (new GithubRepositoryService(getGithubRepoUrl()).hasDockerFile(getSha())) { return BuildType.DockerLocal; } return BuildType.BareMetal; } private BuildConfiguration calculateBuildConfiguration(BuildListener listener) throws IOException, InterruptedException, InvalidDotCiYmlException { return new EffectiveBuildConfigurationCalculator().calculateBuildConfiguration(getGithubRepoUrl(), getSha(), getEnvironment(listener)); } @Override public BuildConfiguration getBuildConfiguration() { return DynamicBuild.this.getBuildConfiguration(); } } @Override @Exported public Executor getExecutor() { return super.getExecutor() == null ? getOneOffExecutor() : super.getExecutor(); } private DynamicProject getConductor() { return this.getParent(); } public Iterable<DynamicSubProject> getRunSubProjects() { return getConductor().getSubProjects(model.getMainRunCombinations(getAxisList())); } public Iterable<Combination> getAxisList() { return DynamicBuildLayouter.calculateAxisList(this).list(); } public Iterable<DynamicSubProject> getAllSubProjects() { return Iterables.concat(getRunSubProjects(), getPostBuildSubProjects()); } public Iterable<DynamicSubProject> getPostBuildSubProjects() { Combination postBuildCombination = model.getPostBuildCombination(getAxisList()); return postBuildCombination == null ? new ArrayList<DynamicSubProject>() : getConductor().getSubProjects(Arrays.asList(postBuildCombination)); } public Build getRun(Combination combination) { for (DynamicSubProject subProject : getAllSubProjects()) { if (subProject.getCombination().equals(combination)) { return getRunForConfiguration(subProject); } } return null; } @Override public DynamicProject getParent() { return super.getParent(); } private DynamicSubBuild getRunForConfiguration(DynamicSubProject c) { DynamicSubBuild r = c.getBuildByNumber(getNumber()); return r != null ? r : null; } public BuildConfiguration getBuildConfiguration() { return buildConfiguration; } public void setBuildConfiguration(BuildConfiguration buildConfiguration) throws IOException { this.buildConfiguration = buildConfiguration; this.save(); // make sure it get saved into the db } @Override public boolean equals(Object other) { if (other instanceof DynamicBuild) { DbBackedBuild<DynamicProject, DynamicBuild> otherBuild = (DbBackedBuild<DynamicProject, DynamicBuild>) other; if (otherBuild.getName().equals(this.getName()) && otherBuild.getNumber() == this.getNumber()) { return true; } } return false; } @Override public int hashCode() { return Objects.hashCode(getName(), getNumber()); } @Override public String getSha() { return this.getCause() == null ? "" : getCause().getSha(); } public boolean isConfigurationCalculated() { return buildConfiguration != null; } @Override public BuildCause getCause() { return model.getBuildCause(); } public String getGithubRepoUrl() { return getProject().getGithubRepoUrl(); } public void addCause(Cause manualCause) { this.getAction(CauseAction.class).getCauses().add(manualCause); } /* * Jenkins method is final cannot be mocked. Work around to make this * mockable without powermock */ public String getFullUrl() { return this.getAbsoluteUrl(); } public Map<String, String> getDotCiEnvVars() { return model.getDotCiEnvVars(); } public void skip() { addAction(new SkippedBuildAction()); } }
Revert "Not supporting older versions of jenkins anymore" This reverts commit 2c5bc69040750e364c7da81eab5f4b02c6f98c02.
src/main/java/com/groupon/jenkins/dynamic/build/DynamicBuild.java
Revert "Not supporting older versions of jenkins anymore"
Java
mit
3e0e1816d5d61802fe3b3e7b7d906bb61676cf86
0
aterai/java-swing-tips,aterai/java-swing-tips,mhcrnl/java-swing-tips,aterai/java-swing-tips,mhcrnl/java-swing-tips,aoguren/java-swing-tips,mhcrnl/java-swing-tips,aoguren/java-swing-tips,aterai/java-swing-tips,aoguren/java-swing-tips
package example; //-*- mode:java; encoding:utf8n; coding:utf-8 -*- // vim:set fileencoding=utf-8: //@homepage@ import java.awt.*; import java.awt.event.*; import java.util.ArrayList; import javax.swing.*; import javax.swing.border.*; import javax.swing.plaf.synth.*; public class MainPanel extends JPanel { private final JPanel panel = new JPanel(); private final JCheckBox check = new JCheckBox("color"); public MainPanel() { super(new BorderLayout()); panel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); check.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { layoutComboBoxPanel(panel, initComboBoxes(check.isSelected())); panel.revalidate(); } }); layoutComboBoxPanel(panel, initComboBoxes(check.isSelected())); JMenuBar mb = new JMenuBar(); mb.add(createLookAndFeelMenu()); Box box = Box.createHorizontalBox(); box.add(check); box.add(Box.createHorizontalGlue()); add(mb, BorderLayout.NORTH); add(panel); add(box, BorderLayout.SOUTH); setPreferredSize(new Dimension(320, 320)); } private void layoutComboBoxPanel(JPanel p2, ArrayList<JComboBox> list) { p2.removeAll(); p2.setLayout(new GridBagLayout()); Border inside = BorderFactory.createEmptyBorder(10,5+2,10,10+2); Border outside = BorderFactory.createTitledBorder("JComboBox Padding Test"); p2.setBorder(BorderFactory.createCompoundBorder(outside, inside)); for(int i=0;i<list.size();i++) { GridBagConstraints c = new GridBagConstraints(); c.gridheight = 1; c.gridx = 0; c.insets = new Insets(5, 5, 5, 0); c.anchor = GridBagConstraints.WEST; c.gridy = i; p2.add(new JLabel(""+i+":"), c); c.gridx = 1; c.weightx = 1.0; c.fill = GridBagConstraints.HORIZONTAL; c.gridy = i; p2.add(list.get(i), c); } p2.revalidate(); //??? JDK 1.7.0 Nimbus ??? } private ArrayList<JComboBox> initComboBoxes(boolean isColor) { // if(uiCheck.isSelected()) { // // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7158712 // UIManager.put("ComboBox.padding", new javax.swing.plaf.InsetsUIResource(1,15,1,1)); // } ArrayList<JComboBox> list = new ArrayList<JComboBox>(); for(int i=0;i<7;i++) { list.add(makeComboBox()); } JComboBox combo; JTextField editor; // ---- 00 ---- combo = list.get(0); combo.setEditable(false); combo.setToolTipText("combo.setEditable(false);"); // ---- 01 ---- combo = list.get(1); combo.setEditable(true); editor = (JTextField)combo.getEditor().getEditorComponent(); editor.setBorder(BorderFactory.createCompoundBorder(editor.getBorder(), getPaddingBorder(isColor))); combo.setToolTipText("editor.setBorder(BorderFactory.createCompoundBorder(editor.getBorder(), padding));"); // ---- 02 ---- combo = list.get(2); combo.setEditable(true); editor = (JTextField)combo.getEditor().getEditorComponent(); editor.setBorder(getPaddingBorder(isColor)); combo.setToolTipText("editor.setBorder(padding);"); // ---- 03 ---- combo = list.get(3); combo.setEditable(true); editor = (JTextField)combo.getEditor().getEditorComponent(); Insets i = editor.getInsets(); editor.setMargin(new Insets(i.top,i.left+5,i.bottom,i.right)); combo.setToolTipText("Insets i = editor.getInsets(); editor.setMargin(new Insets(i.top,i.left+5,i.bottom,i.right));"); // ---- 04 ---- combo = list.get(4); combo.setEditable(true); editor = (JTextField)combo.getEditor().getEditorComponent(); Insets m = editor.getMargin(); editor.setMargin(new Insets(m.top,m.left+5,m.bottom,m.right)); combo.setToolTipText("Insets m = editor.getMargin(); editor.setMargin(new Insets(m.top,m.left+5,m.bottom,m.right));"); // ---- 05 ---- combo = list.get(5); combo.setEditable(true); combo.setBorder(BorderFactory.createCompoundBorder(combo.getBorder(), getPaddingBorder(isColor))); combo.setToolTipText("combo.setBorder(BorderFactory.createCompoundBorder(combo.getBorder(), padding));"); // ---- 06 ---- combo = list.get(6); combo.setEditable(true); combo.setBorder(BorderFactory.createCompoundBorder(getPaddingBorder(isColor), combo.getBorder())); combo.setToolTipText("combo.setBorder(BorderFactory.createCompoundBorder(padding, combo.getBorder()));"); if(isColor) { Color c = new Color(.8f,1f,.8f); for(JComboBox cb:list) { cb.setOpaque(true); cb.setBackground(c); editor = (JTextField)cb.getEditor().getEditorComponent(); editor.setOpaque(true); editor.setBackground(c); } } return list; } //<blockquote cite="http://java.net/projects/swingset3/sources/svn/content/trunk/SwingSet3/src/com/sun/swingset3/SwingSet3.java"> private ButtonGroup lookAndFeelRadioGroup; private String lookAndFeel; protected JMenu createLookAndFeelMenu() { JMenu menu = new JMenu("LookAndFeel"); lookAndFeel = UIManager.getLookAndFeel().getClass().getName(); lookAndFeelRadioGroup = new ButtonGroup(); for(UIManager.LookAndFeelInfo lafInfo: UIManager.getInstalledLookAndFeels()) { menu.add(createLookAndFeelItem(lafInfo.getName(), lafInfo.getClassName())); } return menu; } protected JRadioButtonMenuItem createLookAndFeelItem(String lafName, String lafClassName) { JRadioButtonMenuItem lafItem = new JRadioButtonMenuItem(); lafItem.setSelected(lafClassName.equals(lookAndFeel)); lafItem.setHideActionText(true); lafItem.setAction(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { ButtonModel m = lookAndFeelRadioGroup.getSelection(); try{ setLookAndFeel(m.getActionCommand()); }catch(Exception ex) { ex.printStackTrace(); } } }); lafItem.setText(lafName); lafItem.setActionCommand(lafClassName); lookAndFeelRadioGroup.add(lafItem); return lafItem; } public void setLookAndFeel(String lookAndFeel) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException { String oldLookAndFeel = this.lookAndFeel; if(!oldLookAndFeel.equals(lookAndFeel)) { UIManager.setLookAndFeel(lookAndFeel); this.lookAndFeel = lookAndFeel; updateLookAndFeel(); firePropertyChange("lookAndFeel", oldLookAndFeel, lookAndFeel); } } private void updateLookAndFeel() { for(Window window: Frame.getWindows()) { SwingUtilities.updateComponentTreeUI(window); } } //</blockquote> private static Border getPaddingBorder(boolean isColor) { return isColor ? BorderFactory.createMatteBorder(0,5,0,0,new Color(1f,.8f,.8f,.5f)) : BorderFactory.createEmptyBorder(0,5,0,0); } @SuppressWarnings("unchecked") private static JComboBox makeComboBox() { DefaultComboBoxModel model = new DefaultComboBoxModel(); model.addElement("aaaaaaaaaaaaaaaaaaaaaaaaa"); model.addElement("aaaabbb"); model.addElement("aaaabbbcc"); model.addElement("bbb1"); model.addElement("bbb12"); JComboBox combo = new JComboBox(model); ListCellRenderer lcr = combo.getRenderer(); ((JLabel)lcr).setBorder(getPaddingBorder(false)); return combo; } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }catch(Exception e) { e.printStackTrace(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
PaddingComboBox/src/java/example/MainPanel.java
package example; //-*- mode:java; encoding:utf8n; coding:utf-8 -*- // vim:set fileencoding=utf-8: //@homepage@ import java.awt.*; import java.awt.event.*; import java.util.ArrayList; import javax.swing.*; import javax.swing.border.*; import javax.swing.plaf.synth.*; public class MainPanel extends JPanel { private final JPanel panel = new JPanel(); private final JCheckBox check = new JCheckBox("color"); public MainPanel() { super(new BorderLayout()); panel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); check.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { layoutComboBoxPanel(panel, initComboBoxes(check.isSelected())); panel.revalidate(); } }); layoutComboBoxPanel(panel, initComboBoxes(check.isSelected())); JMenuBar mb = new JMenuBar(); mb.add(createLookAndFeelMenu()); Box box = Box.createHorizontalBox(); box.add(check); box.add(Box.createHorizontalGlue()); add(mb, BorderLayout.NORTH); add(panel); add(box, BorderLayout.SOUTH); setPreferredSize(new Dimension(320, 320)); } private void layoutComboBoxPanel(JPanel p2, ArrayList<JComboBox> list) { p2.removeAll(); p2.setLayout(new GridBagLayout()); Border inside = BorderFactory.createEmptyBorder(10,5+2,10,10+2); Border outside = BorderFactory.createTitledBorder("JComboBox Padding Test"); p2.setBorder(BorderFactory.createCompoundBorder(outside, inside)); for(int i=0;i<list.size();i++) { GridBagConstraints c = new GridBagConstraints(); c.gridheight = 1; c.gridx = 0; c.insets = new Insets(5, 5, 5, 0); c.anchor = GridBagConstraints.WEST; c.gridy = i; p2.add(new JLabel(""+i+":"), c); c.gridx = 1; c.weightx = 1.0; c.fill = GridBagConstraints.HORIZONTAL; c.gridy = i; p2.add(list.get(i), c); } } private ArrayList<JComboBox> initComboBoxes(boolean isColor) { // if(uiCheck.isSelected()) { // UIManager.put("ComboBox.padding", new javax.swing.plaf.InsetsUIResource(1,15,1,1)); // } ArrayList<JComboBox> list = new ArrayList<JComboBox>(); for(int i=0;i<7;i++) { list.add(makeComboBox()); } JComboBox combo; JTextField editor; // ---- 00 ---- combo = list.get(0); combo.setEditable(false); combo.setToolTipText("combo.setEditable(false);"); // ---- 01 ---- combo = list.get(1); combo.setEditable(true); editor = (JTextField)combo.getEditor().getEditorComponent(); editor.setBorder(BorderFactory.createCompoundBorder(editor.getBorder(), getPaddingBorder(isColor))); combo.setToolTipText("editor.setBorder(BorderFactory.createCompoundBorder(editor.getBorder(), padding));"); // ---- 02 ---- combo = list.get(2); combo.setEditable(true); editor = (JTextField)combo.getEditor().getEditorComponent(); editor.setBorder(getPaddingBorder(isColor)); combo.setToolTipText("editor.setBorder(padding);"); // ---- 03 ---- combo = list.get(3); combo.setEditable(true); editor = (JTextField)combo.getEditor().getEditorComponent(); Insets i = editor.getInsets(); editor.setMargin(new Insets(i.top,i.left+5,i.bottom,i.right)); combo.setToolTipText("Insets i = editor.getInsets(); editor.setMargin(new Insets(i.top,i.left+5,i.bottom,i.right));"); // ---- 04 ---- combo = list.get(4); combo.setEditable(true); editor = (JTextField)combo.getEditor().getEditorComponent(); Insets m = editor.getMargin(); editor.setMargin(new Insets(m.top,m.left+5,m.bottom,m.right)); combo.setToolTipText("Insets m = editor.getMargin(); editor.setMargin(new Insets(m.top,m.left+5,m.bottom,m.right));"); // ---- 05 ---- combo = list.get(5); combo.setEditable(true); combo.setBorder(BorderFactory.createCompoundBorder(combo.getBorder(), getPaddingBorder(isColor))); combo.setToolTipText("combo.setBorder(BorderFactory.createCompoundBorder(combo.getBorder(), padding));"); // ---- 06 ---- combo = list.get(6); combo.setEditable(true); combo.setBorder(BorderFactory.createCompoundBorder(getPaddingBorder(isColor), combo.getBorder())); combo.setToolTipText("combo.setBorder(BorderFactory.createCompoundBorder(padding, combo.getBorder()));"); if(isColor) { Color c = new Color(.8f,1f,.8f); for(JComboBox cb:list) { cb.setOpaque(true); cb.setBackground(c); editor = (JTextField)cb.getEditor().getEditorComponent(); editor.setOpaque(true); editor.setBackground(c); } } return list; } //<blockquote cite="http://java.net/projects/swingset3/sources/svn/content/trunk/SwingSet3/src/com/sun/swingset3/SwingSet3.java"> private ButtonGroup lookAndFeelRadioGroup; private String lookAndFeel; protected JMenu createLookAndFeelMenu() { JMenu menu = new JMenu("LookAndFeel"); lookAndFeel = UIManager.getLookAndFeel().getClass().getName(); lookAndFeelRadioGroup = new ButtonGroup(); for(UIManager.LookAndFeelInfo lafInfo: UIManager.getInstalledLookAndFeels()) { menu.add(createLookAndFeelItem(lafInfo.getName(), lafInfo.getClassName())); } return menu; } protected JRadioButtonMenuItem createLookAndFeelItem(String lafName, String lafClassName) { JRadioButtonMenuItem lafItem = new JRadioButtonMenuItem(); lafItem.setSelected(lafClassName.equals(lookAndFeel)); lafItem.setHideActionText(true); lafItem.setAction(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { ButtonModel m = lookAndFeelRadioGroup.getSelection(); try{ setLookAndFeel(m.getActionCommand()); }catch(Exception ex) { ex.printStackTrace(); } } }); lafItem.setText(lafName); lafItem.setActionCommand(lafClassName); lookAndFeelRadioGroup.add(lafItem); return lafItem; } public void setLookAndFeel(String lookAndFeel) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException { String oldLookAndFeel = this.lookAndFeel; if(!oldLookAndFeel.equals(lookAndFeel)) { UIManager.setLookAndFeel(lookAndFeel); this.lookAndFeel = lookAndFeel; updateLookAndFeel(); firePropertyChange("lookAndFeel", oldLookAndFeel, lookAndFeel); } } private void updateLookAndFeel() { for(Window window: Frame.getWindows()) { SwingUtilities.updateComponentTreeUI(window); } } //</blockquote> private static Border getPaddingBorder(boolean isColor) { return isColor ? BorderFactory.createMatteBorder(0,5,0,0,new Color(1f,.8f,.8f,.5f)) : BorderFactory.createEmptyBorder(0,5,0,0); } @SuppressWarnings("unchecked") private static JComboBox makeComboBox() { DefaultComboBoxModel model = new DefaultComboBoxModel(); model.addElement("aaaaaaaaaaaaaaaaaaaaaaaaa"); model.addElement("aaaabbb"); model.addElement("aaaabbbcc"); model.addElement("bbb1"); model.addElement("bbb12"); JComboBox combo = new JComboBox(model); ListCellRenderer lcr = combo.getRenderer(); ((JLabel)lcr).setBorder(getPaddingBorder(false)); return combo; } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }catch(Exception e) { e.printStackTrace(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
comment
PaddingComboBox/src/java/example/MainPanel.java
comment
Java
mpl-2.0
c4bba02c336df9092c1fe71c6c704ef758ffe558
0
fredoboulo/jeromq,zeromq/jeromq,trevorbernard/jeromq,trevorbernard/jeromq,fredoboulo/jeromq,zeromq/jeromq
package zmq; import java.io.IOException; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.nio.channels.SelectableChannel; import java.nio.channels.Selector; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.zeromq.ZMQException; import zmq.io.IOThread; import zmq.pipe.Pipe; import zmq.socket.Sockets; import zmq.util.Errno; import zmq.util.MultiMap; //Context object encapsulates all the global state associated with // the library. public class Ctx { private static final int WAIT_FOREVER = -1; // Information associated with inproc endpoint. Note that endpoint options // are registered as well so that the peer can access them without a need // for synchronization, handshaking or similar. public static class Endpoint { public final SocketBase socket; public final Options options; public Endpoint(SocketBase socket, Options options) { this.socket = socket; this.options = options; } } private static class PendingConnection { private final Endpoint endpoint; private final Pipe connectPipe; private final Pipe bindPipe; public PendingConnection(Endpoint endpoint, Pipe connectPipe, Pipe bindPipe) { super(); this.endpoint = endpoint; this.connectPipe = connectPipe; this.bindPipe = bindPipe; } } private enum Side { CONNECT, BIND } // Used to check whether the object is a context. private boolean active; // Sockets belonging to this context. We need the list so that // we can notify the sockets when zmq_term() is called. The sockets // will return ETERM then. private final List<SocketBase> sockets; // List of unused thread slots. private final Deque<Integer> emptySlots; // If true, init has been called but no socket has been created // yet. Launching of I/O threads is delayed. private final AtomicBoolean starting = new AtomicBoolean(true); // If true, zmq_term was already called. private boolean terminating; // Synchronization of accesses to global slot-related data: // sockets, emptySlots, terminating. It also synchronizes // access to zombie sockets as such (as opposed to slots) and provides // a memory barrier to ensure that all CPU cores see the same data. private final Lock slotSync; // A list of poll selectors opened under this context. When the context is // destroyed, each of the selectors is closed to ensure resource // deallocation. private final List<Selector> selectors = new ArrayList<>(); // The reaper thread. private Reaper reaper; // I/O threads. private final List<IOThread> ioThreads; // Array of pointers to mailboxes for both application and I/O threads. private int slotCount; private IMailbox[] slots; // Mailbox for zmq_term thread. private final Mailbox termMailbox; // List of inproc endpoints within this context. private final Map<String, Endpoint> endpoints; // Synchronization of access to the list of inproc endpoints. private final Lock endpointsSync; // Maximum socket ID. private static AtomicInteger maxSocketId = new AtomicInteger(0); // Maximum number of sockets that can be opened at the same time. private int maxSockets; // Number of I/O threads to launch. private int ioThreadCount; // Does context wait (possibly forever) on termination? private boolean blocky; // Synchronization of access to context options. private final Lock optSync; // Synchronization of access to selectors. private final Lock selectorSync = new ReentrantLock(); static final int TERM_TID = 0; private static final int REAPER_TID = 1; private final MultiMap<String, PendingConnection> pendingConnections = new MultiMap<>(); private boolean ipv6; private final Errno errno = new Errno(); /** * A class that holds the informations needed to forward channel in monitor sockets. * Of course, it only works with inproc sockets. * <p> * It uses WeakReference to avoid holding references to channel if the monitor event is * lost. * <p> * A class is used as a lock in lazy allocation of the needed objects. */ private static class ChannelForwardHolder { private final AtomicInteger handleSource = new AtomicInteger(0); private final Map<Integer, WeakReference<SelectableChannel>> map = new ConcurrentHashMap<>(); // The WeakReference is empty when the reference is empty, so keep a reverse empty to clean the direct map. private final Map<WeakReference<SelectableChannel>, Integer> reversemap = new ConcurrentHashMap<>(); private final ReferenceQueue<SelectableChannel> queue = new ReferenceQueue<>(); } private ChannelForwardHolder forwardHolder = null; public Ctx() { active = true; terminating = false; reaper = null; slotCount = 0; slots = null; maxSockets = ZMQ.ZMQ_MAX_SOCKETS_DFLT; ioThreadCount = ZMQ.ZMQ_IO_THREADS_DFLT; ipv6 = false; blocky = true; slotSync = new ReentrantLock(); endpointsSync = new ReentrantLock(); optSync = new ReentrantLock(); termMailbox = new Mailbox(this, "terminater", -1); emptySlots = new ArrayDeque<>(); ioThreads = new ArrayList<>(); sockets = new ArrayList<>(); endpoints = new HashMap<>(); } private void destroy() throws IOException { assert (sockets.isEmpty()); for (IOThread it : ioThreads) { it.stop(); } for (IOThread it : ioThreads) { it.close(); } ioThreads.clear(); selectorSync.lock(); try { for (Selector selector : selectors) { if (selector != null) { selector.close(); } } selectors.clear(); } finally { selectorSync.unlock(); } // Deallocate the reaper thread object. if (reaper != null) { reaper.close(); } // Deallocate the array of mailboxes. No special work is // needed as mailboxes themselves were deallocated with their // corresponding io_thread/socket objects. termMailbox.close(); active = false; } /** * @return false if {@link #terminate()}terminate() has been called. */ public boolean isActive() { return active; } /** * @return false if {@link #terminate()}terminate() has been called. * @deprecated use {@link #isActive()} instead */ @Deprecated public boolean checkTag() { return active; } // This function is called when user invokes zmq_term. If there are // no more sockets open it'll cause all the infrastructure to be shut // down. If there are open sockets still, the deallocation happens // after the last one is closed. public void terminate() { slotSync.lock(); try { // Connect up any pending inproc connections, otherwise we will hang for (Entry<PendingConnection, String> pending : pendingConnections.entries()) { SocketBase s = createSocket(ZMQ.ZMQ_PAIR); // create_socket might fail eg: out of memory/sockets limit reached assert (s != null); s.bind(pending.getValue()); s.close(); } if (!starting.get()) { // Check whether termination was already underway, but interrupted and now // restarted. boolean restarted = terminating; terminating = true; // First attempt to terminate the context. if (!restarted) { // First send stop command to sockets so that any blocking calls // can be interrupted. If there are no sockets we can ask reaper // thread to stop. for (SocketBase socket : sockets) { socket.stop(); } if (sockets.isEmpty()) { reaper.stop(); } } } } finally { slotSync.unlock(); } if (!starting.get()) { // Wait till reaper thread closes all the sockets. Command cmd = termMailbox.recv(WAIT_FOREVER); if (cmd == null) { throw new ZMQException(errno.get()); } assert (cmd.type == Command.Type.DONE) : cmd; slotSync.lock(); try { assert (sockets.isEmpty()); } finally { slotSync.unlock(); } } // Deallocate the resources. try { destroy(); } catch (IOException e) { throw new ZError.IOException(e); } } final void shutdown() { slotSync.lock(); try { if (!starting.get() && !terminating) { terminating = true; // Send stop command to sockets so that any blocking calls // can be interrupted. If there are no sockets we can ask reaper // thread to stop. for (SocketBase socket : sockets) { socket.stop(); } if (sockets.isEmpty()) { reaper.stop(); } } } finally { slotSync.unlock(); } } public boolean set(int option, int optval) { if (option == ZMQ.ZMQ_MAX_SOCKETS && optval >= 1) { optSync.lock(); try { maxSockets = optval; } finally { optSync.unlock(); } } else if (option == ZMQ.ZMQ_IO_THREADS && optval >= 0) { optSync.lock(); try { ioThreadCount = optval; } finally { optSync.unlock(); } } else if (option == ZMQ.ZMQ_BLOCKY && optval >= 0) { optSync.lock(); try { blocky = (optval != 0); } finally { optSync.unlock(); } } else if (option == ZMQ.ZMQ_IPV6 && optval >= 0) { optSync.lock(); try { ipv6 = (optval != 0); } finally { optSync.unlock(); } } else { return false; } return true; } public int get(int option) { int rc; if (option == ZMQ.ZMQ_MAX_SOCKETS) { rc = maxSockets; } else if (option == ZMQ.ZMQ_IO_THREADS) { rc = ioThreadCount; } else if (option == ZMQ.ZMQ_BLOCKY) { rc = blocky ? 1 : 0; } else if (option == ZMQ.ZMQ_IPV6) { rc = ipv6 ? 1 : 0; } else { throw new IllegalArgumentException("option = " + option); } return rc; } public SocketBase createSocket(int type) { SocketBase s = null; slotSync.lock(); try { if (starting.compareAndSet(true, false)) { initSlots(); } // Once zmq_term() was called, we can't create new sockets. if (terminating) { throw new ZError.CtxTerminatedException(); } // If maxSockets limit was reached, return error. if (emptySlots.isEmpty()) { throw new ZMQException(ZError.EMFILE); } // Choose a slot for the socket. int slot = emptySlots.pollLast(); // Generate new unique socket ID. int sid = maxSocketId.incrementAndGet(); // Create the socket and register its mailbox. s = Sockets.create(type, this, slot, sid); if (s == null) { emptySlots.addLast(slot); return null; } sockets.add(s); slots[slot] = s.getMailbox(); } finally { slotSync.unlock(); } return s; } private void initSlots() { slotSync.lock(); try { // Initialize the array of mailboxes. Additional two slots are for // zmq_term thread and reaper thread. int ios; optSync.lock(); try { ios = ioThreadCount; slotCount = maxSockets + ioThreadCount + 2; } finally { optSync.unlock(); } slots = new IMailbox[slotCount]; // Initialize the infrastructure for zmq_term thread. slots[TERM_TID] = termMailbox; // Create the reaper thread. reaper = new Reaper(this, REAPER_TID); slots[REAPER_TID] = reaper.getMailbox(); reaper.start(); // Create I/O thread objects and launch them. for (int i = 2; i != ios + 2; i++) { IOThread ioThread = new IOThread(this, i); //alloc_assert (io_thread); ioThreads.add(ioThread); slots[i] = ioThread.getMailbox(); ioThread.start(); } // In the unused part of the slot array, create a list of empty slots. for (int i = slotCount - 1; i >= ios + 2; i--) { emptySlots.add(i); slots[i] = null; } } finally { slotSync.unlock(); } } void destroySocket(SocketBase socket) { slotSync.lock(); // Free the associated thread slot. try { int tid = socket.getTid(); emptySlots.add(tid); slots[tid] = null; // Remove the socket from the list of sockets. sockets.remove(socket); // If zmq_term() was already called and there are no more socket // we can ask reaper thread to terminate. if (terminating && sockets.isEmpty()) { reaper.stop(); } } finally { slotSync.unlock(); } } // Creates a Selector that will be closed when the context is destroyed. public Selector createSelector() { selectorSync.lock(); try { Selector selector = Selector.open(); assert (selector != null); selectors.add(selector); return selector; } catch (IOException e) { throw new ZError.IOException(e); } finally { selectorSync.unlock(); } } public boolean closeSelector(Selector selector) { selectorSync.lock(); try { boolean rc = selectors.remove(selector); if (rc) { try { selector.close(); } catch (IOException e) { throw new ZError.IOException(e); } } return rc; } finally { selectorSync.unlock(); } } // Returns reaper thread object. ZObject getReaper() { return reaper; } // Send command to the destination thread. void sendCommand(int tid, final Command command) { // System.out.println(Thread.currentThread().getName() + ": Sending command " + command); slots[tid].send(command); } // Returns the I/O thread that is the least busy at the moment. // Affinity specifies which I/O threads are eligible (0 = all). // Returns NULL if no I/O thread is available. IOThread chooseIoThread(long affinity) { if (ioThreads.isEmpty()) { return null; } // Find the I/O thread with minimum load. int minLoad = -1; IOThread selectedIoThread = null; for (int i = 0; i != ioThreads.size(); i++) { if (affinity == 0 || (affinity & (1L << i)) > 0) { int load = ioThreads.get(i).getLoad(); if (selectedIoThread == null || load < minLoad) { minLoad = load; selectedIoThread = ioThreads.get(i); } } } return selectedIoThread; } // Management of inproc endpoints. boolean registerEndpoint(String addr, Endpoint endpoint) { endpointsSync.lock(); Endpoint inserted = null; try { inserted = endpoints.put(addr, endpoint); } finally { endpointsSync.unlock(); } if (inserted != null) { return false; } return true; } boolean unregisterEndpoint(String addr, SocketBase socket) { endpointsSync.lock(); try { Endpoint endpoint = endpoints.get(addr); if (endpoint != null && socket == endpoint.socket) { endpoints.remove(addr); return true; } } finally { endpointsSync.unlock(); } return false; } void unregisterEndpoints(SocketBase socket) { endpointsSync.lock(); try { Iterator<Entry<String, Endpoint>> it = endpoints.entrySet().iterator(); while (it.hasNext()) { Entry<String, Endpoint> e = it.next(); if (e.getValue().socket == socket) { it.remove(); } } } finally { endpointsSync.unlock(); } } Endpoint findEndpoint(String addr) { Endpoint endpoint = null; endpointsSync.lock(); try { endpoint = endpoints.get(addr); if (endpoint == null) { return new Endpoint(null, new Options()); } // Increment the command sequence number of the peer so that it won't // get deallocated until "bind" command is issued by the caller. // The subsequent 'bind' has to be called with inc_seqnum parameter // set to false, so that the seqnum isn't incremented twice. endpoint.socket.incSeqnum(); } finally { endpointsSync.unlock(); } return endpoint; } void pendConnection(String addr, Endpoint endpoint, Pipe[] pipes) { PendingConnection pendingConnection = new PendingConnection(endpoint, pipes[0], pipes[1]); endpointsSync.lock(); try { Endpoint existing = endpoints.get(addr); if (existing == null) { // Still no bind. endpoint.socket.incSeqnum(); pendingConnections.insert(addr, pendingConnection); } else { // Bind has happened in the mean time, connect directly connectInprocSockets(existing.socket, existing.options, pendingConnection, Side.CONNECT); } } finally { endpointsSync.unlock(); } } void connectPending(String addr, SocketBase bindSocket) { endpointsSync.lock(); try { Collection<PendingConnection> pendings = pendingConnections.remove(addr); if (pendings != null) { for (PendingConnection pending : pendings) { connectInprocSockets(bindSocket, endpoints.get(addr).options, pending, Side.BIND); } } } finally { endpointsSync.unlock(); } } private void connectInprocSockets(SocketBase bindSocket, Options bindOptions, PendingConnection pendingConnection, Side side) { bindSocket.incSeqnum(); pendingConnection.bindPipe.setTid(bindSocket.getTid()); if (!bindOptions.recvIdentity) { Msg msg = pendingConnection.bindPipe.read(); assert (msg != null); } int sndhwm = 0; if (pendingConnection.endpoint.options.sendHwm != 0 && bindOptions.recvHwm != 0) { sndhwm = pendingConnection.endpoint.options.sendHwm + bindOptions.recvHwm; } int rcvhwm = 0; if (pendingConnection.endpoint.options.recvHwm != 0 && bindOptions.sendHwm != 0) { rcvhwm = pendingConnection.endpoint.options.recvHwm + bindOptions.sendHwm; } boolean conflate = pendingConnection.endpoint.options.conflate && (pendingConnection.endpoint.options.type == ZMQ.ZMQ_DEALER || pendingConnection.endpoint.options.type == ZMQ.ZMQ_PULL || pendingConnection.endpoint.options.type == ZMQ.ZMQ_PUSH || pendingConnection.endpoint.options.type == ZMQ.ZMQ_PUB || pendingConnection.endpoint.options.type == ZMQ.ZMQ_SUB); int[] hwms = { conflate ? -1 : sndhwm, conflate ? -1 : rcvhwm }; pendingConnection.connectPipe.setHwms(hwms[1], hwms[0]); pendingConnection.bindPipe.setHwms(hwms[0], hwms[1]); if (side == Side.BIND) { Command cmd = new Command(null, Command.Type.BIND, pendingConnection.bindPipe); bindSocket.processCommand(cmd); bindSocket.sendInprocConnected(pendingConnection.endpoint.socket); } else { pendingConnection.connectPipe.sendBind(bindSocket, pendingConnection.bindPipe, false); } // When a ctx is terminated all pending inproc connection will be // connected, but the socket will already be closed and the pipe will be // in waiting_for_delimiter state, which means no more writes can be done // and the identity write fails and causes an assert. Check if the socket // is open before sending. if (pendingConnection.endpoint.options.recvIdentity && pendingConnection.endpoint.socket.isActive()) { Msg id = new Msg(bindOptions.identitySize); id.put(bindOptions.identity, 0, bindOptions.identitySize); id.setFlags(Msg.IDENTITY); boolean written = pendingConnection.bindPipe.write(id); assert (written); pendingConnection.bindPipe.flush(); } // If set, send the hello msg of the peer to the local socket. if (bindOptions.canSendHelloMsg && bindOptions.helloMsg != null) { boolean written = pendingConnection.bindPipe.write(bindOptions.helloMsg); assert (written); pendingConnection.bindPipe.flush(); } } public Errno errno() { return errno; } /** * Forward a channel in a monitor socket. * @param channel a channel to forward * @return the handle of the channel to be forwarded, used to retrieve it in {@link #getForwardedChannel(Integer)} */ int forwardChannel(SelectableChannel channel) { synchronized (ChannelForwardHolder.class) { if (forwardHolder == null) { forwardHolder = new ChannelForwardHolder(); } } WeakReference<SelectableChannel> ref = new WeakReference<SelectableChannel>(channel, forwardHolder.queue); int handle = forwardHolder.handleSource.getAndIncrement(); forwardHolder.map.put(handle, ref); forwardHolder.reversemap.put(ref, handle); cleanForwarded(); return handle; } /** * Retrieve a channel, using the handle returned by {@link #forwardChannel(SelectableChannel)}. As WeakReference are used, if the channel was discarded * and a GC ran, it will not be found and this method will return null. * @param handle * @return */ SelectableChannel getForwardedChannel(Integer handle) { cleanForwarded(); WeakReference<SelectableChannel> ref = forwardHolder.map.remove(handle); if (ref != null) { return ref.get(); } else { return null; } } /** * Clean all empty references */ private void cleanForwarded() { Reference<? extends SelectableChannel> ref; while ((ref = forwardHolder.queue.poll()) != null) { Integer handle = forwardHolder.reversemap.remove(ref); forwardHolder.map.remove(handle); } } }
src/main/java/zmq/Ctx.java
package zmq; import java.io.IOException; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.nio.channels.SelectableChannel; import java.nio.channels.Selector; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.zeromq.ZMQException; import zmq.io.IOThread; import zmq.pipe.Pipe; import zmq.socket.Sockets; import zmq.util.Errno; import zmq.util.MultiMap; //Context object encapsulates all the global state associated with // the library. public class Ctx { private static final int WAIT_FOREVER = -1; // Information associated with inproc endpoint. Note that endpoint options // are registered as well so that the peer can access them without a need // for synchronization, handshaking or similar. public static class Endpoint { public final SocketBase socket; public final Options options; public Endpoint(SocketBase socket, Options options) { this.socket = socket; this.options = options; } } private static class PendingConnection { private final Endpoint endpoint; private final Pipe connectPipe; private final Pipe bindPipe; public PendingConnection(Endpoint endpoint, Pipe connectPipe, Pipe bindPipe) { super(); this.endpoint = endpoint; this.connectPipe = connectPipe; this.bindPipe = bindPipe; } } private enum Side { CONNECT, BIND } // Used to check whether the object is a context. private boolean active; // Sockets belonging to this context. We need the list so that // we can notify the sockets when zmq_term() is called. The sockets // will return ETERM then. private final List<SocketBase> sockets; // List of unused thread slots. private final Deque<Integer> emptySlots; // If true, init has been called but no socket has been created // yet. Launching of I/O threads is delayed. private final AtomicBoolean starting = new AtomicBoolean(true); // If true, zmq_term was already called. private boolean terminating; // Synchronization of accesses to global slot-related data: // sockets, emptySlots, terminating. It also synchronizes // access to zombie sockets as such (as opposed to slots) and provides // a memory barrier to ensure that all CPU cores see the same data. private final Lock slotSync; // A list of poll selectors opened under this context. When the context is // destroyed, each of the selectors is closed to ensure resource // deallocation. private final List<Selector> selectors = new ArrayList<>(); // The reaper thread. private Reaper reaper; // I/O threads. private final List<IOThread> ioThreads; // Array of pointers to mailboxes for both application and I/O threads. private int slotCount; private IMailbox[] slots; // Mailbox for zmq_term thread. private final Mailbox termMailbox; // List of inproc endpoints within this context. private final Map<String, Endpoint> endpoints; // Synchronization of access to the list of inproc endpoints. private final Lock endpointsSync; // Maximum socket ID. private static AtomicInteger maxSocketId = new AtomicInteger(0); // Maximum number of sockets that can be opened at the same time. private int maxSockets; // Number of I/O threads to launch. private int ioThreadCount; // Does context wait (possibly forever) on termination? private boolean blocky; // Synchronization of access to context options. private final Lock optSync; // Synchronization of access to selectors. private final Lock selectorSync = new ReentrantLock(); static final int TERM_TID = 0; private static final int REAPER_TID = 1; private final MultiMap<String, PendingConnection> pendingConnections = new MultiMap<>(); private boolean ipv6; private final Errno errno = new Errno(); /** * A class that holds the informations needed to forward channel in monitor sockets. * Of course, it only works with inproc sockets. * <p> * It uses WeakReference to avoid holding references to channel if the monitor event is * lost. * <p> * A class is used as a lock in lazy allocation of the needed objects. */ private static class ChannelForwardHolder { private final Map<Integer, WeakReference<SelectableChannel>> map = new HashMap<>(); // The WeakReference is empty when the reference is empty, so keep a reverse empty to clean the direct map. private final Map<WeakReference<SelectableChannel>, Integer> reversemap = new HashMap<>(); private final ReferenceQueue<SelectableChannel> queue = new ReferenceQueue<>(); } private ChannelForwardHolder forwardHolder = null; public Ctx() { active = true; terminating = false; reaper = null; slotCount = 0; slots = null; maxSockets = ZMQ.ZMQ_MAX_SOCKETS_DFLT; ioThreadCount = ZMQ.ZMQ_IO_THREADS_DFLT; ipv6 = false; blocky = true; slotSync = new ReentrantLock(); endpointsSync = new ReentrantLock(); optSync = new ReentrantLock(); termMailbox = new Mailbox(this, "terminater", -1); emptySlots = new ArrayDeque<>(); ioThreads = new ArrayList<>(); sockets = new ArrayList<>(); endpoints = new HashMap<>(); } private void destroy() throws IOException { assert (sockets.isEmpty()); for (IOThread it : ioThreads) { it.stop(); } for (IOThread it : ioThreads) { it.close(); } ioThreads.clear(); selectorSync.lock(); try { for (Selector selector : selectors) { if (selector != null) { selector.close(); } } selectors.clear(); } finally { selectorSync.unlock(); } // Deallocate the reaper thread object. if (reaper != null) { reaper.close(); } // Deallocate the array of mailboxes. No special work is // needed as mailboxes themselves were deallocated with their // corresponding io_thread/socket objects. termMailbox.close(); active = false; } /** * @return false if {@link #terminate()}terminate() has been called. */ public boolean isActive() { return active; } /** * @return false if {@link #terminate()}terminate() has been called. * @deprecated use {@link #isActive()} instead */ @Deprecated public boolean checkTag() { return active; } // This function is called when user invokes zmq_term. If there are // no more sockets open it'll cause all the infrastructure to be shut // down. If there are open sockets still, the deallocation happens // after the last one is closed. public void terminate() { slotSync.lock(); try { // Connect up any pending inproc connections, otherwise we will hang for (Entry<PendingConnection, String> pending : pendingConnections.entries()) { SocketBase s = createSocket(ZMQ.ZMQ_PAIR); // create_socket might fail eg: out of memory/sockets limit reached assert (s != null); s.bind(pending.getValue()); s.close(); } if (!starting.get()) { // Check whether termination was already underway, but interrupted and now // restarted. boolean restarted = terminating; terminating = true; // First attempt to terminate the context. if (!restarted) { // First send stop command to sockets so that any blocking calls // can be interrupted. If there are no sockets we can ask reaper // thread to stop. for (SocketBase socket : sockets) { socket.stop(); } if (sockets.isEmpty()) { reaper.stop(); } } } } finally { slotSync.unlock(); } if (!starting.get()) { // Wait till reaper thread closes all the sockets. Command cmd = termMailbox.recv(WAIT_FOREVER); if (cmd == null) { throw new ZMQException(errno.get()); } assert (cmd.type == Command.Type.DONE) : cmd; slotSync.lock(); try { assert (sockets.isEmpty()); } finally { slotSync.unlock(); } } // Deallocate the resources. try { destroy(); } catch (IOException e) { throw new ZError.IOException(e); } } final void shutdown() { slotSync.lock(); try { if (!starting.get() && !terminating) { terminating = true; // Send stop command to sockets so that any blocking calls // can be interrupted. If there are no sockets we can ask reaper // thread to stop. for (SocketBase socket : sockets) { socket.stop(); } if (sockets.isEmpty()) { reaper.stop(); } } } finally { slotSync.unlock(); } } public boolean set(int option, int optval) { if (option == ZMQ.ZMQ_MAX_SOCKETS && optval >= 1) { optSync.lock(); try { maxSockets = optval; } finally { optSync.unlock(); } } else if (option == ZMQ.ZMQ_IO_THREADS && optval >= 0) { optSync.lock(); try { ioThreadCount = optval; } finally { optSync.unlock(); } } else if (option == ZMQ.ZMQ_BLOCKY && optval >= 0) { optSync.lock(); try { blocky = (optval != 0); } finally { optSync.unlock(); } } else if (option == ZMQ.ZMQ_IPV6 && optval >= 0) { optSync.lock(); try { ipv6 = (optval != 0); } finally { optSync.unlock(); } } else { return false; } return true; } public int get(int option) { int rc; if (option == ZMQ.ZMQ_MAX_SOCKETS) { rc = maxSockets; } else if (option == ZMQ.ZMQ_IO_THREADS) { rc = ioThreadCount; } else if (option == ZMQ.ZMQ_BLOCKY) { rc = blocky ? 1 : 0; } else if (option == ZMQ.ZMQ_IPV6) { rc = ipv6 ? 1 : 0; } else { throw new IllegalArgumentException("option = " + option); } return rc; } public SocketBase createSocket(int type) { SocketBase s = null; slotSync.lock(); try { if (starting.compareAndSet(true, false)) { initSlots(); } // Once zmq_term() was called, we can't create new sockets. if (terminating) { throw new ZError.CtxTerminatedException(); } // If maxSockets limit was reached, return error. if (emptySlots.isEmpty()) { throw new ZMQException(ZError.EMFILE); } // Choose a slot for the socket. int slot = emptySlots.pollLast(); // Generate new unique socket ID. int sid = maxSocketId.incrementAndGet(); // Create the socket and register its mailbox. s = Sockets.create(type, this, slot, sid); if (s == null) { emptySlots.addLast(slot); return null; } sockets.add(s); slots[slot] = s.getMailbox(); } finally { slotSync.unlock(); } return s; } private void initSlots() { slotSync.lock(); try { // Initialize the array of mailboxes. Additional two slots are for // zmq_term thread and reaper thread. int ios; optSync.lock(); try { ios = ioThreadCount; slotCount = maxSockets + ioThreadCount + 2; } finally { optSync.unlock(); } slots = new IMailbox[slotCount]; // Initialize the infrastructure for zmq_term thread. slots[TERM_TID] = termMailbox; // Create the reaper thread. reaper = new Reaper(this, REAPER_TID); slots[REAPER_TID] = reaper.getMailbox(); reaper.start(); // Create I/O thread objects and launch them. for (int i = 2; i != ios + 2; i++) { IOThread ioThread = new IOThread(this, i); //alloc_assert (io_thread); ioThreads.add(ioThread); slots[i] = ioThread.getMailbox(); ioThread.start(); } // In the unused part of the slot array, create a list of empty slots. for (int i = slotCount - 1; i >= ios + 2; i--) { emptySlots.add(i); slots[i] = null; } } finally { slotSync.unlock(); } } void destroySocket(SocketBase socket) { slotSync.lock(); // Free the associated thread slot. try { int tid = socket.getTid(); emptySlots.add(tid); slots[tid] = null; // Remove the socket from the list of sockets. sockets.remove(socket); // If zmq_term() was already called and there are no more socket // we can ask reaper thread to terminate. if (terminating && sockets.isEmpty()) { reaper.stop(); } } finally { slotSync.unlock(); } } // Creates a Selector that will be closed when the context is destroyed. public Selector createSelector() { selectorSync.lock(); try { Selector selector = Selector.open(); assert (selector != null); selectors.add(selector); return selector; } catch (IOException e) { throw new ZError.IOException(e); } finally { selectorSync.unlock(); } } public boolean closeSelector(Selector selector) { selectorSync.lock(); try { boolean rc = selectors.remove(selector); if (rc) { try { selector.close(); } catch (IOException e) { throw new ZError.IOException(e); } } return rc; } finally { selectorSync.unlock(); } } // Returns reaper thread object. ZObject getReaper() { return reaper; } // Send command to the destination thread. void sendCommand(int tid, final Command command) { // System.out.println(Thread.currentThread().getName() + ": Sending command " + command); slots[tid].send(command); } // Returns the I/O thread that is the least busy at the moment. // Affinity specifies which I/O threads are eligible (0 = all). // Returns NULL if no I/O thread is available. IOThread chooseIoThread(long affinity) { if (ioThreads.isEmpty()) { return null; } // Find the I/O thread with minimum load. int minLoad = -1; IOThread selectedIoThread = null; for (int i = 0; i != ioThreads.size(); i++) { if (affinity == 0 || (affinity & (1L << i)) > 0) { int load = ioThreads.get(i).getLoad(); if (selectedIoThread == null || load < minLoad) { minLoad = load; selectedIoThread = ioThreads.get(i); } } } return selectedIoThread; } // Management of inproc endpoints. boolean registerEndpoint(String addr, Endpoint endpoint) { endpointsSync.lock(); Endpoint inserted = null; try { inserted = endpoints.put(addr, endpoint); } finally { endpointsSync.unlock(); } if (inserted != null) { return false; } return true; } boolean unregisterEndpoint(String addr, SocketBase socket) { endpointsSync.lock(); try { Endpoint endpoint = endpoints.get(addr); if (endpoint != null && socket == endpoint.socket) { endpoints.remove(addr); return true; } } finally { endpointsSync.unlock(); } return false; } void unregisterEndpoints(SocketBase socket) { endpointsSync.lock(); try { Iterator<Entry<String, Endpoint>> it = endpoints.entrySet().iterator(); while (it.hasNext()) { Entry<String, Endpoint> e = it.next(); if (e.getValue().socket == socket) { it.remove(); } } } finally { endpointsSync.unlock(); } } Endpoint findEndpoint(String addr) { Endpoint endpoint = null; endpointsSync.lock(); try { endpoint = endpoints.get(addr); if (endpoint == null) { return new Endpoint(null, new Options()); } // Increment the command sequence number of the peer so that it won't // get deallocated until "bind" command is issued by the caller. // The subsequent 'bind' has to be called with inc_seqnum parameter // set to false, so that the seqnum isn't incremented twice. endpoint.socket.incSeqnum(); } finally { endpointsSync.unlock(); } return endpoint; } void pendConnection(String addr, Endpoint endpoint, Pipe[] pipes) { PendingConnection pendingConnection = new PendingConnection(endpoint, pipes[0], pipes[1]); endpointsSync.lock(); try { Endpoint existing = endpoints.get(addr); if (existing == null) { // Still no bind. endpoint.socket.incSeqnum(); pendingConnections.insert(addr, pendingConnection); } else { // Bind has happened in the mean time, connect directly connectInprocSockets(existing.socket, existing.options, pendingConnection, Side.CONNECT); } } finally { endpointsSync.unlock(); } } void connectPending(String addr, SocketBase bindSocket) { endpointsSync.lock(); try { Collection<PendingConnection> pendings = pendingConnections.remove(addr); if (pendings != null) { for (PendingConnection pending : pendings) { connectInprocSockets(bindSocket, endpoints.get(addr).options, pending, Side.BIND); } } } finally { endpointsSync.unlock(); } } private void connectInprocSockets(SocketBase bindSocket, Options bindOptions, PendingConnection pendingConnection, Side side) { bindSocket.incSeqnum(); pendingConnection.bindPipe.setTid(bindSocket.getTid()); if (!bindOptions.recvIdentity) { Msg msg = pendingConnection.bindPipe.read(); assert (msg != null); } int sndhwm = 0; if (pendingConnection.endpoint.options.sendHwm != 0 && bindOptions.recvHwm != 0) { sndhwm = pendingConnection.endpoint.options.sendHwm + bindOptions.recvHwm; } int rcvhwm = 0; if (pendingConnection.endpoint.options.recvHwm != 0 && bindOptions.sendHwm != 0) { rcvhwm = pendingConnection.endpoint.options.recvHwm + bindOptions.sendHwm; } boolean conflate = pendingConnection.endpoint.options.conflate && (pendingConnection.endpoint.options.type == ZMQ.ZMQ_DEALER || pendingConnection.endpoint.options.type == ZMQ.ZMQ_PULL || pendingConnection.endpoint.options.type == ZMQ.ZMQ_PUSH || pendingConnection.endpoint.options.type == ZMQ.ZMQ_PUB || pendingConnection.endpoint.options.type == ZMQ.ZMQ_SUB); int[] hwms = { conflate ? -1 : sndhwm, conflate ? -1 : rcvhwm }; pendingConnection.connectPipe.setHwms(hwms[1], hwms[0]); pendingConnection.bindPipe.setHwms(hwms[0], hwms[1]); if (side == Side.BIND) { Command cmd = new Command(null, Command.Type.BIND, pendingConnection.bindPipe); bindSocket.processCommand(cmd); bindSocket.sendInprocConnected(pendingConnection.endpoint.socket); } else { pendingConnection.connectPipe.sendBind(bindSocket, pendingConnection.bindPipe, false); } // When a ctx is terminated all pending inproc connection will be // connected, but the socket will already be closed and the pipe will be // in waiting_for_delimiter state, which means no more writes can be done // and the identity write fails and causes an assert. Check if the socket // is open before sending. if (pendingConnection.endpoint.options.recvIdentity && pendingConnection.endpoint.socket.isActive()) { Msg id = new Msg(bindOptions.identitySize); id.put(bindOptions.identity, 0, bindOptions.identitySize); id.setFlags(Msg.IDENTITY); boolean written = pendingConnection.bindPipe.write(id); assert (written); pendingConnection.bindPipe.flush(); } // If set, send the hello msg of the peer to the local socket. if (bindOptions.canSendHelloMsg && bindOptions.helloMsg != null) { boolean written = pendingConnection.bindPipe.write(bindOptions.helloMsg); assert (written); pendingConnection.bindPipe.flush(); } } public Errno errno() { return errno; } /** * A channel that will forward a channel in a monitor socket. * It will be referenced by it's {@link Object#hashCode()} that can * serialized as an integer. * @param ch a channel to forward * @return the id of the channel to be forwarded */ int forwardChannel(SelectableChannel ch) { synchronized (ChannelForwardHolder.class) { if (forwardHolder == null) { forwardHolder = new ChannelForwardHolder(); } } WeakReference<SelectableChannel> ref = new WeakReference<SelectableChannel>(ch, forwardHolder.queue); forwardHolder.map.put(ch.hashCode(), ref); forwardHolder.reversemap.put(ref, ch.hashCode()); cleanForwarded(); return ch.hashCode(); } /** * Retrieve a channel, given it's hash value. As WeakReference are used, if the channel was discarded * and a GC ran, it will not be found and this method will return null. * @param id * @return */ SelectableChannel getForwardedChannel(Integer id) { try { WeakReference<SelectableChannel> ref = forwardHolder.map.get(id); if (ref != null) { return ref.get(); } else { return null; } } finally { // Done after, to avoid removing the candidate channel cleanForwarded(); } } /** * Clean all empty references */ private void cleanForwarded() { Reference<? extends SelectableChannel> ref; while ((ref = forwardHolder.queue.poll()) != null) { Integer channeldId = forwardHolder.reversemap.remove(ref); forwardHolder.map.remove(channeldId); } } }
Many problems in the way channel were forwarded in event. Was not handling concurrency, using the hashId is not a good idea.
src/main/java/zmq/Ctx.java
Many problems in the way channel were forwarded in event. Was not handling concurrency, using the hashId is not a good idea.
Java
lgpl-2.1
04f0796e897937bb3bb3a1127aaecf45cb3aceed
0
vigna/Sux4J,vigna/Sux4J,vigna/Sux4J,vigna/Sux4J
/* * Sux4J: Succinct data structures for Java * * Copyright (C) 2008-2020 Sebastiano Vigna * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. * */ package it.unimi.dsi.sux4j.bits; import static it.unimi.dsi.bits.LongArrayBitVector.bits; import static it.unimi.dsi.bits.LongArrayBitVector.word; import static it.unimi.dsi.bits.LongArrayBitVector.words; import java.io.IOException; import java.io.ObjectInputStream; import it.unimi.dsi.bits.BitVector; import it.unimi.dsi.bits.Fast; import it.unimi.dsi.bits.LongArrayBitVector; import it.unimi.dsi.fastutil.longs.LongArrays; import it.unimi.dsi.fastutil.longs.LongBigList; import it.unimi.dsi.sux4j.util.EliasFanoMonotoneLongBigList; /** A simple zero-select implementation based on a two-level inventory, a spill list and broadword bit search. * * <p>This implementation uses around 13.75% additional space on evenly distributed bit arrays, and, * under the same conditions, provide very fast selects. For very unevenly distributed arrays * the space occupancy will grow significantly, and access time might vary wildly. * * <p>An additional {@linkplain #selectZero(long, long[], int, int) bulk method} makes it possible * to select several consecutive bits at high speed, if the array is reasonably uniform. This is * the typical case when this structure is backing an {@link EliasFanoMonotoneLongBigList}. */ public class SimpleSelectZero implements SelectZero { private static final long serialVersionUID = 1L; private static final int MAX_ONES_PER_INVENTORY = 8192; private static final int MAX_LOG2_LONGWORDS_PER_SUBINVENTORY = 3; /** The maximum size of span to qualify for a subinventory made of 16-bit offsets. */ private static final int MAX_SPAN = (1 << 16); /** The underlying bit vector. */ private final BitVector bitVector; /** The number of ones in {@link #bitVector}. */ private final long numOnes; /** The number of words in {@link #bitVector}. */ private final int numWords; /** The cached result of {@link BitVector#bits() bitVector.bits()}. */ private transient long[] bits; /** The first-level inventory containing information about one bit each {@link #onesPerInventory}. * If the entry is nonnegative, it is the rank of the bit and subsequent information is recorded in {@link #subinventory16} * as offsets of one bit each {@link #onesPerSub16} (then, sequential search is necessary). Otherwise, a negative value * means that offsets are too large and they have been recorded as 64-bit values. If {@link #onesPerSub64} is 1, then offsets are directly stored * into {@link #subinventory}. Otherwise, the first {@link #subinventory} entry is actually a pointer to {@link #exactSpill}, * where the offsets can be found. */ private final long[] inventory; /** The logarithm of the number of ones per {@link #inventory} entry. */ private final int log2OnesPerInventory; /** The number of ones per {@link #inventory} entry. */ private final int onesPerInventory; /** The mask associated to the number of ones per {@link #inventory} entry. */ private final int onesPerInventoryMask; /** The second-level inventory (records the offset of each bit w.r.t. the first-level inventory). */ private final long[] subinventory; /** Exposes {@link #subinventory} as a list of 16-bits positive integers. */ private transient LongBigList subinventory16; /** The logarithm of the number of longwords used in the part of the subinventory associated to an inventory entry. */ private final int log2LongwordsPerSubinventory; /** The logarithm of the number of ones for each {@link #subinventory} longword. */ private final int log2OnesPerSub64; /** The number of ones for each {@link #subinventory} longword. */ private final int onesPerSub64; /** The logarithm of the number of ones for each {@link #subinventory} short. */ private final int log2OnesPerSub16; /** The number of ones for each {@link #subinventory} short. */ private final int onesPerSub16; /** The mask associated to number of ones for each {@link #subinventory} short. */ private final int onesPerSub16Mask; /** The list of exact spills. */ private final long[] exactSpill; /** Creates a new selection structure using a bit vector specified by an array of longs and a number of bits. * * @param bits an array of longs representing a bit array. * @param length the number of bits to use from <code>bits</code>. */ public SimpleSelectZero(final long[] bits, final long length) { this(LongArrayBitVector.wrap(bits, length)); } /** Creates a new selection structure using the specified bit vector. * * @param bitVector a bit vector. */ public SimpleSelectZero(final BitVector bitVector) { this.bitVector = bitVector; this.bits = bitVector.bits(); final long length = bitVector.length(); numWords = words(length); // We compute quickly the number of ones (possibly counting spurious bits in the last word). long d = 0; for(int i = numWords; i-- != 0;) d += Long.bitCount(~bits[i]); onesPerInventory = 1 << (log2OnesPerInventory = Fast.mostSignificantBit(length == 0 ? 1 : (int)((d * MAX_ONES_PER_INVENTORY + length - 1) / length))); onesPerInventoryMask = onesPerInventory - 1; final int inventorySize = (int)((d + onesPerInventory - 1) / onesPerInventory); inventory = new long[inventorySize + 1]; final int numWords = this.numWords; final long[] bits = this.bits; final long[] inventory = this.inventory; final int log2OnesPerInventory = this.log2OnesPerInventory; final int onesPerInventoryMask = this.onesPerInventoryMask; // First phase: we build an inventory for each one out of onesPerInventory. d = 0; for(int i = 0; i < numWords; i++) for (int j = 0; j < Long.SIZE; j++) { if (bits(i) + j >= length) break; if ((~bits[i] & 1L << j) != 0) { if ((d & onesPerInventoryMask) == 0) inventory[(int)(d >>> log2OnesPerInventory)] = bits(i) + j; d++; } } numOnes = d; inventory[inventorySize] = length; log2LongwordsPerSubinventory = Math.min(MAX_LOG2_LONGWORDS_PER_SUBINVENTORY, Math.max(0, log2OnesPerInventory - 2)); log2OnesPerSub64 = Math.max(0, log2OnesPerInventory - log2LongwordsPerSubinventory); log2OnesPerSub16 = Math.max(0, log2OnesPerSub64 - 2); onesPerSub64 = (1 << log2OnesPerSub64); onesPerSub16 = (1 << log2OnesPerSub16); onesPerSub16Mask = onesPerSub16 - 1; final long numOnes = this.numOnes; final int onesPerInventory = this.onesPerInventory; final int onesPerSub16 = this.onesPerSub16; final int log2OnesPerSub16 = this.log2OnesPerSub16; final int onesPerSub64 = this.onesPerSub64; if (onesPerInventory > 1) { d = 0; int ones; long diff16 = 0, start = 0, span = 0; int spilled = 0, inventoryIndex = 0; for(int i = 0; i < numWords; i++) // We estimate the subinventory and exact spill size for (int j = 0; j < Long.SIZE; j++) { if (bits(i) + j >= length) break; if ((~bits[i] & 1L << j) != 0) { if ((d & onesPerInventoryMask) == 0) { inventoryIndex = (int)(d >>> log2OnesPerInventory); start = inventory[inventoryIndex]; span = inventory[inventoryIndex + 1] - start; ones = (int)Math.min(numOnes - d, onesPerInventory); // We must always count (possibly unused) diff16's. And we cannot store less then 4 diff16. diff16 += Math.max(4, (ones + onesPerSub16 - 1) >>> log2OnesPerSub16); if (span >= MAX_SPAN && onesPerSub64 > 1) spilled += ones; } d++; } } final int subinventorySize = (int)((diff16 + 3) >> 2); final int exactSpillSize = spilled; subinventory = new long[subinventorySize]; exactSpill = new long[exactSpillSize]; subinventory16 = LongArrayBitVector.wrap(subinventory).asLongBigList(Short.SIZE); int offset = 0; spilled = 0; d = 0; final int onesPerSub16Mask = this.onesPerSub16Mask; final int log2LongwordsPerSubinventory = this.log2LongwordsPerSubinventory; final long[] subinventory = this.subinventory; final LongBigList subinventory16 = this.subinventory16; for(int i = 0; i < numWords; i++) for (int j = 0; j < Long.SIZE; j++) { if (bits(i) + j >= length) break; if ((~bits[i] & 1L << j) != 0) { if ((d & onesPerInventoryMask) == 0) { inventoryIndex = (int)(d >>> log2OnesPerInventory); start = inventory[inventoryIndex]; span = inventory[inventoryIndex + 1] - start; offset = 0; } if (span < MAX_SPAN) { assert bits(i) + j - start <= MAX_SPAN; if ((d & onesPerSub16Mask) == 0) { subinventory16.set((inventoryIndex << log2LongwordsPerSubinventory + 2) + offset++, bits(i) + j - start); } } else { assert onesPerSub64 > 1; if ((d & onesPerInventoryMask) == 0) { inventory[inventoryIndex] |= 1L << 63; subinventory[inventoryIndex << log2LongwordsPerSubinventory] = spilled; } exactSpill[spilled++] = bits(i) + j; } d++; } } } else { subinventory = exactSpill = LongArrays.EMPTY_ARRAY; subinventory16 = null; } } @Override public long selectZero(final long rank) { assert rank >= 0; assert rank < numOnes; final int inventoryIndex = (int)(rank >>> log2OnesPerInventory); final long inventoryRank = inventory[inventoryIndex]; final int subrank = (int)(rank & onesPerInventoryMask); if (subrank == 0) return inventoryRank & ~(1L << 63); long start; int residual; if (inventoryRank >= 0) { final int index16 = (inventoryIndex << log2LongwordsPerSubinventory + 2) + (subrank >>> log2OnesPerSub16); start = inventoryRank + ((subinventory[index16 >>> 2] >>> ((index16 & 3) << 4) & 0xFFFF)); residual = subrank & onesPerSub16Mask; } else { assert onesPerSub64 > 1; return exactSpill[(int)(subinventory[inventoryIndex << log2LongwordsPerSubinventory] + subrank)]; } if (residual == 0) return start; final long bits[] = this.bits; int wordIndex = word(start); long word = ~bits[wordIndex] & -1L << start; for(;;) { final int bitCount = Long.bitCount(word); if (residual < bitCount) break; word = ~bits[++wordIndex]; residual -= bitCount; } return bits(wordIndex) + Fast.select(word, residual); } /** * Performs a bulk select of consecutive ranks into a given array fragment. * * <p> * <strong>Warning</strong>: form Sux4J 5.1.5, {@code dest} must be of length greater than * {@code offset} even if {@code length} is zero. * * @param rank the first rank to select. * @param dest the destination array; it will be filled with {@code length} positions of consecutive * bits starting at position {@code offset}; must be of length greater than * {@code offset}. * @param offset the first bit position written in {@code dest}. * @param length the number of bit positions in {@code dest} starting at {@code offset}. * @return {@code dest} * @see #selectZero(long, long[]) */ public long[] selectZero(final long rank, final long[] dest, int offset, final int length) { assert rank >= 0; assert rank < numOnes; assert offset >= 0; assert dest != null; assert offset < dest.length; assert length >= 0; assert offset + length <= dest.length; final long s = selectZero(rank); dest[offset] = s; int curr = word(s); final long[] bits = this.bits; long window = ~bits[curr] & -1L << s; window &= window - 1; for(int i = 1; i < length; i++) { while(window == 0) window = ~bits[++curr]; dest[++offset] = bits(curr) + Long.numberOfTrailingZeros(window); window &= window - 1; } return dest; } /** * Performs a bulk select of consecutive ranks into a given array. * * <p> * <strong>Warning</strong>: from Sux4J 5.1.5, {@code dest} must be of length greater than zero. * * @param rank the first rank to select. * @param dest the destination array; it will be filled with position of consecutive bits; must be * of length greater than zero. * @return {@code dest} * @see #selectZero(long, long[], int, int) */ public long[] selectZero(final long rank, final long[] dest) { assert rank >= 0; assert rank < numOnes; assert dest != null; assert dest.length > 0; return selectZero(rank, dest, 0, dest.length); } private void readObject(final ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); subinventory16 = LongArrayBitVector.wrap(subinventory).asLongBigList(Short.SIZE); bits = bitVector.bits(); } @Override public long numBits() { return bits(inventory.length) + bits(subinventory.length) + bits(exactSpill.length); } @Override public BitVector bitVector() { return bitVector; } }
src/it/unimi/dsi/sux4j/bits/SimpleSelectZero.java
/* * Sux4J: Succinct data structures for Java * * Copyright (C) 2008-2020 Sebastiano Vigna * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. * */ package it.unimi.dsi.sux4j.bits; import static it.unimi.dsi.bits.LongArrayBitVector.bits; import static it.unimi.dsi.bits.LongArrayBitVector.word; import static it.unimi.dsi.bits.LongArrayBitVector.words; import java.io.IOException; import java.io.ObjectInputStream; import it.unimi.dsi.bits.BitVector; import it.unimi.dsi.bits.Fast; import it.unimi.dsi.bits.LongArrayBitVector; import it.unimi.dsi.fastutil.longs.LongArrays; import it.unimi.dsi.fastutil.longs.LongBigList; import it.unimi.dsi.sux4j.util.EliasFanoMonotoneLongBigList; /** A simple zero-select implementation based on a two-level inventory, a spill list and broadword bit search. * * <p>This implementation uses around 13.75% additional space on evenly distributed bit arrays, and, * under the same conditions, provide very fast selects. For very unevenly distributed arrays * the space occupancy will grow significantly, and access time might vary wildly. * * <p>An additional {@linkplain #selectZero(long, long[], int, int) bulk method} makes it possible * to select several consecutive bits at high speed, if the array is reasonably uniform. This is * the typical case when this structure is backing an {@link EliasFanoMonotoneLongBigList}. */ public class SimpleSelectZero implements SelectZero { private static final long serialVersionUID = 1L; private static final int MAX_ONES_PER_INVENTORY = 8192; private static final int MAX_LOG2_LONGWORDS_PER_SUBINVENTORY = 3; /** The maximum size of span to qualify for a subinventory made of 16-bit offsets. */ private static final int MAX_SPAN = (1 << 16); /** The underlying bit vector. */ private final BitVector bitVector; /** The number of ones in {@link #bitVector}. */ private final long numOnes; /** The number of words in {@link #bitVector}. */ private final int numWords; /** The cached result of {@link BitVector#bits() bitVector.bits()}. */ private transient long[] bits; /** The first-level inventory containing information about one bit each {@link #onesPerInventory}. * If the entry is nonnegative, it is the rank of the bit and subsequent information is recorded in {@link #subinventory16} * as offsets of one bit each {@link #onesPerSub16} (then, sequential search is necessary). Otherwise, a negative value * means that offsets are too large and they have been recorded as 64-bit values. If {@link #onesPerSub64} is 1, then offsets are directly stored * into {@link #subinventory}. Otherwise, the first {@link #subinventory} entry is actually a pointer to {@link #exactSpill}, * where the offsets can be found. */ private final long[] inventory; /** The logarithm of the number of ones per {@link #inventory} entry. */ private final int log2OnesPerInventory; /** The number of ones per {@link #inventory} entry. */ private final int onesPerInventory; /** The mask associated to the number of ones per {@link #inventory} entry. */ private final int onesPerInventoryMask; /** The second-level inventory (records the offset of each bit w.r.t. the first-level inventory). */ private final long[] subinventory; /** Exposes {@link #subinventory} as a list of 16-bits positive integers. */ private transient LongBigList subinventory16; /** The logarithm of the number of longwords used in the part of the subinventory associated to an inventory entry. */ private final int log2LongwordsPerSubinventory; /** The logarithm of the number of ones for each {@link #subinventory} longword. */ private final int log2OnesPerSub64; /** The number of ones for each {@link #subinventory} longword. */ private final int onesPerSub64; /** The logarithm of the number of ones for each {@link #subinventory} short. */ private final int log2OnesPerSub16; /** The number of ones for each {@link #subinventory} short. */ private final int onesPerSub16; /** The mask associated to number of ones for each {@link #subinventory} short. */ private final int onesPerSub16Mask; /** The list of exact spills. */ private final long[] exactSpill; /** Creates a new selection structure using a bit vector specified by an array of longs and a number of bits. * * @param bits an array of longs representing a bit array. * @param length the number of bits to use from <code>bits</code>. */ public SimpleSelectZero(final long[] bits, final long length) { this(LongArrayBitVector.wrap(bits, length)); } /** Creates a new selection structure using the specified bit vector. * * @param bitVector a bit vector. */ public SimpleSelectZero(final BitVector bitVector) { this.bitVector = bitVector; this.bits = bitVector.bits(); final long length = bitVector.length(); numWords = words(length); // We compute quickly the number of ones (possibly counting spurious bits in the last word). long d = 0; for(int i = numWords; i-- != 0;) d += Long.bitCount(~bits[i]); onesPerInventory = 1 << (log2OnesPerInventory = Fast.mostSignificantBit(length == 0 ? 1 : (int)((d * MAX_ONES_PER_INVENTORY + length - 1) / length))); onesPerInventoryMask = onesPerInventory - 1; final int inventorySize = (int)((d + onesPerInventory - 1) / onesPerInventory); inventory = new long[inventorySize + 1]; final int numWords = this.numWords; final long[] bits = this.bits; final long[] inventory = this.inventory; final int log2OnesPerInventory = this.log2OnesPerInventory; final int onesPerInventoryMask = this.onesPerInventoryMask; // First phase: we build an inventory for each one out of onesPerInventory. d = 0; for(int i = 0; i < numWords; i++) for (int j = 0; j < Long.SIZE; j++) { if (bits(i) + j >= length) break; if ((~bits[i] & 1L << j) != 0) { if ((d & onesPerInventoryMask) == 0) inventory[(int)(d >>> log2OnesPerInventory)] = bits(i) + j; d++; } } numOnes = d; inventory[inventorySize] = length; log2LongwordsPerSubinventory = Math.min(MAX_LOG2_LONGWORDS_PER_SUBINVENTORY, Math.max(0, log2OnesPerInventory - 2)); log2OnesPerSub64 = Math.max(0, log2OnesPerInventory - log2LongwordsPerSubinventory); log2OnesPerSub16 = Math.max(0, log2OnesPerSub64 - 2); onesPerSub64 = (1 << log2OnesPerSub64); onesPerSub16 = (1 << log2OnesPerSub16); onesPerSub16Mask = onesPerSub16 - 1; final long numOnes = this.numOnes; final int onesPerInventory = this.onesPerInventory; final int onesPerSub16 = this.onesPerSub16; final int log2OnesPerSub16 = this.log2OnesPerSub16; final int onesPerSub64 = this.onesPerSub64; if (onesPerInventory > 1) { d = 0; int ones; long diff16 = 0, start = 0, span = 0; int spilled = 0, inventoryIndex = 0; for(int i = 0; i < numWords; i++) // We estimate the subinventory and exact spill size for (int j = 0; j < Long.SIZE; j++) { if (bits(i) + j >= length) break; if ((~bits[i] & 1L << j) != 0) { if ((d & onesPerInventoryMask) == 0) { inventoryIndex = (int)(d >>> log2OnesPerInventory); start = inventory[inventoryIndex]; span = inventory[inventoryIndex + 1] - start; ones = (int)Math.min(numOnes - d, onesPerInventory); // We must always count (possibly unused) diff16's. And we cannot store less then 4 diff16. diff16 += Math.max(4, (ones + onesPerSub16 - 1) >>> log2OnesPerSub16); if (span >= MAX_SPAN && onesPerSub64 > 1) spilled += ones; } d++; } } final int subinventorySize = (int)((diff16 + 3) >> 2); final int exactSpillSize = spilled; subinventory = new long[subinventorySize]; exactSpill = new long[exactSpillSize]; subinventory16 = LongArrayBitVector.wrap(subinventory).asLongBigList(Short.SIZE); int offset = 0; spilled = 0; d = 0; final int onesPerSub16Mask = this.onesPerSub16Mask; final int log2LongwordsPerSubinventory = this.log2LongwordsPerSubinventory; final long[] subinventory = this.subinventory; final LongBigList subinventory16 = this.subinventory16; for(int i = 0; i < numWords; i++) for (int j = 0; j < Long.SIZE; j++) { if (bits(i) + j >= length) break; if ((~bits[i] & 1L << j) != 0) { if ((d & onesPerInventoryMask) == 0) { inventoryIndex = (int)(d >>> log2OnesPerInventory); start = inventory[inventoryIndex]; span = inventory[inventoryIndex + 1] - start; offset = 0; } if (span < MAX_SPAN) { assert bits(i) + j - start <= MAX_SPAN; if ((d & onesPerSub16Mask) == 0) { subinventory16.set((inventoryIndex << log2LongwordsPerSubinventory + 2) + offset++, bits(i) + j - start); } } else { assert onesPerSub64 > 1; if ((d & onesPerInventoryMask) == 0) { inventory[inventoryIndex] |= 1L << 63; subinventory[inventoryIndex << log2LongwordsPerSubinventory] = spilled; } exactSpill[spilled++] = bits(i) + j; } d++; } } } else { subinventory = exactSpill = LongArrays.EMPTY_ARRAY; subinventory16 = null; } } @Override public long selectZero(final long rank) { assert rank >= 0; assert rank < numOnes; final int inventoryIndex = (int)(rank >>> log2OnesPerInventory); final long inventoryRank = inventory[inventoryIndex]; final int subrank = (int)(rank & onesPerInventoryMask); if (subrank == 0) return inventoryRank & ~(1L << 63); long start; int residual; if (inventoryRank >= 0) { final int index16 = (inventoryIndex << log2LongwordsPerSubinventory + 2) + (subrank >>> log2OnesPerSub16); start = inventoryRank + ((subinventory[index16 >>> 2] >>> ((index16 & 3) << 4) & 0xFFFF)); residual = subrank & onesPerSub16Mask; } else { assert onesPerSub64 > 1; return exactSpill[(int)(subinventory[inventoryIndex << log2LongwordsPerSubinventory] + subrank)]; } if (residual == 0) return start; final long bits[] = this.bits; int wordIndex = word(start); long word = ~bits[wordIndex] & -1L << start; for(;;) { final int bitCount = Long.bitCount(word); if (residual < bitCount) break; word = ~bits[++wordIndex]; residual -= bitCount; } return bits(wordIndex) + Fast.select(word, residual); } /** * Performs a bulk select of consecutive ranks into a given array fragment. * * <p> * <strong>Warning</strong>: form Sux4J 5.1.5, {@code dest} must be of length greater than * {@code offset} even if {@code length} is zero. * * @param rank the first rank to select. * @param dest the destination array; it will be filled with {@code length} positions of consecutive * bits starting at position {@code offset}; must be of length greater than * {@code offset}. * @param offset the first bit position written in {@code dest}. * @param length the number of bit positions in {@code dest} starting at {@code offset}. * @return {@code dest} * @see #selectZero(long, long[]) */ public long[] selectZero(final long rank, final long[] dest, int offset, final int length) { assert dest.length > 0; final long s = selectZero(rank); dest[offset] = s; int curr = word(s); long window = ~bits[curr] & -1L << s; window &= window - 1; for(int i = 1; i < length; i++) { while(window == 0) window = ~bits[++curr]; dest[++offset] = bits(curr) + Long.numberOfTrailingZeros(window); window &= window - 1; } return dest; } /** * Performs a bulk select of consecutive ranks into a given array. * * <p> * <strong>Warning</strong>: from Sux4J 5.1.5, {@code dest} must be of length greater than zero. * * @param rank the first rank to select. * @param dest the destination array; it will be filled with position of consecutive bits; must be * of length greater than zero. * @return {@code dest} * @see #selectZero(long, long[], int, int) */ public long[] selectZero(final long rank, final long[] dest) { return selectZero(rank, dest, 0, dest.length); } private void readObject(final ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); subinventory16 = LongArrayBitVector.wrap(subinventory).asLongBigList(Short.SIZE); bits = bitVector.bits(); } @Override public long numBits() { return bits(inventory.length) + bits(subinventory.length) + bits(exactSpill.length); } @Override public BitVector bitVector() { return bitVector; } }
Regenerated SimpleSelectZero
src/it/unimi/dsi/sux4j/bits/SimpleSelectZero.java
Regenerated SimpleSelectZero
Java
unlicense
7125aed07685ddc1af8ddeec6742ec6015626d62
0
bodydomelight/tij-problems
package test.chessboardcoverage; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class CoverageFinder { private List<String> paths = new ArrayList<>(); private PieceStrategy piece; private boolean[][] chessboard; private StringBuilder path = new StringBuilder(); private long numberFound = 0; public CoverageFinder(PieceStrategy p) { piece = p; chessboard = new boolean[p.getBoard().getWidth()][p.getBoard().getHeight()]; } private boolean noEmptySquares() { for (boolean[] row : chessboard) { for (boolean square : row) { if (!square) { return false; } } } return true; } private boolean hasBeenVisited(Position p) { return chessboard[p.getX()][p.getY()]; } private List<Position> getNextValidMoves(Position p) { List<Position> validMoves = piece.getPositions(p); Iterator<Position> it = validMoves.iterator(); Position pos; while (it.hasNext()) { pos = it.next(); if (hasBeenVisited(pos)) { it.remove(); } } return validMoves; } private void findPath(Position p) { chessboard[p.getX()][p.getY()] = true; path.append(p.toString()).append("-"); List<Position> nextPositions = getNextValidMoves(p); if (nextPositions.isEmpty()) { if (noEmptySquares()) { System.out.println("path " + (++numberFound) + ": " + path.substring(0, path.length() - 1)); paths.add(path.toString()); } } else { for (Position pos : nextPositions) { findPath(pos); } } chessboard[p.getX()][p.getY()] = false; path.delete(path.length() - 3, path.length()); } public List<String> getPaths(Position start) { findPath(start); return paths; } public static void main(String[] args) { //test Chessboard b = new Chessboard(7, 7); CoverageFinder cf = new CoverageFinder(new Horse(b)); List<String> list = cf.getPaths(new Position(b, 'a', 1)); System.out.println("list " + list.size()); } }
src/test/chessboardcoverage/CoverageFinder.java
package test.chessboardcoverage; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class CoverageFinder { private List<String> paths = new ArrayList<>(); private PieceStrategy piece; private boolean[][] chessboard; private StringBuilder path = new StringBuilder(); private long numberFound = 0; public CoverageFinder(PieceStrategy p) { piece = p; chessboard = new boolean[p.getBoard().getWidth()][p.getBoard().getHeight()]; } private boolean noEmptySquares() { for (boolean[] row : chessboard) { for (boolean square : row) { if (!square) { return false; } } } return true; } private boolean hasBeenVisited(Position p) { return chessboard[p.getX()][p.getY()]; } private List<Position> getNextValidMoves(Position p) { List<Position> validMoves = piece.getPositions(p); Iterator<Position> it = validMoves.iterator(); Position pos; while (it.hasNext()) { pos = it.next(); if (hasBeenVisited(pos)) { it.remove(); } } return validMoves; } private void findPath(Position p) { chessboard[p.getX()][p.getY()] = true; path.append(p.toString()).append("-"); List<Position> nextPositions = getNextValidMoves(p); if (nextPositions.isEmpty()) { if (noEmptySquares()) { System.out.println("path " + (++numberFound) + ": " + path.substring(0, path.length() - 1)); paths.add(path.toString()); } } else { for (Position pos : nextPositions) { findPath(pos); } } chessboard[p.getX()][p.getY()] = false; path.delete(path.length() - 3, path.length()); } public List<String> getPaths(Position start) { findPath(start); return paths; } public static void main(String[] args) { //test Chessboard b = new Chessboard(6, 6); CoverageFinder cf = new CoverageFinder(new Horse(b)); List<String> list = cf.getPaths(new Position(b, 'a', 3)); System.out.println("list " + list.size()); } }
knight's tour test
src/test/chessboardcoverage/CoverageFinder.java
knight's tour test
Java
apache-2.0
2e4508e11e0b6d8a4634dff159a8ce3e50c133ca
0
stickyd/libgdx,xpenatan/libgdx-LWJGL3,anserran/libgdx,designcrumble/libgdx,Senth/libgdx,toloudis/libgdx,MetSystem/libgdx,libgdx/libgdx,PedroRomanoBarbosa/libgdx,nave966/libgdx,del-sol/libgdx,gouessej/libgdx,del-sol/libgdx,JFixby/libgdx,realitix/libgdx,JDReutt/libgdx,JDReutt/libgdx,flaiker/libgdx,1yvT0s/libgdx,snovak/libgdx,samskivert/libgdx,kagehak/libgdx,junkdog/libgdx,thepullman/libgdx,xpenatan/libgdx-LWJGL3,tell10glu/libgdx,firefly2442/libgdx,nudelchef/libgdx,josephknight/libgdx,SidneyXu/libgdx,revo09/libgdx,anserran/libgdx,FredGithub/libgdx,Xhanim/libgdx,BlueRiverInteractive/libgdx,designcrumble/libgdx,shiweihappy/libgdx,UnluckyNinja/libgdx,KrisLee/libgdx,jasonwee/libgdx,luischavez/libgdx,tommyettinger/libgdx,copystudy/libgdx,SidneyXu/libgdx,Xhanim/libgdx,nelsonsilva/libgdx,JDReutt/libgdx,bgroenks96/libgdx,saltares/libgdx,saqsun/libgdx,sjosegarcia/libgdx,czyzby/libgdx,bgroenks96/libgdx,Badazdz/libgdx,Wisienkas/libgdx,ricardorigodon/libgdx,tommycli/libgdx,libgdx/libgdx,ThiagoGarciaAlves/libgdx,codepoke/libgdx,zommuter/libgdx,ztv/libgdx,youprofit/libgdx,MikkelTAndersen/libgdx,jsjolund/libgdx,FredGithub/libgdx,antag99/libgdx,Badazdz/libgdx,Wisienkas/libgdx,bgroenks96/libgdx,jsjolund/libgdx,titovmaxim/libgdx,nrallakis/libgdx,copystudy/libgdx,curtiszimmerman/libgdx,JDReutt/libgdx,czyzby/libgdx,jsjolund/libgdx,curtiszimmerman/libgdx,TheAks999/libgdx,kotcrab/libgdx,shiweihappy/libgdx,ya7lelkom/libgdx,PedroRomanoBarbosa/libgdx,Gliby/libgdx,MikkelTAndersen/libgdx,antag99/libgdx,gouessej/libgdx,flaiker/libgdx,SidneyXu/libgdx,petugez/libgdx,katiepino/libgdx,bladecoder/libgdx,firefly2442/libgdx,tell10glu/libgdx,FredGithub/libgdx,FyiurAmron/libgdx,nelsonsilva/libgdx,fwolff/libgdx,stinsonga/libgdx,xranby/libgdx,nudelchef/libgdx,mumer92/libgdx,fwolff/libgdx,del-sol/libgdx,designcrumble/libgdx,haedri/libgdx-1,Deftwun/libgdx,NathanSweet/libgdx,junkdog/libgdx,PedroRomanoBarbosa/libgdx,gdos/libgdx,saltares/libgdx,fwolff/libgdx,EsikAntony/libgdx,ricardorigodon/libgdx,bsmr-java/libgdx,jsjolund/libgdx,sjosegarcia/libgdx,MadcowD/libgdx,srwonka/libGdx,sarkanyi/libgdx,kotcrab/libgdx,shiweihappy/libgdx,xranby/libgdx,js78/libgdx,junkdog/libgdx,TheAks999/libgdx,flaiker/libgdx,gf11speed/libgdx,tommycli/libgdx,xpenatan/libgdx-LWJGL3,fwolff/libgdx,saqsun/libgdx,djom20/libgdx,revo09/libgdx,samskivert/libgdx,MovingBlocks/libgdx,czyzby/libgdx,azakhary/libgdx,fwolff/libgdx,snovak/libgdx,Heart2009/libgdx,mumer92/libgdx,NathanSweet/libgdx,gf11speed/libgdx,kagehak/libgdx,yangweigbh/libgdx,ricardorigodon/libgdx,thepullman/libgdx,realitix/libgdx,youprofit/libgdx,czyzby/libgdx,collinsmith/libgdx,petugez/libgdx,ninoalma/libgdx,alex-dorokhov/libgdx,Dzamir/libgdx,xoppa/libgdx,flaiker/libgdx,nudelchef/libgdx,1yvT0s/libgdx,MadcowD/libgdx,Xhanim/libgdx,firefly2442/libgdx,js78/libgdx,fiesensee/libgdx,alireza-hosseini/libgdx,haedri/libgdx-1,UnluckyNinja/libgdx,noelsison2/libgdx,MikkelTAndersen/libgdx,andyvand/libgdx,MovingBlocks/libgdx,MetSystem/libgdx,antag99/libgdx,Senth/libgdx,saltares/libgdx,MetSystem/libgdx,yangweigbh/libgdx,Heart2009/libgdx,SidneyXu/libgdx,jasonwee/libgdx,nudelchef/libgdx,tommycli/libgdx,noelsison2/libgdx,stickyd/libgdx,cypherdare/libgdx,saltares/libgdx,ztv/libgdx,309746069/libgdx,noelsison2/libgdx,gdos/libgdx,revo09/libgdx,Wisienkas/libgdx,ttencate/libgdx,realitix/libgdx,kagehak/libgdx,kotcrab/libgdx,stickyd/libgdx,Gliby/libgdx,Dzamir/libgdx,MadcowD/libgdx,curtiszimmerman/libgdx,mumer92/libgdx,UnluckyNinja/libgdx,Gliby/libgdx,jasonwee/libgdx,andyvand/libgdx,designcrumble/libgdx,fiesensee/libgdx,BlueRiverInteractive/libgdx,youprofit/libgdx,xranby/libgdx,junkdog/libgdx,copystudy/libgdx,bsmr-java/libgdx,309746069/libgdx,revo09/libgdx,309746069/libgdx,luischavez/libgdx,czyzby/libgdx,Thotep/libgdx,alex-dorokhov/libgdx,josephknight/libgdx,designcrumble/libgdx,ya7lelkom/libgdx,309746069/libgdx,katiepino/libgdx,Gliby/libgdx,Heart2009/libgdx,czyzby/libgdx,alex-dorokhov/libgdx,josephknight/libgdx,Senth/libgdx,srwonka/libGdx,josephknight/libgdx,youprofit/libgdx,shiweihappy/libgdx,MetSystem/libgdx,fiesensee/libgdx,gdos/libgdx,shiweihappy/libgdx,JFixby/libgdx,Wisienkas/libgdx,samskivert/libgdx,toloudis/libgdx,alex-dorokhov/libgdx,alireza-hosseini/libgdx,youprofit/libgdx,srwonka/libGdx,Badazdz/libgdx,hyvas/libgdx,katiepino/libgdx,davebaol/libgdx,del-sol/libgdx,MetSystem/libgdx,MovingBlocks/libgdx,js78/libgdx,ricardorigodon/libgdx,GreenLightning/libgdx,copystudy/libgdx,PedroRomanoBarbosa/libgdx,Dzamir/libgdx,mumer92/libgdx,codepoke/libgdx,fiesensee/libgdx,jberberick/libgdx,Wisienkas/libgdx,noelsison2/libgdx,designcrumble/libgdx,Thotep/libgdx,stinsonga/libgdx,cypherdare/libgdx,noelsison2/libgdx,fiesensee/libgdx,titovmaxim/libgdx,jasonwee/libgdx,gouessej/libgdx,flaiker/libgdx,davebaol/libgdx,billgame/libgdx,hyvas/libgdx,gouessej/libgdx,KrisLee/libgdx,petugez/libgdx,EsikAntony/libgdx,Dzamir/libgdx,stickyd/libgdx,fiesensee/libgdx,kagehak/libgdx,Senth/libgdx,yangweigbh/libgdx,alex-dorokhov/libgdx,Heart2009/libgdx,mumer92/libgdx,EsikAntony/libgdx,gdos/libgdx,petugez/libgdx,alex-dorokhov/libgdx,BlueRiverInteractive/libgdx,toa5/libgdx,EsikAntony/libgdx,zhimaijoy/libgdx,codepoke/libgdx,xpenatan/libgdx-LWJGL3,davebaol/libgdx,thepullman/libgdx,del-sol/libgdx,titovmaxim/libgdx,luischavez/libgdx,revo09/libgdx,BlueRiverInteractive/libgdx,yangweigbh/libgdx,copystudy/libgdx,TheAks999/libgdx,petugez/libgdx,JDReutt/libgdx,srwonka/libGdx,cypherdare/libgdx,bsmr-java/libgdx,gouessej/libgdx,JDReutt/libgdx,antag99/libgdx,MadcowD/libgdx,hyvas/libgdx,1yvT0s/libgdx,flaiker/libgdx,kotcrab/libgdx,MovingBlocks/libgdx,fwolff/libgdx,zommuter/libgdx,nelsonsilva/libgdx,ttencate/libgdx,ricardorigodon/libgdx,309746069/libgdx,anserran/libgdx,saqsun/libgdx,davebaol/libgdx,luischavez/libgdx,copystudy/libgdx,bsmr-java/libgdx,zhimaijoy/libgdx,Senth/libgdx,andyvand/libgdx,anserran/libgdx,tommyettinger/libgdx,xoppa/libgdx,JFixby/libgdx,mumer92/libgdx,nave966/libgdx,TheAks999/libgdx,billgame/libgdx,BlueRiverInteractive/libgdx,flaiker/libgdx,tell10glu/libgdx,tommycli/libgdx,Badazdz/libgdx,toa5/libgdx,codepoke/libgdx,realitix/libgdx,Gliby/libgdx,junkdog/libgdx,nrallakis/libgdx,petugez/libgdx,kotcrab/libgdx,cypherdare/libgdx,GreenLightning/libgdx,ricardorigodon/libgdx,MadcowD/libgdx,FredGithub/libgdx,noelsison2/libgdx,titovmaxim/libgdx,tell10glu/libgdx,MadcowD/libgdx,MetSystem/libgdx,KrisLee/libgdx,gdos/libgdx,ninoalma/libgdx,saqsun/libgdx,stinsonga/libgdx,andyvand/libgdx,andyvand/libgdx,snovak/libgdx,haedri/libgdx-1,davebaol/libgdx,nelsonsilva/libgdx,xoppa/libgdx,1yvT0s/libgdx,FyiurAmron/libgdx,flaiker/libgdx,alex-dorokhov/libgdx,Zonglin-Li6565/libgdx,ttencate/libgdx,gouessej/libgdx,Deftwun/libgdx,Deftwun/libgdx,js78/libgdx,hyvas/libgdx,xranby/libgdx,djom20/libgdx,jberberick/libgdx,alireza-hosseini/libgdx,haedri/libgdx-1,andyvand/libgdx,zommuter/libgdx,yangweigbh/libgdx,samskivert/libgdx,Dzamir/libgdx,xpenatan/libgdx-LWJGL3,saltares/libgdx,1yvT0s/libgdx,kagehak/libgdx,gf11speed/libgdx,snovak/libgdx,billgame/libgdx,Xhanim/libgdx,noelsison2/libgdx,MetSystem/libgdx,FredGithub/libgdx,revo09/libgdx,gf11speed/libgdx,bgroenks96/libgdx,MikkelTAndersen/libgdx,BlueRiverInteractive/libgdx,nave966/libgdx,jsjolund/libgdx,haedri/libgdx-1,curtiszimmerman/libgdx,djom20/libgdx,collinsmith/libgdx,stinsonga/libgdx,TheAks999/libgdx,codepoke/libgdx,PedroRomanoBarbosa/libgdx,EsikAntony/libgdx,curtiszimmerman/libgdx,hyvas/libgdx,saqsun/libgdx,GreenLightning/libgdx,js78/libgdx,anserran/libgdx,Thotep/libgdx,libgdx/libgdx,SidneyXu/libgdx,ya7lelkom/libgdx,gdos/libgdx,nrallakis/libgdx,sarkanyi/libgdx,gf11speed/libgdx,djom20/libgdx,del-sol/libgdx,fwolff/libgdx,TheAks999/libgdx,alex-dorokhov/libgdx,sarkanyi/libgdx,stickyd/libgdx,zommuter/libgdx,SidneyXu/libgdx,snovak/libgdx,petugez/libgdx,junkdog/libgdx,GreenLightning/libgdx,kotcrab/libgdx,kagehak/libgdx,ThiagoGarciaAlves/libgdx,js78/libgdx,TheAks999/libgdx,Zonglin-Li6565/libgdx,tommycli/libgdx,toa5/libgdx,tell10glu/libgdx,toloudis/libgdx,del-sol/libgdx,stickyd/libgdx,ya7lelkom/libgdx,FyiurAmron/libgdx,NathanSweet/libgdx,KrisLee/libgdx,sarkanyi/libgdx,Senth/libgdx,ya7lelkom/libgdx,jberberick/libgdx,bladecoder/libgdx,Deftwun/libgdx,ninoalma/libgdx,collinsmith/libgdx,Heart2009/libgdx,ttencate/libgdx,kotcrab/libgdx,ninoalma/libgdx,samskivert/libgdx,anserran/libgdx,toloudis/libgdx,titovmaxim/libgdx,bsmr-java/libgdx,Wisienkas/libgdx,shiweihappy/libgdx,stickyd/libgdx,zommuter/libgdx,nave966/libgdx,youprofit/libgdx,FredGithub/libgdx,Xhanim/libgdx,saltares/libgdx,bgroenks96/libgdx,ThiagoGarciaAlves/libgdx,tommyettinger/libgdx,jberberick/libgdx,sjosegarcia/libgdx,czyzby/libgdx,josephknight/libgdx,junkdog/libgdx,firefly2442/libgdx,fwolff/libgdx,katiepino/libgdx,Heart2009/libgdx,gf11speed/libgdx,Senth/libgdx,toa5/libgdx,anserran/libgdx,Badazdz/libgdx,shiweihappy/libgdx,JDReutt/libgdx,cypherdare/libgdx,BlueRiverInteractive/libgdx,curtiszimmerman/libgdx,KrisLee/libgdx,titovmaxim/libgdx,Badazdz/libgdx,Xhanim/libgdx,JFixby/libgdx,stickyd/libgdx,tell10glu/libgdx,haedri/libgdx-1,snovak/libgdx,nrallakis/libgdx,toa5/libgdx,katiepino/libgdx,Wisienkas/libgdx,srwonka/libGdx,curtiszimmerman/libgdx,stinsonga/libgdx,JFixby/libgdx,gdos/libgdx,katiepino/libgdx,andyvand/libgdx,nave966/libgdx,djom20/libgdx,toa5/libgdx,gf11speed/libgdx,UnluckyNinja/libgdx,bgroenks96/libgdx,curtiszimmerman/libgdx,ya7lelkom/libgdx,luischavez/libgdx,collinsmith/libgdx,codepoke/libgdx,Zonglin-Li6565/libgdx,djom20/libgdx,gouessej/libgdx,JDReutt/libgdx,codepoke/libgdx,MikkelTAndersen/libgdx,realitix/libgdx,tell10glu/libgdx,Dzamir/libgdx,hyvas/libgdx,Zonglin-Li6565/libgdx,luischavez/libgdx,saqsun/libgdx,UnluckyNinja/libgdx,petugez/libgdx,bladecoder/libgdx,sjosegarcia/libgdx,FyiurAmron/libgdx,nelsonsilva/libgdx,realitix/libgdx,azakhary/libgdx,ttencate/libgdx,Zomby2D/libgdx,MovingBlocks/libgdx,nrallakis/libgdx,anserran/libgdx,nave966/libgdx,billgame/libgdx,alireza-hosseini/libgdx,youprofit/libgdx,ya7lelkom/libgdx,Zomby2D/libgdx,jsjolund/libgdx,xoppa/libgdx,mumer92/libgdx,ztv/libgdx,billgame/libgdx,nudelchef/libgdx,alireza-hosseini/libgdx,ya7lelkom/libgdx,Thotep/libgdx,ThiagoGarciaAlves/libgdx,realitix/libgdx,bsmr-java/libgdx,libgdx/libgdx,Dzamir/libgdx,copystudy/libgdx,NathanSweet/libgdx,toloudis/libgdx,zommuter/libgdx,Heart2009/libgdx,nudelchef/libgdx,Senth/libgdx,Gliby/libgdx,bgroenks96/libgdx,ricardorigodon/libgdx,toloudis/libgdx,FredGithub/libgdx,snovak/libgdx,luischavez/libgdx,jberberick/libgdx,Zomby2D/libgdx,noelsison2/libgdx,billgame/libgdx,GreenLightning/libgdx,Thotep/libgdx,KrisLee/libgdx,samskivert/libgdx,Heart2009/libgdx,collinsmith/libgdx,gouessej/libgdx,codepoke/libgdx,jsjolund/libgdx,FyiurAmron/libgdx,ThiagoGarciaAlves/libgdx,js78/libgdx,firefly2442/libgdx,ttencate/libgdx,1yvT0s/libgdx,designcrumble/libgdx,nudelchef/libgdx,zhimaijoy/libgdx,josephknight/libgdx,Badazdz/libgdx,MetSystem/libgdx,davebaol/libgdx,Zomby2D/libgdx,tommyettinger/libgdx,sarkanyi/libgdx,MikkelTAndersen/libgdx,luischavez/libgdx,bladecoder/libgdx,revo09/libgdx,Deftwun/libgdx,UnluckyNinja/libgdx,youprofit/libgdx,hyvas/libgdx,azakhary/libgdx,bgroenks96/libgdx,alireza-hosseini/libgdx,designcrumble/libgdx,SidneyXu/libgdx,azakhary/libgdx,ThiagoGarciaAlves/libgdx,yangweigbh/libgdx,ricardorigodon/libgdx,ninoalma/libgdx,srwonka/libGdx,ninoalma/libgdx,jasonwee/libgdx,Zonglin-Li6565/libgdx,zhimaijoy/libgdx,xpenatan/libgdx-LWJGL3,PedroRomanoBarbosa/libgdx,xoppa/libgdx,thepullman/libgdx,Deftwun/libgdx,jberberick/libgdx,ztv/libgdx,jasonwee/libgdx,antag99/libgdx,tommyettinger/libgdx,Gliby/libgdx,saqsun/libgdx,Wisienkas/libgdx,NathanSweet/libgdx,thepullman/libgdx,EsikAntony/libgdx,GreenLightning/libgdx,sjosegarcia/libgdx,jasonwee/libgdx,Zonglin-Li6565/libgdx,zhimaijoy/libgdx,kotcrab/libgdx,KrisLee/libgdx,samskivert/libgdx,firefly2442/libgdx,katiepino/libgdx,haedri/libgdx-1,309746069/libgdx,sjosegarcia/libgdx,haedri/libgdx-1,antag99/libgdx,djom20/libgdx,saltares/libgdx,EsikAntony/libgdx,PedroRomanoBarbosa/libgdx,snovak/libgdx,FyiurAmron/libgdx,czyzby/libgdx,sarkanyi/libgdx,UnluckyNinja/libgdx,bsmr-java/libgdx,MikkelTAndersen/libgdx,Thotep/libgdx,ttencate/libgdx,ThiagoGarciaAlves/libgdx,PedroRomanoBarbosa/libgdx,MadcowD/libgdx,MadcowD/libgdx,shiweihappy/libgdx,Zomby2D/libgdx,srwonka/libGdx,thepullman/libgdx,antag99/libgdx,JFixby/libgdx,Deftwun/libgdx,josephknight/libgdx,Dzamir/libgdx,saqsun/libgdx,FredGithub/libgdx,Thotep/libgdx,JFixby/libgdx,Badazdz/libgdx,MovingBlocks/libgdx,toa5/libgdx,jsjolund/libgdx,nudelchef/libgdx,firefly2442/libgdx,zommuter/libgdx,MovingBlocks/libgdx,Zonglin-Li6565/libgdx,UnluckyNinja/libgdx,SidneyXu/libgdx,alireza-hosseini/libgdx,Deftwun/libgdx,xoppa/libgdx,collinsmith/libgdx,yangweigbh/libgdx,gf11speed/libgdx,antag99/libgdx,Xhanim/libgdx,309746069/libgdx,jasonwee/libgdx,samskivert/libgdx,xoppa/libgdx,1yvT0s/libgdx,xpenatan/libgdx-LWJGL3,yangweigbh/libgdx,xoppa/libgdx,Thotep/libgdx,jberberick/libgdx,tell10glu/libgdx,copystudy/libgdx,ztv/libgdx,djom20/libgdx,toa5/libgdx,nrallakis/libgdx,srwonka/libGdx,libgdx/libgdx,309746069/libgdx,JFixby/libgdx,ninoalma/libgdx,xranby/libgdx,tommycli/libgdx,gdos/libgdx,toloudis/libgdx,1yvT0s/libgdx,nave966/libgdx,bladecoder/libgdx,ThiagoGarciaAlves/libgdx,xranby/libgdx,saltares/libgdx,MikkelTAndersen/libgdx,alireza-hosseini/libgdx,MovingBlocks/libgdx,sarkanyi/libgdx,fiesensee/libgdx,ttencate/libgdx,xranby/libgdx,billgame/libgdx,FyiurAmron/libgdx,TheAks999/libgdx,toloudis/libgdx,xpenatan/libgdx-LWJGL3,josephknight/libgdx,collinsmith/libgdx,titovmaxim/libgdx,Gliby/libgdx,fiesensee/libgdx,firefly2442/libgdx,zommuter/libgdx,katiepino/libgdx,ninoalma/libgdx,ztv/libgdx,tommycli/libgdx,jberberick/libgdx,azakhary/libgdx,hyvas/libgdx,nave966/libgdx,collinsmith/libgdx,zhimaijoy/libgdx,del-sol/libgdx,Zonglin-Li6565/libgdx,GreenLightning/libgdx,FyiurAmron/libgdx,azakhary/libgdx,BlueRiverInteractive/libgdx,ztv/libgdx,mumer92/libgdx,nrallakis/libgdx,titovmaxim/libgdx,zhimaijoy/libgdx,js78/libgdx,junkdog/libgdx,zhimaijoy/libgdx,ztv/libgdx,tommycli/libgdx,thepullman/libgdx,sjosegarcia/libgdx,Xhanim/libgdx,sjosegarcia/libgdx,andyvand/libgdx,nrallakis/libgdx,xranby/libgdx,GreenLightning/libgdx,kagehak/libgdx,revo09/libgdx,billgame/libgdx,KrisLee/libgdx,thepullman/libgdx,nelsonsilva/libgdx,kagehak/libgdx,bsmr-java/libgdx,realitix/libgdx,sarkanyi/libgdx,EsikAntony/libgdx
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.graphics.g3d.loader; import com.badlogic.gdx.assets.loaders.FileHandleResolver; import com.badlogic.gdx.assets.loaders.ModelLoader; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.g3d.model.data.ModelAnimation; import com.badlogic.gdx.graphics.g3d.model.data.ModelData; import com.badlogic.gdx.graphics.g3d.model.data.ModelMaterial; import com.badlogic.gdx.graphics.g3d.model.data.ModelMesh; import com.badlogic.gdx.graphics.g3d.model.data.ModelMeshPart; import com.badlogic.gdx.graphics.g3d.model.data.ModelNode; import com.badlogic.gdx.graphics.g3d.model.data.ModelNodeAnimation; import com.badlogic.gdx.graphics.g3d.model.data.ModelNodeKeyframe; import com.badlogic.gdx.graphics.g3d.model.data.ModelNodePart; import com.badlogic.gdx.graphics.g3d.model.data.ModelTexture; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Quaternion; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ArrayMap; import com.badlogic.gdx.utils.BaseJsonReader; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.JsonValue; public class G3dModelLoader extends ModelLoader<ModelLoader.ModelParameters> { public static final short VERSION_HI = 0; public static final short VERSION_LO = 1; protected final BaseJsonReader reader; public G3dModelLoader (final BaseJsonReader reader) { this(reader, null); } public G3dModelLoader (BaseJsonReader reader, FileHandleResolver resolver) { super(resolver); this.reader = reader; } @Override public ModelData loadModelData (FileHandle fileHandle, ModelLoader.ModelParameters parameters) { return parseModel(fileHandle); } public ModelData parseModel (FileHandle handle) { JsonValue json = reader.parse(handle); ModelData model = new ModelData(); JsonValue version = json.require("version"); model.version[0] = version.getShort(0); model.version[1] = version.getShort(1); if (model.version[0] != VERSION_HI || model.version[1] != VERSION_LO) throw new GdxRuntimeException("Model version not supported"); model.id = json.getString("id", ""); parseMeshes(model, json); parseMaterials(model, json, handle.parent().path()); parseNodes(model, json); parseAnimations(model, json); return model; } private void parseMeshes (ModelData model, JsonValue json) { JsonValue meshes = json.get("meshes"); if (meshes != null) { model.meshes.ensureCapacity(meshes.size); for (JsonValue mesh = meshes.child; mesh != null; mesh = mesh.next) { ModelMesh jsonMesh = new ModelMesh(); String id = mesh.getString("id", ""); jsonMesh.id = id; JsonValue attributes = mesh.require("attributes"); jsonMesh.attributes = parseAttributes(attributes); jsonMesh.vertices = mesh.require("vertices").asFloatArray(); JsonValue meshParts = mesh.require("parts"); Array<ModelMeshPart> parts = new Array<ModelMeshPart>(); for (JsonValue meshPart = meshParts.child; meshPart != null; meshPart = meshPart.next) { ModelMeshPart jsonPart = new ModelMeshPart(); String partId = meshPart.getString("id", null); if (partId == null) { throw new GdxRuntimeException("Not id given for mesh part"); } for (ModelMeshPart other : parts) { if (other.id.equals(partId)) { throw new GdxRuntimeException("Mesh part with id '" + partId + "' already in defined"); } } jsonPart.id = partId; String type = meshPart.getString("type", null); if (type == null) { throw new GdxRuntimeException("No primitive type given for mesh part '" + partId + "'"); } jsonPart.primitiveType = parseType(type); jsonPart.indices = meshPart.require("indices").asShortArray(); parts.add(jsonPart); } jsonMesh.parts = parts.toArray(ModelMeshPart.class); model.meshes.add(jsonMesh); } } } private int parseType (String type) { if (type.equals("TRIANGLES")) { return GL20.GL_TRIANGLES; } else if (type.equals("LINES")) { return GL20.GL_LINES; } else if (type.equals("POINTS")) { return GL20.GL_POINTS; } else if (type.equals("TRIANGLE_STRIP")) { return GL20.GL_TRIANGLE_STRIP; } else if (type.equals("LINE_STRIP")) { return GL20.GL_LINE_STRIP; } else { throw new GdxRuntimeException("Unknown primitive type '" + type + "', should be one of triangle, trianglestrip, line, linestrip, lineloop or point"); } } private VertexAttribute[] parseAttributes (JsonValue attributes) { Array<VertexAttribute> vertexAttributes = new Array<VertexAttribute>(); int unit = 0; int blendWeightCount = 0; for (JsonValue value = attributes.child; value != null; value = value.next) { String attribute = value.asString(); String attr = (String)attribute; if (attr.equals("POSITION")) { vertexAttributes.add(VertexAttribute.Position()); } else if (attr.equals("NORMAL")) { vertexAttributes.add(VertexAttribute.Normal()); } else if (attr.equals("COLOR")) { vertexAttributes.add(VertexAttribute.ColorUnpacked()); } else if (attr.equals("COLORPACKED")) { vertexAttributes.add(VertexAttribute.ColorPacked()); } else if (attr.equals("TANGENT")) { vertexAttributes.add(VertexAttribute.Tangent()); } else if (attr.equals("BINORMAL")) { vertexAttributes.add(VertexAttribute.Binormal()); } else if (attr.startsWith("TEXCOORD")) { vertexAttributes.add(VertexAttribute.TexCoords(unit++)); } else if (attr.startsWith("BLENDWEIGHT")) { vertexAttributes.add(VertexAttribute.BoneWeight(blendWeightCount++)); } else { throw new GdxRuntimeException("Unknown vertex attribute '" + attr + "', should be one of position, normal, uv, tangent or binormal"); } } return vertexAttributes.toArray(VertexAttribute.class); } private void parseMaterials (ModelData model, JsonValue json, String materialDir) { JsonValue materials = json.get("materials"); if (materials == null) { // we should probably create some default material in this case } else { model.materials.ensureCapacity(materials.size); for (JsonValue material = materials.child; material != null; material = material.next) { ModelMaterial jsonMaterial = new ModelMaterial(); String id = material.getString("id", null); if (id == null) throw new GdxRuntimeException("Material needs an id."); jsonMaterial.id = id; // Read material colors final JsonValue diffuse = material.get("diffuse"); if (diffuse != null) jsonMaterial.diffuse = parseColor(diffuse); final JsonValue ambient = material.get("ambient"); if (ambient != null) jsonMaterial.ambient = parseColor(ambient); final JsonValue emissive = material.get("emissive"); if (emissive != null) jsonMaterial.emissive = parseColor(emissive); final JsonValue specular = material.get("specular"); if (specular != null) jsonMaterial.specular = parseColor(specular); final JsonValue reflection = material.get("reflection"); if (reflection != null) jsonMaterial.reflection = parseColor(reflection); // Read shininess jsonMaterial.shininess = material.getFloat("shininess", 0.0f); // Read opacity jsonMaterial.opacity = material.getFloat("opacity", 1.0f); // Read textures JsonValue textures = material.get("textures"); if (textures != null) { for (JsonValue texture = textures.child; texture != null; texture = texture.next) { ModelTexture jsonTexture = new ModelTexture(); String textureId = texture.getString("id", null); if (textureId == null) throw new GdxRuntimeException("Texture has no id."); jsonTexture.id = textureId; String fileName = texture.getString("filename", null); if (fileName == null) throw new GdxRuntimeException("Texture needs filename."); jsonTexture.fileName = materialDir + (materialDir.length() == 0 || materialDir.endsWith("/") ? "" : "/") + fileName; jsonTexture.uvTranslation = readVector2(texture.get("uvTranslation"), 0f, 0f); jsonTexture.uvScaling = readVector2(texture.get("uvScaling"), 1f, 1f); String textureType = texture.getString("type", null); if (textureType == null) throw new GdxRuntimeException("Texture needs type."); jsonTexture.usage = parseTextureUsage(textureType); if (jsonMaterial.textures == null) jsonMaterial.textures = new Array<ModelTexture>(); jsonMaterial.textures.add(jsonTexture); } } model.materials.add(jsonMaterial); } } } private int parseTextureUsage (final String value) { if (value.equalsIgnoreCase("AMBIENT")) return ModelTexture.USAGE_AMBIENT; else if (value.equalsIgnoreCase("BUMP")) return ModelTexture.USAGE_BUMP; else if (value.equalsIgnoreCase("DIFFUSE")) return ModelTexture.USAGE_DIFFUSE; else if (value.equalsIgnoreCase("EMISSIVE")) return ModelTexture.USAGE_EMISSIVE; else if (value.equalsIgnoreCase("NONE")) return ModelTexture.USAGE_NONE; else if (value.equalsIgnoreCase("NORMAL")) return ModelTexture.USAGE_NORMAL; else if (value.equalsIgnoreCase("REFLECTION")) return ModelTexture.USAGE_REFLECTION; else if (value.equalsIgnoreCase("SHININESS")) return ModelTexture.USAGE_SHININESS; else if (value.equalsIgnoreCase("SPECULAR")) return ModelTexture.USAGE_SPECULAR; else if (value.equalsIgnoreCase("TRANSPARENCY")) return ModelTexture.USAGE_TRANSPARENCY; return ModelTexture.USAGE_UNKNOWN; } private Color parseColor (JsonValue colorArray) { if (colorArray.size >= 3) return new Color(colorArray.getFloat(0), colorArray.getFloat(1), colorArray.getFloat(2), 1.0f); else throw new GdxRuntimeException("Expected Color values <> than three."); } private Vector2 readVector2 (JsonValue vectorArray, float x, float y) { if (vectorArray == null) return new Vector2(x, y); else if (vectorArray.size == 2) return new Vector2(vectorArray.getFloat(0), vectorArray.getFloat(1)); else throw new GdxRuntimeException("Expected Vector2 values <> than two."); } private Array<ModelNode> parseNodes (ModelData model, JsonValue json) { JsonValue nodes = json.get("nodes"); if (nodes != null) { model.nodes.ensureCapacity(nodes.size); for (JsonValue node = nodes.child; node != null; node = node.next) { model.nodes.add(parseNodesRecursively(node)); } } return model.nodes; } private final Quaternion tempQ = new Quaternion(); private ModelNode parseNodesRecursively (JsonValue json) { ModelNode jsonNode = new ModelNode(); String id = json.getString("id", null); if (id == null) throw new GdxRuntimeException("Node id missing."); jsonNode.id = id; JsonValue translation = json.get("translation"); if (translation != null && translation.size != 3) throw new GdxRuntimeException("Node translation incomplete"); jsonNode.translation = translation == null ? null : new Vector3(translation.getFloat(0), translation.getFloat(1), translation.getFloat(2)); JsonValue rotation = json.get("rotation"); if (rotation != null && rotation.size != 4) throw new GdxRuntimeException("Node rotation incomplete"); jsonNode.rotation = rotation == null ? null : new Quaternion(rotation.getFloat(0), rotation.getFloat(1), rotation.getFloat(2), rotation.getFloat(3)); JsonValue scale = json.get("scale"); if (scale != null && scale.size != 3) throw new GdxRuntimeException("Node scale incomplete"); jsonNode.scale = scale == null ? null : new Vector3(scale.getFloat(0), scale.getFloat(1), scale.getFloat(2)); String meshId = json.getString("mesh", null); if (meshId != null) jsonNode.meshId = meshId; JsonValue materials = json.get("parts"); if (materials != null) { jsonNode.parts = new ModelNodePart[materials.size]; int i = 0; for (JsonValue material = materials.child; material != null; material = material.next, i++) { ModelNodePart nodePart = new ModelNodePart(); String meshPartId = material.getString("meshpartid", null); String materialId = material.getString("materialid", null); if (meshPartId == null || materialId == null) { throw new GdxRuntimeException("Node " + id + " part is missing meshPartId or materialId"); } nodePart.materialId = materialId; nodePart.meshPartId = meshPartId; JsonValue bones = material.get("bones"); if (bones != null) { nodePart.bones = new ArrayMap<String, Matrix4>(true, bones.size, String.class, Matrix4.class); int j = 0; for (JsonValue bone = bones.child; bone != null; bone = bone.next, j++) { String nodeId = bone.getString("node", null); if (nodeId == null) throw new GdxRuntimeException("Bone node ID missing"); Matrix4 transform = new Matrix4(); JsonValue val = bone.get("translation"); if (val != null && val.size >= 3) transform.translate(val.getFloat(0), val.getFloat(1), val.getFloat(2)); val = bone.get("rotation"); if (val != null && val.size >= 4) transform.rotate(tempQ.set(val.getFloat(0), val.getFloat(1), val.getFloat(2), val.getFloat(3))); val = bone.get("scale"); if (val != null && val.size >= 3) transform.scale(val.getFloat(0), val.getFloat(1), val.getFloat(2)); nodePart.bones.put(nodeId, transform); } } jsonNode.parts[i] = nodePart; } } JsonValue children = json.get("children"); if (children != null) { jsonNode.children = new ModelNode[children.size]; int i = 0; for (JsonValue child = children.child; child != null; child = child.next, i++) { jsonNode.children[i] = parseNodesRecursively(child); } } return jsonNode; } private void parseAnimations (ModelData model, JsonValue json) { JsonValue animations = json.get("animations"); if (animations == null) return; model.animations.ensureCapacity(animations.size); for (JsonValue anim = animations.child; anim != null; anim = anim.next) { JsonValue nodes = anim.get("bones"); if (nodes == null) continue; ModelAnimation animation = new ModelAnimation(); model.animations.add(animation); animation.nodeAnimations.ensureCapacity(nodes.size); animation.id = anim.getString("id"); for (JsonValue node = nodes.child; node != null; node = node.next) { JsonValue keyframes = node.get("keyframes"); ModelNodeAnimation nodeAnim = new ModelNodeAnimation(); animation.nodeAnimations.add(nodeAnim); nodeAnim.nodeId = node.getString("boneId"); nodeAnim.keyframes.ensureCapacity(keyframes.size); for (JsonValue keyframe = keyframes.child; keyframe != null; keyframe = keyframe.next) { ModelNodeKeyframe kf = new ModelNodeKeyframe(); nodeAnim.keyframes.add(kf); kf.keytime = keyframe.getFloat("keytime") / 1000.f; JsonValue translation = keyframe.get("translation"); if (translation != null && translation.size == 3) kf.translation = new Vector3(translation.getFloat(0), translation.getFloat(1), translation.getFloat(2)); JsonValue rotation = keyframe.get("rotation"); if (rotation != null && rotation.size == 4) kf.rotation = new Quaternion(rotation.getFloat(0), rotation.getFloat(1), rotation.getFloat(2), rotation.getFloat(3)); JsonValue scale = keyframe.get("scale"); if (scale != null && scale.size == 3) kf.scale = new Vector3(scale.getFloat(0), scale.getFloat(1), scale.getFloat(2)); } } } } }
gdx/src/com/badlogic/gdx/graphics/g3d/loader/G3dModelLoader.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.graphics.g3d.loader; import com.badlogic.gdx.assets.loaders.FileHandleResolver; import com.badlogic.gdx.assets.loaders.ModelLoader; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.g3d.model.data.ModelAnimation; import com.badlogic.gdx.graphics.g3d.model.data.ModelData; import com.badlogic.gdx.graphics.g3d.model.data.ModelMaterial; import com.badlogic.gdx.graphics.g3d.model.data.ModelMesh; import com.badlogic.gdx.graphics.g3d.model.data.ModelMeshPart; import com.badlogic.gdx.graphics.g3d.model.data.ModelNode; import com.badlogic.gdx.graphics.g3d.model.data.ModelNodeAnimation; import com.badlogic.gdx.graphics.g3d.model.data.ModelNodeKeyframe; import com.badlogic.gdx.graphics.g3d.model.data.ModelNodePart; import com.badlogic.gdx.graphics.g3d.model.data.ModelTexture; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Quaternion; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ArrayMap; import com.badlogic.gdx.utils.BaseJsonReader; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.JsonValue; public class G3dModelLoader extends ModelLoader<ModelLoader.ModelParameters> { public static final short VERSION_HI = 0; public static final short VERSION_LO = 1; protected final BaseJsonReader reader; public G3dModelLoader (final BaseJsonReader reader) { this(reader, null); } public G3dModelLoader (BaseJsonReader reader, FileHandleResolver resolver) { super(resolver); this.reader = reader; } @Override public ModelData loadModelData (FileHandle fileHandle, ModelLoader.ModelParameters parameters) { return parseModel(fileHandle); } public ModelData parseModel (FileHandle handle) { JsonValue json = reader.parse(handle); ModelData model = new ModelData(); JsonValue version = json.require("version"); model.version[0] = version.getShort(0); model.version[1] = version.getShort(1); if (model.version[0] != VERSION_HI || model.version[1] != VERSION_LO) throw new GdxRuntimeException("Model version not supported"); model.id = json.getString("id", ""); parseMeshes(model, json); parseMaterials(model, json, handle.parent().path()); parseNodes(model, json); parseAnimations(model, json); return model; } private void parseMeshes (ModelData model, JsonValue json) { JsonValue meshes = json.get("meshes"); if (meshes != null) { model.meshes.ensureCapacity(meshes.size); for (JsonValue mesh = meshes.child; mesh != null; mesh = mesh.next) { ModelMesh jsonMesh = new ModelMesh(); String id = mesh.getString("id", ""); jsonMesh.id = id; JsonValue attributes = mesh.require("attributes"); jsonMesh.attributes = parseAttributes(attributes); jsonMesh.vertices = mesh.require("vertices").asFloatArray(); JsonValue meshParts = mesh.require("parts"); Array<ModelMeshPart> parts = new Array<ModelMeshPart>(); for (JsonValue meshPart = meshParts.child; meshPart != null; meshPart = meshPart.next) { ModelMeshPart jsonPart = new ModelMeshPart(); String partId = meshPart.getString("id", null); if (id == null) { throw new GdxRuntimeException("Not id given for mesh part"); } for (ModelMeshPart other : parts) { if (other.id.equals(partId)) { throw new GdxRuntimeException("Mesh part with id '" + partId + "' already in defined"); } } jsonPart.id = partId; String type = meshPart.getString("type", null); if (type == null) { throw new GdxRuntimeException("No primitive type given for mesh part '" + partId + "'"); } jsonPart.primitiveType = parseType(type); jsonPart.indices = meshPart.require("indices").asShortArray(); parts.add(jsonPart); } jsonMesh.parts = parts.toArray(ModelMeshPart.class); model.meshes.add(jsonMesh); } } } private int parseType (String type) { if (type.equals("TRIANGLES")) { return GL20.GL_TRIANGLES; } else if (type.equals("LINES")) { return GL20.GL_LINES; } else if (type.equals("POINTS")) { return GL20.GL_POINTS; } else if (type.equals("TRIANGLE_STRIP")) { return GL20.GL_TRIANGLE_STRIP; } else if (type.equals("LINE_STRIP")) { return GL20.GL_LINE_STRIP; } else { throw new GdxRuntimeException("Unknown primitive type '" + type + "', should be one of triangle, trianglestrip, line, linestrip, lineloop or point"); } } private VertexAttribute[] parseAttributes (JsonValue attributes) { Array<VertexAttribute> vertexAttributes = new Array<VertexAttribute>(); int unit = 0; int blendWeightCount = 0; for (JsonValue value = attributes.child; value != null; value = value.next) { String attribute = value.asString(); String attr = (String)attribute; if (attr.equals("POSITION")) { vertexAttributes.add(VertexAttribute.Position()); } else if (attr.equals("NORMAL")) { vertexAttributes.add(VertexAttribute.Normal()); } else if (attr.equals("COLOR")) { vertexAttributes.add(VertexAttribute.ColorUnpacked()); } else if (attr.equals("COLORPACKED")) { vertexAttributes.add(VertexAttribute.ColorPacked()); } else if (attr.equals("TANGENT")) { vertexAttributes.add(VertexAttribute.Tangent()); } else if (attr.equals("BINORMAL")) { vertexAttributes.add(VertexAttribute.Binormal()); } else if (attr.startsWith("TEXCOORD")) { vertexAttributes.add(VertexAttribute.TexCoords(unit++)); } else if (attr.startsWith("BLENDWEIGHT")) { vertexAttributes.add(VertexAttribute.BoneWeight(blendWeightCount++)); } else { throw new GdxRuntimeException("Unknown vertex attribute '" + attr + "', should be one of position, normal, uv, tangent or binormal"); } } return vertexAttributes.toArray(VertexAttribute.class); } private void parseMaterials (ModelData model, JsonValue json, String materialDir) { JsonValue materials = json.get("materials"); if (materials == null) { // we should probably create some default material in this case } else { model.materials.ensureCapacity(materials.size); for (JsonValue material = materials.child; material != null; material = material.next) { ModelMaterial jsonMaterial = new ModelMaterial(); String id = material.getString("id", null); if (id == null) throw new GdxRuntimeException("Material needs an id."); jsonMaterial.id = id; // Read material colors final JsonValue diffuse = material.get("diffuse"); if (diffuse != null) jsonMaterial.diffuse = parseColor(diffuse); final JsonValue ambient = material.get("ambient"); if (ambient != null) jsonMaterial.ambient = parseColor(ambient); final JsonValue emissive = material.get("emissive"); if (emissive != null) jsonMaterial.emissive = parseColor(emissive); final JsonValue specular = material.get("specular"); if (specular != null) jsonMaterial.specular = parseColor(specular); final JsonValue reflection = material.get("reflection"); if (reflection != null) jsonMaterial.reflection = parseColor(reflection); // Read shininess jsonMaterial.shininess = material.getFloat("shininess", 0.0f); // Read opacity jsonMaterial.opacity = material.getFloat("opacity", 1.0f); // Read textures JsonValue textures = material.get("textures"); if (textures != null) { for (JsonValue texture = textures.child; texture != null; texture = texture.next) { ModelTexture jsonTexture = new ModelTexture(); String textureId = texture.getString("id", null); if (textureId == null) throw new GdxRuntimeException("Texture has no id."); jsonTexture.id = textureId; String fileName = texture.getString("filename", null); if (fileName == null) throw new GdxRuntimeException("Texture needs filename."); jsonTexture.fileName = materialDir + (materialDir.length() == 0 || materialDir.endsWith("/") ? "" : "/") + fileName; jsonTexture.uvTranslation = readVector2(texture.get("uvTranslation"), 0f, 0f); jsonTexture.uvScaling = readVector2(texture.get("uvScaling"), 1f, 1f); String textureType = texture.getString("type", null); if (textureType == null) throw new GdxRuntimeException("Texture needs type."); jsonTexture.usage = parseTextureUsage(textureType); if (jsonMaterial.textures == null) jsonMaterial.textures = new Array<ModelTexture>(); jsonMaterial.textures.add(jsonTexture); } } model.materials.add(jsonMaterial); } } } private int parseTextureUsage (final String value) { if (value.equalsIgnoreCase("AMBIENT")) return ModelTexture.USAGE_AMBIENT; else if (value.equalsIgnoreCase("BUMP")) return ModelTexture.USAGE_BUMP; else if (value.equalsIgnoreCase("DIFFUSE")) return ModelTexture.USAGE_DIFFUSE; else if (value.equalsIgnoreCase("EMISSIVE")) return ModelTexture.USAGE_EMISSIVE; else if (value.equalsIgnoreCase("NONE")) return ModelTexture.USAGE_NONE; else if (value.equalsIgnoreCase("NORMAL")) return ModelTexture.USAGE_NORMAL; else if (value.equalsIgnoreCase("REFLECTION")) return ModelTexture.USAGE_REFLECTION; else if (value.equalsIgnoreCase("SHININESS")) return ModelTexture.USAGE_SHININESS; else if (value.equalsIgnoreCase("SPECULAR")) return ModelTexture.USAGE_SPECULAR; else if (value.equalsIgnoreCase("TRANSPARENCY")) return ModelTexture.USAGE_TRANSPARENCY; return ModelTexture.USAGE_UNKNOWN; } private Color parseColor (JsonValue colorArray) { if (colorArray.size >= 3) return new Color(colorArray.getFloat(0), colorArray.getFloat(1), colorArray.getFloat(2), 1.0f); else throw new GdxRuntimeException("Expected Color values <> than three."); } private Vector2 readVector2 (JsonValue vectorArray, float x, float y) { if (vectorArray == null) return new Vector2(x, y); else if (vectorArray.size == 2) return new Vector2(vectorArray.getFloat(0), vectorArray.getFloat(1)); else throw new GdxRuntimeException("Expected Vector2 values <> than two."); } private Array<ModelNode> parseNodes (ModelData model, JsonValue json) { JsonValue nodes = json.get("nodes"); if (nodes != null) { model.nodes.ensureCapacity(nodes.size); for (JsonValue node = nodes.child; node != null; node = node.next) { model.nodes.add(parseNodesRecursively(node)); } } return model.nodes; } private final Quaternion tempQ = new Quaternion(); private ModelNode parseNodesRecursively (JsonValue json) { ModelNode jsonNode = new ModelNode(); String id = json.getString("id", null); if (id == null) throw new GdxRuntimeException("Node id missing."); jsonNode.id = id; JsonValue translation = json.get("translation"); if (translation != null && translation.size != 3) throw new GdxRuntimeException("Node translation incomplete"); jsonNode.translation = translation == null ? null : new Vector3(translation.getFloat(0), translation.getFloat(1), translation.getFloat(2)); JsonValue rotation = json.get("rotation"); if (rotation != null && rotation.size != 4) throw new GdxRuntimeException("Node rotation incomplete"); jsonNode.rotation = rotation == null ? null : new Quaternion(rotation.getFloat(0), rotation.getFloat(1), rotation.getFloat(2), rotation.getFloat(3)); JsonValue scale = json.get("scale"); if (scale != null && scale.size != 3) throw new GdxRuntimeException("Node scale incomplete"); jsonNode.scale = scale == null ? null : new Vector3(scale.getFloat(0), scale.getFloat(1), scale.getFloat(2)); String meshId = json.getString("mesh", null); if (meshId != null) jsonNode.meshId = meshId; JsonValue materials = json.get("parts"); if (materials != null) { jsonNode.parts = new ModelNodePart[materials.size]; int i = 0; for (JsonValue material = materials.child; material != null; material = material.next, i++) { ModelNodePart nodePart = new ModelNodePart(); String meshPartId = material.getString("meshpartid", null); String materialId = material.getString("materialid", null); if (meshPartId == null || materialId == null) { throw new GdxRuntimeException("Node " + id + " part is missing meshPartId or materialId"); } nodePart.materialId = materialId; nodePart.meshPartId = meshPartId; JsonValue bones = material.get("bones"); if (bones != null) { nodePart.bones = new ArrayMap<String, Matrix4>(true, bones.size, String.class, Matrix4.class); int j = 0; for (JsonValue bone = bones.child; bone != null; bone = bone.next, j++) { String nodeId = bone.getString("node", null); if (nodeId == null) throw new GdxRuntimeException("Bone node ID missing"); Matrix4 transform = new Matrix4(); JsonValue val = bone.get("translation"); if (val != null && val.size >= 3) transform.translate(val.getFloat(0), val.getFloat(1), val.getFloat(2)); val = bone.get("rotation"); if (val != null && val.size >= 4) transform.rotate(tempQ.set(val.getFloat(0), val.getFloat(1), val.getFloat(2), val.getFloat(3))); val = bone.get("scale"); if (val != null && val.size >= 3) transform.scale(val.getFloat(0), val.getFloat(1), val.getFloat(2)); nodePart.bones.put(nodeId, transform); } } jsonNode.parts[i] = nodePart; } } JsonValue children = json.get("children"); if (children != null) { jsonNode.children = new ModelNode[children.size]; int i = 0; for (JsonValue child = children.child; child != null; child = child.next, i++) { jsonNode.children[i] = parseNodesRecursively(child); } } return jsonNode; } private void parseAnimations (ModelData model, JsonValue json) { JsonValue animations = json.get("animations"); if (animations == null) return; model.animations.ensureCapacity(animations.size); for (JsonValue anim = animations.child; anim != null; anim = anim.next) { JsonValue nodes = anim.get("bones"); if (nodes == null) continue; ModelAnimation animation = new ModelAnimation(); model.animations.add(animation); animation.nodeAnimations.ensureCapacity(nodes.size); animation.id = anim.getString("id"); for (JsonValue node = nodes.child; node != null; node = node.next) { JsonValue keyframes = node.get("keyframes"); ModelNodeAnimation nodeAnim = new ModelNodeAnimation(); animation.nodeAnimations.add(nodeAnim); nodeAnim.nodeId = node.getString("boneId"); nodeAnim.keyframes.ensureCapacity(keyframes.size); for (JsonValue keyframe = keyframes.child; keyframe != null; keyframe = keyframe.next) { ModelNodeKeyframe kf = new ModelNodeKeyframe(); nodeAnim.keyframes.add(kf); kf.keytime = keyframe.getFloat("keytime") / 1000.f; JsonValue translation = keyframe.get("translation"); if (translation != null && translation.size == 3) kf.translation = new Vector3(translation.getFloat(0), translation.getFloat(1), translation.getFloat(2)); JsonValue rotation = keyframe.get("rotation"); if (rotation != null && rotation.size == 4) kf.rotation = new Quaternion(rotation.getFloat(0), rotation.getFloat(1), rotation.getFloat(2), rotation.getFloat(3)); JsonValue scale = keyframe.get("scale"); if (scale != null && scale.size == 3) kf.scale = new Vector3(scale.getFloat(0), scale.getFloat(1), scale.getFloat(2)); } } } } }
Update G3dModelLoader.java Fixed wrong variable being nullchecked.
gdx/src/com/badlogic/gdx/graphics/g3d/loader/G3dModelLoader.java
Update G3dModelLoader.java
Java
apache-2.0
6ea14051264685f6c3594367fdfbe9a87f50d260
0
292388900/cglib,mohanaraosv/cglib,lncosie/cglib,xgbj/cglib,mcmakev/cglib,lukesandberg/cglib,HubSpot/cglib,TopicusZorg/cglib,baishuo/cglib,mcculls/cglib,cglib/cglib,liuyb02/cglib,ligzy/cglib,evertrue/cglib,chuz/cglib,yseasony/cglib,wangf111/cglib
/* * The Apache Software License, Version 1.1 * * Copyright (c) 2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package net.sf.cglib.util; import java.util.*; import net.sf.cglib.core.*; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.Type; /** * This class implements a simple String->int mapping for a fixed set of keys. */ abstract public class StringSwitcher { private static final Type STRING_SWITCHER = TypeUtils.parseType("net.sf.cglib.util.StringSwitcher"); private static final Signature INT_VALUE = TypeUtils.parseSignature("int intValue(String)"); private static final StringSwitcherKey KEY_FACTORY = (StringSwitcherKey)KeyFactory.create(StringSwitcherKey.class); interface StringSwitcherKey { public Object newInstance(String[] strings, int[] ints, boolean fixedInput); } /** * Helper method to create a StringSwitcher. * For finer control over the generated instance, use a new instance of StringSwitcher.Generator * instead of this static method. * @param strings the array of String keys; must be the same length as the value array * @param ints the array of integer results; must be the same length as the key array * @param fixedInput if false, an unknown key will be returned from {@link #intValue} as <code>-1</code>; if true, * the result will be undefined, and the resulting code will be faster */ public static StringSwitcher create(String[] strings, int[] ints, boolean fixedInput) { Generator gen = new Generator(); gen.setStrings(strings); gen.setInts(ints); gen.setFixedInput(fixedInput); return gen.create(); } protected StringSwitcher() { } /** * Return the integer associated with the given key. * @param s the key * @return the associated integer value, or <code>-1</code> if the key is unknown (unless * <code>fixedInput</code> was specified when this <code>StringSwitcher</code> was created, * in which case the return value for an unknown key is undefined) */ abstract public int intValue(String s); public static class Generator extends AbstractClassGenerator { private static final Source SOURCE = new Source(StringSwitcher.class.getName()); private String[] strings; private int[] ints; private boolean fixedInput; public Generator() { super(SOURCE); } /** * Set the array of recognized Strings. * @param strings the array of String keys; must be the same length as the value array * @see #setInts */ public void setStrings(String[] strings) { this.strings = strings; } /** * Set the array of integer results. * @param ints the array of integer results; must be the same length as the key array * @see #setStrings */ public void setInts(int[] ints) { this.ints = ints; } /** * Configure how unknown String keys will be handled. * @param fixedInput if false, an unknown key will be returned from {@link #intValue} as <code>-1</code>; if true, * the result will be undefined, and the resulting code will be faster */ public void setFixedInput(boolean fixedInput) { this.fixedInput = fixedInput; } protected ClassLoader getDefaultClassLoader() { return getClass().getClassLoader(); } /** * Generate the <code>StringSwitcher</code>. */ public StringSwitcher create() { setNamePrefix(StringSwitcher.class.getName()); Object key = KEY_FACTORY.newInstance(strings, ints, fixedInput); return (StringSwitcher)super.create(key); } public void generateClass(ClassVisitor v) throws Exception { ClassEmitter ce = new ClassEmitter(v); ce.begin_class(Constants.ACC_PUBLIC, getClassName(), STRING_SWITCHER, null, Constants.SOURCE_FILE); ComplexOps.null_constructor(ce); final CodeEmitter e = ce.begin_method(Constants.ACC_PUBLIC, INT_VALUE, null); e.load_arg(0); final List stringList = Arrays.asList(strings); int style = fixedInput ? Constants.SWITCH_STYLE_HASHONLY : Constants.SWITCH_STYLE_HASH; ComplexOps.string_switch(e, strings, style, new ObjectSwitchCallback() { public void processCase(Object key, Label end) { e.push(ints[stringList.indexOf(key)]); e.return_value(); } public void processDefault() { e.push(-1); e.return_value(); } }); e.end_method(); ce.end_class(); } protected Object firstInstance(Class type) { return (StringSwitcher)ReflectUtils.newInstance(type); } protected Object nextInstance(Object instance) { return instance; } } }
src/proxy/net/sf/cglib/util/StringSwitcher.java
/* * The Apache Software License, Version 1.1 * * Copyright (c) 2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package net.sf.cglib.util; import java.util.*; import net.sf.cglib.core.*; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.Type; abstract public class StringSwitcher { private static final Type STRING_SWITCHER = TypeUtils.parseType("net.sf.cglib.util.StringSwitcher"); private static final Signature INT_VALUE = TypeUtils.parseSignature("int intValue(String)"); private static final StringSwitcherKey KEY_FACTORY = (StringSwitcherKey)KeyFactory.create(StringSwitcherKey.class); interface StringSwitcherKey { public Object newInstance(String[] strings, int[] ints, boolean fixedInput); } public static StringSwitcher create(String[] strings, int[] ints, boolean fixedInput) { Generator gen = new Generator(); gen.setStrings(strings); gen.setInts(ints); gen.setFixedInput(fixedInput); return gen.create(); } protected StringSwitcher() { } abstract public int intValue(String s); public static class Generator extends AbstractClassGenerator { private static final Source SOURCE = new Source(StringSwitcher.class.getName()); private String[] strings; private int[] ints; private boolean fixedInput; public Generator() { super(SOURCE); } public void setStrings(String[] strings) { this.strings = strings; } public void setInts(int[] ints) { this.ints = ints; } public void setFixedInput(boolean fixedInput) { this.fixedInput = fixedInput; } protected ClassLoader getDefaultClassLoader() { return getClass().getClassLoader(); } public StringSwitcher create() { setNamePrefix(StringSwitcher.class.getName()); Object key = KEY_FACTORY.newInstance(strings, ints, fixedInput); return (StringSwitcher)super.create(key); } public void generateClass(ClassVisitor v) throws Exception { ClassEmitter ce = new ClassEmitter(v); ce.begin_class(Constants.ACC_PUBLIC, getClassName(), STRING_SWITCHER, null, Constants.SOURCE_FILE); ComplexOps.null_constructor(ce); final CodeEmitter e = ce.begin_method(Constants.ACC_PUBLIC, INT_VALUE, null); e.load_arg(0); final List stringList = Arrays.asList(strings); int style = fixedInput ? Constants.SWITCH_STYLE_HASHONLY : Constants.SWITCH_STYLE_HASH; ComplexOps.string_switch(e, strings, style, new ObjectSwitchCallback() { public void processCase(Object key, Label end) { e.push(ints[stringList.indexOf(key)]); e.return_value(); } public void processDefault() { e.push(-1); e.return_value(); } }); e.end_method(); ce.end_class(); } protected Object firstInstance(Class type) { return (StringSwitcher)ReflectUtils.newInstance(type); } protected Object nextInstance(Object instance) { return instance; } } }
Add docs
src/proxy/net/sf/cglib/util/StringSwitcher.java
Add docs
Java
apache-2.0
76a107239b6f2ec917cbe6828412f084b98590c6
0
pongo710/sopa
package de.sopa.manager; import android.graphics.Color; import android.media.MediaPlayer; import de.sopa.GameActivity; import de.sopa.R; import de.sopa.helper.LevelService; import java.util.Map; import org.andengine.engine.Engine; import org.andengine.engine.camera.Camera; import org.andengine.opengl.font.IFont; import org.andengine.opengl.texture.TextureOptions; import org.andengine.opengl.texture.region.ITextureRegion; import org.andengine.opengl.texture.region.TextureRegion; import org.andengine.opengl.vbo.VertexBufferObjectManager; /** * David Schilling - [email protected] */ public class ResourcesManager { private static final ResourcesManager INSTANCE = new ResourcesManager(); public SceneService sceneService; public Engine engine; public GameActivity activity; public Camera camera; public VertexBufferObjectManager vbom; private ResourceLoader resourceLoader; public ITextureRegion level_mode_region; public ITextureRegion settingsRegion; public ITextureRegion loadingScreenBackgroundRegion; public Map<Character, TextureRegion> regionTileMap; public ITextureRegion tilesBorderRegion; public ITextureRegion levelChoiceRegion; public ITextureRegion levelChoiceArrowRightRegion; public ITextureRegion levelChoiceArrowLeftRegion; public ITextureRegion levelChoiceRegionLocked; public ITextureRegion starRegion; public ITextureRegion starSWRegion; public ITextureRegion backToChoiceRegion; public ITextureRegion muteRegion; public ITextureRegion nextLevelRegion; public ITextureRegion levelChoiceRegionSW; public ITextureRegion backToMenuRegionA; public ITextureRegion backToMenuRegionP; public ITextureRegion restartRegion; public ITextureRegion unMuteRegion; public ITextureRegion tutorialSecondRegionA; public ITextureRegion tutorialSecondRegionB; public ITextureRegion tutorialLetsGoRegion; public ITextureRegion tutorialFirstRegionA; public ITextureRegion tutorialFirstRegionB; public IFont scoreFont; public IFont levelChoiceFont; public IFont movesScoreFont; public IFont levelChoiceSWFont; public LevelService levelService; private boolean preparedTextures = false; public MusicService musicService; public SettingsService settingsService; public ITextureRegion levelChoiseStarRegion; public ITextureRegion levelChoiseStarSWRegion; public IFont minMovesFont; public IFont levelFont; public void loadMenuSceneResources() { loadMenuSceneGraphics(); } public void loadLoadingSceneResources() { loadingScreenBackgroundRegion = resourceLoader.getTexture("scenes/loading/LoadingScreen2.png"); loadingScreenBackgroundRegion.getTexture().load(); //TODO: Unload loadingScreenBackgroundRegion } public void loadGameSceneResources() { loadGameSceneGraphics(); scoreFont = resourceLoader.getFont("Impact.ttf", TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA, 200, Color.WHITE, 2, Color.TRANSPARENT); minMovesFont = resourceLoader.getFont("Impact.ttf", TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA, 200, Color.WHITE, 2, Color.TRANSPARENT); levelFont = resourceLoader.getFont("Impact.ttf", TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA, 200, Color.WHITE, 2, Color.TRANSPARENT); } public void loadLevelChoiceSceneResources() { prepareTextures(); levelChoiceRegion.getTexture().load(); levelChoiceRegionSW.getTexture().load(); levelChoiceRegionLocked.getTexture().load(); levelChoiceArrowLeftRegion.getTexture().load(); levelChoiceArrowRightRegion.getTexture().load(); levelChoiseStarRegion.getTexture().load(); levelChoiseStarSWRegion.getTexture().load(); levelChoiceFont = resourceLoader.getFont("Impact.ttf", TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA, 110, 0xFFca540f, 0, 0xFFca540f); levelChoiceSWFont = resourceLoader.getFont("Impact.ttf", TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA, 110, 0xFF808080, 0, 0xFF808080); } public void loadScoreSceneResources() { prepareTextures(); movesScoreFont = resourceLoader.getFont("DroidSans-Bold.ttf", TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA, 100, Color.WHITE, 0, 0x00000000); starRegion.getTexture().load(); starSWRegion.getTexture().load(); nextLevelRegion.getTexture().load(); backToChoiceRegion.getTexture().load(); backToMenuRegionA.getTexture().load(); backToMenuRegionP.getTexture().load(); } private void loadMenuSceneGraphics() { prepareTextures(); level_mode_region.getTexture().load(); settingsRegion.getTexture().load(); } private void loadGameSceneGraphics() { prepareTextures(); regionTileMap = this.resourceLoader.getTileTextures(); for (TextureRegion textureRegion : regionTileMap.values()) { textureRegion.getTexture().load(); } tilesBorderRegion.getTexture().load(); restartRegion.getTexture().load(); } public void unloadGameSceneResources() { unloadGameSceneTextures(); } public void unloadLevelChoiceSceneTextures() { levelChoiceRegion.getTexture().unload(); levelChoiceRegionSW.getTexture().unload(); levelChoiceRegionLocked.getTexture().unload(); levelChoiceArrowLeftRegion.getTexture().unload(); levelChoiceArrowRightRegion.getTexture().unload(); levelChoiseStarRegion.getTexture().unload(); levelChoiseStarSWRegion.getTexture().unload(); levelChoiceFont.getTexture().unload(); levelChoiceSWFont.getTexture().unload(); levelChoiceFont = null; levelChoiceSWFont = null; } public void unloadMenuSceneResources() { unloadMenuSceneTextures(); } private void unloadMenuSceneTextures() { level_mode_region.getTexture().unload(); settingsRegion.getTexture().unload(); } private void unloadGameSceneTextures() { for (TextureRegion textureRegion : regionTileMap.values()) { textureRegion.getTexture().unload(); } restartRegion.getTexture().unload(); tilesBorderRegion.getTexture().unload(); scoreFont.getTexture().unload(); scoreFont = null; } public static void prepareManager(Engine engine, GameActivity activity, Camera camera, VertexBufferObjectManager vbom, ResourceLoader resourceLoader, SceneService sceneService, LevelService levelService, SettingsService settingsService) { getInstance().engine = engine; getInstance().activity = activity; getInstance().camera = camera; getInstance().vbom = vbom; getInstance().resourceLoader = resourceLoader; getInstance().sceneService = sceneService; getInstance().levelService = levelService; getInstance().musicService = new MusicService(MediaPlayer.create(activity.getApplicationContext(), R.raw.theme), true); getInstance().settingsService = settingsService; } public static ResourcesManager getInstance() { return INSTANCE; } public void unloadScoreSceneResources() { movesScoreFont.getTexture().unload(); starRegion.getTexture().unload(); starSWRegion.getTexture().unload(); nextLevelRegion.getTexture().unload(); backToChoiceRegion.getTexture().unload(); backToMenuRegionA.getTexture().unload(); backToMenuRegionP.getTexture().unload(); } public void loadSettingsScene() { prepareTextures(); muteRegion.getTexture().load(); unMuteRegion.getTexture().load(); } public void unloadSettingsScene() { muteRegion.getTexture().unload(); unMuteRegion.getTexture().unload(); } public void prepareTextures() { if (!preparedTextures) { levelChoiceRegion = resourceLoader.getTexture("scenes/levelChoice/Level.png"); levelChoiceRegionSW = resourceLoader.getTexture("scenes/levelChoice/LevelSW.png"); levelChoiceRegionLocked = resourceLoader.getTexture("scenes/levelChoice/LevelSW.png"); levelChoiceArrowLeftRegion = resourceLoader.getTexture("scenes/levelChoice/ArrowLeft.png"); levelChoiceArrowRightRegion = resourceLoader.getTexture("scenes/levelChoice/ArrowRight.png"); levelChoiseStarRegion = resourceLoader.getTexture("scenes/levelChoice/star.png"); levelChoiseStarSWRegion = resourceLoader.getTexture("scenes/levelChoice/starSW.png"); starRegion = resourceLoader.getTexture("scenes/score/star.png"); starSWRegion = resourceLoader.getTexture("scenes/score/starSW.png"); nextLevelRegion = resourceLoader.getTexture("scenes/score/NextLevel.png"); backToChoiceRegion = resourceLoader.getTexture("scenes/score/LevelChoice.png"); backToMenuRegionA = resourceLoader.getTexture("scenes/score/Restart.png"); backToMenuRegionP = resourceLoader.getTexture("scenes/score/BackP.png"); level_mode_region = resourceLoader.getTexture("scenes/menu/LevelMode.png"); settingsRegion = resourceLoader.getTexture("scenes/menu/Settings.png"); regionTileMap = this.resourceLoader.getTileTextures(); tilesBorderRegion = resourceLoader.getTexture("scenes/game/borders.png"); restartRegion = resourceLoader.getTexture("scenes/game/Restart.png"); muteRegion = resourceLoader.getTexture("scenes/settings/mute.png"); unMuteRegion = resourceLoader.getTexture("scenes/settings/unmute.png"); tutorialLetsGoRegion = resourceLoader.getTexture("scenes/tutorial/letsGo.png"); tutorialFirstRegionB = resourceLoader.getTexture("scenes/tutorial/firstTutorialScreenB.png"); tutorialFirstRegionA = resourceLoader.getTexture("scenes/tutorial/firstTutorialScreenA.png"); tutorialSecondRegionA = resourceLoader.getTexture("scenes/tutorial/secondTutorialScreenA.png"); tutorialSecondRegionB = resourceLoader.getTexture("scenes/tutorial/secondTutorialScreenB.png"); } preparedTextures = true; } public void loadTutorialSceneResources() { prepareTextures(); tutorialFirstRegionB.getTexture().load(); tutorialFirstRegionA.getTexture().load(); tutorialSecondRegionA.getTexture().load(); tutorialSecondRegionB.getTexture().load(); tutorialLetsGoRegion.getTexture().load(); } public void unloadTutorialScene() { tutorialLetsGoRegion.getTexture().unload(); tutorialSecondRegionA.getTexture().unload(); tutorialSecondRegionB.getTexture().unload(); tutorialFirstRegionA.getTexture().unload(); tutorialFirstRegionB.getTexture().unload(); } }
app/src/main/java/de/sopa/manager/ResourcesManager.java
package de.sopa.manager; import android.graphics.Color; import android.media.MediaPlayer; import de.sopa.GameActivity; import de.sopa.R; import de.sopa.helper.LevelService; import java.util.Map; import org.andengine.engine.Engine; import org.andengine.engine.camera.Camera; import org.andengine.opengl.font.IFont; import org.andengine.opengl.texture.TextureOptions; import org.andengine.opengl.texture.region.ITextureRegion; import org.andengine.opengl.texture.region.TextureRegion; import org.andengine.opengl.vbo.VertexBufferObjectManager; /** * David Schilling - [email protected] */ public class ResourcesManager { private static final ResourcesManager INSTANCE = new ResourcesManager(); public SceneService sceneService; public Engine engine; public GameActivity activity; public Camera camera; public VertexBufferObjectManager vbom; private ResourceLoader resourceLoader; public ITextureRegion level_mode_region; public ITextureRegion settingsRegion; public ITextureRegion loadingScreenBackgroundRegion; public Map<Character, TextureRegion> regionTileMap; public ITextureRegion tilesBorderRegion; public ITextureRegion levelChoiceRegion; public ITextureRegion levelChoiceArrowRightRegion; public ITextureRegion levelChoiceArrowLeftRegion; public ITextureRegion levelChoiceRegionLocked; public ITextureRegion starRegion; public ITextureRegion starSWRegion; public ITextureRegion backToChoiceRegion; public ITextureRegion muteRegion; public ITextureRegion nextLevelRegion; public ITextureRegion levelChoiceRegionSW; public ITextureRegion backToMenuRegionA; public ITextureRegion backToMenuRegionP; public ITextureRegion restartRegion; public ITextureRegion unMuteRegion; public ITextureRegion tutorialSecondRegionA; public ITextureRegion tutorialSecondRegionB; public ITextureRegion tutorialLetsGoRegion; public ITextureRegion tutorialFirstRegionA; public ITextureRegion tutorialFirstRegionB; public IFont scoreFont; public IFont levelChoiceFont; public IFont movesScoreFont; public IFont settingsFont; public IFont levelChoiceSWFont; public LevelService levelService; private boolean preparedTextures = false; public MusicService musicService; public SettingsService settingsService; public ITextureRegion levelChoiseStarRegion; public ITextureRegion levelChoiseStarSWRegion; public IFont minMovesFont; public IFont levelFont; public void loadMenuSceneResources() { loadMenuSceneGraphics(); } public void loadLoadingSceneResources() { loadingScreenBackgroundRegion = resourceLoader.getTexture("scenes/loading/LoadingScreen2.png"); loadingScreenBackgroundRegion.getTexture().load(); //TODO: Unload loadingScreenBackgroundRegion } public void loadGameSceneResources() { loadGameSceneGraphics(); scoreFont = resourceLoader.getFont("Impact.ttf", TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA, 200, Color.WHITE, 2, Color.TRANSPARENT); minMovesFont = resourceLoader.getFont("Impact.ttf", TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA, 200, Color.WHITE, 2, Color.TRANSPARENT); levelFont = resourceLoader.getFont("Impact.ttf", TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA, 200, Color.WHITE, 2, Color.TRANSPARENT); } public void loadLevelChoiceSceneResources() { prepareTextures(); levelChoiceRegion.getTexture().load(); levelChoiceRegionSW.getTexture().load(); levelChoiceRegionLocked.getTexture().load(); levelChoiceArrowLeftRegion.getTexture().load(); levelChoiceArrowRightRegion.getTexture().load(); levelChoiseStarRegion.getTexture().load(); levelChoiseStarSWRegion.getTexture().load(); levelChoiceFont = resourceLoader.getFont("Impact.ttf", TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA, 110, 0xFFca540f, 0, 0xFFca540f); levelChoiceSWFont = resourceLoader.getFont("Impact.ttf", TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA, 110, 0xFF808080, 0, 0xFF808080); } public void loadScoreSceneResources() { prepareTextures(); movesScoreFont = resourceLoader.getFont("DroidSans-Bold.ttf", TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA, 100, Color.WHITE, 0, 0x00000000); starRegion.getTexture().load(); starSWRegion.getTexture().load(); nextLevelRegion.getTexture().load(); backToChoiceRegion.getTexture().load(); backToMenuRegionA.getTexture().load(); backToMenuRegionP.getTexture().load(); } private void loadMenuSceneGraphics() { prepareTextures(); level_mode_region.getTexture().load(); settingsRegion.getTexture().load(); } private void loadGameSceneGraphics() { prepareTextures(); regionTileMap = this.resourceLoader.getTileTextures(); for (TextureRegion textureRegion : regionTileMap.values()) { textureRegion.getTexture().load(); } tilesBorderRegion.getTexture().load(); restartRegion.getTexture().load(); } public void unloadGameSceneResources() { unloadGameSceneTextures(); } public void unloadLevelChoiceSceneTextures() { levelChoiceRegion.getTexture().unload(); levelChoiceRegionSW.getTexture().unload(); levelChoiceRegionLocked.getTexture().unload(); levelChoiceArrowLeftRegion.getTexture().unload(); levelChoiceArrowRightRegion.getTexture().unload(); levelChoiseStarRegion.getTexture().unload(); levelChoiseStarSWRegion.getTexture().unload(); levelChoiceFont.getTexture().unload(); levelChoiceSWFont.getTexture().unload(); levelChoiceFont = null; levelChoiceSWFont = null; } public void unloadMenuSceneResources() { unloadMenuSceneTextures(); } private void unloadMenuSceneTextures() { level_mode_region.getTexture().unload(); settingsRegion.getTexture().unload(); } private void unloadGameSceneTextures() { for (TextureRegion textureRegion : regionTileMap.values()) { textureRegion.getTexture().unload(); } restartRegion.getTexture().unload(); tilesBorderRegion.getTexture().unload(); scoreFont.getTexture().unload(); scoreFont = null; } public static void prepareManager(Engine engine, GameActivity activity, Camera camera, VertexBufferObjectManager vbom, ResourceLoader resourceLoader, SceneService sceneService, LevelService levelService, SettingsService settingsService) { getInstance().engine = engine; getInstance().activity = activity; getInstance().camera = camera; getInstance().vbom = vbom; getInstance().resourceLoader = resourceLoader; getInstance().sceneService = sceneService; getInstance().levelService = levelService; getInstance().musicService = new MusicService(MediaPlayer.create(activity.getApplicationContext(), R.raw.theme), true); getInstance().settingsService = settingsService; } public static ResourcesManager getInstance() { return INSTANCE; } public void unloadScoreSceneResources() { movesScoreFont.getTexture().unload(); starRegion.getTexture().unload(); starSWRegion.getTexture().unload(); nextLevelRegion.getTexture().unload(); backToChoiceRegion.getTexture().unload(); backToMenuRegionA.getTexture().unload(); backToMenuRegionP.getTexture().unload(); } public void loadSettingsScene() { prepareTextures(); muteRegion.getTexture().load(); unMuteRegion.getTexture().load(); settingsFont = resourceLoader.getFont("Impact.ttf", TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA, 100, Color.BLUE, 0, Color.BLUE); } public void unloadSettingsScene() { muteRegion.getTexture().unload(); unMuteRegion.getTexture().unload(); settingsFont.unload(); settingsFont = null; } public void prepareTextures() { if (!preparedTextures) { levelChoiceRegion = resourceLoader.getTexture("scenes/levelChoice/Level.png"); levelChoiceRegionSW = resourceLoader.getTexture("scenes/levelChoice/LevelSW.png"); levelChoiceRegionLocked = resourceLoader.getTexture("scenes/levelChoice/LevelSW.png"); levelChoiceArrowLeftRegion = resourceLoader.getTexture("scenes/levelChoice/ArrowLeft.png"); levelChoiceArrowRightRegion = resourceLoader.getTexture("scenes/levelChoice/ArrowRight.png"); levelChoiseStarRegion = resourceLoader.getTexture("scenes/levelChoice/star.png"); levelChoiseStarSWRegion = resourceLoader.getTexture("scenes/levelChoice/starSW.png"); starRegion = resourceLoader.getTexture("scenes/score/star.png"); starSWRegion = resourceLoader.getTexture("scenes/score/starSW.png"); nextLevelRegion = resourceLoader.getTexture("scenes/score/NextLevel.png"); backToChoiceRegion = resourceLoader.getTexture("scenes/score/LevelChoice.png"); backToMenuRegionA = resourceLoader.getTexture("scenes/score/Restart.png"); backToMenuRegionP = resourceLoader.getTexture("scenes/score/BackP.png"); level_mode_region = resourceLoader.getTexture("scenes/menu/LevelMode.png"); settingsRegion = resourceLoader.getTexture("scenes/menu/Settings.png"); regionTileMap = this.resourceLoader.getTileTextures(); tilesBorderRegion = resourceLoader.getTexture("scenes/game/borders.png"); restartRegion = resourceLoader.getTexture("scenes/game/Restart.png"); muteRegion = resourceLoader.getTexture("scenes/settings/mute.png"); unMuteRegion = resourceLoader.getTexture("scenes/settings/unmute.png"); tutorialLetsGoRegion = resourceLoader.getTexture("scenes/tutorial/letsGo.png"); tutorialFirstRegionB = resourceLoader.getTexture("scenes/tutorial/firstTutorialScreenB.png"); tutorialFirstRegionA = resourceLoader.getTexture("scenes/tutorial/firstTutorialScreenA.png"); tutorialSecondRegionA = resourceLoader.getTexture("scenes/tutorial/secondTutorialScreenA.png"); tutorialSecondRegionB = resourceLoader.getTexture("scenes/tutorial/secondTutorialScreenB.png"); } preparedTextures = true; } public void loadTutorialSceneResources() { prepareTextures(); tutorialFirstRegionB.getTexture().load(); tutorialFirstRegionA.getTexture().load(); tutorialSecondRegionA.getTexture().load(); tutorialSecondRegionB.getTexture().load(); tutorialLetsGoRegion.getTexture().load(); } public void unloadTutorialScene() { tutorialLetsGoRegion.getTexture().unload(); tutorialSecondRegionA.getTexture().unload(); tutorialSecondRegionB.getTexture().unload(); tutorialFirstRegionA.getTexture().unload(); tutorialFirstRegionB.getTexture().unload(); } }
remove unused font loading
app/src/main/java/de/sopa/manager/ResourcesManager.java
remove unused font loading
Java
apache-2.0
489d9ff447a95cfd8bf3d06acf909210439592bc
0
dimagi/commcare-core,dimagi/commcare,dimagi/javarosa,dimagi/javarosa,dimagi/commcare-core,dimagi/commcare,dimagi/javarosa,dimagi/commcare-core,dimagi/commcare
/** * */ package org.commcare.xml; import java.io.IOException; import java.io.InputStream; import org.commcare.resources.model.Resource; import org.commcare.resources.model.ResourceTable; import org.commcare.resources.model.installers.LoginImageInstaller; import org.commcare.resources.model.installers.SuiteInstaller; import org.commcare.suite.model.Profile; import org.commcare.util.CommCareInstance; import org.commcare.xml.util.InvalidStructureException; import org.commcare.xml.util.UnfullfilledRequirementsException; import org.javarosa.core.reference.RootTranslator; import org.javarosa.core.services.storage.StorageFullException; import org.kxml2.io.KXmlParser; import org.xmlpull.v1.XmlPullParserException; /** * @author ctsims * */ public class ProfileParser extends ElementParser<Profile> { ResourceTable table; String resourceId; int initialResourceStatus; CommCareInstance instance; boolean forceVersion = false; public ProfileParser(InputStream suiteStream, CommCareInstance instance, ResourceTable table, String resourceId, int initialResourceStatus, boolean forceVersion) throws IOException { super(suiteStream); this.table = table; this.resourceId = resourceId; this.initialResourceStatus = initialResourceStatus; this.instance = instance; this.forceVersion = forceVersion; } public Profile parse() throws InvalidStructureException, IOException, XmlPullParserException, UnfullfilledRequirementsException { checkNode("profile"); String sVersion = parser.getAttributeValue(null, "version"); int version = parseInt(sVersion); String authRef = parser.getAttributeValue(null, "update"); String sMajor = parser.getAttributeValue(null,"requiredMajor"); String sMinor = parser.getAttributeValue(null,"requiredMinor"); //String uniqueId = parser.getAttributeValue(null, "uniqueId"); int major = -1; int minor = -1; if(sMajor != null) { major = parseInt(sMajor); } if(sMinor != null) { minor = parseInt(sMinor); } //If version information is available, check valid versions if ((!forceVersion && this.instance != null) && (major != -1) && (minor != -1)){ //For the major version, only a matching number is valid, 2.0 cannot be run on either 1.0 or 3.0 if (this.instance.getMajorVersion() != -1 && this.instance.getMajorVersion() != major) { //changed < to != throw new UnfullfilledRequirementsException( "Major Version Mismatch (Required: " + major + " | Available: " + this.instance.getMajorVersion() + ")", UnfullfilledRequirementsException.SEVERITY_PROMPT, UnfullfilledRequirementsException.REQUIREMENT_MAJOR_APP_VERSION,major,minor,this.instance.getMajorVersion(),this.instance.getMinorVersion()); } //For the minor version, anything greater than the profile's version is valid if (this.instance.getMinorVersion() != -1 && this.instance.getMinorVersion() < minor) { throw new UnfullfilledRequirementsException( "Minor Version Mismatch (Required: " + minor + " | Available: " + this.instance.getMinorVersion() + ")", UnfullfilledRequirementsException.SEVERITY_PROMPT, UnfullfilledRequirementsException.REQUIREMENT_MINOR_APP_VERSION,major,minor,this.instance.getMajorVersion(),this.instance.getMinorVersion()); } } String registrationNamespace = null; //TODO: change resourceId to actual uniqueId Profile profile = new Profile(version, authRef, resourceId); try { // Now that we've covered being inside of the profile, // start traversing. parser.next(); int eventType; eventType = parser.getEventType(); do { if (eventType == KXmlParser.END_DOCUMENT) { } else if (eventType == KXmlParser.START_TAG) { if (parser.getName().toLowerCase().equals("property")) { String key = parser.getAttributeValue(null,"key"); String value = parser.getAttributeValue(null,"value"); String force = parser.getAttributeValue(null,"force"); if(force != null) { if("true".equals(force.toLowerCase())) { profile.addPropertySetter(key,value, true); } else { profile.addPropertySetter(key,value,false); } } else { profile.addPropertySetter(key,value); } } else if (parser.getName().toLowerCase().equals("root")) { RootTranslator root = new RootParser(this.parser).parse(); profile.addRoot(root); } else if (parser.getName().toLowerCase().equals("login")) { //Get the resource block or fail out getNextTagInBlock("login"); Resource resource = new ResourceParser(parser, maximumResourceAuthority).parse(); table.addResource(resource, table.getInstallers().getLoginImageInstaller(), resourceId,initialResourceStatus); } else if (parser.getName().toLowerCase().equals("features")) { while(nextTagInBlock("features")) { String tag = parser.getName().toLowerCase(); String active = parser.getAttributeValue(null,"active"); boolean isActive = false; if (active != null && active.toLowerCase().equals("true")) { isActive = true; } if (tag.equals("checkoff")) { } else if (tag.equals("reminders")) { if(nextTagInBlock("reminders")) { checkNode("time"); String reminderTime = parser.nextText(); int days = this.parseInt(reminderTime); } } else if (tag.equals("package")) { //nothing (yet) } else if (tag.equals("users")) { while(nextTagInBlock("users")) { if(parser.getName().toLowerCase().equals("registration")) { registrationNamespace = parser.nextText(); profile.addPropertySetter("user_reg_namespace", registrationNamespace, true); } else if(parser.getName().toLowerCase().equals("logo")) { String logo = parser.nextText(); profile.addPropertySetter("cc_login_image", logo, true); } else { throw new InvalidStructureException("Unrecognized tag " + parser.getName() + " inside of users feature block", parser); } } } else if (tag.equals("sense")) { } profile.setFeatureActive(tag, isActive); //TODO: set feature activation in profile } } else if (parser.getName().toLowerCase().equals("suite")) { // Get the resource block or fail out getNextTagInBlock("suite"); Resource resource = new ResourceParser(parser, maximumResourceAuthority).parse(); //TODO: Possibly add a real parent reference if we decide these go in the table table.addResource(resource, table.getInstallers().getSuiteInstaller(), resourceId, initialResourceStatus); } else { System.out.println("Unrecognized Tag: " + parser.getName()); } } else if (eventType == KXmlParser.END_TAG) { // we shouldn't ever get this I don't believe, maybe on the // last node? } else if (eventType == KXmlParser.TEXT) { // Shouldn't ever get this (Delete the if, if so). } eventType = parser.next(); } while (eventType != KXmlParser.END_DOCUMENT); return profile; } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new InvalidStructureException("Pull Parse Exception, malformed XML.",parser); } catch (StorageFullException e) { e.printStackTrace(); //BUT not really! This should maybe be added to the high level declaration //instead? Or maybe there should be a more general Resource Management Exception? throw new InvalidStructureException("Problem storing parser suite XML",parser); } } int maximumResourceAuthority = -1; public void setMaximumAuthority(int authority) { maximumResourceAuthority = authority; } }
backend/src/org/commcare/xml/ProfileParser.java
/** * */ package org.commcare.xml; import java.io.IOException; import java.io.InputStream; import org.commcare.resources.model.Resource; import org.commcare.resources.model.ResourceTable; import org.commcare.resources.model.installers.LoginImageInstaller; import org.commcare.resources.model.installers.SuiteInstaller; import org.commcare.suite.model.Profile; import org.commcare.util.CommCareInstance; import org.commcare.xml.util.InvalidStructureException; import org.commcare.xml.util.UnfullfilledRequirementsException; import org.javarosa.core.reference.RootTranslator; import org.javarosa.core.services.storage.StorageFullException; import org.kxml2.io.KXmlParser; import org.xmlpull.v1.XmlPullParserException; /** * @author ctsims * */ public class ProfileParser extends ElementParser<Profile> { ResourceTable table; String resourceId; int initialResourceStatus; CommCareInstance instance; boolean forceVersion = false; public ProfileParser(InputStream suiteStream, CommCareInstance instance, ResourceTable table, String resourceId, int initialResourceStatus, boolean forceVersion) throws IOException { super(suiteStream); this.table = table; this.resourceId = resourceId; this.initialResourceStatus = initialResourceStatus; this.instance = instance; this.forceVersion = forceVersion; } public Profile parse() throws InvalidStructureException, IOException, XmlPullParserException, UnfullfilledRequirementsException { checkNode("profile"); String sVersion = parser.getAttributeValue(null, "version"); int version = parseInt(sVersion); String authRef = parser.getAttributeValue(null, "update"); String sMajor = parser.getAttributeValue(null,"requiredMajor"); String sMinor = parser.getAttributeValue(null,"requiredMinor"); //String uniqueId = parser.getAttributeValue(null, "uniqueId"); int major = -1; int minor = -1; if(sMajor != null) { major = parseInt(sMajor); } if(sMinor != null) { minor = parseInt(sMinor); } //If version information is available, check valid versions if ((!forceVersion && this.instance != null) && (major != -1) && (minor != -1)){ //For the major version, only a matching number is valid, 2.0 cannot be run on either 1.0 or 3.0 if (this.instance.getMajorVersion() != -1 && this.instance.getMajorVersion() != major) { //changed < to != throw new UnfullfilledRequirementsException( "Major Version Mismatch (Required: " + major + " | Available: " + this.instance.getMajorVersion() + ")", UnfullfilledRequirementsException.SEVERITY_PROMPT, UnfullfilledRequirementsException.REQUIREMENT_MAJOR_APP_VERSION,major,minor,this.instance.getMajorVersion(),this.instance.getMinorVersion()); } //For the minor version, anything greater than the profile's version is valid if (this.instance.getMinorVersion() != -1 && this.instance.getMinorVersion() < minor) { throw new UnfullfilledRequirementsException( "Minor Version Mismatch (Required: " + minor + " | Available: " + this.instance.getMinorVersion() + ")", UnfullfilledRequirementsException.SEVERITY_PROMPT, UnfullfilledRequirementsException.REQUIREMENT_MINOR_APP_VERSION,major,minor,this.instance.getMajorVersion(),this.instance.getMinorVersion()); } } String registrationNamespace = null; //TODO: pass uniqueId to this Profile profile = new Profile(version, authRef, ""); try { // Now that we've covered being inside of the profile, // start traversing. parser.next(); int eventType; eventType = parser.getEventType(); do { if (eventType == KXmlParser.END_DOCUMENT) { } else if (eventType == KXmlParser.START_TAG) { if (parser.getName().toLowerCase().equals("property")) { String key = parser.getAttributeValue(null,"key"); String value = parser.getAttributeValue(null,"value"); String force = parser.getAttributeValue(null,"force"); if(force != null) { if("true".equals(force.toLowerCase())) { profile.addPropertySetter(key,value, true); } else { profile.addPropertySetter(key,value,false); } } else { profile.addPropertySetter(key,value); } } else if (parser.getName().toLowerCase().equals("root")) { RootTranslator root = new RootParser(this.parser).parse(); profile.addRoot(root); } else if (parser.getName().toLowerCase().equals("login")) { //Get the resource block or fail out getNextTagInBlock("login"); Resource resource = new ResourceParser(parser, maximumResourceAuthority).parse(); table.addResource(resource, table.getInstallers().getLoginImageInstaller(), resourceId,initialResourceStatus); } else if (parser.getName().toLowerCase().equals("features")) { while(nextTagInBlock("features")) { String tag = parser.getName().toLowerCase(); String active = parser.getAttributeValue(null,"active"); boolean isActive = false; if (active != null && active.toLowerCase().equals("true")) { isActive = true; } if (tag.equals("checkoff")) { } else if (tag.equals("reminders")) { if(nextTagInBlock("reminders")) { checkNode("time"); String reminderTime = parser.nextText(); int days = this.parseInt(reminderTime); } } else if (tag.equals("package")) { //nothing (yet) } else if (tag.equals("users")) { while(nextTagInBlock("users")) { if(parser.getName().toLowerCase().equals("registration")) { registrationNamespace = parser.nextText(); profile.addPropertySetter("user_reg_namespace", registrationNamespace, true); } else if(parser.getName().toLowerCase().equals("logo")) { String logo = parser.nextText(); profile.addPropertySetter("cc_login_image", logo, true); } else { throw new InvalidStructureException("Unrecognized tag " + parser.getName() + " inside of users feature block", parser); } } } else if (tag.equals("sense")) { } profile.setFeatureActive(tag, isActive); //TODO: set feature activation in profile } } else if (parser.getName().toLowerCase().equals("suite")) { // Get the resource block or fail out getNextTagInBlock("suite"); Resource resource = new ResourceParser(parser, maximumResourceAuthority).parse(); //TODO: Possibly add a real parent reference if we decide these go in the table table.addResource(resource, table.getInstallers().getSuiteInstaller(), resourceId, initialResourceStatus); } else { System.out.println("Unrecognized Tag: " + parser.getName()); } } else if (eventType == KXmlParser.END_TAG) { // we shouldn't ever get this I don't believe, maybe on the // last node? } else if (eventType == KXmlParser.TEXT) { // Shouldn't ever get this (Delete the if, if so). } eventType = parser.next(); } while (eventType != KXmlParser.END_DOCUMENT); return profile; } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new InvalidStructureException("Pull Parse Exception, malformed XML.",parser); } catch (StorageFullException e) { e.printStackTrace(); //BUT not really! This should maybe be added to the high level declaration //instead? Or maybe there should be a more general Resource Management Exception? throw new InvalidStructureException("Problem storing parser suite XML",parser); } } int maximumResourceAuthority = -1; public void setMaximumAuthority(int authority) { maximumResourceAuthority = authority; } }
ProfileParser ready to get uniqueId from profile.xml once implemented in HQ
backend/src/org/commcare/xml/ProfileParser.java
ProfileParser ready to get uniqueId from profile.xml once implemented in HQ
Java
apache-2.0
63999e5b8a4310c5fb3309b82b31774e27f0309e
0
Z-starts/hutool,WilliamRen/hutool,WilliamRen/hutool,Z-starts/hutool
package com.xiaoleilu.hutool.db; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import com.xiaoleilu.hutool.Conver; import com.xiaoleilu.hutool.InjectUtil; import com.xiaoleilu.hutool.StrUtil; import com.xiaoleilu.hutool.exceptions.UtilException; /** * 数据实体对象<br> * 数据实体类充当两个角色:<br> * 1. 数据的载体,一个Entity对应数据库中的一个row<br> * 2. SQL条件,Entity中的每一个字段对应一个条件,字段值对应条件的值 * @author loolly * */ public class Entity extends HashMap<String, Object>{ private static final long serialVersionUID = -1951012511464327448L; //--------------------------------------------------------------- Static method start /** * 创建Entity * @param tableName 表名 * @return Entity */ public static Entity create(String tableName) { return new Entity(tableName); } /** * 将PO对象转为Entity * @param <T> * @param vo 值对象 * @return Entity */ public static <T> Entity parse(T vo) { return create(null).fromVo(vo); } //--------------------------------------------------------------- Static method end private String tableName; //--------------------------------------------------------------- Constructor start public Entity() { } /** * 构造 * @param tableName 数据表名 */ public Entity(String tableName) { this.tableName = tableName; } //--------------------------------------------------------------- Constructor end //--------------------------------------------------------------- Getters and Setters start /** * @return 获得表名 */ public String getTableName() { return tableName; } /** * 设置表名 * @param tableName 表名 * @return 本身 */ public Entity setTableName(String tableName) { this.tableName = tableName; return this; } //--------------------------------------------------------------- Getters and Setters end /** * 填充Value Object对象 * @param <T> * @param vo Value Object(或者POJO) * @return Entity */ public <T> Entity fillVo(T vo) { InjectUtil.injectFromMap(vo, this); return this; } /** * 填充Value Object对象 * @param clazz Value Object(或者POJO)的类 * @param ignoreCase 是否忽略大小写 * @return vo */ public <T> T toVo(Class<T> clazz, boolean ignoreCase) { if(clazz == null) { throw new NullPointerException("Provided Class is null!"); } T vo; try { vo = clazz.newInstance(); } catch (Exception e) { throw new UtilException(StrUtil.format("Instance Value Object [] error!", clazz.getName())); } if(ignoreCase){ InjectUtil.injectFromMapIgnoreCase(vo, this); }else{ InjectUtil.injectFromMap(vo, this); } return vo; } /** * 填充Value Object对象 * @param clazz Value Object(或者POJO)的类 * @return vo */ public <T> T toVo(Class<T> clazz) { return toVo(clazz, false); } /** * 填充Value Object对象,忽略大小写 * @param clazz Value Object(或者POJO)的类 * @return vo */ public <T> T toVoIgnoreCase(Class<T> clazz) { return toVo(clazz, true); } /** * 将值对象转换为Entity<br> * 类名会被当作表名,小写第一个字母 * @param <T> * @param vo 值对象 * @return 自己 */ public <T> Entity fromVo(T vo) { String tableName = vo.getClass().getSimpleName(); tableName = StrUtil.lowerFirst(tableName); this.setTableName(tableName); this.putAll(InjectUtil.toMap(vo, false)); return this; } /** * 与给定实体对比并去除相同的部分<br> * 此方法用于在更新操作时避免所有字段被更新,跳过不需要更新的字段 * version from 2.0.0 * @param entity * @param withoutNames 不需要去除的字段名 */ public <T extends Entity> void removeEqual(T entity, String... withoutNames) { HashSet<String> withoutSet = new HashSet<String>(); for (String name : withoutNames) { withoutSet.add(name); } for(Entry<String, Object> entry : entity.entrySet()) { if(withoutSet.contains(entry.getKey())) { continue; } final Object value = this.get(entry.getKey()); if(null != value && value.equals(entry.getValue())) { this.remove(entry.getKey()); } } } //-------------------------------------------------------------------- 特定类型值 /** * 设置列 * @param attr 属性 * @param value 值 * @return 本身 */ public Entity set(String attr, Object value) { super.put(attr, value); return this; } /** * 设置列,当键或值为null时忽略 * @param attr 属性 * @param value 值 * @return 本身 */ public Entity setIgnoreNull(String attr, Object value) { if(null != attr && null != value) { set(attr, value); } return this; } /** * 获得特定类型值 * @param attr 字段名 * @param defaultValue 默认值 * @return 字段值 */ @SuppressWarnings("unchecked") public <T> T get(String attr, T defaultValue) { final Object result = get(attr); return (T)(result != null ? result : defaultValue); } /** * @param attr 字段名 * @return 字段值 */ public String getStr(String attr) { return Conver.toStr(get(attr), null); } /** * @param attr 字段名 * @return 字段值 */ public Integer getInt(String attr) { return Conver.toInt(get(attr), null); } /** * @param attr 字段名 * @return 字段值 */ public Long getLong(String attr) { return Conver.toLong(get(attr), null); } /** * @param attr 字段名 * @return 字段值 */ public Float getFloat(String attr) { return Conver.toFloat(get(attr), null); } /** * @param attr 字段名 * @return 字段值 */ public Boolean getBool(String attr) { return Conver.toBool(get(attr), null); } /** * @param attr 字段名 * @return 字段值 */ public byte[] getBytes(String attr) { return get(attr, null); } /** * @param attr 字段名 * @return 字段值 */ public Date getDate(String attr) { return get(attr, null); } /** * @param attr 字段名 * @return 字段值 */ public Time getTime(String attr) { return get(attr, null); } /** * @param attr 字段名 * @return 字段值 */ public Timestamp getTimestamp(String attr) { return get(attr, null); } /** * @param attr 字段名 * @return 字段值 */ public Number getNumber(String attr) { return get(attr, null); } /** * @param attr 字段名 * @return 字段值 */ public BigDecimal getBigDecimal(String attr) { return get(attr, null); } /** * @param attr 字段名 * @return 字段值 */ public BigInteger getBigInteger(String attr) { return get(attr, null); } }
src/main/java/com/xiaoleilu/hutool/db/Entity.java
package com.xiaoleilu.hutool.db; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import com.xiaoleilu.hutool.Conver; import com.xiaoleilu.hutool.InjectUtil; import com.xiaoleilu.hutool.StrUtil; import com.xiaoleilu.hutool.exceptions.UtilException; /** * 数据实体对象<br> * 数据实体类充当两个角色:<br> * 1. 数据的载体,一个Entity对应数据库中的一个row<br> * 2. SQL条件,Entity中的每一个字段对应一个条件,字段值对应条件的值 * @author loolly * */ public class Entity extends HashMap<String, Object>{ private static final long serialVersionUID = -1951012511464327448L; //--------------------------------------------------------------- Static method start /** * 创建Entity * @param tableName 表名 * @return Entity */ public static Entity create(String tableName) { return new Entity(tableName); } /** * 将PO对象转为Entity * @param <T> * @param vo 值对象 * @return Entity */ public static <T> Entity parse(T vo) { return create(null).fromVo(vo); } //--------------------------------------------------------------- Static method end private String tableName; //--------------------------------------------------------------- Constructor start public Entity() { } /** * 构造 * @param tableName 数据表名 */ public Entity(String tableName) { this.tableName = tableName; } //--------------------------------------------------------------- Constructor end //--------------------------------------------------------------- Getters and Setters start /** * @return 获得表名 */ public String getTableName() { return tableName; } /** * 设置表名 * @param tableName 表名 * @return 本身 */ public Entity setTableName(String tableName) { this.tableName = tableName; return this; } //--------------------------------------------------------------- Getters and Setters end /** * 填充Value Object对象 * @param <T> * @param vo Value Object(或者POJO) * @return Entity */ public <T> Entity fillVo(T vo) { InjectUtil.injectFromMap(vo, this); return this; } /** * 填充Value Object对象 * @param clazz Value Object(或者POJO)的类 * @param ignoreCase 是否忽略大小写 * @return vo */ public <T> T toVo(Class<T> clazz, boolean ignoreCase) { if(clazz == null) { throw new NullPointerException("Provided Class is null!"); } T vo; try { vo = clazz.newInstance(); } catch (Exception e) { throw new UtilException(StrUtil.format("Instance Value Object [] error!", clazz.getName())); } InjectUtil.injectFromMap(vo, this); return vo; } /** * 填充Value Object对象 * @param clazz Value Object(或者POJO)的类 * @return vo */ public <T> T toVo(Class<T> clazz) { return toVo(clazz, false); } /** * 填充Value Object对象,忽略大小写 * @param clazz Value Object(或者POJO)的类 * @return vo */ public <T> T toVoIgnoreCase(Class<T> clazz) { return toVo(clazz, true); } /** * 将值对象转换为Entity<br> * 类名会被当作表名,小写第一个字母 * @param <T> * @param vo 值对象 * @return 自己 */ public <T> Entity fromVo(T vo) { String tableName = vo.getClass().getSimpleName(); tableName = StrUtil.lowerFirst(tableName); this.setTableName(tableName); this.putAll(InjectUtil.toMap(vo, false)); return this; } /** * 与给定实体对比并去除相同的部分<br> * 此方法用于在更新操作时避免所有字段被更新,跳过不需要更新的字段 * version from 2.0.0 * @param entity * @param withoutNames 不需要去除的字段名 */ public <T extends Entity> void removeEqual(T entity, String... withoutNames) { HashSet<String> withoutSet = new HashSet<String>(); for (String name : withoutNames) { withoutSet.add(name); } for(Entry<String, Object> entry : entity.entrySet()) { if(withoutSet.contains(entry.getKey())) { continue; } final Object value = this.get(entry.getKey()); if(null != value && value.equals(entry.getValue())) { this.remove(entry.getKey()); } } } //-------------------------------------------------------------------- 特定类型值 /** * 设置列 * @param attr 属性 * @param value 值 * @return 本身 */ public Entity set(String attr, Object value) { super.put(attr, value); return this; } /** * 设置列,当键或值为null时忽略 * @param attr 属性 * @param value 值 * @return 本身 */ public Entity setIgnoreNull(String attr, Object value) { if(null != attr && null != value) { set(attr, value); } return this; } /** * 获得特定类型值 * @param attr 字段名 * @param defaultValue 默认值 * @return 字段值 */ @SuppressWarnings("unchecked") public <T> T get(String attr, T defaultValue) { final Object result = get(attr); return (T)(result != null ? result : defaultValue); } /** * @param attr 字段名 * @return 字段值 */ public String getStr(String attr) { return Conver.toStr(get(attr), null); } /** * @param attr 字段名 * @return 字段值 */ public Integer getInt(String attr) { return Conver.toInt(get(attr), null); } /** * @param attr 字段名 * @return 字段值 */ public Long getLong(String attr) { return Conver.toLong(get(attr), null); } /** * @param attr 字段名 * @return 字段值 */ public Float getFloat(String attr) { return Conver.toFloat(get(attr), null); } /** * @param attr 字段名 * @return 字段值 */ public Boolean getBool(String attr) { return Conver.toBool(get(attr), null); } /** * @param attr 字段名 * @return 字段值 */ public byte[] getBytes(String attr) { return get(attr, null); } /** * @param attr 字段名 * @return 字段值 */ public Date getDate(String attr) { return get(attr, null); } /** * @param attr 字段名 * @return 字段值 */ public Time getTime(String attr) { return get(attr, null); } /** * @param attr 字段名 * @return 字段值 */ public Timestamp getTimestamp(String attr) { return get(attr, null); } /** * @param attr 字段名 * @return 字段值 */ public Number getNumber(String attr) { return get(attr, null); } /** * @param attr 字段名 * @return 字段值 */ public BigDecimal getBigDecimal(String attr) { return get(attr, null); } /** * @param attr 字段名 * @return 字段值 */ public BigInteger getBigInteger(String attr) { return get(attr, null); } }
fix Entity
src/main/java/com/xiaoleilu/hutool/db/Entity.java
fix Entity
Java
apache-2.0
7ff104598535a7063d7b54388cd7a0c81777af93
0
bozimmerman/CoffeeMud,oriontribunal/CoffeeMud,Tycheo/coffeemud,sfunk1x/CoffeeMud,MaxRau/CoffeeMud,bozimmerman/CoffeeMud,sfunk1x/CoffeeMud,Tycheo/coffeemud,bozimmerman/CoffeeMud,MaxRau/CoffeeMud,oriontribunal/CoffeeMud,Tycheo/coffeemud,oriontribunal/CoffeeMud,sfunk1x/CoffeeMud,oriontribunal/CoffeeMud,MaxRau/CoffeeMud,bozimmerman/CoffeeMud,Tycheo/coffeemud,MaxRau/CoffeeMud,sfunk1x/CoffeeMud
package com.planet_ink.coffee_mud.Items; import com.planet_ink.coffee_mud.interfaces.*; import com.planet_ink.coffee_mud.common.*; import com.planet_ink.coffee_mud.utils.*; import java.util.*; import java.io.*; public class StdJournal extends StdItem { public StdJournal() { super(); myID=this.getClass().getName().substring(this.getClass().getName().lastIndexOf('.')+1); name="a journal"; displayText="a journal sits here."; description="Use the READ command to read the journal, and WRITE to add your own entries."; isReadable=true; } public Environmental newInstance() { return new StdJournal(); } public boolean okAffect(Affect affect) { MOB mob=affect.source(); if(affect.amITarget(this)) switch(affect.targetMinor()) { case Affect.TYP_WRITE: return true; } return super.okAffect(affect); } public void affect(Affect affect) { MOB mob=affect.source(); if(affect.amITarget(this)) switch(affect.targetMinor()) { case Affect.TYP_READSOMETHING: if(!Sense.canBeSeenBy(this,mob)) mob.tell("You can't see that!"); else if(!mob.isMonster()) { int which=-1; if(Util.s_long(affect.targetMessage())>0) which=Util.s_int(affect.targetMessage()); StringBuffer entry=DBRead(name(),mob.name(),which-1,Util.s_long(readableText().trim())); boolean mineAble=false; if(entry.charAt(0)=='*') { mineAble=true; entry.setCharAt(0,' '); } mob.tell(entry.toString()+"\n\r"); setReadableText(IQCalendar.getInstance().getTime().getTime()+""); if((entry.toString().trim().length()>0)&&(which>0)) { try { boolean reply=false; if(mineAble) { String s=mob.session().choose("R)eply, D)elete, or RETURN: ","RD\n","\n"); if(s.equalsIgnoreCase("R")) reply=true; else if(s.equalsIgnoreCase("D")) { ExternalPlay.DBDeleteJournal(name(),which-1); mob.tell("Entry deleted."); } } else reply=mob.session().confirm("Reply (y/N)?","N"); if(reply) { String replyMsg=mob.session().prompt("Enter your response\n\r: "); if(replyMsg.trim().length()>0) { ExternalPlay.DBWriteJournal(name(),mob.name(),"","",replyMsg,which-1); mob.tell("Reply added."); } else mob.tell("Aborted."); } } catch(IOException e) { Log.errOut("JournalItem",e); } } else if(which<0) { mob.tell("Enter 'READ [NUMBER] [JOURNAL]' to read an entry."); mob.tell("Use your WRITE skill to add new entries. "); } else mob.tell("That message is private."); return; } return; case Affect.TYP_WRITE: try { if((affect.targetMessage().toUpperCase().startsWith("DEL")) &&(mob.isASysOp(null)) &&(!mob.isMonster())) { if(mob.session().confirm("Delete all journal entries? Are you sure (y/N)?","N")) ExternalPlay.DBDeleteJournal(name(),-1); } else if(!mob.isMonster()) { String to="ALL"; if(mob.session().confirm("Is this a private message (y/N)?","N")) { to=mob.session().prompt("To whom:"); if(!ExternalPlay.DBUserSearch(null,to)) { mob.tell("I'm sorry, there is no such user."); return; } } String subject=mob.session().prompt("Enter a subject: "); if(subject.trim().length()==0) { mob.tell("Aborted."); return; } String message=mob.session().prompt("Enter your message\n\r: "); if(message.trim().length()==0) { mob.tell("Aborted."); return; } ExternalPlay.DBWriteJournal(name(),mob.name(),to,subject,message,-1); mob.tell("Journal entry added."); } return; } catch(IOException e) { Log.errOut("JournalItem",e); } return; } super.affect(affect); } public StringBuffer DBRead(String Journal, String username, int which, long lastTimeDate) { StringBuffer buf=new StringBuffer(""); Vector journal=ExternalPlay.DBReadJournal(Journal); if(which<0) { buf.append("\n\r "+Util.padRight("#",5)+Util.padRight("From",16)+Util.padRight("To",16)+"Subject\n\r"); buf.append("---------------------------------------------\n\r"); } if(journal==null) return buf; if((which<0)||(which>=journal.size())) { for(int j=0;j<journal.size();j++) { Vector entry=(Vector)journal.elementAt(j); String from=(String)entry.elementAt(1); String date=(String)entry.elementAt(2); String to=(String)entry.elementAt(3); String subject=(String)entry.elementAt(4); if(to.equals("ALL")||to.equalsIgnoreCase(username)||from.equalsIgnoreCase(username)) { if(Util.s_long(date)>lastTimeDate) buf.append("*"); else buf.append(" "); buf.append(Util.padRight((j+1)+"",3)+") "+Util.padRight(from,15)+" "+Util.padRight(to,15)+" "+subject+"\n\r"); } } } else { Vector entry=(Vector)journal.elementAt(which); String from=(String)entry.elementAt(1); String date=(String)entry.elementAt(2); String to=(String)entry.elementAt(3); String subject=(String)entry.elementAt(4); String message=(String)entry.elementAt(5); boolean mineAble=to.equalsIgnoreCase(username)||from.equalsIgnoreCase(username); if(mineAble) buf.append("*"); else buf.append(" "); if(to.equals("ALL")||mineAble) buf.append("\n\r"+Util.padRight((which+1)+"",3)+")\n\r"+"FROM: "+Util.padRight(from,15)+"\n\rTO : "+Util.padRight(to,15)+"\n\rSUBJ: "+subject+"\n\r"+message); } return buf; } }
com/planet_ink/coffee_mud/Items/StdJournal.java
package com.planet_ink.coffee_mud.Items; import com.planet_ink.coffee_mud.interfaces.*; import com.planet_ink.coffee_mud.common.*; import com.planet_ink.coffee_mud.utils.*; import java.util.*; import java.io.*; public class StdJournal extends StdItem { public StdJournal() { super(); myID=this.getClass().getName().substring(this.getClass().getName().lastIndexOf('.')+1); name="a journal"; displayText="a journal sits here."; description="Use the READ command to read the journal, and WRITE to add your own entries."; isReadable=true; } public Environmental newInstance() { return new StdJournal(); } public boolean okAffect(Affect affect) { MOB mob=affect.source(); if(affect.amITarget(this)) switch(affect.targetMinor()) { case Affect.TYP_WRITE: return true; } return super.okAffect(affect); } public void affect(Affect affect) { MOB mob=affect.source(); if(affect.amITarget(this)) switch(affect.targetMinor()) { case Affect.TYP_READSOMETHING: if(!Sense.canBeSeenBy(this,mob)) mob.tell("You can't see that!"); else if(!mob.isMonster()) { int which=-1; if(Util.s_long(affect.targetMessage())>0) which=Util.s_int(affect.targetMessage()); StringBuffer entry=DBRead(name(),mob.name(),which-1,Util.s_long(readableText().trim())); boolean mineAble=false; if(entry.charAt(0)=='*') { mineAble=true; entry.setCharAt(0,' '); } mob.tell(entry.toString()+"\n\r"); setReadableText(IQCalendar.getInstance().getTime().getTime()+""); if((entry.toString().trim().length()>0)&&(which>0)) { try { boolean reply=false; if(mineAble) { String s=mob.session().choose("R)eply, D)elete, or RETURN: ","RD\n","\n"); if(s.equalsIgnoreCase("R")) reply=true; else if(s.equalsIgnoreCase("D")) { ExternalPlay.DBDeleteJournal(name(),which-1); mob.tell("Entry deleted."); } } else reply=mob.session().confirm("Reply (y/N)?","N"); if(reply) { String replyMsg=mob.session().prompt("Enter your response\n\r: "); if(replyMsg.trim().length()>0) { ExternalPlay.DBWriteJournal(name(),mob.name(),"","",replyMsg,which-1); mob.tell("Reply added."); } else mob.tell("Aborted."); } } catch(IOException e) { Log.errOut("JournalItem",e); } } else if(which<0) { mob.tell("Enter 'READ [NUMBER] [JOURNAL]' to read an entry."); mob.tell("Use your WRITE skill to add new entries. "); } else mob.tell("That message is private."); return; } return; case Affect.TYP_WRITE: try { if((affect.targetMessage().toUpperCase().startsWith("DEL")) &&(mob.isASysOp(null)) &&(!mob.isMonster())) { if(mob.session().confirm("Delete all journal entries? Are you sure (y/N)?","N")) ExternalPlay.DBDeleteJournal(name(),-1); } else if(!mob.isMonster()) { String to="ALL"; if(mob.session().confirm("Is this a private message (y/N)?","N")) { to=mob.session().prompt("To whom:"); if(!ExternalPlay.DBUserSearch(null,to)) { mob.tell("I'm sorry, there is no such user."); return; } } String subject=mob.session().prompt("Enter a subject: "); if(subject.trim().length()==0) { mob.tell("Aborted."); return; } String message=mob.session().prompt("Enter your message\n\r: "); if(message.trim().length()==0) { mob.tell("Aborted."); return; } ExternalPlay.DBWriteJournal(name(),mob.name(),to,subject,message,-1); mob.tell("Journal entry added."); } return; } catch(IOException e) { Log.errOut("JournalItem",e); } return; } super.affect(affect); } public StringBuffer DBRead(String Journal, String username, int which, long lastTimeDate) { StringBuffer buf=new StringBuffer(""); Vector journal=ExternalPlay.DBReadJournal(Journal); if(which<0) { buf.append("\n\r"+Util.padRight("#",6)+Util.padRight("From",16)+Util.padRight("To",16)+"Subject\n\r"); buf.append("---------------------------------------------\n\r"); } if(journal==null) return buf; if((which<0)||(which>=journal.size())) { for(int j=0;j<journal.size();j++) { Vector entry=(Vector)journal.elementAt(j); String from=(String)entry.elementAt(1); String date=(String)entry.elementAt(2); String to=(String)entry.elementAt(3); String subject=(String)entry.elementAt(4); if(to.equals("ALL")||to.equalsIgnoreCase(username)||from.equalsIgnoreCase(username)) { if(Util.s_long(date)>lastTimeDate) buf.append("*"); else buf.append(" "); buf.append(Util.padRight((j+1)+"",3)+") "+Util.padRight(from,15)+" "+Util.padRight(to,15)+" "+subject+"\n\r"); } } } else { Vector entry=(Vector)journal.elementAt(which); String from=(String)entry.elementAt(1); String date=(String)entry.elementAt(2); String to=(String)entry.elementAt(3); String subject=(String)entry.elementAt(4); String message=(String)entry.elementAt(5); boolean mineAble=to.equalsIgnoreCase(username)||from.equalsIgnoreCase(username); if(mineAble) buf.append("*"); else buf.append(" "); if(to.equals("ALL")||mineAble) buf.append("\n\r"+Util.padRight((which+1)+"",3)+")\n\r"+"FROM: "+Util.padRight(from,15)+"\n\rTO : "+Util.padRight(to,15)+"\n\rSUBJ: "+subject+"\n\r"+message); } return buf; } }
git-svn-id: svn://192.168.1.10/public/CoffeeMud@255 0d6f1817-ed0e-0410-87c9-987e46238f29
com/planet_ink/coffee_mud/Items/StdJournal.java
Java
apache-2.0
737322db657b16360bd4386fa3b1fb5a5685da2a
0
rvansa/JGroups,ligzy/JGroups,ibrahimshbat/JGroups,Sanne/JGroups,ibrahimshbat/JGroups,kedzie/JGroups,rpelisse/JGroups,pruivo/JGroups,ligzy/JGroups,dimbleby/JGroups,slaskawi/JGroups,rhusar/JGroups,danberindei/JGroups,tristantarrant/JGroups,kedzie/JGroups,dimbleby/JGroups,deepnarsay/JGroups,belaban/JGroups,pferraro/JGroups,deepnarsay/JGroups,belaban/JGroups,belaban/JGroups,kedzie/JGroups,slaskawi/JGroups,danberindei/JGroups,pruivo/JGroups,rhusar/JGroups,rpelisse/JGroups,ibrahimshbat/JGroups,rvansa/JGroups,dimbleby/JGroups,pferraro/JGroups,slaskawi/JGroups,Sanne/JGroups,danberindei/JGroups,pruivo/JGroups,Sanne/JGroups,TarantulaTechnology/JGroups,TarantulaTechnology/JGroups,rpelisse/JGroups,vjuranek/JGroups,vjuranek/JGroups,pferraro/JGroups,TarantulaTechnology/JGroups,ibrahimshbat/JGroups,vjuranek/JGroups,deepnarsay/JGroups,tristantarrant/JGroups,ligzy/JGroups,rhusar/JGroups
package org.jgroups.util; import org.jgroups.Message; /** * A store for messages to be retransmitted or delivered. Used on sender and receiver side, as a replacement for * HashMap. RetransmitTable should use less memory than HashMap, as HashMap.Entry has 4 fields, plus arrays for storage. * <p/> * RetransmitTable maintains a matrix (an array of arrays) of messages. Messages are stored in the matrix by mapping * their seqno to an index. E.g. when we have 10 rows of 1000 messages each, and first_seqno is 3000, then a message with * seqno=5600, will be stored in the 3rd row, at index 600. * <p/> * Rows are removed when all messages in that row have been received.<p/> * This class in not synchronized; the caller has to make sure access to it is synchronized * @author Bela Ban */ public class RetransmitTable { protected final int num_rows; protected final int msgs_per_row; protected final double resize_factor; protected Message[][] matrix; /** The first seqno, at matrix[0][0] */ protected long offset; protected int size=0; /** The highest seqno purged */ protected long highest_seqno_purged; /** The highest seqno in the table */ protected long highest_seqno; /** Time (in ms) after which a compaction should take place. 0 disables compaction */ protected long max_compaction_time=DEFAULT_MAX_COMPACTION_TIME; /** The time when the last compaction took place. If a {@link #compact()} takes place and sees that the * last compaction is more than max_compaction_time ms ago, a compaction will take place */ protected long last_compaction_timestamp=0; protected static final long DEFAULT_MAX_COMPACTION_TIME=2 * 60 * 1000L; protected static final double DEFAULT_RESIZE_FACTOR=1.2; public RetransmitTable() { this(5, 10000, 0, DEFAULT_RESIZE_FACTOR); } public RetransmitTable(int num_rows, int msgs_per_row, long offset) { this(num_rows, msgs_per_row, offset, DEFAULT_RESIZE_FACTOR); } public RetransmitTable(int num_rows, int msgs_per_row, long offset, double resize_factor) { this(num_rows, msgs_per_row, offset, resize_factor, DEFAULT_MAX_COMPACTION_TIME); } public RetransmitTable(int num_rows, int msgs_per_row, long offset, double resize_factor, long max_compaction_time) { this.num_rows=num_rows; this.msgs_per_row=msgs_per_row; this.resize_factor=resize_factor; this.max_compaction_time=max_compaction_time; this.offset=this.highest_seqno_purged=this.highest_seqno=offset; matrix=new Message[num_rows][]; if(resize_factor <= 1) throw new IllegalArgumentException("resize_factor needs to be > 1"); } public long getOffset() { return offset; } /** Returns the total capacity in the matrix */ public int capacity() {return matrix.length * msgs_per_row;} /** Returns the numbers of messages in the table */ public int size() {return size;} public boolean isEmpty() {return size <= 0;} public long getHighest() { return highest_seqno; } public long getHighestPurged() { return highest_seqno_purged; } public long getMaxCompactionTime() { return max_compaction_time; } public void setMaxCompactionTime(long max_compaction_time) { this.max_compaction_time=max_compaction_time; } /** Returns the ratio between size and capacity, as a percentage */ public double getFillFactor() { return size == 0? 0.0 : (int)(((double)size / capacity()) * 100); } /** * Adds a new message to the index computed as a function of seqno * @param seqno * @param msg * @return True if the element at the computed index was null, else false */ public boolean put(long seqno, Message msg) { return putIfAbsent(seqno, msg) == null; } /** * Adds a message if the element at the given index is null. Returns null if no message existed at the given index, * else returns the existing message and doesn't set the element. * @param seqno * @param msg * @return The existing message, or null if there wasn't any */ public Message putIfAbsent(long seqno, Message msg) { int row_index=computeRow(seqno); if(row_index >= matrix.length) { resize(seqno); row_index=computeRow(seqno); } Message[] row=getRow(row_index); int index=computeIndex(seqno); Message existing_msg=row[index]; if(existing_msg == null) { row[index]=msg; size++; if(seqno > highest_seqno) highest_seqno=seqno; return null; } else return existing_msg; } public Message get(long seqno) { int row_index=computeRow(seqno); if(row_index < 0 || row_index >= matrix.length) return null; Message[] row=matrix[row_index]; if(row == null) return null; int index=computeIndex(seqno); return index >= 0? row[index] : null; } /** Removes the message with seqno from the table, nulls the index */ public Message remove(long seqno) { int row_index=computeRow(seqno); if(row_index < 0 || row_index >= matrix.length) return null; Message[] row=matrix[row_index]; if(row == null) return null; int index=computeIndex(seqno); if(index < 0) return null; Message existing_msg=row[index]; if(existing_msg != null) { row[index]=null; size=Math.max(size-1, 0); // cannot be < 0 (well that would be a bug, but let's have this 2nd line of defense !) } return existing_msg; } /** Removes all elements. This method is usually called just before removing a retransmit table, so typically * it is not used anymore after returning */ public void clear() { matrix=new Message[num_rows][]; size=0; offset=highest_seqno_purged=highest_seqno=0; } /** * Removes all messages less than or equal to seqno from the table. Does this by nulling entire rows in the matrix * and nulling all elements < index(seqno) of the first row that cannot be removed * @param seqno */ public void purge(long seqno) { int num_rows_to_remove=(int)(seqno - offset) / msgs_per_row; for(int i=0; i < num_rows_to_remove; i++) // Null all rows which can be fully removed matrix[i]=null; int row_index=computeRow(seqno); if(row_index < 0 || row_index >= matrix.length) return; Message[] row=matrix[row_index]; if(row != null) { int index=computeIndex(seqno); for(int i=0; i <= index; i++) // null all messages up to and including seqno in the given row row[i]=null; } size=computeSize(); if(seqno > highest_seqno_purged) highest_seqno_purged=seqno; // see if compaction should be triggered if(max_compaction_time <= 0) return; long current_time=System.currentTimeMillis(); if(last_compaction_timestamp > 0) { if(current_time - last_compaction_timestamp >= max_compaction_time) { compact(); last_compaction_timestamp=current_time; } } else last_compaction_timestamp=current_time; } /** Moves rows down the matrix, by removing purged rows. If resizing to accommodate seqno is still needed, computes * a new size. Then either moves existing rows down, or copies them into a new array (if resizing took place) */ protected void resize(long seqno) { int num_rows_to_purge=(int)((highest_seqno_purged - offset) / msgs_per_row); int row_index=computeRow(seqno) - num_rows_to_purge; if(row_index < 0) return; int new_size=Math.max(row_index +1, matrix.length); if(new_size > matrix.length) { Message[][] new_matrix=new Message[new_size][]; System.arraycopy(matrix, num_rows_to_purge, new_matrix, 0, matrix.length - num_rows_to_purge); matrix=new_matrix; } else if(num_rows_to_purge > 0) { move(num_rows_to_purge); } offset+=(num_rows_to_purge * msgs_per_row); size=computeSize(); } /** Moves contents of matrix num_rows down. Avoids a System.arraycopy() */ protected void move(int num_rows) { if(num_rows <= 0 || num_rows > matrix.length) return; int target_index=0; for(int i=num_rows; i < matrix.length; i++) matrix[target_index++]=matrix[i]; for(int i=matrix.length - num_rows; i < matrix.length; i++) matrix[i]=null; } /** * Moves the contents of matrix down by the number of purged rows and resizes the matrix accordingly. The * capacity of the matrix should be size * resize_factor */ public void compact() { // This is the range we need to copy into the new matrix (including from and to) int from=computeRow(highest_seqno_purged), to=computeRow(highest_seqno); int range=to - from +1; // e.g. from=3, to=5, new_size has to be [3 .. 5] (=3) int new_size=(int)Math.max(range * resize_factor, range +1); new_size=Math.max(new_size, num_rows); // don't fall below the initial size defined if(new_size < matrix.length) { // System.out.println("<<< compacting matrix from " + matrix.length + " rows to " + new_size + " rows"); Message[][] new_matrix=new Message[new_size][]; System.arraycopy(matrix, from, new_matrix, 0, range); matrix=new_matrix; offset+=from * msgs_per_row; size=computeSize(); } } /** Iterate from highest_seqno_purged to highest_seqno and add up non-null values */ public int computeSize() { int retval=0; int from=computeRow(highest_seqno_purged), to=computeRow(highest_seqno); for(int i=from; i <= to; i++) { Message[] row=matrix[i]; if(row == null) continue; for(int j=0; j < row.length; j++) { if(row[j] != null) retval++; } } return retval; } /** Returns the number of null elements up to 'to' */ public int getNullMessages(long to) { int retval=0; for(long i=offset; i <= to; i++) { int row_index=computeRow(i); if(row_index < 0 || row_index >= matrix.length) continue; Message[] row=matrix[row_index]; if(row != null && row[computeIndex(i)] == null) retval++; } return retval; } public String toString() { StringBuilder sb=new StringBuilder(); sb.append("size=" + size + ", capacity=" + capacity() + ", highest_purged=" + highest_seqno_purged + ", highest=" + highest_seqno); return sb.toString(); } /** Dumps the seqnos in the table as a list */ public String dump() { StringBuilder sb=new StringBuilder(); boolean first=true; for(int i=0; i < matrix.length; i++) { Message[] row=matrix[i]; if(row == null) continue; for(int j=0; j < row.length; j++) { if(row[j] != null) { long seqno=offset + (i * msgs_per_row) + j; if(first) first=false; else sb.append(", "); sb.append(seqno); } } } return sb.toString(); } /** Dumps the non-null in the table in a pseudo graphic way */ public String dumpMatrix() { StringBuilder sb=new StringBuilder(); for(int i=0; i < matrix.length; i++) { Message[] row=matrix[i]; sb.append(i + ": "); if(row == null) { sb.append("\n"); continue; } for(int j=0; j < row.length; j++) { if(row[j] != null) sb.append("* "); else sb.append(" "); } sb.append("\n"); } return sb.toString(); } /** * Returns a row. Creates a new row and inserts it at index if the row at index doesn't exist * @param index * @return A row */ protected Message[] getRow(int index) { Message[] row=matrix[index]; if(row == null) { row=new Message[msgs_per_row]; matrix[index]=row; } return row; } /** Computes and returns the row index for seqno */ protected int computeRow(long seqno) { int diff=(int)(seqno-offset); if(diff < 0) return diff; return diff / msgs_per_row; } /** Computes and returns the index within a row for seqno */ protected int computeIndex(long seqno) { int diff=(int)(seqno - offset); if(diff < 0) return diff; return diff % msgs_per_row; } }
src/org/jgroups/util/RetransmitTable.java
package org.jgroups.util; import org.jgroups.Message; /** * A store for messages to be retransmitted or delivered. Used on sender and receiver side, as a replacement for * HashMap. RetransmitTable should use less memory than HashMap, as HashMap.Entry has 4 fields, plus arrays for storage. * <p/> * RetransmitTable maintains a matrix (an array of arrays) of messages. Messages are stored in the matrix by mapping * their seqno to an index. E.g. when we have 10 rows of 1000 messages each, and first_seqno is 3000, then a message with * seqno=5600, will be stored in the 3rd row, at index 600. * <p/> * Rows are removed when all messages in that row have been received.<p/> * This class in not synchronized; the caller has to make sure access to it is synchronized * @author Bela Ban */ public class RetransmitTable { protected final int num_rows; protected final int msgs_per_row; protected final double resize_factor; protected Message[][] matrix; /** The first seqno, at matrix[0][0] */ protected long offset; protected int size=0; /** The highest seqno purged */ protected long highest_seqno_purged; /** The highest seqno in the table */ protected long highest_seqno; /** Time (in ms) after which a compaction should take place. 0 disables compaction */ protected long max_compaction_time=DEFAULT_MAX_COMPACTION_TIME; /** The time when the last compaction took place. If a {@link #compact(long)} takes place and sees that the * last compaction is more than max_compaction_time ms ago, a compaction will take place */ protected long last_compaction_timestamp=0; protected static final long DEFAULT_MAX_COMPACTION_TIME=2 * 60 * 1000L; protected static final double DEFAULT_RESIZE_FACTOR=1.2; public RetransmitTable() { this(5, 10000, 0, DEFAULT_RESIZE_FACTOR); } public RetransmitTable(int num_rows, int msgs_per_row, long offset) { this(num_rows, msgs_per_row, offset, DEFAULT_RESIZE_FACTOR); } public RetransmitTable(int num_rows, int msgs_per_row, long offset, double resize_factor) { this(num_rows, msgs_per_row, offset, resize_factor, DEFAULT_MAX_COMPACTION_TIME); } public RetransmitTable(int num_rows, int msgs_per_row, long offset, double resize_factor, long max_compaction_time) { this.num_rows=num_rows; this.msgs_per_row=msgs_per_row; this.resize_factor=resize_factor; this.max_compaction_time=max_compaction_time; this.offset=this.highest_seqno_purged=this.highest_seqno=offset; matrix=new Message[num_rows][]; if(resize_factor <= 1) throw new IllegalArgumentException("resize_factor needs to be > 1"); } public long getOffset() { return offset; } /** Returns the total capacity in the matrix */ public int capacity() {return matrix.length * msgs_per_row;} /** Returns the numbers of messages in the table */ public int size() {return size;} public boolean isEmpty() {return size <= 0;} public long getHighest() { return highest_seqno; } public long getHighestPurged() { return highest_seqno_purged; } public long getMaxCompactionTime() { return max_compaction_time; } public void setMaxCompactionTime(long max_compaction_time) { this.max_compaction_time=max_compaction_time; } /** Returns the ratio between size and capacity, as a percentage */ public double getFillFactor() { return size == 0? 0.0 : (int)(((double)size / capacity()) * 100); } /** * Adds a new message to the index computed as a function of seqno * @param seqno * @param msg * @return True if the element at the computed index was null, else false */ public boolean put(long seqno, Message msg) { return putIfAbsent(seqno, msg) == null; } /** * Adds a message if the element at the given index is null. Returns null if no message existed at the given index, * else returns the existing message and doesn't set the element. * @param seqno * @param msg * @return The existing message, or null if there wasn't any */ public Message putIfAbsent(long seqno, Message msg) { int row_index=computeRow(seqno); if(row_index >= matrix.length) { resize(seqno); row_index=computeRow(seqno); } Message[] row=getRow(row_index); int index=computeIndex(seqno); Message existing_msg=row[index]; if(existing_msg == null) { row[index]=msg; size++; if(seqno > highest_seqno) highest_seqno=seqno; return null; } else return existing_msg; } public Message get(long seqno) { int row_index=computeRow(seqno); if(row_index < 0 || row_index >= matrix.length) return null; Message[] row=matrix[row_index]; if(row == null) return null; int index=computeIndex(seqno); return index >= 0? row[index] : null; } /** Removes the message with seqno from the table, nulls the index */ public Message remove(long seqno) { int row_index=computeRow(seqno); if(row_index < 0 || row_index >= matrix.length) return null; Message[] row=matrix[row_index]; if(row == null) return null; int index=computeIndex(seqno); if(index < 0) return null; Message existing_msg=row[index]; if(existing_msg != null) { row[index]=null; size=Math.max(size-1, 0); // cannot be < 0 (well that would be a bug, but let's have this 2nd line of defense !) } return existing_msg; } /** Removes all elements. This method is usually called just before removing a retransmit table, so typically * it is not used anymore after returning */ public void clear() { matrix=new Message[num_rows][]; size=0; offset=highest_seqno_purged=highest_seqno=0; } /** * Removes all messages less than or equal to seqno from the table. Does this by nulling entire rows in the matrix * and nulling all elements < index(seqno) of the first row that cannot be removed * @param seqno */ public void purge(long seqno) { int num_rows_to_remove=(int)(seqno - offset) / msgs_per_row; for(int i=0; i < num_rows_to_remove; i++) // Null all rows which can be fully removed matrix[i]=null; int row_index=computeRow(seqno); if(row_index < 0 || row_index >= matrix.length) return; Message[] row=matrix[row_index]; if(row != null) { int index=computeIndex(seqno); for(int i=0; i <= index; i++) // null all messages up to and including seqno in the given row row[i]=null; } size=computeSize(); if(seqno > highest_seqno_purged) highest_seqno_purged=seqno; // see if compaction should be triggered if(max_compaction_time <= 0) return; long current_time=System.currentTimeMillis(); if(last_compaction_timestamp > 0) { if(current_time - last_compaction_timestamp >= max_compaction_time) { compact(); last_compaction_timestamp=current_time; } } else last_compaction_timestamp=current_time; } /** Moves rows down the matrix, by removing purged rows. If resizing to accommodate seqno is still needed, computes * a new size. Then either moves existing rows down, or copies them into a new array (if resizing took place) */ protected void resize(long seqno) { int num_rows_to_purge=(int)((highest_seqno_purged - offset) / msgs_per_row); int row_index=computeRow(seqno) - num_rows_to_purge; if(row_index < 0) return; int new_size=Math.max(row_index +1, matrix.length); if(new_size > matrix.length) { Message[][] new_matrix=new Message[new_size][]; System.arraycopy(matrix, num_rows_to_purge, new_matrix, 0, matrix.length - num_rows_to_purge); matrix=new_matrix; } else if(num_rows_to_purge > 0) { move(num_rows_to_purge); } offset+=(num_rows_to_purge * msgs_per_row); size=computeSize(); } /** Moves contents of matrix num_rows down. Avoids a System.arraycopy() */ protected void move(int num_rows) { if(num_rows <= 0 || num_rows > matrix.length) return; int target_index=0; for(int i=num_rows; i < matrix.length; i++) matrix[target_index++]=matrix[i]; for(int i=matrix.length - num_rows; i < matrix.length; i++) matrix[i]=null; } /** * Moves the contents of matrix down by the number of purged rows and resizes the matrix accordingly. The * capacity of the matrix should be size * resize_factor */ public void compact() { int num_rows_to_purge=(int)((highest_seqno_purged - offset) / msgs_per_row); int num_unused_rows=(int)((highest_seqno - highest_seqno_purged) / msgs_per_row); int new_size=(int)((matrix.length - num_rows_to_purge - num_unused_rows) * resize_factor); int alt_new_size=(int)(size * resize_factor); // ??? assert new_size == alt_new_size; if(new_size < matrix.length) { Message[][] new_matrix=new Message[new_size][]; System.arraycopy(matrix, num_rows_to_purge, new_matrix, 0, matrix.length - num_rows_to_purge - num_unused_rows); matrix=new_matrix; } } /** Iterate from highest_seqno_purged to highest_seqno and add up non-null values */ public int computeSize() { int retval=0; int from=computeRow(highest_seqno_purged), to=computeRow(highest_seqno); for(int i=from; i <= to; i++) { Message[] row=matrix[i]; if(row == null) continue; for(int j=0; j < row.length; j++) { if(row[j] != null) retval++; } } return retval; } /** Returns the number of null elements up to 'to' */ public int getNullMessages(long to) { int retval=0; for(long i=offset; i <= to; i++) { int row_index=computeRow(i); if(row_index < 0 || row_index >= matrix.length) continue; Message[] row=matrix[row_index]; if(row != null && row[computeIndex(i)] == null) retval++; } return retval; } public String toString() { StringBuilder sb=new StringBuilder(); sb.append("size=" + size + ", capacity=" + capacity() + ", highest_purged=" + highest_seqno_purged + ", highest=" + highest_seqno); return sb.toString(); } /** Dumps the seqnos in the table as a list */ public String dump() { StringBuilder sb=new StringBuilder(); boolean first=true; for(int i=0; i < matrix.length; i++) { Message[] row=matrix[i]; if(row == null) continue; for(int j=0; j < row.length; j++) { if(row[j] != null) { long seqno=offset + (i * msgs_per_row) + j; if(first) first=false; else sb.append(", "); sb.append(seqno); } } } return sb.toString(); } /** Dumps the non-null in the table in a pseudo graphic way */ public String dumpMatrix() { StringBuilder sb=new StringBuilder(); for(int i=0; i < matrix.length; i++) { Message[] row=matrix[i]; sb.append(i + ": "); if(row == null) { sb.append("\n"); continue; } for(int j=0; j < row.length; j++) { if(row[j] != null) sb.append("* "); else sb.append(" "); } sb.append("\n"); } return sb.toString(); } /** * Returns a row. Creates a new row and inserts it at index if the row at index doesn't exist * @param index * @return A row */ protected Message[] getRow(int index) { Message[] row=matrix[index]; if(row == null) { row=new Message[msgs_per_row]; matrix[index]=row; } return row; } /** Computes and returns the row index for seqno */ protected int computeRow(long seqno) { int diff=(int)(seqno-offset); if(diff < 0) return diff; return diff / msgs_per_row; } /** Computes and returns the index within a row for seqno */ protected int computeIndex(long seqno) { int diff=(int)(seqno - offset); if(diff < 0) return diff; return diff % msgs_per_row; } }
fixed compact()
src/org/jgroups/util/RetransmitTable.java
fixed compact()
Java
apache-2.0
cfb410d831229f75df3373e2f392cc715b03d61b
0
pyamsoft/home-button
/* * Copyright 2013 - 2016 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pyamsoft.homebutton; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.FragmentManager; import android.support.v7.widget.Toolbar; import android.text.Spannable; import android.view.MenuItem; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; import com.pyamsoft.pydroid.lib.AboutLibrariesFragment; import com.pyamsoft.pydroid.lib.DonationActivity; import com.pyamsoft.pydroid.lib.RatingDialog; import com.pyamsoft.pydroid.util.StringUtil; public class MainActivity extends DonationActivity implements RatingDialog.ChangeLogProvider { @BindView(R.id.toolbar) Toolbar toolbar; private Unbinder unbinder; @Override protected final void onCreate(final Bundle savedInstanceState) { setTheme(R.style.Theme_HomeButton_Light); super.onCreate(savedInstanceState); unbinder = ButterKnife.bind(this); setupToolbar(); addPreferenceFragment(); } private void addPreferenceFragment() { final FragmentManager fragmentManager = getSupportFragmentManager(); if (fragmentManager.findFragmentByTag(HomePreferencesFragment.TAG) == null && fragmentManager.findFragmentByTag(AboutLibrariesFragment.TAG) == null) { fragmentManager.beginTransaction() .add(R.id.main_view_container, new HomePreferencesFragment(), HomePreferencesFragment.TAG) .commitNow(); } } @Override protected int bindActivityToView() { setContentView(R.layout.activity_main); return R.id.ad_view; } @Override protected void onDestroy() { super.onDestroy(); unbinder.unbind(); } @Override public void onBackPressed() { final FragmentManager fragmentManager = getSupportFragmentManager(); final int backStackCount = fragmentManager.getBackStackEntryCount(); if (backStackCount > 0) { fragmentManager.popBackStack(); } else { super.onBackPressed(); } } @Override public boolean onOptionsItemSelected(final @NonNull MenuItem item) { final int itemId = item.getItemId(); boolean handled; switch (itemId) { case android.R.id.home: onBackPressed(); handled = true; break; default: handled = false; } return handled || super.onOptionsItemSelected(item); } void setupToolbar() { toolbar.setTitle(getString(R.string.app_name)); setSupportActionBar(toolbar); } @Override protected void onPostResume() { super.onPostResume(); RatingDialog.showRatingDialog(this, this); } @NonNull @Override public Spannable getChangeLogText() { // The changelog text final String title = "What's New in Version " + BuildConfig.VERSION_NAME; final String line1 = "CHANGE: Removed Advertisements and Analytics tracking"; // Turn it into a spannable final Spannable spannable = StringUtil.createLineBreakBuilder(title, line1); int start = 0; int end = title.length(); final int largeSize = StringUtil.getTextSizeFromAppearance(this, android.R.attr.textAppearanceLarge); final int largeColor = StringUtil.getTextColorFromAppearance(this, android.R.attr.textAppearanceLarge); final int smallSize = StringUtil.getTextSizeFromAppearance(this, android.R.attr.textAppearanceSmall); final int smallColor = StringUtil.getTextColorFromAppearance(this, android.R.attr.textAppearanceSmall); StringUtil.boldSpan(spannable, start, end); StringUtil.sizeSpan(spannable, start, end, largeSize); StringUtil.colorSpan(spannable, start, end, largeColor); start += end + 2; end += 2 + line1.length(); StringUtil.sizeSpan(spannable, start, end, smallSize); StringUtil.colorSpan(spannable, start, end, smallColor); return spannable; } @Override public int getApplicationIcon() { return R.mipmap.ic_launcher; } @NonNull @Override public String provideApplicationName() { return "Home Button"; } @Override public int getCurrentApplicationVersion() { return BuildConfig.VERSION_CODE; } }
src/main/java/com/pyamsoft/homebutton/MainActivity.java
/* * Copyright 2013 - 2016 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pyamsoft.homebutton; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.FragmentManager; import android.support.v7.widget.Toolbar; import android.text.Spannable; import android.view.MenuItem; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; import com.pyamsoft.pydroid.lib.AboutLibrariesFragment; import com.pyamsoft.pydroid.lib.DonationActivity; import com.pyamsoft.pydroid.lib.RatingDialog; import com.pyamsoft.pydroid.util.StringUtil; public class MainActivity extends DonationActivity implements RatingDialog.ChangeLogProvider { @BindView(R.id.toolbar) Toolbar toolbar; private Unbinder unbinder; @Override protected final void onCreate(final Bundle savedInstanceState) { setTheme(R.style.Theme_HomeButton_Light); super.onCreate(savedInstanceState); unbinder = ButterKnife.bind(this); setupToolbar(); addPreferenceFragment(); } private void addPreferenceFragment() { final FragmentManager fragmentManager = getSupportFragmentManager(); if (fragmentManager.findFragmentByTag(HomePreferencesFragment.TAG) == null && fragmentManager.findFragmentByTag(AboutLibrariesFragment.TAG) == null) { fragmentManager.beginTransaction() .add(R.id.main_view_container, new HomePreferencesFragment(), HomePreferencesFragment.TAG) .commitNow(); } } @Override protected int bindActivityToView() { setContentView(R.layout.activity_main); return R.id.ad_view; } @Override protected void onDestroy() { super.onDestroy(); unbinder.unbind(); } @Override public void onBackPressed() { final FragmentManager fragmentManager = getSupportFragmentManager(); final int backStackCount = fragmentManager.getBackStackEntryCount(); if (backStackCount > 0) { fragmentManager.popBackStack(); } else { super.onBackPressed(); } } @Override public boolean onOptionsItemSelected(final @NonNull MenuItem item) { final int itemId = item.getItemId(); boolean handled; switch (itemId) { case android.R.id.home: onBackPressed(); handled = true; break; default: handled = false; } return handled || super.onOptionsItemSelected(item); } void setupToolbar() { toolbar.setTitle(getString(R.string.app_name)); setSupportActionBar(toolbar); } @Override protected void onPostResume() { super.onPostResume(); RatingDialog.showRatingDialog(this, this); } @NonNull @Override public Spannable getChangeLogText() { // The changelog text final String title = "What's New in Version " + BuildConfig.VERSION_NAME; final String line1 = "CHANGE: Pro Version applications!\nAdvertisements can be disabled from the settings screen once the Pro version of the application is installed"; final String line2 = "BUGFIX: Clean up memory management"; // Turn it into a spannable final Spannable spannable = StringUtil.createLineBreakBuilder(title, line1, line2); int start = 0; int end = title.length(); final int largeSize = StringUtil.getTextSizeFromAppearance(this, android.R.attr.textAppearanceLarge); final int largeColor = StringUtil.getTextColorFromAppearance(this, android.R.attr.textAppearanceLarge); final int smallSize = StringUtil.getTextSizeFromAppearance(this, android.R.attr.textAppearanceSmall); final int smallColor = StringUtil.getTextColorFromAppearance(this, android.R.attr.textAppearanceSmall); StringUtil.boldSpan(spannable, start, end); StringUtil.sizeSpan(spannable, start, end, largeSize); StringUtil.colorSpan(spannable, start, end, largeColor); start += end + 2; end += 2 + line1.length() + 2 + line2.length(); StringUtil.sizeSpan(spannable, start, end, smallSize); StringUtil.colorSpan(spannable, start, end, smallColor); return spannable; } @Override public int getApplicationIcon() { return R.mipmap.ic_launcher; } @NonNull @Override public String provideApplicationName() { return "Home Button"; } @Override public int getCurrentApplicationVersion() { return BuildConfig.VERSION_CODE; } }
Update changelog
src/main/java/com/pyamsoft/homebutton/MainActivity.java
Update changelog
Java
apache-2.0
bc37978f9aea2e876dbdd1b857173631bb9166a1
0
ilkkatoje/robotframework-jmslibrary,ilkkatoje/robotframework-jmslibrary
import java.io.IOException; import java.util.Map; import java.util.Properties; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSException; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import fi.toje.himmeli.jmslibrary.ProviderConnection; import fi.toje.himmeli.jmslibrary.ProviderSession; /** * Robot Framework library for testing applications utilizing JMS. * * Set the library and chosen JMS provider jars into classpath and start * testing. * * Library uses one connection which has one session. Session includes one * message producer and one message consumer for topic. Queue consumers are * created on the fly when receiving. Currently, messages can be received only * from one topic at time. Producer specific settings (timeToLive etc.) apply * within a session. Settings will be reset, if session is reinitialized. * * Default receive timeout is 100 ms. * * = Example with ActiveMQ = * * | *** Settings *** * | Library String * | Library JMSLibrary ${INITIAL_CONTEXT_FACTORY} ${PROVIDER_URL} * | Suite Setup Connect And Start * | Suite Teardown Close Connection * | Test Setup Clear Queue ${QUEUE} * | Test Tear Down Clear Queue ${QUEUE} * | * | *** Variables *** * | ${INITIAL_CONTEXT_FACTORY} org.apache.activemq.jndi.ActiveMQInitialContextFactory * | ${PROVIDER_URL} tcp://localhost:61616?jms.useAsyncSend=false * | ${QUEUE} QUEUE.JMSLIBRARY.TEST * | ${TOPIC} TOPIC.JMSLIBRARY.TEST * | * | *** Test Cases *** * | Queue Send and Receive TextMessage * | ${text}= Generate Random String * | Create Text Message ${text} * | Send To Queue ${QUEUE} * | Receive From Queue ${QUEUE} * | ${body}= Get Text * | Should Be Equal ${body} ${text} * | * | Topic Send and Receive TextMessage * | Subscribe ${TOPIC} * | ${text}= Generate Random String * | Create Text Message ${text} * | Send To Topic ${TOPIC} * | Receive From Topic * | ${body}= Get Text * | Should Be Equal ${body} ${text} * | Unsubscribe */ public class JMSLibrary { public static final String ROBOT_LIBRARY_SCOPE = "TEST SUITE"; public static final String ROBOT_LIBRARY_VERSION = "1.0.0-beta.3"; public static final String DEFAULT_CONNECTION_FACTORY_LOOKUP_NAME = "ConnectionFactory"; public static final String SETTINGS_KW_CONNECTION_FACTORY_LOOKUP_NAME = "connection_factory_name"; private InitialContext initialContext; private ConnectionFactory connectionFactory; private ProviderConnection providerConnection; /** * Settings for selecting JMS provider. Default JNDI connection factory * look up string is 'ConnectionFactory'. * * Optional settings: * - _connection_factory_name_: lookup name for connection factory * * Examples: * | Library | JMSLibrary | org.apache.activemq.jndi.ActiveMQInitialContextFactory | tcp://localhost:61616?jms.useAsyncSend=false | * | Library | JMSLibrary | com.sun.jndi.fscontext.RefFSContextFactory | file:/C:/JNDI-Directory | connection_factory_name=myCF | */ public JMSLibrary(String initialContextFactory, String providerUrl, Map<String, String> settings) throws NamingException { Properties env = new Properties( ); env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory); env.put(Context.PROVIDER_URL, providerUrl); initialContext = new InitialContext(env); connectionFactory = (ConnectionFactory)initialContext.lookup(getConnectionFactoryLookupName(settings)); } private String getConnectionFactoryLookupName(Map<String, String> settings) { String lookupName = DEFAULT_CONNECTION_FACTORY_LOOKUP_NAME; if (settings.containsKey(SETTINGS_KW_CONNECTION_FACTORY_LOOKUP_NAME)) { lookupName = settings.get(SETTINGS_KW_CONNECTION_FACTORY_LOOKUP_NAME); } return lookupName; } /** * Connects to provider. Does not initialize session or start connection. */ public void connect() throws Exception { connect(null, null); } /** * Connects to provider. Does not initialize session or start connection. */ public void connect(String username, String password) throws Exception { if (providerConnection != null) { throw new Exception("Connection exists"); } Connection connection; if (username != null) { connection = connectionFactory.createConnection(username, password); } else { connection = connectionFactory.createConnection(); } providerConnection = new ProviderConnection(connection); } /** * Connects to provider. Initializes default session and starts the * connection. */ public void connectAndStart() throws Exception { connect(); initializeSession(); start(); } /** * Connects to provider. Initializes default session and starts the * connection. */ public void connectAndStart(String username, String password) throws Exception { connect(username, password); initializeSession(); start(); } /** * Sets clientId. Must be used right after connect, refer JMS specs. */ public void setClientId(String clientId) throws JMSException { providerConnection.setClientId(clientId); } /** * Returns clientId. */ public String getClientId() throws JMSException { return providerConnection.getClientId(); } /** * (Re)initializes session with default attributes (non-transacted, * AUTO_ACKNOWLEDGE). */ public void initializeSession() throws Exception { initializeSession(false, ProviderSession.AUTO_ACKNOWLEDGE); } /** * (Re)initializes session. * * Arguments: * - _transacted_: true or false * - _type_: AUTO_ACKNOWLEDGE, CLIENT_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE or SESSION_TRANSACTED */ public void initializeSession(boolean transacted, String type) throws Exception { providerConnection.initSession(transacted, type); } /** * Starts connection. */ public void start() throws JMSException { providerConnection.start(); } /** * Stops connection. */ public void stop() throws JMSException { providerConnection.stop(); } /** * Closes provider connection. Closes all resources (session, producer and * consumer). */ public void closeConnection() throws Exception { providerConnection.close(); providerConnection = null; } /** * Commits all messages in the session. */ public void commit() throws JMSException { ProviderSession ps = providerConnection.getProviderSession(); ps.commit(); } /** * Rolls back messages in the session. */ public void rollback() throws JMSException { ProviderSession ps = providerConnection.getProviderSession(); ps.rollback(); } /** * Acknowledges all consumed messages of the session. Used in * CLIENT_ACKNOWLEDGE mode. */ public void acknowledge() throws JMSException { ProviderSession ps = providerConnection.getProviderSession(); ps.acknowledge(); } /** * Creates TextMessage. Additional properties can be set after creation. */ public void createTextMessage(String text) throws Exception { ProviderSession ps = providerConnection.getProviderSession(); ps.createTextMessage(text); } /** * Creates BytesMessage from file. Additional properties can be set after * creation. * * Argument: * - _file_: name of the file */ public void createBytesMessageFromFile(String file) throws JMSException, IOException { ProviderSession ps = providerConnection.getProviderSession(); ps.createBytesMessage(file); } /** * Sets JMSType of message. */ public void setJMSType(String type) throws JMSException { ProviderSession ps = providerConnection.getProviderSession(); ps.setType(type); } /** * Returns JMSType of message. */ public String getJMSType() throws JMSException { ProviderSession ps = providerConnection.getProviderSession(); return ps.getType(); } /** * Sets JMSCorrelationID for message. */ public void setJMSCorrelationId(String correlationId) throws JMSException { ProviderSession ps = providerConnection.getProviderSession(); ps.setCorrelationId(correlationId); } /** * Returns JMSCorrelationID of message. */ public String getJMSCorrelationId() throws JMSException { ProviderSession ps = providerConnection.getProviderSession(); return ps.getCorrelationId(); } /** * Sets JMSReplyTo queue for message. */ public void setJMSReplyToQueue(String queue) throws JMSException { ProviderSession ps = providerConnection.getProviderSession(); ps.setReplyToQueue(queue); } /** * JMSReplyTo queue of message. * * Returns queue if it was set and was type of queue, otherwise (not set or * is topic) null */ public String getJMSReplyToQueue() throws JMSException { ProviderSession ps = providerConnection.getProviderSession(); return ps.getReplyToQueue(); } /** * Sets JMSReplyTo topic for message. */ public void setJMSReplyToTopic(String topic) throws JMSException { ProviderSession ps = providerConnection.getProviderSession(); ps.setReplyToTopic(topic); } /** * JMSReplyTo value of message. * * Returns topic if it was set and was type of topic, otherwise (not set or * is queue) null */ public String getJMSReplyToTopic() throws JMSException { ProviderSession ps = providerConnection.getProviderSession(); return ps.getReplyToTopic(); } /** * Sets time to live for the producer. * * Argument: * - _timeToLive_: time to live in milliseconds */ public void setProducerTimeToLive(long timeToLive) throws JMSException { ProviderSession ps = providerConnection.getProviderSession(); ps.setProducerTimeToLive(timeToLive); } /** * JMSExpiration of received message. * * Returns expiration of message */ public long getJMSExpiration() throws JMSException { ProviderSession ps = providerConnection.getProviderSession(); return ps.getExpiration(); } /** * Sets delivery mode for the producer. * * Argument: * - _deliveryMode_: PERSISTENT or NON_PERSISTENT */ public void setProducerDeliveryMode(String deliveryMode) throws Exception { ProviderSession ps = providerConnection.getProviderSession(); ps.setProducerDeliveryMode(deliveryMode); } /** * Returns delivery mode of the producer: PERSISTENT or NON_PERSISTENT. */ public String getProducerDeliveryMode() throws Exception { ProviderSession ps = providerConnection.getProviderSession(); return ps.getProducerDeliveryMode(); } /** * Returns delivery mode of received message: PERSISTENT or NON_PERSISTENT. */ public String getDeliveryMode() throws Exception { ProviderSession ps = providerConnection.getProviderSession(); return ps.getDeliveryMode(); } /** * JMSRedelivered of received message. * * Return true if message was redelivered */ public boolean getJMSRedelivered() throws JMSException { ProviderSession ps = providerConnection.getProviderSession(); return ps.getJmsRedelivered(); } /** * Sets string property for message. */ public void setStringProperty(String name, String value) throws Exception { ProviderSession ps = providerConnection.getProviderSession(); ps.setStringProperty(name, value); System.out.println(name + "=" + value); } /** * Returns string property of message. * * Arguments: * - _name_: name of the property */ public String getStringProperty(String name) throws Exception { ProviderSession ps = providerConnection.getProviderSession(); String value = ps.getStringProperty(name); System.out.println(name + "=" + value); return value; } /** * JMSMessageID * * Returns message id. */ public String getJMSMessageId() throws JMSException { ProviderSession ps = providerConnection.getProviderSession(); String id = ps.getMessageId(); System.out.println("MessageId=" + id); return id; } /** * Sends message to queue. The message must have been created beforehand * using one of the create message methods. Message id can be accessed after * sending. */ public void sendToQueue(String queue) throws Exception { ProviderSession ps = providerConnection.getProviderSession(); ps.sendToQueue(queue); } /** * Receives message from queue. The message is set to internal message * object and its body and properties can be accessed via methods. */ public void receiveFromQueue(String queue) throws Exception { ProviderSession ps = providerConnection.getProviderSession(); ps.receiveFromQueue(queue); } /** * Receives message from queue. The message is set to internal message * object and its body and properties can be accessed via methods. * * Arguments: * - _queue_: name of the queue * - _timeout_: receive timeout in milliseconds */ public void receiveFromQueue(String queue, long timeout) throws Exception { ProviderSession ps = providerConnection.getProviderSession(); ps.receiveFromQueue(queue, timeout); } /** * Sends message to topic. The message must have been created beforehand * using one of the create message methods. Message id can be accessed after * sending. */ public void sendToTopic(String topic) throws Exception { ProviderSession ps = providerConnection.getProviderSession(); ps.sendToTopic(topic); } /** * Subscribes to topic. Receive From Topic can be called after. */ public void subscribe(String topic) throws JMSException { ProviderSession ps = providerConnection.getProviderSession(); ps.subscribe(topic); } /** * Unsubscribes from topic and closes topic consumer. This can be used also * after Subscribe Durable (Durable subscription will still remain). */ public void unsubscribe() throws JMSException { ProviderSession ps = providerConnection.getProviderSession(); ps.unsubscribe(); } /** * Subscribes durably to topic. Receive From Topic can be called after. * * Arguments: * - _topic_: topic name * - _name_: subscription name */ public void subscribeDurable(String topic, String name) throws JMSException { ProviderSession ps = providerConnection.getProviderSession(); ps.subscribeDurable(topic, name); } /** * Unsubscribes from topic and closes topic consumer. * * Argument: * - _name_: subscription name */ public void unsubscribeDurable(String name) throws JMSException { ProviderSession ps = providerConnection.getProviderSession(); ps.unsubscribeDurable(name); } /** * Subscribe (Subscribe Durable) must have been called before this. */ public void receiveFromTopic() throws Exception { ProviderSession ps = providerConnection.getProviderSession(); ps.receiveFromTopic(); } /** * Subscribe (Subscribe Durable) must have been called before this. * * Argument: * - _timeout_: receive timeout in milliseconds */ public void receiveFromTopic(long timeout) throws Exception { ProviderSession ps = providerConnection.getProviderSession(); ps.receiveFromTopic(timeout); } /** * Returns the body of TextMessage. */ public String getText() throws Exception { ProviderSession ps = providerConnection.getProviderSession(); return ps.getText(); } /** * Writes body of BytesMessage into file. */ public void writeBytesToFile(String file) throws JMSException, IOException { ProviderSession ps = providerConnection.getProviderSession(); ps.writeBytes(file); } /** * Returns queue depth. Implemented using QueueBrowser. */ public int queueDepth(String queue) throws Exception { ProviderSession ps = providerConnection.getProviderSession(); int depth = ps.queueDepth(queue); System.out.println(queue + " depth is " + depth); return depth; } /** * Clears the queue by reading all available messages. Acknowledges or * commits depending on the configuration. * * Returns message count that was consumed from the queue */ public int clearQueue(String queue) throws Exception { ProviderSession ps = providerConnection.getProviderSession(); int count = ps.clearQueue(queue); System.out.println(queue + " cleared. " + count + " messages consumed."); return count; } /** * Clears the topic by reading all available messages. Acknowledges or * commits depending on the configuration. Subscription must have been done * before. * * Returns message count that was consumed from the topic. */ public int clearTopic() throws JMSException { ProviderSession ps = providerConnection.getProviderSession(); int count = ps.clearTopic(); System.out.println("Topic cleared. " + count + " messages consumed."); return count; } }
src/main/java/JMSLibrary.java
import java.io.IOException; import java.util.Map; import java.util.Properties; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSException; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import fi.toje.himmeli.jmslibrary.ProviderConnection; import fi.toje.himmeli.jmslibrary.ProviderSession; /** * Robot Framework library for testing applications utilizing JMS. * * Set the library and chosen JMS provider jars into classpath and start * testing. * * Library uses one connection which has one session. Session includes one * message producer and one message consumer for topic. Queue consumers are * created on the fly when receiving. Currently, messages can be received only * from one topic at time. Producer specific settings (timeToLive etc.) apply * within a session. Settings will be reset, if session is reinitialized. * * Default receive timeout is 100 ms. * * = Example with ActiveMQ = * * | *** Settings *** * | Library String * | Library JMSLibrary ${INITIAL_CONTEXT_FACTORY} ${PROVIDER_URL} * | Suite Setup Connect And Start * | Suite Teardown Close Connection * | Test Setup Clear Queue ${QUEUE} * | Test Tear Down Clear Queue ${QUEUE} * | * | *** Variables *** * | ${INITIAL_CONTEXT_FACTORY} org.apache.activemq.jndi.ActiveMQInitialContextFactory * | ${PROVIDER_URL} tcp://localhost:61616?jms.useAsyncSend=false * | ${QUEUE} QUEUE.JMSLIBRARY.TEST * | ${TOPIC} TOPIC.JMSLIBRARY.TEST * | * | *** Test Cases *** * | Queue Send and Receive TextMessage * | ${text}= Generate Random String * | Create Text Message ${text} * | Send To Queue ${QUEUE} * | Receive From Queue ${QUEUE} * | ${body}= Get Text * | Should Be Equal ${body} ${text} * | * | Topic Send and Receive TextMessage * | Subscribe ${TOPIC} * | ${text}= Generate Random String * | Create Text Message ${text} * | Send To Topic ${TOPIC} * | Receive From Topic * | ${body}= Get Text * | Should Be Equal ${body} ${text} * | Unsubscribe */ public class JMSLibrary { public static final String ROBOT_LIBRARY_SCOPE = "TEST SUITE"; public static final String ROBOT_LIBRARY_VERSION = "1.0.0-beta.3"; public static final String DEFAULT_CONNECTION_FACTORY_LOOKUP_NAME = "ConnectionFactory"; public static final String SETTINGS_KW_CONNECTION_FACTORY_LOOKUP_NAME = "connection_factory_name"; private InitialContext initialContext; private ConnectionFactory connectionFactory; private ProviderConnection providerConnection; /** * Settings for selecting JMS provider. Default JNDI connection factory * look up string is 'ConnectionFactory'. * * Optional settings: * - _connection_factory_name_: lookup name for connection factory * * Examples: * | Library | JMSLibrary | org.apache.activemq.jndi.ActiveMQInitialContextFactory | tcp://localhost:61616?jms.useAsyncSend=false | * | Library | JMSLibrary | com.sun.jndi.fscontext.RefFSContextFactory | file:/C:/JNDI-Directory | connection_factory_name=myCF | */ public JMSLibrary(String initialContextFactory, String providerUrl, Map<String, String> settings) throws NamingException { Properties env = new Properties( ); env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory); env.put(Context.PROVIDER_URL, providerUrl); initialContext = new InitialContext(env); connectionFactory = (ConnectionFactory)initialContext.lookup(getConnectionFactoryLookupName(settings)); } private String getConnectionFactoryLookupName(Map<String, String> settings) { String lookupName = DEFAULT_CONNECTION_FACTORY_LOOKUP_NAME; if (settings.containsKey(SETTINGS_KW_CONNECTION_FACTORY_LOOKUP_NAME)) { lookupName = settings.get(SETTINGS_KW_CONNECTION_FACTORY_LOOKUP_NAME); } return lookupName; } /** * Connects to provider. Does not initialize session or start connection. */ public void connect() throws Exception { connect(null, null); } /** * Connects to provider. Does not initialize session or start connection. */ public void connect(String username, String password) throws Exception { if (providerConnection != null) { throw new Exception("Connection exists"); } Connection connection; if (username != null) { connection = connectionFactory.createConnection(username, password); } else { connection = connectionFactory.createConnection(); } providerConnection = new ProviderConnection(connection); } /** * Connects to provider. Initializes default session and starts the * connection. */ public void connectAndStart() throws Exception { connect(); initializeSession(); start(); } /** * Connects to provider. Initializes default session and starts the * connection. */ public void connectAndStart(String username, String password) throws Exception { connect(username, password); initializeSession(); start(); } /** * Sets clientId. Must be used right after connect, refer JMS specs. */ public void setClientId(String clientId) throws JMSException { providerConnection.setClientId(clientId); } /** * Returns clientId. */ public String getClientId() throws JMSException { return providerConnection.getClientId(); } /** * (Re)initializes session with default attributes (non-transacted, * AUTO_ACKNOWLEDGE). */ public void initializeSession() throws Exception { initializeSession(false, ProviderSession.AUTO_ACKNOWLEDGE); } /** * (Re)initializes session. * * Arguments: * - _transacted_: true or false * - _type_: AUTO_ACKNOWLEDGE, CLIENT_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE or SESSION_TRANSACTED */ public void initializeSession(boolean transacted, String type) throws Exception { providerConnection.initSession(transacted, type); } /** * Starts connection. */ public void start() throws JMSException { providerConnection.start(); } /** * Stops connection. */ public void stop() throws JMSException { providerConnection.stop(); } /** * Closes provider connection. Closes all resources (session, producer and * consumer). */ public void closeConnection() throws Exception { providerConnection.close(); providerConnection = null; } /** * Commits all messages in the session. */ public void commit() throws JMSException { ProviderSession bs = providerConnection.getProviderSession(); bs.commit(); } /** * Rolls back messages in the session. */ public void rollback() throws JMSException { ProviderSession bs = providerConnection.getProviderSession(); bs.rollback(); } /** * Acknowledges all consumed messages of the session. Used in * CLIENT_ACKNOWLEDGE mode. */ public void acknowledge() throws JMSException { ProviderSession bs = providerConnection.getProviderSession(); bs.acknowledge(); } /** * Creates TextMessage. Additional properties can be set after creation. */ public void createTextMessage(String text) throws Exception { ProviderSession bs = providerConnection.getProviderSession(); bs.createTextMessage(text); } /** * Creates BytesMessage from file. Additional properties can be set after * creation. * * Argument: * - _file_: name of the file */ public void createBytesMessageFromFile(String file) throws JMSException, IOException { ProviderSession bs = providerConnection.getProviderSession(); bs.createBytesMessage(file); } /** * Sets JMSType of message. */ public void setJMSType(String type) throws JMSException { ProviderSession bs = providerConnection.getProviderSession(); bs.setType(type); } /** * Returns JMSType of message. */ public String getJMSType() throws JMSException { ProviderSession bs = providerConnection.getProviderSession(); return bs.getType(); } /** * Sets JMSCorrelationID for message. */ public void setJMSCorrelationId(String correlationId) throws JMSException { ProviderSession bs = providerConnection.getProviderSession(); bs.setCorrelationId(correlationId); } /** * Returns JMSCorrelationID of message. */ public String getJMSCorrelationId() throws JMSException { ProviderSession bs = providerConnection.getProviderSession(); return bs.getCorrelationId(); } /** * Sets JMSReplyTo queue for message. */ public void setJMSReplyToQueue(String queue) throws JMSException { ProviderSession bs = providerConnection.getProviderSession(); bs.setReplyToQueue(queue); } /** * JMSReplyTo queue of message. * * Returns queue if it was set and was type of queue, otherwise (not set or * is topic) null */ public String getJMSReplyToQueue() throws JMSException { ProviderSession bs = providerConnection.getProviderSession(); return bs.getReplyToQueue(); } /** * Sets JMSReplyTo topic for message. */ public void setJMSReplyToTopic(String topic) throws JMSException { ProviderSession bs = providerConnection.getProviderSession(); bs.setReplyToTopic(topic); } /** * JMSReplyTo value of message. * * Returns topic if it was set and was type of topic, otherwise (not set or * is queue) null */ public String getJMSReplyToTopic() throws JMSException { ProviderSession bs = providerConnection.getProviderSession(); return bs.getReplyToTopic(); } /** * Sets time to live for the producer. * * Argument: * - _timeToLive_: time to live in milliseconds */ public void setProducerTimeToLive(long timeToLive) throws JMSException { ProviderSession bs = providerConnection.getProviderSession(); bs.setProducerTimeToLive(timeToLive); } /** * JMSExpiration of received message. * * Returns expiration of message */ public long getJMSExpiration() throws JMSException { ProviderSession bs = providerConnection.getProviderSession(); return bs.getExpiration(); } /** * Sets delivery mode for the producer. * * Argument: * - _deliveryMode_: PERSISTENT or NON_PERSISTENT */ public void setProducerDeliveryMode(String deliveryMode) throws Exception { ProviderSession bs = providerConnection.getProviderSession(); bs.setProducerDeliveryMode(deliveryMode); } /** * Returns delivery mode of the producer: PERSISTENT or NON_PERSISTENT. */ public String getProducerDeliveryMode() throws Exception { ProviderSession bs = providerConnection.getProviderSession(); return bs.getProducerDeliveryMode(); } /** * Returns delivery mode of received message: PERSISTENT or NON_PERSISTENT. */ public String getDeliveryMode() throws Exception { ProviderSession bs = providerConnection.getProviderSession(); return bs.getDeliveryMode(); } /** * JMSRedelivered of received message. * * Return true if message was redelivered */ public boolean getJMSRedelivered() throws JMSException { ProviderSession bs = providerConnection.getProviderSession(); return bs.getJmsRedelivered(); } /** * Sets string property for message. */ public void setStringProperty(String name, String value) throws Exception { ProviderSession bs = providerConnection.getProviderSession(); bs.setStringProperty(name, value); System.out.println(name + "=" + value); } /** * Returns string property of message. * * Arguments: * - _name_: name of the property */ public String getStringProperty(String name) throws Exception { ProviderSession bs = providerConnection.getProviderSession(); String value = bs.getStringProperty(name); System.out.println(name + "=" + value); return value; } /** * JMSMessageID * * Returns message id. */ public String getJMSMessageId() throws JMSException { ProviderSession bs = providerConnection.getProviderSession(); String id = bs.getMessageId(); System.out.println("MessageId=" + id); return id; } /** * Sends message to queue. The message must have been created beforehand * using one of the create message methods. Message id can be accessed after * sending. */ public void sendToQueue(String queue) throws Exception { ProviderSession bs = providerConnection.getProviderSession(); bs.sendToQueue(queue); } /** * Receives message from queue. The message is set to internal message * object and its body and properties can be accessed via methods. */ public void receiveFromQueue(String queue) throws Exception { ProviderSession bs = providerConnection.getProviderSession(); bs.receiveFromQueue(queue); } /** * Receives message from queue. The message is set to internal message * object and its body and properties can be accessed via methods. * * Arguments: * - _queue_: name of the queue * - _timeout_: receive timeout in milliseconds */ public void receiveFromQueue(String queue, long timeout) throws Exception { ProviderSession bs = providerConnection.getProviderSession(); bs.receiveFromQueue(queue, timeout); } /** * Sends message to topic. The message must have been created beforehand * using one of the create message methods. Message id can be accessed after * sending. */ public void sendToTopic(String topic) throws Exception { ProviderSession bs = providerConnection.getProviderSession(); bs.sendToTopic(topic); } /** * Subscribes to topic. Receive From Topic can be called after. */ public void subscribe(String topic) throws JMSException { ProviderSession bs = providerConnection.getProviderSession(); bs.subscribe(topic); } /** * Unsubscribes from topic and closes topic consumer. This can be used also * after Subscribe Durable (Durable subscription will still remain). */ public void unsubscribe() throws JMSException { ProviderSession bs = providerConnection.getProviderSession(); bs.unsubscribe(); } /** * Subscribes durably to topic. Receive From Topic can be called after. * * Arguments: * - _topic_: topic name * - _name_: subscription name */ public void subscribeDurable(String topic, String name) throws JMSException { ProviderSession bs = providerConnection.getProviderSession(); bs.subscribeDurable(topic, name); } /** * Unsubscribes from topic and closes topic consumer. * * Argument: * - _name_: subscription name */ public void unsubscribeDurable(String name) throws JMSException { ProviderSession bs = providerConnection.getProviderSession(); bs.unsubscribeDurable(name); } /** * Subscribe (Subscribe Durable) must have been called before this. */ public void receiveFromTopic() throws Exception { ProviderSession bs = providerConnection.getProviderSession(); bs.receiveFromTopic(); } /** * Subscribe (Subscribe Durable) must have been called before this. * * Argument: * - _timeout_: receive timeout in milliseconds */ public void receiveFromTopic(long timeout) throws Exception { ProviderSession bs = providerConnection.getProviderSession(); bs.receiveFromTopic(timeout); } /** * Returns the body of TextMessage. */ public String getText() throws Exception { ProviderSession bs = providerConnection.getProviderSession(); return bs.getText(); } /** * Writes body of BytesMessage into file. */ public void writeBytesToFile(String file) throws JMSException, IOException { ProviderSession bs = providerConnection.getProviderSession(); bs.writeBytes(file); } /** * Returns queue depth. Implemented using QueueBrowser. */ public int queueDepth(String queue) throws Exception { ProviderSession bs = providerConnection.getProviderSession(); int depth = bs.queueDepth(queue); System.out.println(queue + " depth is " + depth); return depth; } /** * Clears the queue by reading all available messages. Acknowledges or * commits depending on the configuration. * * Returns message count that was consumed from the queue */ public int clearQueue(String queue) throws Exception { ProviderSession bs = providerConnection.getProviderSession(); int count = bs.clearQueue(queue); System.out.println(queue + " cleared. " + count + " messages consumed."); return count; } /** * Clears the topic by reading all available messages. Acknowledges or * commits depending on the configuration. Subscription must have been done * before. * * Returns message count that was consumed from the topic. */ public int clearTopic() throws JMSException { ProviderSession bs = providerConnection.getProviderSession(); int count = bs.clearTopic(); System.out.println("Topic cleared. " + count + " messages consumed."); return count; } }
variable rename
src/main/java/JMSLibrary.java
variable rename
Java
apache-2.0
0053337184c7021522640dd4907678053f65a248
0
jeo/jeo,jeo/jeo,jeo/jeo
/* Copyright 2013 The jeo project. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.jeo.mongo; import java.io.IOException; import java.util.Arrays; import java.util.EnumSet; import java.util.List; import java.util.Map; import io.jeo.vector.VectorDriver; import io.jeo.vector.Schema; import io.jeo.util.Key; import io.jeo.util.Messages; import io.jeo.util.Password; import static io.jeo.vector.VectorDriver.Capability.APPEND; import static io.jeo.vector.VectorDriver.Capability.BOUND; import static io.jeo.vector.VectorDriver.Capability.LIMIT; import static io.jeo.vector.VectorDriver.Capability.OFFSET; import static io.jeo.vector.VectorDriver.Capability.UPDATE; public class MongoDB implements VectorDriver<MongoWorkspace> { public static final Key<String> DB = new Key<String>("db", String.class); public static final Key<String> HOST = new Key<String>("host", String.class, "localhost"); public static final Key<Integer> PORT = new Key<Integer>("port", Integer.class, 27017); public static final Key<String> USER = new Key<String>("user", String.class, System.getProperty("user.name")); public static final Key<Password> PASSWD = new Key<Password>("passwd", Password.class); public static MongoWorkspace open(MongoOpts opts) throws IOException { return new MongoWorkspace(opts); } @Override public boolean isEnabled(Messages messages) { return true; } @Override public String name() { return "MongoDB"; } @Override public List<String> aliases() { return Arrays.asList("mongo"); } @Override public Class<MongoWorkspace> type() { return MongoWorkspace.class; } @Override public List<Key<?>> keys() { return (List) Arrays.asList(DB, HOST, PORT, USER, PASSWD); } @Override public String family() { return "jeo"; } @Override public boolean canOpen(Map<?, Object> opts, Messages msgs) { if (!DB.in(opts)) { Messages.of(msgs).report("No " + DB + " option specified"); return false; } return true; } @Override public MongoWorkspace open(Map<?, Object> opts) throws IOException { return new MongoWorkspace(MongoOpts.fromMap(opts)); } @Override public boolean canCreate(Map<?, Object> opts, Messages msgs) { Messages.of(msgs).report("Creation not suported"); return false; } @Override public MongoWorkspace create(Map<?, Object> opts, Schema schema) throws IOException { throw new UnsupportedOperationException(); } static final EnumSet<Capability> CAPABILITIES = EnumSet.of(APPEND, UPDATE, BOUND, LIMIT, OFFSET); @Override public boolean supports(Capability cap) { return CAPABILITIES.contains(cap); } }
src/main/java/io/jeo/mongo/MongoDB.java
/* Copyright 2013 The jeo project. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.jeo.mongo; import java.io.IOException; import java.util.Arrays; import java.util.EnumSet; import java.util.List; import java.util.Map; import io.jeo.vector.VectorDriver; import io.jeo.vector.Schema; import io.jeo.util.Key; import io.jeo.util.Messages; import io.jeo.util.Password; public class MongoDB implements VectorDriver<MongoWorkspace> { public static final Key<String> DB = new Key<String>("db", String.class); public static final Key<String> HOST = new Key<String>("host", String.class, "localhost"); public static final Key<Integer> PORT = new Key<Integer>("port", Integer.class, 27017); public static final Key<String> USER = new Key<String>("user", String.class, System.getProperty("user.name")); public static final Key<Password> PASSWD = new Key<Password>("passwd", Password.class); public static MongoWorkspace open(MongoOpts opts) throws IOException { return new MongoWorkspace(opts); } @Override public boolean isEnabled(Messages messages) { return true; } @Override public String name() { return "MongoDB"; } @Override public List<String> aliases() { return Arrays.asList("mongo"); } @Override public Class<MongoWorkspace> type() { return MongoWorkspace.class; } @Override public List<Key<?>> keys() { return (List) Arrays.asList(DB, HOST, PORT, USER, PASSWD); } @Override public String family() { return "jeo"; } @Override public boolean canOpen(Map<?, Object> opts, Messages msgs) { if (!DB.in(opts)) { Messages.of(msgs).report("No " + DB + " option specified"); return false; } return true; } @Override public MongoWorkspace open(Map<?, Object> opts) throws IOException { return new MongoWorkspace(MongoOpts.fromMap(opts)); } @Override public boolean canCreate(Map<?, Object> opts, Messages msgs) { Messages.of(msgs).report("Creation not suported"); return false; } @Override public MongoWorkspace create(Map<?, Object> opts, Schema schema) throws IOException { throw new UnsupportedOperationException(); } static final EnumSet<Capability> CAPABILITIES = EnumSet.of(Capability.BOUND, Capability.LIMIT, Capability.OFFSET); @Override public boolean supports(Capability cap) { return CAPABILITIES.contains(cap); } }
Declaring UPDATE and APPEND capability.
src/main/java/io/jeo/mongo/MongoDB.java
Declaring UPDATE and APPEND capability.
Java
apache-2.0
1949583f39ce5d0b4210867f02c651cd88523873
0
BURAI-team/burai
/* * Copyright (C) 2016 Satomichi Nishihara * * This file is distributed under the terms of the * GNU General Public License. See the file `LICENSE' * in the root directory of the present distribution, * or http://www.gnu.org/copyleft/gpl.txt . */ package burai.com.periodic; import java.util.Map; import burai.app.QEFXMain; import burai.atoms.element.ElementUtil; import javafx.geometry.Pos; import javafx.scene.control.ButtonType; import javafx.scene.control.Dialog; import javafx.scene.control.DialogPane; import javafx.scene.layout.GridPane; public class PeriodicTable extends Dialog<ElementButton> { private GridPane gridPane; public PeriodicTable() { this(null); } public PeriodicTable(Map<String, String> styles) { super(); DialogPane dialogPane = this.getDialogPane(); QEFXMain.initializeStyleSheets(dialogPane.getStylesheets()); QEFXMain.initializeDialogOwner(this); this.setResizable(false); this.setTitle("Periodic Table"); dialogPane.setHeaderText("Select an element."); dialogPane.getButtonTypes().addAll(ButtonType.CANCEL); this.createGridPane(styles); dialogPane.setContent(this.gridPane); this.setResultConverter(buttonType -> { return null; }); } private void createGridPane(Map<String, String> styles) { this.gridPane = new GridPane(); this.gridPane.setHgap(0.0); this.gridPane.setVgap(0.0); this.gridPane.setAlignment(Pos.CENTER); String[] elementNames = ElementUtil.listAllElements(); for (String elementName : elementNames) { ElementButton elementButton = new ElementButton(elementName); elementButton.setDialog(this); if (styles != null && !styles.isEmpty()) { String style = styles.get(elementName); if (style != null && !style.isEmpty()) { elementButton.setStyle(style); } } this.gridPane.add(elementButton, elementButton.getY() - 1, elementButton.getX() - 1); } } }
src/burai/com/periodic/PeriodicTable.java
/* * Copyright (C) 2016 Satomichi Nishihara * * This file is distributed under the terms of the * GNU General Public License. See the file `LICENSE' * in the root directory of the present distribution, * or http://www.gnu.org/copyleft/gpl.txt . */ package burai.com.periodic; import javafx.geometry.Pos; import javafx.scene.control.ButtonType; import javafx.scene.control.Dialog; import javafx.scene.control.DialogPane; import javafx.scene.layout.GridPane; import burai.app.QEFXMain; import burai.atoms.element.ElementUtil; public class PeriodicTable extends Dialog<ElementButton> { private GridPane gridPane; public PeriodicTable() { super(); DialogPane dialogPane = this.getDialogPane(); QEFXMain.initializeStyleSheets(dialogPane.getStylesheets()); QEFXMain.initializeDialogOwner(this); this.setResizable(false); this.setTitle("Periodic Table"); dialogPane.setHeaderText("Select an element."); dialogPane.getButtonTypes().addAll(ButtonType.CANCEL); this.createGridPane(); dialogPane.setContent(this.gridPane); this.setResultConverter(buttonType -> { return null; }); } private void createGridPane() { this.gridPane = new GridPane(); this.gridPane.setHgap(0.0); this.gridPane.setVgap(0.0); this.gridPane.setAlignment(Pos.CENTER); String[] elementNames = ElementUtil.listAllElements(); for (String elementName : elementNames) { ElementButton elementButton = new ElementButton(elementName); elementButton.setDialog(this); this.gridPane.add(elementButton, elementButton.getY() - 1, elementButton.getX() - 1); } } }
update PeriodicTable
src/burai/com/periodic/PeriodicTable.java
update PeriodicTable
Java
apache-2.0
ba458bd9b4161bfd1940eb85d191ef1c1eb1c227
0
tombujok/hazelcast,emrahkocaman/hazelcast,emre-aydin/hazelcast,mesutcelik/hazelcast,dsukhoroslov/hazelcast,emrahkocaman/hazelcast,Donnerbart/hazelcast,emre-aydin/hazelcast,mesutcelik/hazelcast,tkountis/hazelcast,juanavelez/hazelcast,lmjacksoniii/hazelcast,tufangorel/hazelcast,emre-aydin/hazelcast,dsukhoroslov/hazelcast,dbrimley/hazelcast,mdogan/hazelcast,dbrimley/hazelcast,mesutcelik/hazelcast,tkountis/hazelcast,tufangorel/hazelcast,tkountis/hazelcast,mdogan/hazelcast,tufangorel/hazelcast,tombujok/hazelcast,lmjacksoniii/hazelcast,mdogan/hazelcast,Donnerbart/hazelcast,Donnerbart/hazelcast,dbrimley/hazelcast,juanavelez/hazelcast
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.mapreduce; import com.hazelcast.core.ExecutionCallback; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.ICompletableFuture; import com.hazelcast.core.IList; import com.hazelcast.core.IMap; import com.hazelcast.core.ISet; import com.hazelcast.core.MultiMap; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.DataSerializable; import com.hazelcast.spi.NodeEngine; import com.hazelcast.test.AssertTask; import com.hazelcast.test.HazelcastParallelClassRunner; import com.hazelcast.test.HazelcastTestSupport; import com.hazelcast.test.TestHazelcastInstanceFactory; import com.hazelcast.test.annotation.QuickTest; import org.junit.Ignore; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Semaphore; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @RunWith(HazelcastParallelClassRunner.class) @Category(QuickTest.class) @SuppressWarnings("unused") public class MapReduceTest extends HazelcastTestSupport { private static final String MAP_NAME = "default"; @Test(timeout = 30000) public void testPartitionPostpone() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); final HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); final HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); final HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); assertTrueEventually(new AssertTask() { @Override public void run() { assertEquals(3, h1.getCluster().getMembers().size()); } }); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } JobTracker tracker = h1.getJobTracker("default"); KeyValueSource<Integer, Integer> kvs = KeyValueSource.fromMap(m1); KeyValueSource<Integer, Integer> wrapper = new MapKeyValueSourceAdapter<Integer, Integer>(kvs); Job<Integer, Integer> job = tracker.newJob(wrapper); ICompletableFuture<Map<String, List<Integer>>> future = job.mapper(new TestMapper()) .submit(); Map<String, List<Integer>> result = future.get(); assertEquals(100, result.size()); for (List<Integer> value : result.values()) { assertEquals(1, value.size()); } } @Test(timeout = 30000, expected = ExecutionException.class) public void testExceptionDistribution() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); final HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); final HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); final HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); assertTrueEventually(new AssertTask() { @Override public void run() { assertEquals(3, h1.getCluster().getMembers().size()); } }); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Map<String, List<Integer>>> future = job.mapper(new ExceptionThrowingMapper()) .submit(); try { Map<String, List<Integer>> result = future.get(); } catch (Exception e) { e.printStackTrace(); assertTrue(e.getCause() instanceof NullPointerException); throw e; } } @Test(timeout = 30000, expected = CancellationException.class) public void testInProcessCancellation() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); final HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); final HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); final HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); assertTrueEventually(new AssertTask() { @Override public void run() { assertEquals(3, h1.getCluster().getMembers().size()); } }); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Map<String, List<Integer>>> future = job.mapper(new TimeConsumingMapper()) .submit(); future.cancel(true); try { Map<String, List<Integer>> result = future.get(); } catch (Exception e) { e.printStackTrace(); throw e; } } @Test(timeout = 30000) public void testMapper() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); final HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); final HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); final HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); assertTrueEventually(new AssertTask() { @Override public void run() { assertEquals(3, h1.getCluster().getMembers().size()); } }); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Map<String, List<Integer>>> future = job.mapper(new TestMapper()) .submit(); Map<String, List<Integer>> result = future.get(); assertEquals(100, result.size()); for (List<Integer> value : result.values()) { assertEquals(1, value.size()); } } @Test(timeout = 30000) public void testKeyedMapperCollator() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 10000; i++) { m1.put(i, i); } JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Integer> future = job.onKeys(50) .mapper(new TestMapper()) .submit(new GroupingTestCollator()); int result = future.get(); assertEquals(50, result); } @Test(timeout = 30000) public void testKeyPredicateMapperCollator() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 10000; i++) { m1.put(i, i); } JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Integer> future = job.keyPredicate(new TestKeyPredicate()).mapper(new TestMapper()) .submit(new GroupingTestCollator()); int result = future.get(); assertEquals(50, result); } @Test(timeout = 30000) public void testMapperComplexMapping() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Map<String, List<Integer>>> future = job.mapper(new GroupingTestMapper(2)) .submit(); Map<String, List<Integer>> result = future.get(); assertEquals(1, result.size()); assertEquals(25, result.values().iterator().next().size()); } @Test(timeout = 30000) public void testMapperReducer() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Map<String, Integer>> future = job.mapper(new GroupingTestMapper()) .reducer(new TestReducerFactory()) .submit(); Map<String, Integer> result = future.get(); // Precalculate results int[] expectedResults = new int[4]; for (int i = 0; i < 100; i++) { int index = i % 4; expectedResults[index] += i; } for (int i = 0; i < 4; i++) { assertEquals(expectedResults[i], (int) result.get(String.valueOf(i))); } } @Test(timeout = 60000) public void testMapperReducerChunked() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); final HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); final HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); final HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); assertTrueEventually(new AssertTask() { @Override public void run() { assertEquals(3, h1.getCluster().getMembers().size()); } }); final IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 10000; i++) { m1.put(i, i); } JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); JobCompletableFuture<Map<String, Integer>> future = job.chunkSize(10) .mapper(new GroupingTestMapper()) .reducer(new TestReducerFactory()) .submit(); final TrackableJob trackableJob = tracker.getTrackableJob(future.getJobId()); final JobProcessInformation processInformation = trackableJob.getJobProcessInformation(); Map<String, Integer> result = future.get(); // Precalculate results int[] expectedResults = new int[4]; for (int i = 0; i < 10000; i++) { int index = i % 4; expectedResults[index] += i; } for (int i = 0; i < 4; i++) { assertEquals(expectedResults[i], (int) result.get(String.valueOf(i))); } assertTrueEventually(new AssertTask() { @Override public void run() { if (processInformation.getProcessedRecords() < 10000) { System.err.println(processInformation.getProcessedRecords()); } assertEquals(10000, processInformation.getProcessedRecords()); } }); } @Test(timeout = 30000) public void testMapperCollator() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Integer> future = job.mapper(new GroupingTestMapper()) .submit(new GroupingTestCollator()); int result = future.get(); // Precalculate result int expectedResult = 0; for (int i = 0; i < 100; i++) { expectedResult += i; } for (int i = 0; i < 4; i++) { assertEquals(expectedResult, result); } } @Test(timeout = 30000) public void testMapperReducerCollator() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Integer> future = job.mapper(new GroupingTestMapper()) .reducer(new TestReducerFactory()) .submit(new TestCollator()); int result = future.get(); // Precalculate result int expectedResult = 0; for (int i = 0; i < 100; i++) { expectedResult += i; } for (int i = 0; i < 4; i++) { assertEquals(expectedResult, result); } } @Test(timeout = 30000) public void testAsyncMapper() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } final Map<String, List<Integer>> listenerResults = new HashMap<String, List<Integer>>(); final Semaphore semaphore = new Semaphore(1); semaphore.acquire(); JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Map<String, List<Integer>>> future = job.mapper(new TestMapper()) .submit(); future.andThen(new ExecutionCallback<Map<String, List<Integer>>>() { @Override public void onResponse(Map<String, List<Integer>> response) { try { listenerResults.putAll(response); } finally { semaphore.release(); } } @Override public void onFailure(Throwable t) { semaphore.release(); } }); semaphore.acquire(); assertEquals(100, listenerResults.size()); for (List<Integer> value : listenerResults.values()) { assertEquals(1, value.size()); } } @Test(timeout = 30000) public void testKeyedAsyncMapper() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } final Map<String, List<Integer>> listenerResults = new HashMap<String, List<Integer>>(); final Semaphore semaphore = new Semaphore(1); semaphore.acquire(); JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Map<String, List<Integer>>> future = job.onKeys(50) .mapper(new TestMapper()) .submit(); future.andThen(new ExecutionCallback<Map<String, List<Integer>>>() { @Override public void onResponse(Map<String, List<Integer>> response) { try { listenerResults.putAll(response); } finally { semaphore.release(); } } @Override public void onFailure(Throwable t) { semaphore.release(); } }); semaphore.acquire(); assertEquals(1, listenerResults.size()); for (List<Integer> value : listenerResults.values()) { assertEquals(1, value.size()); } } @Test(timeout = 30000) public void testAsyncMapperReducer() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } final Map<String, Integer> listenerResults = new HashMap<String, Integer>(); final Semaphore semaphore = new Semaphore(1); semaphore.acquire(); JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Map<String, Integer>> future = job.mapper(new GroupingTestMapper()) .reducer(new TestReducerFactory())// .submit(); future.andThen(new ExecutionCallback<Map<String, Integer>>() { @Override public void onResponse(Map<String, Integer> response) { try { listenerResults.putAll(response); } finally { semaphore.release(); } } @Override public void onFailure(Throwable t) { semaphore.release(); } }); // Precalculate results int[] expectedResults = new int[4]; for (int i = 0; i < 100; i++) { int index = i % 4; expectedResults[index] += i; } semaphore.acquire(); for (int i = 0; i < 4; i++) { assertEquals(expectedResults[i], (int) listenerResults.get(String.valueOf(i))); } } @Test(timeout = 30000) public void testAsyncMapperCollator() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } final int[] result = new int[1]; final Semaphore semaphore = new Semaphore(1); semaphore.acquire(); JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Integer> future = job.mapper(new GroupingTestMapper()) .submit(new GroupingTestCollator()); future.andThen(new ExecutionCallback<Integer>() { @Override public void onResponse(Integer response) { try { result[0] = response.intValue(); } finally { semaphore.release(); } } @Override public void onFailure(Throwable t) { semaphore.release(); } }); // Precalculate result int expectedResult = 0; for (int i = 0; i < 100; i++) { expectedResult += i; } semaphore.acquire(); for (int i = 0; i < 4; i++) { assertEquals(expectedResult, result[0]); } } @Test(timeout = 30000) public void testAsyncMapperReducerCollator() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } final int[] result = new int[1]; final Semaphore semaphore = new Semaphore(1); semaphore.acquire(); JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Integer> future = job.mapper(new GroupingTestMapper()) .reducer(new TestReducerFactory()) .submit(new TestCollator()); future.andThen(new ExecutionCallback<Integer>() { @Override public void onResponse(Integer response) { try { result[0] = response.intValue(); } finally { semaphore.release(); } } @Override public void onFailure(Throwable t) { semaphore.release(); } }); // Precalculate result int expectedResult = 0; for (int i = 0; i < 100; i++) { expectedResult += i; } semaphore.acquire(); for (int i = 0; i < 4; i++) { assertEquals(expectedResult, result[0]); } } public static class ExceptionThrowingMapper implements Mapper<Integer, Integer, String, Integer> { @Override public void map(Integer key, Integer value, Context<String, Integer> context) { throw new NullPointerException("BUMM!"); } } public static class TimeConsumingMapper implements Mapper<Integer, Integer, String, Integer> { @Override public void map(Integer key, Integer value, Context<String, Integer> collector) { try { Thread.sleep(1000); } catch (Exception ignore) { } collector.emit(String.valueOf(key), value); } } public static class TestKeyPredicate implements KeyPredicate<Integer> { @Override public boolean evaluate(Integer key) { return key == 50; } } public static class TestMapper implements Mapper<Integer, Integer, String, Integer> { @Override public void map(Integer key, Integer value, Context<String, Integer> collector) { collector.emit(String.valueOf(key), value); } } public static class GroupingTestMapper implements Mapper<Integer, Integer, String, Integer> { private int moduleKey = -1; public GroupingTestMapper() { } public GroupingTestMapper(int moduleKey) { this.moduleKey = moduleKey; } @Override public void map(Integer key, Integer value, Context<String, Integer> collector) { if (moduleKey == -1 || (key % 4) == moduleKey) { collector.emit(String.valueOf(key % 4), value); } } } public static class TestReducer extends Reducer<String, Integer, Integer> { private transient int sum = 0; @Override public void reduce(Integer value) { sum += value; } @Override public Integer finalizeReduce() { return sum; } } public static class TestReducerFactory implements ReducerFactory<String, Integer, Integer> { public TestReducerFactory() { } @Override public Reducer<String, Integer, Integer> newReducer(String key) { return new TestReducer(); } } public static class GroupingTestCollator implements Collator<Map.Entry<String, List<Integer>>, Integer> { @Override public Integer collate(Iterable<Map.Entry<String, List<Integer>>> values) { int sum = 0; for (Map.Entry<String, List<Integer>> entry : values) { for (Integer value : entry.getValue()) { sum += value; } } return sum; } } public static class TestCollator implements Collator<Map.Entry<String, Integer>, Integer> { @Override public Integer collate(Iterable<Map.Entry<String, Integer>> values) { int sum = 0; for (Map.Entry<String, Integer> entry : values) { sum += entry.getValue(); } return sum; } } public static class MapKeyValueSourceAdapter<K, V> extends KeyValueSource<K, V> implements DataSerializable, PartitionIdAware { private volatile KeyValueSource<K, V> keyValueSource; private int openCount = 0; public MapKeyValueSourceAdapter() { } public MapKeyValueSourceAdapter(KeyValueSource<K, V> keyValueSource) { this.keyValueSource = keyValueSource; } @Override public boolean open(NodeEngine nodeEngine) { if (openCount < 2) { openCount++; return false; } return keyValueSource.open(nodeEngine); } @Override public boolean hasNext() { return keyValueSource.hasNext(); } @Override public K key() { return keyValueSource.key(); } @Override public Map.Entry<K, V> element() { return keyValueSource.element(); } @Override public boolean reset() { return keyValueSource.reset(); } @Override public boolean isAllKeysSupported() { return keyValueSource.isAllKeysSupported(); } @Override public Collection<K> getAllKeys0() { return keyValueSource.getAllKeys0(); } public static <K1, V1> KeyValueSource<K1, V1> fromMap(IMap<K1, V1> map) { return KeyValueSource.fromMap(map); } public static <K1, V1> KeyValueSource<K1, V1> fromMultiMap(MultiMap<K1, V1> multiMap) { return KeyValueSource.fromMultiMap(multiMap); } public static <V1> KeyValueSource<String, V1> fromList(IList<V1> list) { return KeyValueSource.fromList(list); } public static <V1> KeyValueSource<String, V1> fromSet(ISet<V1> set) { return KeyValueSource.fromSet(set); } @Override public void close() throws IOException { keyValueSource.close(); } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeObject(keyValueSource); } @Override public void readData(ObjectDataInput in) throws IOException { keyValueSource = in.readObject(); } @Override public void setPartitionId(int partitionId) { if (keyValueSource instanceof PartitionIdAware) { ((PartitionIdAware) keyValueSource).setPartitionId(partitionId); } } } }
hazelcast/src/test/java/com/hazelcast/mapreduce/MapReduceTest.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.mapreduce; import com.hazelcast.core.ExecutionCallback; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.ICompletableFuture; import com.hazelcast.core.IList; import com.hazelcast.core.IMap; import com.hazelcast.core.ISet; import com.hazelcast.core.MultiMap; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.DataSerializable; import com.hazelcast.spi.NodeEngine; import com.hazelcast.test.AssertTask; import com.hazelcast.test.HazelcastParallelClassRunner; import com.hazelcast.test.HazelcastTestSupport; import com.hazelcast.test.TestHazelcastInstanceFactory; import com.hazelcast.test.annotation.QuickTest; import org.junit.Ignore; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Semaphore; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @RunWith(HazelcastParallelClassRunner.class) @Category(QuickTest.class) @Ignore("will be enabled, need to find cause of failing jenkins") @SuppressWarnings("unused") public class MapReduceTest extends HazelcastTestSupport { private static final String MAP_NAME = "default"; @Test(timeout = 30000) public void testPartitionPostpone() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); final HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); final HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); final HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); assertTrueEventually(new AssertTask() { @Override public void run() { assertEquals(3, h1.getCluster().getMembers().size()); } }); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } JobTracker tracker = h1.getJobTracker("default"); KeyValueSource<Integer, Integer> kvs = KeyValueSource.fromMap(m1); KeyValueSource<Integer, Integer> wrapper = new MapKeyValueSourceAdapter<Integer, Integer>(kvs); Job<Integer, Integer> job = tracker.newJob(wrapper); ICompletableFuture<Map<String, List<Integer>>> future = job.mapper(new TestMapper()) .submit(); Map<String, List<Integer>> result = future.get(); assertEquals(100, result.size()); for (List<Integer> value : result.values()) { assertEquals(1, value.size()); } } @Test(timeout = 30000, expected = ExecutionException.class) public void testExceptionDistribution() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); final HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); final HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); final HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); assertTrueEventually(new AssertTask() { @Override public void run() { assertEquals(3, h1.getCluster().getMembers().size()); } }); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Map<String, List<Integer>>> future = job.mapper(new ExceptionThrowingMapper()) .submit(); try { Map<String, List<Integer>> result = future.get(); } catch (Exception e) { e.printStackTrace(); assertTrue(e.getCause() instanceof NullPointerException); throw e; } } @Test(timeout = 30000, expected = CancellationException.class) public void testInProcessCancellation() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); final HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); final HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); final HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); assertTrueEventually(new AssertTask() { @Override public void run() { assertEquals(3, h1.getCluster().getMembers().size()); } }); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Map<String, List<Integer>>> future = job.mapper(new TimeConsumingMapper()) .submit(); future.cancel(true); try { Map<String, List<Integer>> result = future.get(); } catch (Exception e) { e.printStackTrace(); throw e; } } @Test(timeout = 30000) public void testMapper() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); final HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); final HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); final HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); assertTrueEventually(new AssertTask() { @Override public void run() { assertEquals(3, h1.getCluster().getMembers().size()); } }); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Map<String, List<Integer>>> future = job.mapper(new TestMapper()) .submit(); Map<String, List<Integer>> result = future.get(); assertEquals(100, result.size()); for (List<Integer> value : result.values()) { assertEquals(1, value.size()); } } @Test(timeout = 30000) public void testKeyedMapperCollator() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 10000; i++) { m1.put(i, i); } JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Integer> future = job.onKeys(50) .mapper(new TestMapper()) .submit(new GroupingTestCollator()); int result = future.get(); assertEquals(50, result); } @Test(timeout = 30000) public void testKeyPredicateMapperCollator() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 10000; i++) { m1.put(i, i); } JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Integer> future = job.keyPredicate(new TestKeyPredicate()).mapper(new TestMapper()) .submit(new GroupingTestCollator()); int result = future.get(); assertEquals(50, result); } @Test(timeout = 30000) public void testMapperComplexMapping() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Map<String, List<Integer>>> future = job.mapper(new GroupingTestMapper(2)) .submit(); Map<String, List<Integer>> result = future.get(); assertEquals(1, result.size()); assertEquals(25, result.values().iterator().next().size()); } @Test(timeout = 30000) public void testMapperReducer() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Map<String, Integer>> future = job.mapper(new GroupingTestMapper()) .reducer(new TestReducerFactory()) .submit(); Map<String, Integer> result = future.get(); // Precalculate results int[] expectedResults = new int[4]; for (int i = 0; i < 100; i++) { int index = i % 4; expectedResults[index] += i; } for (int i = 0; i < 4; i++) { assertEquals(expectedResults[i], (int) result.get(String.valueOf(i))); } } @Test(timeout = 60000) public void testMapperReducerChunked() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); final HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); final HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); final HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); assertTrueEventually(new AssertTask() { @Override public void run() { assertEquals(3, h1.getCluster().getMembers().size()); } }); final IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 10000; i++) { m1.put(i, i); } JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); JobCompletableFuture<Map<String, Integer>> future = job.chunkSize(10) .mapper(new GroupingTestMapper()) .reducer(new TestReducerFactory()) .submit(); final TrackableJob trackableJob = tracker.getTrackableJob(future.getJobId()); final JobProcessInformation processInformation = trackableJob.getJobProcessInformation(); Map<String, Integer> result = future.get(); // Precalculate results int[] expectedResults = new int[4]; for (int i = 0; i < 10000; i++) { int index = i % 4; expectedResults[index] += i; } for (int i = 0; i < 4; i++) { assertEquals(expectedResults[i], (int) result.get(String.valueOf(i))); } assertTrueEventually(new AssertTask() { @Override public void run() { if (processInformation.getProcessedRecords() < 10000) { System.err.println(processInformation.getProcessedRecords()); } assertEquals(10000, processInformation.getProcessedRecords()); } }); } @Test(timeout = 30000) public void testMapperCollator() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Integer> future = job.mapper(new GroupingTestMapper()) .submit(new GroupingTestCollator()); int result = future.get(); // Precalculate result int expectedResult = 0; for (int i = 0; i < 100; i++) { expectedResult += i; } for (int i = 0; i < 4; i++) { assertEquals(expectedResult, result); } } @Test(timeout = 30000) public void testMapperReducerCollator() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Integer> future = job.mapper(new GroupingTestMapper()) .reducer(new TestReducerFactory()) .submit(new TestCollator()); int result = future.get(); // Precalculate result int expectedResult = 0; for (int i = 0; i < 100; i++) { expectedResult += i; } for (int i = 0; i < 4; i++) { assertEquals(expectedResult, result); } } @Test(timeout = 30000) public void testAsyncMapper() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } final Map<String, List<Integer>> listenerResults = new HashMap<String, List<Integer>>(); final Semaphore semaphore = new Semaphore(1); semaphore.acquire(); JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Map<String, List<Integer>>> future = job.mapper(new TestMapper()) .submit(); future.andThen(new ExecutionCallback<Map<String, List<Integer>>>() { @Override public void onResponse(Map<String, List<Integer>> response) { try { listenerResults.putAll(response); } finally { semaphore.release(); } } @Override public void onFailure(Throwable t) { semaphore.release(); } }); semaphore.acquire(); assertEquals(100, listenerResults.size()); for (List<Integer> value : listenerResults.values()) { assertEquals(1, value.size()); } } @Test(timeout = 30000) public void testKeyedAsyncMapper() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } final Map<String, List<Integer>> listenerResults = new HashMap<String, List<Integer>>(); final Semaphore semaphore = new Semaphore(1); semaphore.acquire(); JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Map<String, List<Integer>>> future = job.onKeys(50) .mapper(new TestMapper()) .submit(); future.andThen(new ExecutionCallback<Map<String, List<Integer>>>() { @Override public void onResponse(Map<String, List<Integer>> response) { try { listenerResults.putAll(response); } finally { semaphore.release(); } } @Override public void onFailure(Throwable t) { semaphore.release(); } }); semaphore.acquire(); assertEquals(1, listenerResults.size()); for (List<Integer> value : listenerResults.values()) { assertEquals(1, value.size()); } } @Test(timeout = 30000) public void testAsyncMapperReducer() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } final Map<String, Integer> listenerResults = new HashMap<String, Integer>(); final Semaphore semaphore = new Semaphore(1); semaphore.acquire(); JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Map<String, Integer>> future = job.mapper(new GroupingTestMapper()) .reducer(new TestReducerFactory())// .submit(); future.andThen(new ExecutionCallback<Map<String, Integer>>() { @Override public void onResponse(Map<String, Integer> response) { try { listenerResults.putAll(response); } finally { semaphore.release(); } } @Override public void onFailure(Throwable t) { semaphore.release(); } }); // Precalculate results int[] expectedResults = new int[4]; for (int i = 0; i < 100; i++) { int index = i % 4; expectedResults[index] += i; } semaphore.acquire(); for (int i = 0; i < 4; i++) { assertEquals(expectedResults[i], (int) listenerResults.get(String.valueOf(i))); } } @Test(timeout = 30000) public void testAsyncMapperCollator() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } final int[] result = new int[1]; final Semaphore semaphore = new Semaphore(1); semaphore.acquire(); JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Integer> future = job.mapper(new GroupingTestMapper()) .submit(new GroupingTestCollator()); future.andThen(new ExecutionCallback<Integer>() { @Override public void onResponse(Integer response) { try { result[0] = response.intValue(); } finally { semaphore.release(); } } @Override public void onFailure(Throwable t) { semaphore.release(); } }); // Precalculate result int expectedResult = 0; for (int i = 0; i < 100; i++) { expectedResult += i; } semaphore.acquire(); for (int i = 0; i < 4; i++) { assertEquals(expectedResult, result[0]); } } @Test(timeout = 30000) public void testAsyncMapperReducerCollator() throws Exception { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(); HazelcastInstance h3 = nodeFactory.newHazelcastInstance(); IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME); for (int i = 0; i < 100; i++) { m1.put(i, i); } final int[] result = new int[1]; final Semaphore semaphore = new Semaphore(1); semaphore.acquire(); JobTracker tracker = h1.getJobTracker("default"); Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1)); ICompletableFuture<Integer> future = job.mapper(new GroupingTestMapper()) .reducer(new TestReducerFactory()) .submit(new TestCollator()); future.andThen(new ExecutionCallback<Integer>() { @Override public void onResponse(Integer response) { try { result[0] = response.intValue(); } finally { semaphore.release(); } } @Override public void onFailure(Throwable t) { semaphore.release(); } }); // Precalculate result int expectedResult = 0; for (int i = 0; i < 100; i++) { expectedResult += i; } semaphore.acquire(); for (int i = 0; i < 4; i++) { assertEquals(expectedResult, result[0]); } } public static class ExceptionThrowingMapper implements Mapper<Integer, Integer, String, Integer> { @Override public void map(Integer key, Integer value, Context<String, Integer> context) { throw new NullPointerException("BUMM!"); } } public static class TimeConsumingMapper implements Mapper<Integer, Integer, String, Integer> { @Override public void map(Integer key, Integer value, Context<String, Integer> collector) { try { Thread.sleep(1000); } catch (Exception ignore) { } collector.emit(String.valueOf(key), value); } } public static class TestKeyPredicate implements KeyPredicate<Integer> { @Override public boolean evaluate(Integer key) { return key == 50; } } public static class TestMapper implements Mapper<Integer, Integer, String, Integer> { @Override public void map(Integer key, Integer value, Context<String, Integer> collector) { collector.emit(String.valueOf(key), value); } } public static class GroupingTestMapper implements Mapper<Integer, Integer, String, Integer> { private int moduleKey = -1; public GroupingTestMapper() { } public GroupingTestMapper(int moduleKey) { this.moduleKey = moduleKey; } @Override public void map(Integer key, Integer value, Context<String, Integer> collector) { if (moduleKey == -1 || (key % 4) == moduleKey) { collector.emit(String.valueOf(key % 4), value); } } } public static class TestReducer extends Reducer<String, Integer, Integer> { private transient int sum = 0; @Override public void reduce(Integer value) { sum += value; } @Override public Integer finalizeReduce() { return sum; } } public static class TestReducerFactory implements ReducerFactory<String, Integer, Integer> { public TestReducerFactory() { } @Override public Reducer<String, Integer, Integer> newReducer(String key) { return new TestReducer(); } } public static class GroupingTestCollator implements Collator<Map.Entry<String, List<Integer>>, Integer> { @Override public Integer collate(Iterable<Map.Entry<String, List<Integer>>> values) { int sum = 0; for (Map.Entry<String, List<Integer>> entry : values) { for (Integer value : entry.getValue()) { sum += value; } } return sum; } } public static class TestCollator implements Collator<Map.Entry<String, Integer>, Integer> { @Override public Integer collate(Iterable<Map.Entry<String, Integer>> values) { int sum = 0; for (Map.Entry<String, Integer> entry : values) { sum += entry.getValue(); } return sum; } } public static class MapKeyValueSourceAdapter<K, V> extends KeyValueSource<K, V> implements DataSerializable, PartitionIdAware { private volatile KeyValueSource<K, V> keyValueSource; private int openCount = 0; public MapKeyValueSourceAdapter() { } public MapKeyValueSourceAdapter(KeyValueSource<K, V> keyValueSource) { this.keyValueSource = keyValueSource; } @Override public boolean open(NodeEngine nodeEngine) { if (openCount < 2) { openCount++; return false; } return keyValueSource.open(nodeEngine); } @Override public boolean hasNext() { return keyValueSource.hasNext(); } @Override public K key() { return keyValueSource.key(); } @Override public Map.Entry<K, V> element() { return keyValueSource.element(); } @Override public boolean reset() { return keyValueSource.reset(); } @Override public boolean isAllKeysSupported() { return keyValueSource.isAllKeysSupported(); } @Override public Collection<K> getAllKeys0() { return keyValueSource.getAllKeys0(); } public static <K1, V1> KeyValueSource<K1, V1> fromMap(IMap<K1, V1> map) { return KeyValueSource.fromMap(map); } public static <K1, V1> KeyValueSource<K1, V1> fromMultiMap(MultiMap<K1, V1> multiMap) { return KeyValueSource.fromMultiMap(multiMap); } public static <V1> KeyValueSource<String, V1> fromList(IList<V1> list) { return KeyValueSource.fromList(list); } public static <V1> KeyValueSource<String, V1> fromSet(ISet<V1> set) { return KeyValueSource.fromSet(set); } @Override public void close() throws IOException { keyValueSource.close(); } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeObject(keyValueSource); } @Override public void readData(ObjectDataInput in) throws IOException { keyValueSource = in.readObject(); } @Override public void setPartitionId(int partitionId) { if (keyValueSource instanceof PartitionIdAware) { ((PartitionIdAware) keyValueSource).setPartitionId(partitionId); } } } }
Enabled the mapReduceTest again, jenkins problems fixed
hazelcast/src/test/java/com/hazelcast/mapreduce/MapReduceTest.java
Enabled the mapReduceTest again, jenkins problems fixed
Java
apache-2.0
acd2aeabc04ae2bc2a02ead201ddfb43ae534fa9
0
roboconf/roboconf-platform,gibello/roboconf,roboconf/roboconf-platform,diarraa/roboconf-platform,gibello/roboconf,vincent-zurczak/roboconf-platform,diarraa/roboconf-platform,vincent-zurczak/roboconf-platform,vincent-zurczak/roboconf-platform,diarraa/roboconf-platform,roboconf/roboconf-platform,gibello/roboconf
/** * Copyright 2013-2015 Linagora, Université Joseph Fourier, Floralis * * The present code is developed in the scope of the joint LINAGORA - * Université Joseph Fourier - Floralis research program and is designated * as a "Result" pursuant to the terms and conditions of the LINAGORA * - Université Joseph Fourier - Floralis research program. Each copyright * holder of Results enumerated here above fully & independently holds complete * ownership of the complete Intellectual Property rights applicable to the whole * of said Results, and may freely exploit it in any manner which does not infringe * the moral rights of the other copyright holders. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.roboconf.core.model.beans; import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Map; import java.util.TreeMap; import net.roboconf.core.model.helpers.InstanceHelpers; /** * An instance object represents a running component instance. * @author Vincent Zurczak - Linagora */ public class Instance implements Serializable { /** * A constant to store the IP address in {@link #getData()}. * <p>Storing this information in a root instance is enough.</p> */ public static final String IP_ADDRESS = "ip.address"; /** * A constant to store the machine ID in {@link #getData()}. * <p>Storing this information in a root instance is enough.</p> */ public static final String MACHINE_ID = "machine.id"; /** * A constant to store the application name in {@link #getData()}. * <p>Storing this information in a root instance is enough.</p> */ public static final String APPLICATION_NAME = "application.name"; private static final long serialVersionUID = -3320865356277185064L; private String name; private Component component; private Instance parent; private final Collection<Instance> children = new LinkedHashSet<Instance> (); private InstanceStatus status = InstanceStatus.NOT_DEPLOYED; public final Collection<String> channels = new HashSet<String> (); public final Map<String,String> overriddenExports = new HashMap<String,String> (); // Data can be accessed through several threads and for various reasons. // ConcurrentHashMap does not accept null values. We could wrap such a map // in a method or in a sub-class to prevent these NPE, but a synchronized map // should be enough and should prevent unpredictable reactions. public final Map<String,String> data = Collections.synchronizedMap( new HashMap<String,String>( 0 )); // At runtime, imported variables are grouped by prefix. // The prefix is a component or a facet name. private final Map<String,Collection<Import>> variablePrefixToImports = new TreeMap<String,Collection<Import>> (); /** * Constructor. */ public Instance() { // nothing } /** * Constructor. * @param name the instance name */ public Instance( String name ) { this.name = name; } /** * @return the name */ public String getName() { return this.name; } /** * @param name the name to set */ public void setName( String name ) { this.name = name; } /** * @return the status */ public synchronized InstanceStatus getStatus() { return this.status; } /** * @param status the status to set */ public synchronized void setStatus( InstanceStatus status ) { this.status = status; } /** * @return the component */ public Component getComponent() { return this.component; } /** * @param component the component to set */ public void setComponent( Component component ) { this.component = component; } /** * @return the parent */ public Instance getParent() { return this.parent; } /** * @param parent the parent to set */ public void setParent( Instance parent ) { this.parent = parent; } /** * @return the children */ public Collection<Instance> getChildren() { return this.children; } @Override public int hashCode() { return InstanceHelpers.computeInstancePath( this ).hashCode(); } @Override public boolean equals( Object obj ) { return obj instanceof Instance && InstanceHelpers.haveSamePath( this, (Instance) obj); } @Override public String toString() { return this.name; } /** * Sets the name in a chain approach. */ public Instance name( String name ) { this.name = name; return this; } /** * Sets the component in a chain approach. */ public Instance component( Component component ) { this.component = component; return this; } /** * Sets the parent in a chain approach. */ public Instance parent( Instance parent ) { this.parent = parent; return this; } /** * Adds a channel in a chain approach. */ public Instance channel( String channel ) { this.channels.add( channel ); return this; } /** * Sets the status in a chain approach. */ public synchronized Instance status( InstanceStatus status ) { this.status = status; return this; } /** * @return the imports (not null, key: component or facet name, value: the associated imports) */ public Map<String,Collection<Import>> getImports() { return this.variablePrefixToImports; } /** * @author Noël - LIG */ public enum InstanceStatus implements Serializable { NOT_DEPLOYED( true ), DEPLOYING( false ), DEPLOYED_STOPPED( true ), UNRESOLVED( true ), STARTING( false ), DEPLOYED_STARTED( true ), STOPPING( false ), UNDEPLOYING( false ), PROBLEM( false ); private final boolean stable; /** * Constructor. * @param stable */ InstanceStatus( boolean stable ) { this.stable = stable; } /** * A secured alternative to {@link InstanceStatus#valueOf(String)}. * @param s a string (can be null) * @return the associated runtime status, or {@link InstanceStatus#NOT_DEPLOYED} otherwise */ public static InstanceStatus whichStatus( String s ) { InstanceStatus result = InstanceStatus.NOT_DEPLOYED; for( InstanceStatus status : InstanceStatus.values()) { if( status.toString().equalsIgnoreCase( s )) { result = status; break; } } return result; } /** * @return the stable */ public boolean isStable() { return this.stable; } } }
core/roboconf-core/src/main/java/net/roboconf/core/model/beans/Instance.java
/** * Copyright 2013-2015 Linagora, Université Joseph Fourier, Floralis * * The present code is developed in the scope of the joint LINAGORA - * Université Joseph Fourier - Floralis research program and is designated * as a "Result" pursuant to the terms and conditions of the LINAGORA * - Université Joseph Fourier - Floralis research program. Each copyright * holder of Results enumerated here above fully & independently holds complete * ownership of the complete Intellectual Property rights applicable to the whole * of said Results, and may freely exploit it in any manner which does not infringe * the moral rights of the other copyright holders. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.roboconf.core.model.beans; import java.io.Serializable; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import net.roboconf.core.model.helpers.InstanceHelpers; /** * An instance object represents a running component instance. * @author Vincent Zurczak - Linagora */ public class Instance implements Serializable { /** * A constant to store the IP address in {@link #getData()}. * <p>Storing this information in a root instance is enough.</p> */ public static final String IP_ADDRESS = "ip.address"; /** * A constant to store the machine ID in {@link #getData()}. * <p>Storing this information in a root instance is enough.</p> */ public static final String MACHINE_ID = "machine.id"; /** * A constant to store the application name in {@link #getData()}. * <p>Storing this information in a root instance is enough.</p> */ public static final String APPLICATION_NAME = "application.name"; private static final long serialVersionUID = -3320865356277185064L; private String name; private Component component; private Instance parent; private final Collection<Instance> children = new LinkedHashSet<Instance> (); private InstanceStatus status = InstanceStatus.NOT_DEPLOYED; public final Collection<String> channels = new HashSet<String> (); public final Map<String,String> data = new ConcurrentHashMap<String,String>( 0 ); public final Map<String,String> overriddenExports = new HashMap<String,String> (); // At runtime, imported variables are grouped by prefix. // The prefix is a component or a facet name. private final Map<String,Collection<Import>> variablePrefixToImports = new TreeMap<String,Collection<Import>> (); /** * Constructor. */ public Instance() { // nothing } /** * Constructor. * @param name the instance name */ public Instance( String name ) { this.name = name; } /** * @return the name */ public String getName() { return this.name; } /** * @param name the name to set */ public void setName( String name ) { this.name = name; } /** * @return the status */ public synchronized InstanceStatus getStatus() { return this.status; } /** * @param status the status to set */ public synchronized void setStatus( InstanceStatus status ) { this.status = status; } /** * @return the component */ public Component getComponent() { return this.component; } /** * @param component the component to set */ public void setComponent( Component component ) { this.component = component; } /** * @return the parent */ public Instance getParent() { return this.parent; } /** * @param parent the parent to set */ public void setParent( Instance parent ) { this.parent = parent; } /** * @return the children */ public Collection<Instance> getChildren() { return this.children; } @Override public int hashCode() { return InstanceHelpers.computeInstancePath( this ).hashCode(); } @Override public boolean equals( Object obj ) { return obj instanceof Instance && InstanceHelpers.haveSamePath( this, (Instance) obj); } @Override public String toString() { return this.name; } /** * Sets the name in a chain approach. */ public Instance name( String name ) { this.name = name; return this; } /** * Sets the component in a chain approach. */ public Instance component( Component component ) { this.component = component; return this; } /** * Sets the parent in a chain approach. */ public Instance parent( Instance parent ) { this.parent = parent; return this; } /** * Adds a channel in a chain approach. */ public Instance channel( String channel ) { this.channels.add( channel ); return this; } /** * Sets the status in a chain approach. */ public synchronized Instance status( InstanceStatus status ) { this.status = status; return this; } /** * @return the imports (not null, key: component or facet name, value: the associated imports) */ public Map<String,Collection<Import>> getImports() { return this.variablePrefixToImports; } /** * @author Noël - LIG */ public enum InstanceStatus implements Serializable { NOT_DEPLOYED( true ), DEPLOYING( false ), DEPLOYED_STOPPED( true ), UNRESOLVED( true ), STARTING( false ), DEPLOYED_STARTED( true ), STOPPING( false ), UNDEPLOYING( false ), PROBLEM( false ); private final boolean stable; /** * Constructor. * @param stable */ InstanceStatus( boolean stable ) { this.stable = stable; } /** * A secured alternative to {@link InstanceStatus#valueOf(String)}. * @param s a string (can be null) * @return the associated runtime status, or {@link InstanceStatus#NOT_DEPLOYED} otherwise */ public static InstanceStatus whichStatus( String s ) { InstanceStatus result = InstanceStatus.NOT_DEPLOYED; for( InstanceStatus status : InstanceStatus.values()) { if( status.toString().equalsIgnoreCase( s )) { result = status; break; } } return result; } /** * @return the stable */ public boolean isStable() { return this.stable; } } }
#193 ConcurrentModificationException in integration tests
core/roboconf-core/src/main/java/net/roboconf/core/model/beans/Instance.java
#193 ConcurrentModificationException in integration tests
Java
apache-2.0
b824350a36d97ee95ff24082acc3377994a21da0
0
eFaps/eFapsApp-Sales
/* * Copyright 2003 - 2017 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.efaps.esjp.sales.document; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.efaps.admin.common.NumberGenerator; import org.efaps.admin.datamodel.Status; import org.efaps.admin.datamodel.Type; import org.efaps.admin.event.Parameter; import org.efaps.admin.event.Return; import org.efaps.admin.event.Return.ReturnValues; import org.efaps.admin.program.esjp.EFapsApplication; import org.efaps.admin.program.esjp.EFapsUUID; import org.efaps.admin.program.esjp.Listener; import org.efaps.ci.CIType; import org.efaps.db.AttributeQuery; import org.efaps.db.Context; import org.efaps.db.Delete; import org.efaps.db.Insert; import org.efaps.db.Instance; import org.efaps.db.InstanceQuery; import org.efaps.db.MultiPrintQuery; import org.efaps.db.PrintQuery; import org.efaps.db.QueryBuilder; import org.efaps.db.SelectBuilder; import org.efaps.db.Update; import org.efaps.esjp.ci.CIERP; import org.efaps.esjp.ci.CIFormSales; import org.efaps.esjp.ci.CISales; import org.efaps.esjp.db.InstanceUtils; import org.efaps.esjp.erp.CurrencyInst; import org.efaps.esjp.erp.Naming; import org.efaps.esjp.erp.NumberFormatter; import org.efaps.esjp.erp.listener.IOnAction; import org.efaps.esjp.sales.Account; import org.efaps.esjp.sales.util.Sales; import org.efaps.util.EFapsException; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * TODO comment! * * @author The eFaps Team */ @EFapsUUID("d93f298b-f0bf-4278-a18e-b065cc330e50") @EFapsApplication("eFapsApp-Sales") public abstract class PettyCashBalance_Base extends AbstractDocumentSum { /** * Logging instance used in this class. */ private static final Logger LOG = LoggerFactory.getLogger(PettyCashBalance.class); /** * Method for create a new petty Cash Balance. * * @param _parameter Parameter as passed from the eFaps API. * @return new Return. * @throws EFapsException on error. */ public Return create(final Parameter _parameter) throws EFapsException { final Return ret = new Return(); final Instance balanceInst = createPettyCashBalanceDoc(_parameter); final CreatedDoc createdDoc = new CreatedDoc(); createdDoc.setInstance(balanceInst); ret.put(ReturnValues.VALUES, createReport(_parameter, createdDoc)); ret.put(ReturnValues.TRUE, true); return ret; } /** * Create the Report again. * * @param _parameter Parameter as passed from the eFaps API. * @return new Return. * @throws EFapsException on error. */ @Override public Return createReport(final Parameter _parameter) throws EFapsException { final Return ret = new Return(); final CreatedDoc createdDoc = new CreatedDoc(); createdDoc.setInstance(_parameter.getInstance()); ret.put(ReturnValues.VALUES, createReport(_parameter, createdDoc)); ret.put(ReturnValues.TRUE, true); return ret; } /** * Internal method to create a PettyCashBalance. * * @param _parameter Parameter as passed from the eFaps API * @return instance of new PettyCashBalance, null if not created * @throws EFapsException on error */ protected Instance createPettyCashBalanceDoc(final Parameter _parameter) throws EFapsException { Instance ret = null; final Instance inst = _parameter.getCallInstance(); final PrintQuery print = new PrintQuery(inst); print.addAttribute(CISales.AccountAbstract.CurrencyLink, CISales.AccountPettyCash.AmountAbstract); print.execute(); final Long curId = print.<Long>getAttribute(CISales.AccountAbstract.CurrencyLink); BigDecimal startAmountOrig = print.<BigDecimal>getAttribute(CISales.AccountPettyCash.AmountAbstract); if (startAmountOrig == null) { startAmountOrig = BigDecimal.ZERO; } final Account acc = new Account(); final String startAmountStr = _parameter.getParameterValue( CIFormSales.Sales_AccountPettyCashBalancingWithDateForm.startAmount.name); final BigDecimal amount = acc.getAmountPayments(_parameter); final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter(); BigDecimal startAmount = BigDecimal.ZERO; try { startAmount = (BigDecimal) formater.parse(startAmountStr); } catch (final ParseException e) { PettyCashBalance_Base.LOG.error("Catched parsing error", e); } final BigDecimal difference; // the transactions sum to Zero if (amount.compareTo(BigDecimal.ZERO) == 0) { // check if it is the first balance if (acc.hasTransaction(_parameter)) { difference = startAmount.subtract(startAmountOrig); } else { difference = startAmount; } } else { difference = amount.negate().add(startAmount.subtract(startAmountOrig)); } if (startAmount.compareTo(startAmountOrig) != 0) { final Update update = new Update(inst); update.add(CISales.AccountPettyCash.AmountAbstract, startAmount); update.execute(); } // only if there is a difference it will be executed if (difference.compareTo(BigDecimal.ZERO) != 0) { final Insert insert = new Insert(CISales.PettyCashBalance); insert.add(CISales.PettyCashBalance.Name, getDocName4Create(_parameter)); insert.add(CISales.PettyCashBalance.Salesperson, Context.getThreadContext().getPersonId()); if (_parameter.getParameterValue("date") != null) { insert.add(CISales.PettyCashBalance.Date, _parameter.getParameterValue("date")); } else { insert.add(CISales.PettyCashBalance.Date, new DateTime()); } insert.add(CISales.PettyCashBalance.Status, Status.find(CISales.PettyCashBalanceStatus.Open)); insert.add(CISales.PettyCashBalance.CrossTotal, difference); insert.add(CISales.PettyCashBalance.NetTotal, BigDecimal.ZERO); insert.add(CISales.PettyCashBalance.DiscountTotal, BigDecimal.ZERO); insert.add(CISales.PettyCashBalance.RateCrossTotal, BigDecimal.ZERO); insert.add(CISales.PettyCashBalance.RateNetTotal, BigDecimal.ZERO); insert.add(CISales.PettyCashBalance.RateDiscountTotal, BigDecimal.ZERO); insert.add(CISales.PettyCashBalance.Rate, new Object[] { 1, 1 }); insert.add(CISales.PettyCashBalance.RateCurrencyId, curId); insert.add(CISales.PettyCashBalance.CurrencyId, curId); insert.execute(); ret = insert.getInstance(); final List<Instance> lstInst = new ArrayList<>(); if (Context.getThreadContext().containsSessionAttribute( CIFormSales.Sales_AccountPettyCashBalancingWithDateForm.paymentsOIDs.name)) { final String[] oids = (String[]) Context.getThreadContext().getSessionAttribute( CIFormSales.Sales_AccountPettyCashBalancingWithDateForm.paymentsOIDs.name); if (oids != null) { for (final String oid : oids) { final Instance instPay = Instance.get(oid); lstInst.add(instPay); } } else { lstInst.addAll(acc.getPayments(_parameter)); } Context.getThreadContext().removeSessionAttribute( CIFormSales.Sales_AccountPettyCashBalancingWithDateForm.paymentsOIDs.name); } else { lstInst.addAll(acc.getPayments(_parameter)); } final Instance balanceInst = insert.getInstance(); // connect account and balance final Insert relInsert = new Insert(CISales.AccountPettyCash2PettyCashBalance); relInsert.add(CISales.AccountPettyCash2PettyCashBalance.FromLink, _parameter.getInstance()); relInsert.add(CISales.AccountPettyCash2PettyCashBalance.ToLink, balanceInst); relInsert.execute(); // connect balance and receipts final MultiPrintQuery multi = new MultiPrintQuery(lstInst); final SelectBuilder sel = SelectBuilder.get().linkto(CISales.Payment.CreateDocument).instance(); multi.addSelect(sel); multi.executeWithoutAccessCheck(); while (multi.next()) { final Instance docInst = multi.<Instance>getSelect(sel); if (docInst != null && docInst.isValid()) { if (docInst.getType().equals(CISales.PettyCashReceipt.getType())) { final Insert rel2Insert = new Insert(CISales.PettyCashBalance2PettyCashReceipt); rel2Insert.add(CISales.PettyCashBalance2PettyCashReceipt.FromLink, balanceInst); rel2Insert.add(CISales.PettyCashBalance2PettyCashReceipt.ToLink, docInst); rel2Insert.execute(); final Update update = new Update(docInst); update.add(CISales.PettyCashReceipt.Status, Status.find(CISales.PettyCashReceiptStatus.Closed)); update.execute(); } else if (docInst.getType().equals(CISales.IncomingCreditNote.getType())) { final Insert rel2Insert = new Insert(CISales.PettyCashBalance2IncomingCreditNote); rel2Insert.add(CISales.PettyCashBalance2IncomingCreditNote.FromLink, balanceInst); rel2Insert.add(CISales.PettyCashBalance2IncomingCreditNote.ToLink, docInst); rel2Insert.execute(); final Update update = new Update(docInst); update.add(CISales.IncomingCreditNote.Status, Status.find(CISales.IncomingCreditNoteStatus.Paid)); update.execute(); } } } for (final Instance instance : lstInst) { final Update update = new Update(instance); update.add(CISales.Payment.TargetDocument, balanceInst); update.execute(); } final Insert payInsert = new Insert(CISales.Payment); payInsert.add(CISales.Payment.Date, new DateTime()); payInsert.add(CISales.Payment.CreateDocument, balanceInst); payInsert.add(CISales.Payment.TargetDocument, balanceInst); payInsert.execute(); final CIType type; if (difference.compareTo(BigDecimal.ZERO) < 0) { type = CISales.TransactionOutbound; } else { type = CISales.TransactionInbound; } final Insert transInsert = new Insert(type); transInsert.add(CISales.TransactionAbstract.Amount, difference.abs()); transInsert.add(CISales.TransactionAbstract.CurrencyId, curId); transInsert.add(CISales.TransactionAbstract.Payment, payInsert.getInstance().getId()); transInsert.add(CISales.TransactionAbstract.Account, inst.getId()); transInsert.add(CISales.TransactionAbstract.Description, getDBProperty("transaction.Create")); transInsert.add(CISales.TransactionAbstract.Date, new DateTime()); transInsert.execute(); } return ret; } /** * Created document CollectionOrder/PaymentOrder. * * @param _parameter Parameter as passed from the eFaps API. * @return new Return. * @throws EFapsException on error. */ public Return createDoc4Account(final Parameter _parameter) throws EFapsException { final SelectBuilder selAccInst = new SelectBuilder() .linkfrom(CISales.AccountPettyCash2PettyCashBalance, CISales.AccountPettyCash2PettyCashBalance.ToLink) .linkto(CISales.AccountPettyCash2PettyCashBalance.FromLink).instance(); final PrintQuery print = new PrintQuery(_parameter.getInstance()); print.addAttribute(CISales.DocumentSumAbstract.Rate, CISales.DocumentSumAbstract.CurrencyId, CISales.DocumentSumAbstract.RateCurrencyId, CISales.DocumentSumAbstract.CrossTotal); print.addSelect(selAccInst); print.execute(); Type type = null; Type relation = null; Type bal2orderType = null; String name = null; Status status = null; Instance actDefInst = null; CIType actDef2doc = null; final BigDecimal crossTotal = print.<BigDecimal>getAttribute(CISales.DocumentSumAbstract.CrossTotal); final Instance accountInst = print.<Instance>getSelect(selAccInst); CurrencyInst.get(print.<Long>getAttribute( CISales.DocumentSumAbstract.RateCurrencyId)); if (crossTotal.compareTo(BigDecimal.ZERO) < 0) { type = CISales.CollectionOrder.getType(); name = new Naming().fromNumberGenerator(_parameter, type.getName()); status = Status.find(CISales.CollectionOrderStatus.Open); relation = CISales.AccountPettyCash2CollectionOrder.getType(); bal2orderType = CISales.PettyCashBalance2CollectionOrder.getType(); actDefInst = Sales.PETTYCASHBAL_ACTDEF4COLORD.get(); actDef2doc = CISales.ActionDefinitionCollectionOrder2Document; } else if (crossTotal.compareTo(BigDecimal.ZERO) > 0) { type = CISales.PaymentOrder.getType(); name = new Naming().fromNumberGenerator(_parameter, type.getName()); status = Status.find(CISales.PaymentOrderStatus.Open); relation = CISales.AccountPettyCash2PaymentOrder.getType(); bal2orderType = CISales.PettyCashBalance2PaymentOrder.getType(); actDefInst = Sales.PETTYCASHBAL_ACTDEF4PAYORD.get(); actDef2doc = CISales.ActionDefinitionPaymentOrder2Document; } if (type != null && accountInst != null && accountInst.isValid()) { final Insert insert = new Insert(type); insert.add(CISales.DocumentSumAbstract.Name, name); insert.add(CISales.DocumentSumAbstract.Date, new DateTime()); insert.add(CISales.DocumentSumAbstract.DueDate, new DateTime()); insert.add(CISales.DocumentSumAbstract.Salesperson, Context.getThreadContext().getPerson().getId()); insert.add(CISales.DocumentSumAbstract.RateCrossTotal, crossTotal.abs()); insert.add(CISales.DocumentSumAbstract.RateNetTotal, crossTotal.abs()); insert.add(CISales.DocumentSumAbstract.RateDiscountTotal, BigDecimal.ZERO); insert.add(CISales.DocumentSumAbstract.CrossTotal, crossTotal.abs()); insert.add(CISales.DocumentSumAbstract.NetTotal, crossTotal.abs()); insert.add(CISales.DocumentSumAbstract.DiscountTotal, BigDecimal.ZERO); insert.add(CISales.DocumentSumAbstract.CurrencyId, print.<Long>getAttribute(CISales.DocumentSumAbstract.CurrencyId)); insert.add(CISales.DocumentSumAbstract.RateCurrencyId, print.<Long>getAttribute(CISales.DocumentSumAbstract.RateCurrencyId)); insert.add(CISales.DocumentSumAbstract.Rate, print.<Object[]>getAttribute(CISales.DocumentSumAbstract.Rate)); insert.add(CISales.DocumentSumAbstract.StatusAbstract, status); insert.add(CISales.DocumentSumAbstract.Note, _parameter.getParameterValue(getFieldName4Attribute(_parameter, CISales.DocumentSumAbstract.Note.name))); insert.execute(); final Insert relInsert = new Insert(relation); relInsert.add(CISales.AccountPettyCash2Document.FromLinkAbstract, accountInst); relInsert.add(CISales.AccountPettyCash2Document.ToLinkAbstract, insert.getInstance()); relInsert.execute(); final Insert relInsert2 = new Insert(bal2orderType); relInsert2.add(CISales.PettyCashBalance2OrderAbstract.FromAbstractLink, _parameter.getInstance()); relInsert2.add(CISales.PettyCashBalance2OrderAbstract.ToAbstractLink, insert.getInstance()); relInsert2.execute(); if (actDefInst.isValid()) { final Insert actDef2DocInsert = new Insert(actDef2doc); actDef2DocInsert.add(CIERP.ActionDefinition2DocumentAbstract.FromLinkAbstract, actDefInst); actDef2DocInsert.add(CIERP.ActionDefinition2DocumentAbstract.ToLinkAbstract, insert.getInstance()); actDef2DocInsert.execute(); } else { PettyCashBalance_Base.LOG.error("Missing or wrong Configuration Links for ActionDefinition: '{}', '{}'", Sales.PETTYCASHBAL_ACTDEF4COLORD.getKey(), Sales.PETTYCASHBAL_ACTDEF4PAYORD.getKey()); } } return new Return(); } /** * @param _parameter Parameter as passed by the eFaps API * @return Return with Access * @throws EFapsException on error */ public Return accessCheck4AccountDoc(final Parameter _parameter) throws EFapsException { final Return ret = new Return(); if (_parameter.getInstance() != null && _parameter.getInstance().isValid()) { final QueryBuilder queryBldr = new QueryBuilder(CISales.PettyCashBalance2OrderAbstract); queryBldr.addWhereAttrEqValue(CISales.PettyCashBalance2OrderAbstract.FromAbstractLink, _parameter.getInstance()); final InstanceQuery query = queryBldr.getQuery(); query.executeWithoutAccessCheck(); if (!query.next()) { if (Sales.PETTYCASHBAL_REQUIREBOOKED4PAY.get()) { final QueryBuilder attrQueryBldr = new QueryBuilder(CISales.PettyCashReceipt); attrQueryBldr.addWhereAttrNotEqValue(CISales.PettyCashReceipt.Status, Status.find(CISales.PettyCashReceiptStatus.Canceled)); final QueryBuilder chQueryBldr = new QueryBuilder(CISales.PettyCashBalance2PettyCashReceipt); chQueryBldr.addWhereAttrEqValue(CISales.Document2DocumentAbstract.FromAbstractLink, _parameter.getInstance()); chQueryBldr.addWhereAttrInQuery(CISales.Document2DocumentAbstract.ToAbstractLink, attrQueryBldr.getAttributeQuery(CISales.PettyCashReceipt.ID)); final InstanceQuery chQuery = chQueryBldr.getQuery(); chQuery.executeWithoutAccessCheck(); if (!chQuery.next()) { ret.put(ReturnValues.TRUE, true); } } else { ret.put(ReturnValues.TRUE, true); } } } return ret; } /** * Method for verify a Petty Cash Balance. * * @param _parameter Parameter as passed from the eFaps API. * @return new Return. * @throws EFapsException on error. */ public Return verify(final Parameter _parameter) throws EFapsException { final Instance instance = _parameter.getInstance(); final QueryBuilder attrQueryBldr = new QueryBuilder(CISales.PettyCashBalance2PettyCashReceipt); attrQueryBldr.addType(CISales.PettyCashBalance2IncomingCreditNote); attrQueryBldr.addWhereAttrEqValue(CISales.Document2DocumentAbstract.FromAbstractLink, instance); final AttributeQuery attrQuery = attrQueryBldr .getAttributeQuery(CISales.Document2DocumentAbstract.ToAbstractLink); final QueryBuilder queryBldr = new QueryBuilder(CISales.DocumentSumAbstract); queryBldr.addWhereAttrInQuery(CISales.DocumentSumAbstract.ID, attrQuery); final MultiPrintQuery multi = queryBldr.getPrint(); multi.addAttribute(CISales.DocumentSumAbstract.Contact); multi.execute(); while (multi.next()) { final Object contactObj = multi.getAttribute(CISales.DocumentSumAbstract.Contact); final Instance docInst = multi.getCurrentInstance(); final Update recUpdate = new Update(docInst); if (docInst.getType().isKindOf(CISales.PettyCashReceipt.getType())) { recUpdate.add(CISales.PettyCashReceipt.Status, Status.find(CISales.PettyCashReceiptStatus.Closed)); if (contactObj != null) { // legal documents final String seqKey = Sales.PETTYCASHRECEIPT_REVSEQ.get(); final NumberGenerator numgen = isUUID(seqKey) ? NumberGenerator.get(UUID.fromString(seqKey)) : NumberGenerator.get(seqKey); if (numgen != null) { final String revision = numgen.getNextVal(); recUpdate.add(CISales.PettyCashReceipt.Revision, revision); } } } else { recUpdate.add(CISales.IncomingCreditNote.Status, Status.find(CISales.IncomingCreditNoteStatus.Paid)); final String seqKey = Sales.INCOMINGCREDITNOTE_REVSEQ.get(); final NumberGenerator numgen = isUUID(seqKey) ? NumberGenerator.get(UUID.fromString(seqKey)) : NumberGenerator.get(seqKey); if (numgen != null) { final String revision = numgen.getNextVal(); recUpdate.add(CISales.IncomingCreditNote.Revision, revision); } } recUpdate.execute(); for (final IOnAction listener : Listener.get().<IOnAction>invoke(IOnAction.class)) { listener.onDocumentUpdate(_parameter, docInst); } } final Update update = new Update(instance); update.add(CISales.PettyCashBalance.Status, Status.find(CISales.PettyCashBalanceStatus.Verified)); update.execute(); return new Return(); } /** * Cancel. * * @param _parameter the parameter * @return the return * @throws EFapsException the eFaps exception */ public Return cancel(final Parameter _parameter) throws EFapsException { final Instance instance = _parameter.getInstance(); final QueryBuilder attrQueryBldr = new QueryBuilder(CISales.Payment); attrQueryBldr.addWhereAttrEqValue(CISales.Payment.CreateDocument, instance); attrQueryBldr.addWhereAttrEqValue(CISales.Payment.TargetDocument, instance); final QueryBuilder transQueryBldr = new QueryBuilder(CISales.TransactionAbstract); transQueryBldr.addWhereAttrInQuery(CISales.TransactionAbstract.Payment, attrQueryBldr.getAttributeQuery( CISales.Payment.ID)); final MultiPrintQuery multi = transQueryBldr.getPrint(); multi.addAttribute(CISales.TransactionAbstract.Amount, CISales.TransactionAbstract.CurrencyId, CISales.TransactionAbstract.Payment, CISales.TransactionAbstract.Account, CISales.TransactionAbstract.Date); multi.execute(); while (multi.next()) { final CIType type; if (InstanceUtils.isKindOf(multi.getCurrentInstance(), CISales.TransactionOutbound)) { type = CISales.TransactionInbound; } else { type = CISales.TransactionOutbound; } final Insert transInsert = new Insert(type); transInsert.add(CISales.TransactionAbstract.Amount, multi.<BigDecimal>getAttribute( CISales.TransactionAbstract.Amount)); transInsert.add(CISales.TransactionAbstract.CurrencyId, multi.<Long>getAttribute( CISales.TransactionAbstract.CurrencyId)); transInsert.add(CISales.TransactionAbstract.Payment, multi.<Long>getAttribute( CISales.TransactionAbstract.Payment)); transInsert.add(CISales.TransactionAbstract.Account, multi.<Long>getAttribute( CISales.TransactionAbstract.Account)); transInsert.add(CISales.TransactionAbstract.Description, getDBProperty("transaction.Cancel")); transInsert.add(CISales.TransactionAbstract.Date, multi.<DateTime>getAttribute( CISales.TransactionAbstract.Date)); transInsert.execute(); } final QueryBuilder paymentQueryBldr = new QueryBuilder(CISales.Payment); paymentQueryBldr.addWhereAttrEqValue(CISales.Payment.TargetDocument, instance); final MultiPrintQuery paymentMulti = paymentQueryBldr.getPrint(); final SelectBuilder sel = SelectBuilder.get().linkto(CISales.Payment.CreateDocument).instance(); paymentMulti.addSelect(sel); paymentMulti.execute(); while (paymentMulti.next()) { final Instance docInst = paymentMulti.getSelect(sel); if (InstanceUtils.isKindOf(docInst, CISales.PettyCashReceipt) || InstanceUtils.isKindOf(docInst, CISales.IncomingCreditNote)) { final Update update = new Update(paymentMulti.getCurrentInstance()); update.add(CISales.Payment.TargetDocument, (Object) null); update.execute(); } } final QueryBuilder queryBldr = new QueryBuilder(CISales.PettyCashBalance2PettyCashReceipt); queryBldr.addType(CISales.PettyCashBalance2IncomingCreditNote); queryBldr.addWhereAttrEqValue(CISales.Document2DocumentAbstract.FromAbstractLink, instance); final InstanceQuery query = queryBldr.getQuery(); query.execute(); while (query.next()) { new Delete(query.getCurrentValue()).execute(); } final Update update = new Update(instance); update.add(CISales.PettyCashBalance.Status, Status.find(CISales.PettyCashBalanceStatus.Canceled)); update.execute(); return new Return(); } }
src/main/efaps/ESJP/org/efaps/esjp/sales/document/PettyCashBalance_Base.java
/* * Copyright 2003 - 2017 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.efaps.esjp.sales.document; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.efaps.admin.common.NumberGenerator; import org.efaps.admin.datamodel.Status; import org.efaps.admin.datamodel.Type; import org.efaps.admin.event.Parameter; import org.efaps.admin.event.Return; import org.efaps.admin.event.Return.ReturnValues; import org.efaps.admin.program.esjp.EFapsApplication; import org.efaps.admin.program.esjp.EFapsUUID; import org.efaps.admin.program.esjp.Listener; import org.efaps.ci.CIType; import org.efaps.db.AttributeQuery; import org.efaps.db.Context; import org.efaps.db.Delete; import org.efaps.db.Insert; import org.efaps.db.Instance; import org.efaps.db.InstanceQuery; import org.efaps.db.MultiPrintQuery; import org.efaps.db.PrintQuery; import org.efaps.db.QueryBuilder; import org.efaps.db.SelectBuilder; import org.efaps.db.Update; import org.efaps.esjp.ci.CIERP; import org.efaps.esjp.ci.CIFormSales; import org.efaps.esjp.ci.CISales; import org.efaps.esjp.db.InstanceUtils; import org.efaps.esjp.erp.CurrencyInst; import org.efaps.esjp.erp.Naming; import org.efaps.esjp.erp.NumberFormatter; import org.efaps.esjp.erp.listener.IOnAction; import org.efaps.esjp.sales.Account; import org.efaps.esjp.sales.util.Sales; import org.efaps.util.EFapsException; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * TODO comment! * * @author The eFaps Team */ @EFapsUUID("d93f298b-f0bf-4278-a18e-b065cc330e50") @EFapsApplication("eFapsApp-Sales") public abstract class PettyCashBalance_Base extends AbstractDocumentSum { /** * Logging instance used in this class. */ private static final Logger LOG = LoggerFactory.getLogger(PettyCashBalance.class); /** * Method for create a new petty Cash Balance. * * @param _parameter Parameter as passed from the eFaps API. * @return new Return. * @throws EFapsException on error. */ public Return create(final Parameter _parameter) throws EFapsException { final Return ret = new Return(); final Instance balanceInst = createPettyCashBalanceDoc(_parameter); final CreatedDoc createdDoc = new CreatedDoc(); createdDoc.setInstance(balanceInst); ret.put(ReturnValues.VALUES, createReport(_parameter, createdDoc)); ret.put(ReturnValues.TRUE, true); return ret; } /** * Create the Report again. * * @param _parameter Parameter as passed from the eFaps API. * @return new Return. * @throws EFapsException on error. */ @Override public Return createReport(final Parameter _parameter) throws EFapsException { final Return ret = new Return(); final CreatedDoc createdDoc = new CreatedDoc(); createdDoc.setInstance(_parameter.getInstance()); ret.put(ReturnValues.VALUES, createReport(_parameter, createdDoc)); ret.put(ReturnValues.TRUE, true); return ret; } /** * Internal method to create a PettyCashBalance. * * @param _parameter Parameter as passed from the eFaps API * @return instance of new PettyCashBalance, null if not created * @throws EFapsException on error */ protected Instance createPettyCashBalanceDoc(final Parameter _parameter) throws EFapsException { Instance ret = null; final Instance inst = _parameter.getCallInstance(); final PrintQuery print = new PrintQuery(inst); print.addAttribute(CISales.AccountAbstract.CurrencyLink, CISales.AccountPettyCash.AmountAbstract); print.execute(); final Long curId = print.<Long>getAttribute(CISales.AccountAbstract.CurrencyLink); BigDecimal startAmountOrig = print.<BigDecimal>getAttribute(CISales.AccountPettyCash.AmountAbstract); if (startAmountOrig == null) { startAmountOrig = BigDecimal.ZERO; } final Account acc = new Account(); final String startAmountStr = _parameter.getParameterValue( CIFormSales.Sales_AccountPettyCashBalancingWithDateForm.startAmount.name); final BigDecimal amount = acc.getAmountPayments(_parameter); final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter(); BigDecimal startAmount = BigDecimal.ZERO; try { startAmount = (BigDecimal) formater.parse(startAmountStr); } catch (final ParseException e) { PettyCashBalance_Base.LOG.error("Catched parsing error", e); } final BigDecimal difference; // the transactions sum to Zero if (amount.compareTo(BigDecimal.ZERO) == 0) { // check if it is the first balance if (acc.hasTransaction(_parameter)) { difference = startAmount.subtract(startAmountOrig); } else { difference = startAmount; } } else { difference = amount.negate().add(startAmount.subtract(startAmountOrig)); } if (startAmount.compareTo(startAmountOrig) != 0) { final Update update = new Update(inst); update.add(CISales.AccountPettyCash.AmountAbstract, startAmount); update.execute(); } // only if there is a difference it will be executed if (difference.compareTo(BigDecimal.ZERO) != 0) { final Insert insert = new Insert(CISales.PettyCashBalance); insert.add(CISales.PettyCashBalance.Name, getDocName4Create(_parameter)); insert.add(CISales.PettyCashBalance.Salesperson, Context.getThreadContext().getPersonId()); if (_parameter.getParameterValue("date") != null) { insert.add(CISales.PettyCashBalance.Date, _parameter.getParameterValue("date")); } else { insert.add(CISales.PettyCashBalance.Date, new DateTime()); } insert.add(CISales.PettyCashBalance.Status, Status.find(CISales.PettyCashBalanceStatus.Open)); insert.add(CISales.PettyCashBalance.CrossTotal, difference); insert.add(CISales.PettyCashBalance.NetTotal, BigDecimal.ZERO); insert.add(CISales.PettyCashBalance.DiscountTotal, BigDecimal.ZERO); insert.add(CISales.PettyCashBalance.RateCrossTotal, BigDecimal.ZERO); insert.add(CISales.PettyCashBalance.RateNetTotal, BigDecimal.ZERO); insert.add(CISales.PettyCashBalance.RateDiscountTotal, BigDecimal.ZERO); insert.add(CISales.PettyCashBalance.Rate, new Object[] { 1, 1 }); insert.add(CISales.PettyCashBalance.RateCurrencyId, curId); insert.add(CISales.PettyCashBalance.CurrencyId, curId); insert.execute(); ret = insert.getInstance(); final List<Instance> lstInst = new ArrayList<>(); if (Context.getThreadContext().containsSessionAttribute( CIFormSales.Sales_AccountPettyCashBalancingWithDateForm.paymentsOIDs.name)) { final String[] oids = (String[]) Context.getThreadContext().getSessionAttribute( CIFormSales.Sales_AccountPettyCashBalancingWithDateForm.paymentsOIDs.name); if (oids != null) { for (final String oid : oids) { final Instance instPay = Instance.get(oid); lstInst.add(instPay); } } else { lstInst.addAll(acc.getPayments(_parameter)); } Context.getThreadContext().removeSessionAttribute( CIFormSales.Sales_AccountPettyCashBalancingWithDateForm.paymentsOIDs.name); } else { lstInst.addAll(acc.getPayments(_parameter)); } final Instance balanceInst = insert.getInstance(); // connect account and balance final Insert relInsert = new Insert(CISales.AccountPettyCash2PettyCashBalance); relInsert.add(CISales.AccountPettyCash2PettyCashBalance.FromLink, _parameter.getInstance()); relInsert.add(CISales.AccountPettyCash2PettyCashBalance.ToLink, balanceInst); relInsert.execute(); // connect balance and receipts final MultiPrintQuery multi = new MultiPrintQuery(lstInst); final SelectBuilder sel = SelectBuilder.get().linkto(CISales.Payment.CreateDocument).instance(); multi.addSelect(sel); multi.executeWithoutAccessCheck(); while (multi.next()) { final Instance docInst = multi.<Instance>getSelect(sel); if (docInst != null && docInst.isValid()) { if (docInst.getType().equals(CISales.PettyCashReceipt.getType())) { final Insert rel2Insert = new Insert(CISales.PettyCashBalance2PettyCashReceipt); rel2Insert.add(CISales.PettyCashBalance2PettyCashReceipt.FromLink, balanceInst); rel2Insert.add(CISales.PettyCashBalance2PettyCashReceipt.ToLink, docInst); rel2Insert.execute(); final Update update = new Update(docInst); update.add(CISales.PettyCashReceipt.Status, Status.find(CISales.PettyCashReceiptStatus.Closed)); update.execute(); } else if (docInst.getType().equals(CISales.IncomingCreditNote.getType())) { final Insert rel2Insert = new Insert(CISales.PettyCashBalance2IncomingCreditNote); rel2Insert.add(CISales.PettyCashBalance2IncomingCreditNote.FromLink, balanceInst); rel2Insert.add(CISales.PettyCashBalance2IncomingCreditNote.ToLink, docInst); rel2Insert.execute(); final Update update = new Update(docInst); update.add(CISales.IncomingCreditNote.Status, Status.find(CISales.IncomingCreditNoteStatus.Paid)); update.execute(); } } } for (final Instance instance : lstInst) { final Update update = new Update(instance); update.add(CISales.Payment.TargetDocument, balanceInst); update.execute(); } final Insert payInsert = new Insert(CISales.Payment); payInsert.add(CISales.Payment.Date, new DateTime()); payInsert.add(CISales.Payment.CreateDocument, balanceInst); payInsert.add(CISales.Payment.TargetDocument, balanceInst); payInsert.execute(); final CIType type; if (difference.compareTo(BigDecimal.ZERO) < 0) { type = CISales.TransactionOutbound; } else { type = CISales.TransactionInbound; } final Insert transInsert = new Insert(type); transInsert.add(CISales.TransactionAbstract.Amount, difference.abs()); transInsert.add(CISales.TransactionAbstract.CurrencyId, curId); transInsert.add(CISales.TransactionAbstract.Payment, payInsert.getInstance().getId()); transInsert.add(CISales.TransactionAbstract.Account, inst.getId()); transInsert.add(CISales.TransactionAbstract.Description, getDBProperty("transaction.Create")); transInsert.add(CISales.TransactionAbstract.Date, new DateTime()); transInsert.execute(); } return ret; } /** * Created document CollectionOrder/PaymentOrder. * * @param _parameter Parameter as passed from the eFaps API. * @return new Return. * @throws EFapsException on error. */ public Return createDoc4Account(final Parameter _parameter) throws EFapsException { final SelectBuilder selAccInst = new SelectBuilder() .linkfrom(CISales.AccountPettyCash2PettyCashBalance, CISales.AccountPettyCash2PettyCashBalance.ToLink) .linkto(CISales.AccountPettyCash2PettyCashBalance.FromLink).instance(); final PrintQuery print = new PrintQuery(_parameter.getInstance()); print.addAttribute(CISales.DocumentSumAbstract.Rate, CISales.DocumentSumAbstract.CurrencyId, CISales.DocumentSumAbstract.RateCurrencyId, CISales.DocumentSumAbstract.CrossTotal); print.addSelect(selAccInst); print.execute(); Type type = null; Type relation = null; Type bal2orderType = null; String name = null; Status status = null; Instance actDefInst = null; CIType actDef2doc = null; final BigDecimal crossTotal = print.<BigDecimal>getAttribute(CISales.DocumentSumAbstract.CrossTotal); final Instance accountInst = print.<Instance>getSelect(selAccInst); CurrencyInst.get(print.<Long>getAttribute( CISales.DocumentSumAbstract.RateCurrencyId)); if (crossTotal.compareTo(BigDecimal.ZERO) < 0) { type = CISales.CollectionOrder.getType(); name = new Naming().fromNumberGenerator(_parameter, type.getName()); status = Status.find(CISales.CollectionOrderStatus.Open); relation = CISales.AccountPettyCash2CollectionOrder.getType(); bal2orderType = CISales.PettyCashBalance2CollectionOrder.getType(); actDefInst = Sales.PETTYCASHBAL_ACTDEF4COLORD.get(); actDef2doc = CISales.ActionDefinitionCollectionOrder2Document; } else if (crossTotal.compareTo(BigDecimal.ZERO) > 0) { type = CISales.PaymentOrder.getType(); name = new Naming().fromNumberGenerator(_parameter, type.getName()); status = Status.find(CISales.PaymentOrderStatus.Open); relation = CISales.AccountPettyCash2PaymentOrder.getType(); bal2orderType = CISales.PettyCashBalance2PaymentOrder.getType(); actDefInst = Sales.PETTYCASHBAL_ACTDEF4PAYORD.get(); actDef2doc = CISales.ActionDefinitionPaymentOrder2Document; } if (type != null && accountInst != null && accountInst.isValid()) { final Insert insert = new Insert(type); insert.add(CISales.DocumentSumAbstract.Name, name); insert.add(CISales.DocumentSumAbstract.Date, new DateTime()); insert.add(CISales.DocumentSumAbstract.DueDate, new DateTime()); insert.add(CISales.DocumentSumAbstract.Salesperson, Context.getThreadContext().getPerson().getId()); insert.add(CISales.DocumentSumAbstract.RateCrossTotal, crossTotal.abs()); insert.add(CISales.DocumentSumAbstract.RateNetTotal, crossTotal.abs()); insert.add(CISales.DocumentSumAbstract.RateDiscountTotal, BigDecimal.ZERO); insert.add(CISales.DocumentSumAbstract.CrossTotal, crossTotal.abs()); insert.add(CISales.DocumentSumAbstract.NetTotal, crossTotal.abs()); insert.add(CISales.DocumentSumAbstract.DiscountTotal, BigDecimal.ZERO); insert.add(CISales.DocumentSumAbstract.CurrencyId, print.<Long>getAttribute(CISales.DocumentSumAbstract.CurrencyId)); insert.add(CISales.DocumentSumAbstract.RateCurrencyId, print.<Long>getAttribute(CISales.DocumentSumAbstract.RateCurrencyId)); insert.add(CISales.DocumentSumAbstract.Rate, print.<Object[]>getAttribute(CISales.DocumentSumAbstract.Rate)); insert.add(CISales.DocumentSumAbstract.StatusAbstract, status); insert.add(CISales.DocumentSumAbstract.Note, _parameter.getParameterValue(getFieldName4Attribute(_parameter, CISales.DocumentSumAbstract.Note.name))); insert.execute(); final Insert relInsert = new Insert(relation); relInsert.add(CISales.AccountPettyCash2Document.FromLinkAbstract, accountInst); relInsert.add(CISales.AccountPettyCash2Document.ToLinkAbstract, insert.getInstance()); relInsert.execute(); final Insert relInsert2 = new Insert(bal2orderType); relInsert2.add(CISales.PettyCashBalance2OrderAbstract.FromAbstractLink, _parameter.getInstance()); relInsert2.add(CISales.PettyCashBalance2OrderAbstract.ToAbstractLink, insert.getInstance()); relInsert2.execute(); if (actDefInst.isValid()) { final Insert actDef2DocInsert = new Insert(actDef2doc); actDef2DocInsert.add(CIERP.ActionDefinition2DocumentAbstract.FromLinkAbstract, actDefInst); actDef2DocInsert.add(CIERP.ActionDefinition2DocumentAbstract.ToLinkAbstract, insert.getInstance()); actDef2DocInsert.execute(); } else { PettyCashBalance_Base.LOG.error("Missing or wrong Configuration Links for ActionDefinition: '{}', '{}'", Sales.PETTYCASHBAL_ACTDEF4COLORD.getKey(), Sales.PETTYCASHBAL_ACTDEF4PAYORD.getKey()); } } return new Return(); } /** * @param _parameter Parameter as passed by the eFaps API * @return Return with Access * @throws EFapsException on error */ public Return accessCheck4AccountDoc(final Parameter _parameter) throws EFapsException { final Return ret = new Return(); if (_parameter.getInstance() != null && _parameter.getInstance().isValid()) { final QueryBuilder queryBldr = new QueryBuilder(CISales.PettyCashBalance2OrderAbstract); queryBldr.addWhereAttrEqValue(CISales.PettyCashBalance2OrderAbstract.FromAbstractLink, _parameter.getInstance()); final InstanceQuery query = queryBldr.getQuery(); query.executeWithoutAccessCheck(); if (!query.next()) { if (Sales.PETTYCASHBAL_REQUIREBOOKED4PAY.get()) { final QueryBuilder attrQueryBldr = new QueryBuilder(CISales.PettyCashReceipt); attrQueryBldr.addWhereAttrNotEqValue(CISales.PettyCashReceipt.Status, Status.find(CISales.PettyCashReceiptStatus.Canceled)); final QueryBuilder chQueryBldr = new QueryBuilder(CISales.PettyCashBalance2PettyCashReceipt); chQueryBldr.addWhereAttrEqValue(CISales.Document2DocumentAbstract.FromAbstractLink, _parameter.getInstance()); chQueryBldr.addWhereAttrInQuery(CISales.Document2DocumentAbstract.ToAbstractLink, attrQueryBldr.getAttributeQuery(CISales.PettyCashReceipt.ID)); final InstanceQuery chQuery = chQueryBldr.getQuery(); chQuery.executeWithoutAccessCheck(); if (!chQuery.next()) { ret.put(ReturnValues.TRUE, true); } } else { ret.put(ReturnValues.TRUE, true); } } } return ret; } /** * Method for verify a Petty Cash Balance. * * @param _parameter Parameter as passed from the eFaps API. * @return new Return. * @throws EFapsException on error. */ public Return verify(final Parameter _parameter) throws EFapsException { final Instance instance = _parameter.getInstance(); final QueryBuilder attrQueryBldr = new QueryBuilder(CISales.PettyCashBalance2PettyCashReceipt); attrQueryBldr.addType(CISales.PettyCashBalance2IncomingCreditNote); attrQueryBldr.addWhereAttrEqValue(CISales.Document2DocumentAbstract.FromAbstractLink, instance); final AttributeQuery attrQuery = attrQueryBldr .getAttributeQuery(CISales.Document2DocumentAbstract.ToAbstractLink); final QueryBuilder queryBldr = new QueryBuilder(CISales.DocumentSumAbstract); queryBldr.addWhereAttrInQuery(CISales.DocumentSumAbstract.ID, attrQuery); final MultiPrintQuery multi = queryBldr.getPrint(); multi.addAttribute(CISales.DocumentSumAbstract.Contact); multi.execute(); while (multi.next()) { final Object contactObj = multi.getAttribute(CISales.DocumentSumAbstract.Contact); final Instance docInst = multi.getCurrentInstance(); final Update recUpdate = new Update(docInst); if (docInst.getType().isKindOf(CISales.PettyCashReceipt.getType())) { recUpdate.add(CISales.PettyCashReceipt.Status, Status.find(CISales.PettyCashReceiptStatus.Closed)); if (contactObj != null) { // legal documents final String seqKey = Sales.PETTYCASHRECEIPT_REVSEQ.get(); final NumberGenerator numgen = isUUID(seqKey) ? NumberGenerator.get(UUID.fromString(seqKey)) : NumberGenerator.get(seqKey); if (numgen != null) { final String revision = numgen.getNextVal(); recUpdate.add(CISales.PettyCashReceipt.Revision, revision); } } } else { recUpdate.add(CISales.IncomingCreditNote.Status, Status.find(CISales.IncomingCreditNoteStatus.Paid)); final String seqKey = Sales.INCOMINGCREDITNOTE_REVSEQ.get(); final NumberGenerator numgen = isUUID(seqKey) ? NumberGenerator.get(UUID.fromString(seqKey)) : NumberGenerator.get(seqKey); if (numgen != null) { final String revision = numgen.getNextVal(); recUpdate.add(CISales.IncomingCreditNote.Revision, revision); } } recUpdate.execute(); for (final IOnAction listener : Listener.get().<IOnAction>invoke(IOnAction.class)) { listener.onDocumentUpdate(_parameter, docInst); } } final Update update = new Update(instance); update.add(CISales.PettyCashBalance.Status, Status.find(CISales.PettyCashBalanceStatus.Verified)); update.execute(); return new Return(); } /** * Cancel. * * @param _parameter the parameter * @return the return * @throws EFapsException the eFaps exception */ public Return cancel(final Parameter _parameter) throws EFapsException { final Instance instance = _parameter.getInstance(); final QueryBuilder attrQueryBldr = new QueryBuilder(CISales.Payment); attrQueryBldr.addWhereAttrEqValue(CISales.Payment.CreateDocument, instance); attrQueryBldr.addWhereAttrEqValue(CISales.Payment.TargetDocument, instance); final QueryBuilder transQueryBldr = new QueryBuilder(CISales.TransactionAbstract); transQueryBldr.addWhereAttrInQuery(CISales.TransactionAbstract.Payment, attrQueryBldr.getAttributeQuery( CISales.Payment.ID)); final MultiPrintQuery multi = transQueryBldr.getPrint(); multi.addAttribute(CISales.TransactionAbstract.Amount, CISales.TransactionAbstract.CurrencyId, CISales.TransactionAbstract.Payment, CISales.TransactionAbstract.Account); multi.execute(); while (multi.next()) { final CIType type; if (InstanceUtils.isKindOf(multi.getCurrentInstance(), CISales.TransactionOutbound)) { type = CISales.TransactionInbound; } else { type = CISales.TransactionOutbound; } final Insert transInsert = new Insert(type); transInsert.add(CISales.TransactionAbstract.Amount, multi.<BigDecimal>getAttribute( CISales.TransactionAbstract.Amount)); transInsert.add(CISales.TransactionAbstract.CurrencyId, multi.<Long>getAttribute( CISales.TransactionAbstract.CurrencyId)); transInsert.add(CISales.TransactionAbstract.Payment, multi.<Long>getAttribute( CISales.TransactionAbstract.Payment)); transInsert.add(CISales.TransactionAbstract.Account, multi.<Long>getAttribute( CISales.TransactionAbstract.Account)); transInsert.add(CISales.TransactionAbstract.Description, getDBProperty("transaction.Cancel")); transInsert.add(CISales.TransactionAbstract.Date, new DateTime()); transInsert.execute(); } final QueryBuilder paymentQueryBldr = new QueryBuilder(CISales.Payment); paymentQueryBldr.addWhereAttrEqValue(CISales.Payment.TargetDocument, instance); final MultiPrintQuery paymentMulti = paymentQueryBldr.getPrint(); final SelectBuilder sel = SelectBuilder.get().linkto(CISales.Payment.CreateDocument).instance(); paymentMulti.addSelect(sel); paymentMulti.execute(); while (paymentMulti.next()) { final Instance docInst = paymentMulti.getSelect(sel); if (InstanceUtils.isKindOf(docInst, CISales.PettyCashReceipt) || InstanceUtils.isKindOf(docInst, CISales.IncomingCreditNote)) { final Update update = new Update(paymentMulti.getCurrentInstance()); update.add(CISales.Payment.TargetDocument, (Object) null); update.execute(); } } final QueryBuilder queryBldr = new QueryBuilder(CISales.PettyCashBalance2PettyCashReceipt); queryBldr.addType(CISales.PettyCashBalance2IncomingCreditNote); queryBldr.addWhereAttrEqValue(CISales.Document2DocumentAbstract.FromAbstractLink, instance); final InstanceQuery query = queryBldr.getQuery(); query.execute(); while (query.next()) { new Delete(query.getCurrentValue()).execute(); } final Update update = new Update(instance); update.add(CISales.PettyCashBalance.Status, Status.find(CISales.PettyCashBalanceStatus.Canceled)); update.execute(); return new Return(); } }
- setting transaction date
src/main/efaps/ESJP/org/efaps/esjp/sales/document/PettyCashBalance_Base.java
- setting transaction date
Java
bsd-2-clause
4531c4275a33760852b82afa94a6fc8de13004b6
0
eregon/mozart-graal,mistasse/mozart-graal,eregon/mozart-graal,eregon/mozart-graal,mistasse/mozart-graal,mistasse/mozart-graal,eregon/mozart-graal,mistasse/mozart-graal,eregon/mozart-graal,eregon/mozart-graal,mistasse/mozart-graal
package org.mozartoz.truffle.translator; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import org.mozartoz.bootcompiler.Main; import org.mozartoz.bootcompiler.ast.BinaryOp; import org.mozartoz.bootcompiler.ast.BindStatement; import org.mozartoz.bootcompiler.ast.CallStatement; import org.mozartoz.bootcompiler.ast.CompoundStatement; import org.mozartoz.bootcompiler.ast.Constant; import org.mozartoz.bootcompiler.ast.Expression; import org.mozartoz.bootcompiler.ast.IfStatement; import org.mozartoz.bootcompiler.ast.LocalStatement; import org.mozartoz.bootcompiler.ast.MatchStatement; import org.mozartoz.bootcompiler.ast.MatchStatementClause; import org.mozartoz.bootcompiler.ast.NoElseStatement; import org.mozartoz.bootcompiler.ast.ProcExpression; import org.mozartoz.bootcompiler.ast.Record; import org.mozartoz.bootcompiler.ast.RecordField; import org.mozartoz.bootcompiler.ast.SkipStatement; import org.mozartoz.bootcompiler.ast.Statement; import org.mozartoz.bootcompiler.ast.UnboundExpression; import org.mozartoz.bootcompiler.ast.Variable; import org.mozartoz.bootcompiler.ast.VariableOrRaw; import org.mozartoz.bootcompiler.oz.False; import org.mozartoz.bootcompiler.oz.OzArity; import org.mozartoz.bootcompiler.oz.OzAtom; import org.mozartoz.bootcompiler.oz.OzBuiltin; import org.mozartoz.bootcompiler.oz.OzFeature; import org.mozartoz.bootcompiler.oz.OzInt; import org.mozartoz.bootcompiler.oz.OzLiteral; import org.mozartoz.bootcompiler.oz.OzPatMatCapture; import org.mozartoz.bootcompiler.oz.OzPatMatWildcard; import org.mozartoz.bootcompiler.oz.OzRecord; import org.mozartoz.bootcompiler.oz.OzRecordField; import org.mozartoz.bootcompiler.oz.OzValue; import org.mozartoz.bootcompiler.oz.True; import org.mozartoz.bootcompiler.oz.UnitVal; import org.mozartoz.bootcompiler.parser.OzParser; import org.mozartoz.bootcompiler.symtab.Program; import org.mozartoz.bootcompiler.symtab.Symbol; import org.mozartoz.bootcompiler.transform.ConstantFolding; import org.mozartoz.bootcompiler.transform.Desugar; import org.mozartoz.bootcompiler.transform.DesugarClass; import org.mozartoz.bootcompiler.transform.DesugarFunctor; import org.mozartoz.bootcompiler.transform.Namer; import org.mozartoz.bootcompiler.transform.PatternMatcher; import org.mozartoz.bootcompiler.transform.Unnester; import org.mozartoz.bootcompiler.util.FilePosition; import org.mozartoz.truffle.nodes.AndNode; import org.mozartoz.truffle.nodes.HeadNodeGen; import org.mozartoz.truffle.nodes.IfNode; import org.mozartoz.truffle.nodes.OzNode; import org.mozartoz.truffle.nodes.OzRootNode; import org.mozartoz.truffle.nodes.PatternMatchCaptureNodeGen; import org.mozartoz.truffle.nodes.PatternMatchConsNodeGen; import org.mozartoz.truffle.nodes.PatternMatchEqualNodeGen; import org.mozartoz.truffle.nodes.PatternMatchRecordNodeGen; import org.mozartoz.truffle.nodes.SequenceNode; import org.mozartoz.truffle.nodes.SkipNode; import org.mozartoz.truffle.nodes.TailNodeGen; import org.mozartoz.truffle.nodes.builtins.AddNodeGen; import org.mozartoz.truffle.nodes.builtins.DivNodeGen; import org.mozartoz.truffle.nodes.builtins.DotNodeGen; import org.mozartoz.truffle.nodes.builtins.EqualNodeGen; import org.mozartoz.truffle.nodes.builtins.GreaterThanNodeGen; import org.mozartoz.truffle.nodes.builtins.LabelNodeGen; import org.mozartoz.truffle.nodes.builtins.LesserThanNodeGen; import org.mozartoz.truffle.nodes.builtins.LesserThanOrEqualNodeGen; import org.mozartoz.truffle.nodes.builtins.ModNodeGen; import org.mozartoz.truffle.nodes.builtins.MulNodeGen; import org.mozartoz.truffle.nodes.builtins.NotNodeGen; import org.mozartoz.truffle.nodes.builtins.RaiseErrorNodeGen; import org.mozartoz.truffle.nodes.builtins.RecordMakeDynamicNodeGen; import org.mozartoz.truffle.nodes.builtins.ShowNodeGen; import org.mozartoz.truffle.nodes.builtins.SubNodeGen; import org.mozartoz.truffle.nodes.call.CallProcNodeGen; import org.mozartoz.truffle.nodes.call.ReadArgumentNode; import org.mozartoz.truffle.nodes.literal.BooleanLiteralNode; import org.mozartoz.truffle.nodes.literal.ConsLiteralNodeGen; import org.mozartoz.truffle.nodes.literal.LiteralNode; import org.mozartoz.truffle.nodes.literal.LongLiteralNode; import org.mozartoz.truffle.nodes.literal.ProcDeclarationNode; import org.mozartoz.truffle.nodes.literal.RecordLiteralNode; import org.mozartoz.truffle.nodes.literal.UnboundLiteralNode; import org.mozartoz.truffle.nodes.local.BindNodeGen; import org.mozartoz.truffle.nodes.local.BindVarValueNodeGen; import org.mozartoz.truffle.nodes.local.InitializeArgNodeGen; import org.mozartoz.truffle.nodes.local.InitializeTmpNode; import org.mozartoz.truffle.nodes.local.InitializeVarNode; import org.mozartoz.truffle.nodes.local.ReadLocalVariableNode; import org.mozartoz.truffle.runtime.Arity; import org.mozartoz.truffle.runtime.OzCons; import org.mozartoz.truffle.runtime.Unit; import scala.collection.JavaConversions; import scala.collection.immutable.HashSet; import scala.util.parsing.combinator.Parsers.ParseResult; import scala.util.parsing.input.CharSequenceReader; import scala.util.parsing.input.Position; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.FrameSlot; import com.oracle.truffle.api.nodes.NodeUtil; import com.oracle.truffle.api.source.Source; import com.oracle.truffle.api.source.SourceSection; public class Translator { static class Environment { private final Environment parent; private final FrameDescriptor frameDescriptor; public Environment(Environment parent, FrameDescriptor frameDescriptor) { this.parent = parent; this.frameDescriptor = frameDescriptor; } } private Environment environment = new Environment(null, new FrameDescriptor()); private final Environment rootEnvironment = environment; private static long id = 0; public Translator() { } private void pushEnvironment(FrameDescriptor frameDescriptor) { environment = new Environment(environment, frameDescriptor); } private void popEnvironment() { environment = environment.parent; } private long nextID() { return id++; } public FrameSlotAndDepth findVariable(Symbol symbol) { int depth = 0; Environment environment = this.environment; while (environment != null) { FrameSlot slot = environment.frameDescriptor.findFrameSlot(symbol); if (slot != null) { return new FrameSlotAndDepth(slot, depth); } else { environment = environment.parent; depth++; } } throw new AssertionError(symbol.fullName()); } public OzRootNode parseAndTranslate(String code) { Program program = new Program(false); program.baseDeclarations().$plus$eq("Show").$plus$eq("Label").$plus$eq("ByNeedDot"); OzParser parser = new OzParser(); String[] builtinTypes = { "Value", "Number", "Float", "Int", "Exception", "Record", "Name", "Object", "Thread" }; List<String> builtins = new ArrayList<>(); for (String buitinType : builtinTypes) { builtins.add("/home/eregon/code/mozart-graal/mozart-graal/builtins/Mod" + buitinType + "-builtin.json"); } Main.loadModuleDefs(program, JavaConversions.asScalaBuffer(builtins).toList()); CharSequenceReader reader = new CharSequenceReader(code); HashSet<String> defines = new HashSet<String>();// .$plus("Show"); ParseResult<Statement> result = parser.parseStatement(reader, new File("test.oz"), defines); if (!result.successful()) { System.err.println("Parse error at " + result.next().pos().toString() + "\n" + result + "\n" + result.next().pos().longString()); throw new RuntimeException(); } program.rawCode_$eq(result.get()); Namer.apply(program); DesugarFunctor.apply(program); DesugarClass.apply(program); Desugar.apply(program); PatternMatcher.apply(program); ConstantFolding.apply(program); Unnester.apply(program); // Flattener.apply(program); Statement ast = program.rawCode(); // System.out.println(ast); FrameSlot baseSlot = rootEnvironment.frameDescriptor.addFrameSlot(program.baseEnvSymbol()); OzNode translated = translate(ast); OzNode showNode = ShowNodeGen.create(new ReadArgumentNode(0)); OzNode labelNode = BindVarValueNodeGen.create(new ReadArgumentNode(1), LabelNodeGen.create(new ReadArgumentNode(0))); OzNode byNeedDotNode = BindVarValueNodeGen.create(new ReadArgumentNode(2), DotNodeGen.create(new ReadArgumentNode(0), new ReadArgumentNode(1))); Arity baseArity = Arity.build("base", "Show", "Label", "ByNeedDot"); OzNode initializeBaseNode = new RecordLiteralNode(baseArity, new OzNode[] { new ProcDeclarationNode(new FrameDescriptor(), showNode), new ProcDeclarationNode(new FrameDescriptor(), labelNode), new ProcDeclarationNode(new FrameDescriptor(), byNeedDotNode) }); translated = new SequenceNode( new InitializeTmpNode(baseSlot, initializeBaseNode), translated); return new OzRootNode(environment.frameDescriptor, translated); } OzNode translate(Statement statement) { if (statement instanceof SkipStatement) { return new SkipNode(); } else if (statement instanceof CompoundStatement) { CompoundStatement compoundStatement = (CompoundStatement) statement; List<OzNode> stmts = new ArrayList<>(); for (Statement sub : toJava(compoundStatement.statements())) { stmts.add(translate(sub)); } return new SequenceNode(stmts.toArray(new OzNode[stmts.size()])); } else if (statement instanceof LocalStatement) { LocalStatement localStatement = (LocalStatement) statement; FrameDescriptor frameDescriptor = environment.frameDescriptor; OzNode[] nodes = new OzNode[localStatement.declarations().size() + 1]; int i = 0; for (Variable variable : toJava(localStatement.declarations())) { FrameSlot slot = frameDescriptor.addFrameSlot(variable.symbol()); nodes[i++] = new InitializeVarNode(slot); } nodes[i] = translate(localStatement.statement()); return new SequenceNode(nodes); } else if (statement instanceof BindStatement) { BindStatement bindStatement = (BindStatement) statement; Expression left = bindStatement.left(); Expression right = bindStatement.right(); if (left instanceof Variable) { final FrameSlotAndDepth leftSlot = findVariable(((Variable) left).symbol()); if (right instanceof Variable) { final FrameSlotAndDepth rightSlot = findVariable(((Variable) right).symbol()); return t(statement, BindNodeGen.create(leftSlot, rightSlot, leftSlot.createReadNode(), rightSlot.createReadNode())); } else { return t(statement, BindNodeGen.create(leftSlot, null, leftSlot.createReadNode(), translate(right))); } } } else if (statement instanceof IfStatement) { IfStatement ifStatement = (IfStatement) statement; return new IfNode(translate(ifStatement.condition()), translate(ifStatement.trueStatement()), translate(ifStatement.falseStatement())); } else if (statement instanceof MatchStatement) { MatchStatement matchStatement = (MatchStatement) statement; FrameDescriptor frameDescriptor = environment.frameDescriptor; FrameSlot valueSlot = frameDescriptor.addFrameSlot("MatchExpression-value" + nextID()); OzNode valueNode = translate(matchStatement.value()); Statement elseStatement = matchStatement.elseStatement(); assert !(elseStatement instanceof NoElseStatement); OzNode elseNode = translate(elseStatement); OzNode caseNode = elseNode; for (MatchStatementClause clause : toJava(matchStatement.clauses())) { assert !clause.hasGuard(); ReadLocalVariableNode value = new ReadLocalVariableNode(valueSlot); List<OzNode> checks = new ArrayList<>(); List<OzNode> bindings = new ArrayList<>(); translatePattern(clause.pattern(), value, checks, bindings); OzNode body = translate(clause.body()); caseNode = new IfNode( new AndNode(checks.toArray(new OzNode[checks.size()])), SequenceNode.sequence(bindings, body), caseNode); } return new SequenceNode( new InitializeTmpNode(valueSlot, valueNode), caseNode); } else if (statement instanceof CallStatement) { CallStatement callStatement = (CallStatement) statement; Expression callable = callStatement.callable(); List<Expression> args = new ArrayList<>(toJava(callStatement.args())); if (callable instanceof Constant && ((Constant) callable).value() instanceof OzBuiltin) { OzBuiltin builtin = (OzBuiltin) ((Constant) callable).value(); if (builtin.builtin().name().equals("raiseError")) { // Proc builtin return t(statement, RaiseErrorNodeGen.create(translate(args.get(0)))); } else { Variable var = (Variable) args.get(args.size() - 1); List<Expression> funArgs = args.subList(0, args.size() - 1); FrameSlotAndDepth slot = findVariable(var.symbol()); return t(statement, BindNodeGen.create(slot, null, slot.createReadNode(), translateExpressionBuiltin(callable, funArgs))); } } else { OzNode[] argsNodes = new OzNode[args.size()]; for (int i = 0; i < args.size(); i++) { argsNodes[i] = translate(args.get(i)); } return t(statement, CallProcNodeGen.create(argsNodes, translate(callable))); } } throw unknown("statement", statement); } OzNode translate(Expression expression) { if (expression instanceof Constant) { Constant constant = (Constant) expression; return translateConstantNode(constant.value()); } else if (expression instanceof Record) { Record record = (Record) expression; List<RecordField> fields = new ArrayList<>(toJava(record.fields())); if (record.isCons()) { return buildCons(translate(fields.get(0).value()), translate(fields.get(1).value())); } else { if (record.hasConstantArity()) { OzNode[] values = new OzNode[fields.size()]; for (int i = 0; i < values.length; i++) { values[i] = translate(fields.get(i).value()); } return new RecordLiteralNode(buildArity(record.getConstantArity()), values); } } } else if (expression instanceof Variable) { Variable variable = (Variable) expression; FrameSlotAndDepth frameSlotAndDepth = findVariable(variable.symbol()); return frameSlotAndDepth.createReadNode(); } else if (expression instanceof UnboundExpression) { return new UnboundLiteralNode(); } else if (expression instanceof BinaryOp) { BinaryOp binaryOp = (BinaryOp) expression; OzNode left = translate(binaryOp.left()); OzNode right = translate(binaryOp.right()); return translateBinaryOp(binaryOp.operator(), left, right); } else if (expression instanceof ProcExpression) { // proc/fun literal ProcExpression procExpression = (ProcExpression) expression; FrameDescriptor frameDescriptor = new FrameDescriptor(); OzNode[] nodes = new OzNode[procExpression.args().size() + 1]; int i = 0; for (VariableOrRaw variable : toJava(procExpression.args())) { if (variable instanceof Variable) { FrameSlot argSlot = frameDescriptor.addFrameSlot(((Variable) variable).symbol()); nodes[i] = InitializeArgNodeGen.create(argSlot, new ReadArgumentNode(i)); i++; } else { throw unknown("variable", variable); } } OzNode body; pushEnvironment(frameDescriptor); try { body = translate(procExpression.body()); } finally { popEnvironment(); } nodes[i] = body; OzNode procBody = new SequenceNode(nodes); return t(expression, new ProcDeclarationNode(frameDescriptor, procBody)); } throw unknown("expression", expression); } private void translatePattern(Expression pattern, OzNode valueNode, List<OzNode> checks, List<OzNode> bindings) { if (pattern instanceof Constant) { OzValue matcher = ((Constant) pattern).value(); if (matcher instanceof OzFeature) { Object feature = translateFeature((OzFeature) matcher); checks.add(PatternMatchEqualNodeGen.create(feature, valueNode)); } else if (matcher instanceof OzRecord) { OzRecord record = (OzRecord) matcher; assert record.isCons(); OzValue head = record.values().apply(0); translateMatcher(head, HeadNodeGen::create, valueNode, checks, bindings); OzValue tail = record.values().apply(1); translateMatcher(tail, TailNodeGen::create, valueNode, checks, bindings); checks.add(PatternMatchConsNodeGen.create(valueNode)); } else { throw unknown("pattern", pattern); } } else { throw unknown("pattern", pattern); } } private void translateMatcher(OzValue matcher, Function<OzNode, OzNode> element, OzNode baseNode, List<OzNode> checks, List<OzNode> bindings) { if (matcher instanceof OzPatMatWildcard) { // Nothing to do } else if (matcher instanceof OzPatMatCapture) { Symbol sym = ((OzPatMatCapture) matcher).variable(); FrameDescriptor frameDescriptor = environment.frameDescriptor; FrameSlot slot = frameDescriptor.findOrAddFrameSlot(sym); OzNode elementNode = element.apply(copy(baseNode)); bindings.add(PatternMatchCaptureNodeGen.create(new ReadLocalVariableNode(slot), elementNode)); } else if (matcher instanceof OzRecord) { OzRecord record = (OzRecord) matcher; Arity arity = buildArity(record.arity()); OzNode elementNode = element.apply(copy(baseNode)); checks.add(PatternMatchRecordNodeGen.create(arity, copy(elementNode))); for (OzRecordField field : toJava(record.fields())) { Object feature = translateFeature(field.feature()); translateMatcher(field.value(), r -> { return DotNodeGen.create(r, new LiteralNode(feature)); }, elementNode, checks, bindings); } } else { throw unknown("pattern matcher", matcher); } } private OzNode translateConstantNode(OzValue value) { if (value instanceof OzInt) { return new LongLiteralNode(((OzInt) value).value()); } else if (value instanceof True) { return new BooleanLiteralNode(true); } else if (value instanceof False) { return new BooleanLiteralNode(false); } else { return new LiteralNode(translateConstantValue(value)); } } private Object translateConstantValue(OzValue value) { if (value instanceof OzFeature) { return translateFeature((OzFeature) value); } else if (value instanceof OzRecord) { OzRecord ozRecord = (OzRecord) value; if (ozRecord.isCons()) { Object left = translateConstantValue(ozRecord.fields().apply(0).value()); Object right = translateConstantValue(ozRecord.fields().apply(1).value()); return new OzCons(left, right); } else { Arity arity = buildArity(ozRecord.arity()); Object[] values = toJava(ozRecord.values()).stream().map(this::translateConstantValue).toArray(Object[]::new); return RecordLiteralNode.buildRecord(arity, values); } } throw unknown("value", value); } private static Object translateFeature(OzFeature feature) { if (feature instanceof OzInt) { return ((OzInt) feature).value(); } else if (feature instanceof True) { return true; } else if (feature instanceof False) { return false; } else if (feature instanceof UnitVal) { return Unit.INSTANCE; } else if (feature instanceof OzAtom) { return translateAtom((OzAtom) feature); } else { throw unknown("feature", feature); } } private static Object translateLiteral(OzLiteral literal) { if (literal instanceof OzAtom) { return translateAtom((OzAtom) literal); } else { throw unknown("literal", literal); } } private static String translateAtom(OzAtom atom) { return atom.value().intern(); } private OzNode translateExpressionBuiltin(Expression callable, List<Expression> args) { String name = ((OzBuiltin) ((Constant) callable).value()).builtin().name(); if (args.size() == 1) { if (name.equals("+1") || name.equals("-1")) { String op = name.substring(0, 1); return translate(new BinaryOp(args.get(0), op, new Constant(new OzInt(1)))); } } else if (args.size() == 2) { OzNode left = translate(args.get(0)); OzNode right = translate(args.get(1)); return translateBinaryOp(name, left, right); } throw unknown("builtin", name); } private OzNode buildCons(OzNode head, OzNode tail) { return ConsLiteralNodeGen.create(head, tail); } private Arity buildArity(OzArity arity) { Object[] features = toJava(arity.features()).stream().map(Translator::translateFeature).toArray(Object[]::new); return Arity.build(translateLiteral(arity.label()), features); } private OzNode translateBinaryOp(String operator, OzNode left, OzNode right) { switch (operator) { case "+": return AddNodeGen.create(left, right); case "-": return SubNodeGen.create(left, right); case "*": return MulNodeGen.create(left, right); case "div": return DivNodeGen.create(left, right); case "mod": return ModNodeGen.create(left, right); case "==": return EqualNodeGen.create(left, right); case "\\=": return NotNodeGen.create(EqualNodeGen.create(left, right)); case "<": return LesserThanNodeGen.create(left, right); case "=<": return LesserThanOrEqualNodeGen.create(left, right); case ">": return GreaterThanNodeGen.create(left, right); case ".": return DotNodeGen.create(left, right); case "makeDynamic": // Record return RecordMakeDynamicNodeGen.create(left, right); default: throw unknown("operator", operator); } } private OzNode copy(OzNode node) { return NodeUtil.cloneNode(node); } private static <E> Collection<E> toJava(scala.collection.immutable.Iterable<E> scalaIterable) { return JavaConversions.asJavaCollection(scalaIterable); } private static RuntimeException unknown(String type, Object description) { return new RuntimeException("Unknown " + type + " " + description.getClass() + ": " + description); } private OzNode t(org.mozartoz.bootcompiler.ast.Node node, OzNode ozNode) { SourceSection sourceSection = t(node); ozNode.assignSourceSection(sourceSection); return ozNode; } private static final Map<String, Source> SOURCES = new HashMap<>(); private SourceSection t(org.mozartoz.bootcompiler.ast.Node node) { Position pos = node.pos(); if (pos instanceof FilePosition) { FilePosition filePosition = (FilePosition) pos; String canonicalPath; try { canonicalPath = filePosition.file().get().getCanonicalPath(); } catch (IOException e) { throw new RuntimeException(e); } Source source = SOURCES.computeIfAbsent(canonicalPath, file -> { try { return Source.fromFileName(file); } catch (IOException e) { throw new RuntimeException(e); } }); return source.createSection("", filePosition.line()); } else { return SourceSection.createUnavailable("unavailable", ""); } } }
vm/src/org/mozartoz/truffle/translator/Translator.java
package org.mozartoz.truffle.translator; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import org.mozartoz.bootcompiler.Main; import org.mozartoz.bootcompiler.ast.BinaryOp; import org.mozartoz.bootcompiler.ast.BindStatement; import org.mozartoz.bootcompiler.ast.CallStatement; import org.mozartoz.bootcompiler.ast.CompoundStatement; import org.mozartoz.bootcompiler.ast.Constant; import org.mozartoz.bootcompiler.ast.Expression; import org.mozartoz.bootcompiler.ast.IfStatement; import org.mozartoz.bootcompiler.ast.LocalStatement; import org.mozartoz.bootcompiler.ast.MatchStatement; import org.mozartoz.bootcompiler.ast.MatchStatementClause; import org.mozartoz.bootcompiler.ast.NoElseStatement; import org.mozartoz.bootcompiler.ast.ProcExpression; import org.mozartoz.bootcompiler.ast.Record; import org.mozartoz.bootcompiler.ast.RecordField; import org.mozartoz.bootcompiler.ast.SkipStatement; import org.mozartoz.bootcompiler.ast.Statement; import org.mozartoz.bootcompiler.ast.UnboundExpression; import org.mozartoz.bootcompiler.ast.Variable; import org.mozartoz.bootcompiler.ast.VariableOrRaw; import org.mozartoz.bootcompiler.oz.False; import org.mozartoz.bootcompiler.oz.OzArity; import org.mozartoz.bootcompiler.oz.OzAtom; import org.mozartoz.bootcompiler.oz.OzBuiltin; import org.mozartoz.bootcompiler.oz.OzFeature; import org.mozartoz.bootcompiler.oz.OzInt; import org.mozartoz.bootcompiler.oz.OzLiteral; import org.mozartoz.bootcompiler.oz.OzPatMatCapture; import org.mozartoz.bootcompiler.oz.OzPatMatWildcard; import org.mozartoz.bootcompiler.oz.OzRecord; import org.mozartoz.bootcompiler.oz.OzRecordField; import org.mozartoz.bootcompiler.oz.OzValue; import org.mozartoz.bootcompiler.oz.True; import org.mozartoz.bootcompiler.oz.UnitVal; import org.mozartoz.bootcompiler.parser.OzParser; import org.mozartoz.bootcompiler.symtab.Program; import org.mozartoz.bootcompiler.symtab.Symbol; import org.mozartoz.bootcompiler.transform.ConstantFolding; import org.mozartoz.bootcompiler.transform.Desugar; import org.mozartoz.bootcompiler.transform.DesugarClass; import org.mozartoz.bootcompiler.transform.DesugarFunctor; import org.mozartoz.bootcompiler.transform.Namer; import org.mozartoz.bootcompiler.transform.PatternMatcher; import org.mozartoz.bootcompiler.transform.Unnester; import org.mozartoz.bootcompiler.util.FilePosition; import org.mozartoz.truffle.nodes.AndNode; import org.mozartoz.truffle.nodes.HeadNodeGen; import org.mozartoz.truffle.nodes.IfNode; import org.mozartoz.truffle.nodes.OzNode; import org.mozartoz.truffle.nodes.OzRootNode; import org.mozartoz.truffle.nodes.PatternMatchCaptureNodeGen; import org.mozartoz.truffle.nodes.PatternMatchConsNodeGen; import org.mozartoz.truffle.nodes.PatternMatchEqualNodeGen; import org.mozartoz.truffle.nodes.PatternMatchRecordNodeGen; import org.mozartoz.truffle.nodes.SequenceNode; import org.mozartoz.truffle.nodes.SkipNode; import org.mozartoz.truffle.nodes.TailNodeGen; import org.mozartoz.truffle.nodes.builtins.AddNodeGen; import org.mozartoz.truffle.nodes.builtins.DivNodeGen; import org.mozartoz.truffle.nodes.builtins.DotNodeGen; import org.mozartoz.truffle.nodes.builtins.EqualNodeGen; import org.mozartoz.truffle.nodes.builtins.GreaterThanNodeGen; import org.mozartoz.truffle.nodes.builtins.LabelNodeGen; import org.mozartoz.truffle.nodes.builtins.LesserThanNodeGen; import org.mozartoz.truffle.nodes.builtins.LesserThanOrEqualNodeGen; import org.mozartoz.truffle.nodes.builtins.ModNodeGen; import org.mozartoz.truffle.nodes.builtins.MulNodeGen; import org.mozartoz.truffle.nodes.builtins.NotNodeGen; import org.mozartoz.truffle.nodes.builtins.RaiseErrorNodeGen; import org.mozartoz.truffle.nodes.builtins.RecordMakeDynamicNodeGen; import org.mozartoz.truffle.nodes.builtins.ShowNodeGen; import org.mozartoz.truffle.nodes.builtins.SubNodeGen; import org.mozartoz.truffle.nodes.call.CallProcNodeGen; import org.mozartoz.truffle.nodes.call.ReadArgumentNode; import org.mozartoz.truffle.nodes.literal.BooleanLiteralNode; import org.mozartoz.truffle.nodes.literal.ConsLiteralNodeGen; import org.mozartoz.truffle.nodes.literal.LiteralNode; import org.mozartoz.truffle.nodes.literal.LongLiteralNode; import org.mozartoz.truffle.nodes.literal.ProcDeclarationNode; import org.mozartoz.truffle.nodes.literal.RecordLiteralNode; import org.mozartoz.truffle.nodes.literal.UnboundLiteralNode; import org.mozartoz.truffle.nodes.local.BindNodeGen; import org.mozartoz.truffle.nodes.local.BindVarValueNodeGen; import org.mozartoz.truffle.nodes.local.InitializeArgNodeGen; import org.mozartoz.truffle.nodes.local.InitializeTmpNode; import org.mozartoz.truffle.nodes.local.InitializeVarNode; import org.mozartoz.truffle.nodes.local.ReadLocalVariableNode; import org.mozartoz.truffle.runtime.Arity; import org.mozartoz.truffle.runtime.OzCons; import org.mozartoz.truffle.runtime.Unit; import scala.collection.JavaConversions; import scala.collection.immutable.HashSet; import scala.util.parsing.combinator.Parsers.ParseResult; import scala.util.parsing.input.CharSequenceReader; import scala.util.parsing.input.Position; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.FrameSlot; import com.oracle.truffle.api.nodes.NodeUtil; import com.oracle.truffle.api.source.Source; import com.oracle.truffle.api.source.SourceSection; public class Translator { static class Environment { private final Environment parent; private final FrameDescriptor frameDescriptor; public Environment(Environment parent, FrameDescriptor frameDescriptor) { this.parent = parent; this.frameDescriptor = frameDescriptor; } } private Environment environment = new Environment(null, new FrameDescriptor()); private final Environment rootEnvironment = environment; private static long id = 0; public Translator() { } private void pushEnvironment(FrameDescriptor frameDescriptor) { environment = new Environment(environment, frameDescriptor); } private void popEnvironment() { environment = environment.parent; } private long nextID() { return id++; } public FrameSlotAndDepth findVariable(Symbol symbol) { int depth = 0; Environment environment = this.environment; while (environment != null) { FrameSlot slot = environment.frameDescriptor.findFrameSlot(symbol); if (slot != null) { return new FrameSlotAndDepth(slot, depth); } else { environment = environment.parent; depth++; } } throw new AssertionError(symbol.fullName()); } public OzRootNode parseAndTranslate(String code) { Program program = new Program(false); program.baseDeclarations().$plus$eq("Show").$plus$eq("Label").$plus$eq("ByNeedDot"); OzParser parser = new OzParser(); String[] builtinTypes = { "Value", "Number", "Float", "Int", "Exception", "Record" }; List<String> builtins = new ArrayList<>(); for (String buitinType : builtinTypes) { builtins.add("/home/eregon/code/mozart-graal/bootcompiler/Mod" + buitinType + "-builtin.json"); } Main.loadModuleDefs(program, JavaConversions.asScalaBuffer(builtins).toList()); CharSequenceReader reader = new CharSequenceReader(code); HashSet<String> defines = new HashSet<String>();// .$plus("Show"); ParseResult<Statement> result = parser.parseStatement(reader, new File("test.oz"), defines); if (!result.successful()) { System.err.println("Parse error at " + result.next().pos().toString() + "\n" + result + "\n" + result.next().pos().longString()); throw new RuntimeException(); } program.rawCode_$eq(result.get()); Namer.apply(program); DesugarFunctor.apply(program); DesugarClass.apply(program); Desugar.apply(program); PatternMatcher.apply(program); ConstantFolding.apply(program); Unnester.apply(program); // Flattener.apply(program); Statement ast = program.rawCode(); // System.out.println(ast); FrameSlot baseSlot = rootEnvironment.frameDescriptor.addFrameSlot(program.baseEnvSymbol()); OzNode translated = translate(ast); OzNode showNode = ShowNodeGen.create(new ReadArgumentNode(0)); OzNode labelNode = BindVarValueNodeGen.create(new ReadArgumentNode(1), LabelNodeGen.create(new ReadArgumentNode(0))); OzNode byNeedDotNode = BindVarValueNodeGen.create(new ReadArgumentNode(2), DotNodeGen.create(new ReadArgumentNode(0), new ReadArgumentNode(1))); Arity baseArity = Arity.build("base", "Show", "Label", "ByNeedDot"); OzNode initializeBaseNode = new RecordLiteralNode(baseArity, new OzNode[] { new ProcDeclarationNode(new FrameDescriptor(), showNode), new ProcDeclarationNode(new FrameDescriptor(), labelNode), new ProcDeclarationNode(new FrameDescriptor(), byNeedDotNode) }); translated = new SequenceNode( new InitializeTmpNode(baseSlot, initializeBaseNode), translated); return new OzRootNode(environment.frameDescriptor, translated); } OzNode translate(Statement statement) { if (statement instanceof SkipStatement) { return new SkipNode(); } else if (statement instanceof CompoundStatement) { CompoundStatement compoundStatement = (CompoundStatement) statement; List<OzNode> stmts = new ArrayList<>(); for (Statement sub : toJava(compoundStatement.statements())) { stmts.add(translate(sub)); } return new SequenceNode(stmts.toArray(new OzNode[stmts.size()])); } else if (statement instanceof LocalStatement) { LocalStatement localStatement = (LocalStatement) statement; FrameDescriptor frameDescriptor = environment.frameDescriptor; OzNode[] nodes = new OzNode[localStatement.declarations().size() + 1]; int i = 0; for (Variable variable : toJava(localStatement.declarations())) { FrameSlot slot = frameDescriptor.addFrameSlot(variable.symbol()); nodes[i++] = new InitializeVarNode(slot); } nodes[i] = translate(localStatement.statement()); return new SequenceNode(nodes); } else if (statement instanceof BindStatement) { BindStatement bindStatement = (BindStatement) statement; Expression left = bindStatement.left(); Expression right = bindStatement.right(); if (left instanceof Variable) { final FrameSlotAndDepth leftSlot = findVariable(((Variable) left).symbol()); if (right instanceof Variable) { final FrameSlotAndDepth rightSlot = findVariable(((Variable) right).symbol()); return t(statement, BindNodeGen.create(leftSlot, rightSlot, leftSlot.createReadNode(), rightSlot.createReadNode())); } else { return t(statement, BindNodeGen.create(leftSlot, null, leftSlot.createReadNode(), translate(right))); } } } else if (statement instanceof IfStatement) { IfStatement ifStatement = (IfStatement) statement; return new IfNode(translate(ifStatement.condition()), translate(ifStatement.trueStatement()), translate(ifStatement.falseStatement())); } else if (statement instanceof MatchStatement) { MatchStatement matchStatement = (MatchStatement) statement; FrameDescriptor frameDescriptor = environment.frameDescriptor; FrameSlot valueSlot = frameDescriptor.addFrameSlot("MatchExpression-value" + nextID()); OzNode valueNode = translate(matchStatement.value()); Statement elseStatement = matchStatement.elseStatement(); assert !(elseStatement instanceof NoElseStatement); OzNode elseNode = translate(elseStatement); OzNode caseNode = elseNode; for (MatchStatementClause clause : toJava(matchStatement.clauses())) { assert !clause.hasGuard(); ReadLocalVariableNode value = new ReadLocalVariableNode(valueSlot); List<OzNode> checks = new ArrayList<>(); List<OzNode> bindings = new ArrayList<>(); translatePattern(clause.pattern(), value, checks, bindings); OzNode body = translate(clause.body()); caseNode = new IfNode( new AndNode(checks.toArray(new OzNode[checks.size()])), SequenceNode.sequence(bindings, body), caseNode); } return new SequenceNode( new InitializeTmpNode(valueSlot, valueNode), caseNode); } else if (statement instanceof CallStatement) { CallStatement callStatement = (CallStatement) statement; Expression callable = callStatement.callable(); List<Expression> args = new ArrayList<>(toJava(callStatement.args())); if (callable instanceof Constant && ((Constant) callable).value() instanceof OzBuiltin) { OzBuiltin builtin = (OzBuiltin) ((Constant) callable).value(); if (builtin.builtin().name().equals("raiseError")) { // Proc builtin return t(statement, RaiseErrorNodeGen.create(translate(args.get(0)))); } else { Variable var = (Variable) args.get(args.size() - 1); List<Expression> funArgs = args.subList(0, args.size() - 1); FrameSlotAndDepth slot = findVariable(var.symbol()); return t(statement, BindNodeGen.create(slot, null, slot.createReadNode(), translateExpressionBuiltin(callable, funArgs))); } } else { OzNode[] argsNodes = new OzNode[args.size()]; for (int i = 0; i < args.size(); i++) { argsNodes[i] = translate(args.get(i)); } return t(statement, CallProcNodeGen.create(argsNodes, translate(callable))); } } throw unknown("statement", statement); } OzNode translate(Expression expression) { if (expression instanceof Constant) { Constant constant = (Constant) expression; return translateConstantNode(constant.value()); } else if (expression instanceof Record) { Record record = (Record) expression; List<RecordField> fields = new ArrayList<>(toJava(record.fields())); if (record.isCons()) { return buildCons(translate(fields.get(0).value()), translate(fields.get(1).value())); } else { if (record.hasConstantArity()) { OzNode[] values = new OzNode[fields.size()]; for (int i = 0; i < values.length; i++) { values[i] = translate(fields.get(i).value()); } return new RecordLiteralNode(buildArity(record.getConstantArity()), values); } } } else if (expression instanceof Variable) { Variable variable = (Variable) expression; FrameSlotAndDepth frameSlotAndDepth = findVariable(variable.symbol()); return frameSlotAndDepth.createReadNode(); } else if (expression instanceof UnboundExpression) { return new UnboundLiteralNode(); } else if (expression instanceof BinaryOp) { BinaryOp binaryOp = (BinaryOp) expression; OzNode left = translate(binaryOp.left()); OzNode right = translate(binaryOp.right()); return translateBinaryOp(binaryOp.operator(), left, right); } else if (expression instanceof ProcExpression) { // proc/fun literal ProcExpression procExpression = (ProcExpression) expression; FrameDescriptor frameDescriptor = new FrameDescriptor(); OzNode[] nodes = new OzNode[procExpression.args().size() + 1]; int i = 0; for (VariableOrRaw variable : toJava(procExpression.args())) { if (variable instanceof Variable) { FrameSlot argSlot = frameDescriptor.addFrameSlot(((Variable) variable).symbol()); nodes[i] = InitializeArgNodeGen.create(argSlot, new ReadArgumentNode(i)); i++; } else { throw unknown("variable", variable); } } OzNode body; pushEnvironment(frameDescriptor); try { body = translate(procExpression.body()); } finally { popEnvironment(); } nodes[i] = body; OzNode procBody = new SequenceNode(nodes); return t(expression, new ProcDeclarationNode(frameDescriptor, procBody)); } throw unknown("expression", expression); } private void translatePattern(Expression pattern, OzNode valueNode, List<OzNode> checks, List<OzNode> bindings) { if (pattern instanceof Constant) { OzValue matcher = ((Constant) pattern).value(); if (matcher instanceof OzFeature) { Object feature = translateFeature((OzFeature) matcher); checks.add(PatternMatchEqualNodeGen.create(feature, valueNode)); } else if (matcher instanceof OzRecord) { OzRecord record = (OzRecord) matcher; assert record.isCons(); OzValue head = record.values().apply(0); translateMatcher(head, HeadNodeGen::create, valueNode, checks, bindings); OzValue tail = record.values().apply(1); translateMatcher(tail, TailNodeGen::create, valueNode, checks, bindings); checks.add(PatternMatchConsNodeGen.create(valueNode)); } else { throw unknown("pattern", pattern); } } else { throw unknown("pattern", pattern); } } private void translateMatcher(OzValue matcher, Function<OzNode, OzNode> element, OzNode baseNode, List<OzNode> checks, List<OzNode> bindings) { if (matcher instanceof OzPatMatWildcard) { // Nothing to do } else if (matcher instanceof OzPatMatCapture) { Symbol sym = ((OzPatMatCapture) matcher).variable(); FrameDescriptor frameDescriptor = environment.frameDescriptor; FrameSlot slot = frameDescriptor.findOrAddFrameSlot(sym); OzNode elementNode = element.apply(copy(baseNode)); bindings.add(PatternMatchCaptureNodeGen.create(new ReadLocalVariableNode(slot), elementNode)); } else if (matcher instanceof OzRecord) { OzRecord record = (OzRecord) matcher; Arity arity = buildArity(record.arity()); OzNode elementNode = element.apply(copy(baseNode)); checks.add(PatternMatchRecordNodeGen.create(arity, copy(elementNode))); for (OzRecordField field : toJava(record.fields())) { Object feature = translateFeature(field.feature()); translateMatcher(field.value(), r -> { return DotNodeGen.create(r, new LiteralNode(feature)); }, elementNode, checks, bindings); } } else { throw unknown("pattern matcher", matcher); } } private OzNode translateConstantNode(OzValue value) { if (value instanceof OzInt) { return new LongLiteralNode(((OzInt) value).value()); } else if (value instanceof True) { return new BooleanLiteralNode(true); } else if (value instanceof False) { return new BooleanLiteralNode(false); } else { return new LiteralNode(translateConstantValue(value)); } } private Object translateConstantValue(OzValue value) { if (value instanceof OzFeature) { return translateFeature((OzFeature) value); } else if (value instanceof OzRecord) { OzRecord ozRecord = (OzRecord) value; if (ozRecord.isCons()) { Object left = translateConstantValue(ozRecord.fields().apply(0).value()); Object right = translateConstantValue(ozRecord.fields().apply(1).value()); return new OzCons(left, right); } else { Arity arity = buildArity(ozRecord.arity()); Object[] values = toJava(ozRecord.values()).stream().map(this::translateConstantValue).toArray(Object[]::new); return RecordLiteralNode.buildRecord(arity, values); } } throw unknown("value", value); } private static Object translateFeature(OzFeature feature) { if (feature instanceof OzInt) { return ((OzInt) feature).value(); } else if (feature instanceof True) { return true; } else if (feature instanceof False) { return false; } else if (feature instanceof UnitVal) { return Unit.INSTANCE; } else if (feature instanceof OzAtom) { return translateAtom((OzAtom) feature); } else { throw unknown("feature", feature); } } private static Object translateLiteral(OzLiteral literal) { if (literal instanceof OzAtom) { return translateAtom((OzAtom) literal); } else { throw unknown("literal", literal); } } private static String translateAtom(OzAtom atom) { return atom.value().intern(); } private OzNode translateExpressionBuiltin(Expression callable, List<Expression> args) { String name = ((OzBuiltin) ((Constant) callable).value()).builtin().name(); if (args.size() == 1) { if (name.equals("+1") || name.equals("-1")) { String op = name.substring(0, 1); return translate(new BinaryOp(args.get(0), op, new Constant(new OzInt(1)))); } } else if (args.size() == 2) { OzNode left = translate(args.get(0)); OzNode right = translate(args.get(1)); return translateBinaryOp(name, left, right); } throw unknown("builtin", name); } private OzNode buildCons(OzNode head, OzNode tail) { return ConsLiteralNodeGen.create(head, tail); } private Arity buildArity(OzArity arity) { Object[] features = toJava(arity.features()).stream().map(Translator::translateFeature).toArray(Object[]::new); return Arity.build(translateLiteral(arity.label()), features); } private OzNode translateBinaryOp(String operator, OzNode left, OzNode right) { switch (operator) { case "+": return AddNodeGen.create(left, right); case "-": return SubNodeGen.create(left, right); case "*": return MulNodeGen.create(left, right); case "div": return DivNodeGen.create(left, right); case "mod": return ModNodeGen.create(left, right); case "==": return EqualNodeGen.create(left, right); case "\\=": return NotNodeGen.create(EqualNodeGen.create(left, right)); case "<": return LesserThanNodeGen.create(left, right); case "=<": return LesserThanOrEqualNodeGen.create(left, right); case ">": return GreaterThanNodeGen.create(left, right); case ".": return DotNodeGen.create(left, right); case "makeDynamic": // Record return RecordMakeDynamicNodeGen.create(left, right); default: throw unknown("operator", operator); } } private OzNode copy(OzNode node) { return NodeUtil.cloneNode(node); } private static <E> Collection<E> toJava(scala.collection.immutable.Iterable<E> scalaIterable) { return JavaConversions.asJavaCollection(scalaIterable); } private static RuntimeException unknown(String type, Object description) { return new RuntimeException("Unknown " + type + " " + description.getClass() + ": " + description); } private OzNode t(org.mozartoz.bootcompiler.ast.Node node, OzNode ozNode) { SourceSection sourceSection = t(node); ozNode.assignSourceSection(sourceSection); return ozNode; } private static final Map<String, Source> SOURCES = new HashMap<>(); private SourceSection t(org.mozartoz.bootcompiler.ast.Node node) { Position pos = node.pos(); if (pos instanceof FilePosition) { FilePosition filePosition = (FilePosition) pos; String canonicalPath; try { canonicalPath = filePosition.file().get().getCanonicalPath(); } catch (IOException e) { throw new RuntimeException(e); } Source source = SOURCES.computeIfAbsent(canonicalPath, file -> { try { return Source.fromFileName(file); } catch (IOException e) { throw new RuntimeException(e); } }); return source.createSection("", filePosition.line()); } else { return SourceSection.createUnavailable("unavailable", ""); } } }
a few more builtin modules
vm/src/org/mozartoz/truffle/translator/Translator.java
a few more builtin modules
Java
bsd-3-clause
cf6855cda8638ce11a40bb3aec862ebbd37e4adf
0
motech-implementations/mim,motech-implementations/mim,motech-implementations/mim,motech-implementations/mim
package org.motechproject.nms.imi.service.impl; import org.apache.commons.httpclient.HttpStatus; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import com.fasterxml.jackson.databind.ObjectMapper; import org.joda.time.DateTime; import org.joda.time.Days; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.motechproject.alerts.contract.AlertService; import org.motechproject.alerts.domain.AlertStatus; import org.motechproject.alerts.domain.AlertType; import org.motechproject.event.MotechEvent; import org.motechproject.event.listener.annotations.MotechListener; import org.motechproject.metrics.service.Timer; import org.motechproject.nms.imi.domain.FileAuditRecord; import org.motechproject.nms.imi.domain.FileProcessedStatus; import org.motechproject.nms.imi.domain.FileType; import org.motechproject.nms.imi.exception.ExecException; import org.motechproject.nms.imi.exception.InternalException; import org.motechproject.nms.imi.repository.FileAuditRecordDataService; import org.motechproject.nms.imi.service.TargetFileService; import org.motechproject.nms.imi.service.contract.TargetFileNotification; import org.motechproject.nms.imi.web.contract.FileProcessedStatusRequest; import org.motechproject.nms.kilkari.domain.CallRetry; import org.motechproject.nms.kilkari.domain.Subscriber; import org.motechproject.nms.kilkari.domain.Subscription; import org.motechproject.nms.kilkari.domain.SubscriptionOrigin; import org.motechproject.nms.kilkari.domain.SubscriptionPack; import org.motechproject.nms.kilkari.domain.SubscriptionPackMessage; import org.motechproject.nms.kilkari.service.CallRetryService; import org.motechproject.nms.kilkari.service.SubscriptionService; import org.motechproject.nms.props.domain.DayOfTheWeek; import org.motechproject.nms.props.domain.RequestId; import org.motechproject.scheduler.contract.RepeatingSchedulableJob; import org.motechproject.scheduler.service.MotechSchedulerService; import org.motechproject.server.config.SettingsFacade; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Collections; import java.util.HashMap; import java.util.List; @Service("targetFileService") public class TargetFileServiceImpl implements TargetFileService { private static final String LOCAL_OBD_DIR = "imi.local_obd_dir"; private static final String TARGET_FILE_TIME = "imi.target_file_time"; private static final String MAX_QUERY_BLOCK = "imi.max_query_block"; private static final String TARGET_FILE_SEC_INTERVAL = "imi.target_file_sec_interval"; private static final String TARGET_FILE_NOTIFICATION_URL = "imi.target_file_notification_url"; private static final String TARGET_FILE_CALL_FLOW_URL = "imi.target_file_call_flow_url"; private static final String NORMAL_PRIORITY = "0"; private static final String HIGH_PRIORITY = "1"; private static final String IMI_FRESH_CHECK_DND = "imi.fresh_check_dnd"; private static final String IMI_FRESH_NO_CHECK_DND = "imi.fresh_no_check_dnd"; private static final String IMI_RETRY_CHECK_DND = "imi.retry_check_dnd"; private static final String IMI_RETRY_NO_CHECK_DND = "imi.retry_no_check_dnd"; private static final String IMI_FRESH_CHECK_DND_JH = "imi.fresh_check_dnd_jh"; private static final String IMI_FRESH_NO_CHECK_DND_JH = "imi.fresh_no_check_dnd_jh"; private static final String IMI_RETRY_CHECK_DND_JH = "imi.retry_check_dnd_jh"; private static final String IMI_RETRY_NO_CHECK_DND_JH = "imi.retry_no_check_dnd_jh"; private static final String generateJhFile = "imi.obd_bifurcate"; private static final String Jh = "JH"; private static final String non_Jh = "NON-JH"; private static final int PROGRESS_INTERVAL = 10000; private static final String GENERATE_TARGET_FILE_EVENT = "nms.obd.generate_target_file"; private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormat.forPattern("yyyyMMddHHmmss"); private static final String DEFAULT_CIRCLE = "99"; // https://applab.atlassian.net/browse/NIP-64 public static final String WROTE = "Wrote {}"; private SettingsFacade settingsFacade; private MotechSchedulerService schedulerService; private AlertService alertService; private SubscriptionService subscriptionService; private CallRetryService callRetryService; private FileAuditRecordDataService fileAuditRecordDataService; private static String freshCheckDND; private static String freshNoCheckDND; private static String retryCheckDND; private static String retryNoCheckDND; private static String freshCheckDNDJh; private static String freshNoCheckDNDJh; private static String retryCheckDNDJh; private static String retryNoCheckDNDJh; private static final Logger LOGGER = LoggerFactory.getLogger(TargetFileServiceImpl.class); /** * Use the MOTECH scheduler to setup a repeating job * The job will start today at the time stored in imi.target_file_time in imi.properties * It will repeat every imi.target_file_sec_interval seconds (default value is a day) */ private void scheduleTargetFileGeneration() { //Calculate today's fire time DateTimeFormatter fmt = DateTimeFormat.forPattern("H:m"); String timeProp = settingsFacade.getProperty(TARGET_FILE_TIME); DateTime time = fmt.parseDateTime(timeProp); DateTime today = DateTime.now() // This means today's date... .withHourOfDay(time.getHourOfDay()) // ...at the hour... .withMinuteOfHour(time.getMinuteOfHour()) // ...and minute specified in imi.properties .withSecondOfMinute(0) .withMillisOfSecond(0); //Second interval between events String intervalProp = settingsFacade.getProperty(TARGET_FILE_SEC_INTERVAL); Integer secInterval = Integer.parseInt(intervalProp); if (secInterval < 1) { LOGGER.warn("{} is set to less than 1 second, no repeating schedule will be set to automatically generate " + "target files!", TARGET_FILE_SEC_INTERVAL); return; } LOGGER.debug(String.format("The %s message will be sent every %ss starting %s", GENERATE_TARGET_FILE_EVENT, secInterval.toString(), today.toString())); //Schedule repeating job MotechEvent event = new MotechEvent(GENERATE_TARGET_FILE_EVENT); RepeatingSchedulableJob job = new RepeatingSchedulableJob(event, //MOTECH event null, //repeatCount, null means infinity secInterval, //repeatIntervalInSeconds today.toDate(), //startTime null, //endTime, null means no end time true); //ignorePastFiresAtStart schedulerService.safeScheduleRepeatingJob(job); } @Autowired public TargetFileServiceImpl(@Qualifier("imiSettings") SettingsFacade settingsFacade, MotechSchedulerService schedulerService, AlertService alertService, SubscriptionService subscriptionService, CallRetryService callRetryService, FileAuditRecordDataService fileAuditRecordDataService) { this.schedulerService = schedulerService; this.settingsFacade = settingsFacade; this.alertService = alertService; this.subscriptionService = subscriptionService; this.callRetryService = callRetryService; this.fileAuditRecordDataService = fileAuditRecordDataService; scheduleTargetFileGeneration(); freshCheckDND = settingsFacade.getProperty(IMI_FRESH_CHECK_DND); freshNoCheckDND = settingsFacade.getProperty(IMI_FRESH_NO_CHECK_DND); retryCheckDND = settingsFacade.getProperty(IMI_RETRY_CHECK_DND); retryNoCheckDND = settingsFacade.getProperty(IMI_RETRY_NO_CHECK_DND); freshCheckDNDJh = settingsFacade.getProperty(IMI_FRESH_CHECK_DND_JH); freshNoCheckDNDJh = settingsFacade.getProperty(IMI_FRESH_NO_CHECK_DND_JH); retryCheckDNDJh = settingsFacade.getProperty(IMI_RETRY_CHECK_DND_JH); retryNoCheckDNDJh = settingsFacade.getProperty(IMI_RETRY_NO_CHECK_DND_JH); } public String serviceIdFromOrigin(boolean freshCall, SubscriptionOrigin origin) { if (origin == SubscriptionOrigin.MCTS_IMPORT || origin == SubscriptionOrigin.RCH_IMPORT) { return freshCall ? freshCheckDND : retryCheckDND; } if (origin == SubscriptionOrigin.IVR) { return freshCall ? freshNoCheckDND : retryNoCheckDND; } throw new IllegalStateException("Unexpected SubscriptionOrigin value"); } public String serviceIdFromOriginJh(boolean freshCall, SubscriptionOrigin origin) { if (origin == SubscriptionOrigin.MCTS_IMPORT || origin == SubscriptionOrigin.RCH_IMPORT) { return freshCall ? freshCheckDNDJh : retryCheckDNDJh; } if (origin == SubscriptionOrigin.IVR) { return freshCall ? freshNoCheckDNDJh : retryNoCheckDNDJh; } throw new IllegalStateException("Unexpected SubscriptionOrigin value"); } private String targetFileName(String timestamp) { return String.format("OBD_NMS_%s.csv", timestamp); } // Helper method that makes the code a bit cleaner private void alert(String id, String name, String description) { alertService.create(id, name, description, AlertType.CRITICAL, AlertStatus.NEW, 0, null); } private void writeHeader(OutputStreamWriter writer) throws IOException { /* * #1 RequestId * */ writer.write("RequestId"); writer.write(","); /* * #2 ServiceId * */ writer.write("ServiceId"); writer.write(","); /* * #3 Msisdn * */ writer.write("Msisdn"); writer.write(","); /* * #4 Cli * */ writer.write("Cli"); writer.write(","); /* * #5 Priority * */ writer.write("Priority"); writer.write(","); /* * #6 CallFlowURL * */ writer.write("CallFlowURL"); writer.write(","); /* * #7 ContentFileName * */ writer.write("ContentFileName"); writer.write(","); /* * #8 WeekId * */ writer.write("WeekId"); writer.write(","); /* * #9 LanguageLocationCode * */ writer.write("LanguageLocationCode"); writer.write(","); /* * #10 Circle * */ writer.write("Circle"); writer.write(","); /* * #11 subscription mode * */ writer.write("SubscriptionOrigin"); writer.write("\n"); } private void writeSubscriptionRow(String requestId, String serviceId, // NO CHECKSTYLE More than 7 parameters String msisdn, String priority, String callFlowUrl, String contentFileName, String weekId, String languageLocationCode, String circle, String subscriptionOrigin, OutputStreamWriter writer) throws IOException { /* * #1 RequestId * * A unique Request id for each obd record */ writer.write(requestId); writer.write(","); /* * #2 ServiceId * * Unique Id provided by IMImobile for a particular service */ writer.write(serviceId); writer.write(","); /* * #3 Msisdn * * 10 digit number to be dialed out */ writer.write(msisdn); writer.write(","); /* * #4 Cli * * 10 Digit number to be displayed as CLI for the call. If left blank, the default CLI of the service * shall be picked up. */ writer.write(""); // No idea why/what that field is: let's write nothing writer.write(","); /* * #5 Priority * * Specifies the priority with which the call is to be made. By default value is 0. * Possible Values: 0-Default, 1-Medium Priority, 2-High Priority */ writer.write(priority); //todo: priorities, what do we want to do? writer.write(","); /* * #6 CallFlowURL * * The URL of the VXML flow. If unspecified, default VXML URL specified for the service shall be picked up */ writer.write(callFlowUrl); writer.write(","); /* * #7 ContentFileName * * Content file to be played */ writer.write(contentFileName); writer.write(","); /* * #8 WeekId * * Week id of the messaged delivered in OBD */ writer.write(weekId); writer.write(","); /* * #9 LanguageLocationCode * * To identify the language */ writer.write(languageLocationCode); writer.write(","); /* * #10 Circle * * Circle of the beneficiary. */ if (circle != null && !circle.isEmpty()) { writer.write(circle); } else { writer.write(DEFAULT_CIRCLE); } writer.write(","); /* * #11 subscription mode * * I for IVR origin, M for MCTS origin */ writer.write(subscriptionOrigin); writer.write("\n"); } private HashMap<String, Integer> generateFreshCalls(DateTime timestamp, int maxQueryBlock, String callFlowUrl, HashMap<String, OutputStreamWriter> wr, List<String> subscriptionIdsJh, boolean split) throws IOException { LOGGER.info("generateFreshCallsObd({})", timestamp); int skippedrecords = 0; DayOfTheWeek dow = DayOfTheWeek.fromDateTime(timestamp); HashMap<String, Integer> recordsMap = new HashMap<>(); int recordsWritten = 0; int recordsWrittenJh = 0; Long offset = 0L; do { List<Subscription> subscriptions = subscriptionService.findActiveSubscriptionsForDay(dow, offset, maxQueryBlock); LOGGER.info("Subs_block_size" + subscriptions.size()); if (subscriptions.size() == 0) { break; } for (Subscription subscription : subscriptions) { LOGGER.debug("Handling Subscription " + subscription.getId()); offset = subscription.getId(); Subscriber subscriber = subscription.getSubscriber(); RequestId requestId = new RequestId(subscription.getSubscriptionId(), TIME_FORMATTER.print(timestamp)); try { SubscriptionPack pack = subscription.getSubscriptionPack(); int daysIntoPack = Days.daysBetween(subscription.getStartDate(), timestamp).getDays(); if (daysIntoPack == pack.getWeeks() * 7) { // // Do not add subscriptions on their last day to the fresh call list since we // will try to fetch message for current +1 week, which wouldn't exist // See https://applab.atlassian.net/browse/NMS-301 // LOGGER.debug("Ignoring last day for subscription {} from fresh calls.", subscription.getSubscriptionId()); skippedrecords++; continue; } SubscriptionPackMessage msg = subscription.nextScheduledMessage(timestamp); if(split && subscriptionIdsJh.contains(subscription.getSubscriptionId())) { writeSubscriptionRow( requestId.toString(), serviceIdFromOriginJh(true, subscription.getOrigin()), subscriber.getCallingNumber().toString(), HIGH_PRIORITY, //todo: how do we choose a priority? callFlowUrl, msg.getMessageFileName(), msg.getWeekId(), // we are happy with empty language and circle since they are optional subscriber.getLanguage() == null ? "" : subscriber.getLanguage().getCode(), subscriber.getCircle() == null ? "" : subscriber.getCircle().getName(), subscription.getOrigin().getCode(), wr.get(Jh)); recordsWrittenJh++; } else { writeSubscriptionRow( requestId.toString(), serviceIdFromOrigin(true, subscription.getOrigin()), subscriber.getCallingNumber().toString(), NORMAL_PRIORITY, //todo: how do we choose a priority? callFlowUrl, msg.getMessageFileName(), msg.getWeekId(), // we are happy with empty language and circle since they are optional subscriber.getLanguage() == null ? "" : subscriber.getLanguage().getCode(), subscriber.getCircle() == null ? "" : subscriber.getCircle().getName(), subscription.getOrigin().getCode(), wr.get(non_Jh)); recordsWritten++; } } catch (IllegalStateException se) { String message = se.toString(); alertService.create(subscription.getSubscriptionId(), "IllegalStateException", message, AlertType.HIGH, AlertStatus.NEW, 0, null); LOGGER.error(message,se); } } } while (true); LOGGER.info(WROTE+non_Jh, recordsWritten); recordsMap.put(non_Jh, recordsWritten); if(split){ LOGGER.info(WROTE+Jh, recordsWrittenJh); recordsMap.put(Jh, recordsWrittenJh); } return recordsMap; } private HashMap<String, Integer> generateRetryCalls(DateTime timestamp, int maxQueryBlock, String callFlowUrl, HashMap<String, OutputStreamWriter> wr, List<String> subscriptionIdsJh, boolean split) throws IOException { LOGGER.info("generateRetryCallsObd({})", timestamp); int count = 0; int countJh = 0; HashMap<String, Integer> retryCount = new HashMap<>(); Long offset = 0L; do { // All calls are rescheduled for the next day which means that we should query for all CallRetry records List<CallRetry> callRetries = callRetryService.retrieveAll(offset, maxQueryBlock); LOGGER.info("Call_Retries"+callRetries.size()); if (callRetries.size() == 0) { break; } for (CallRetry callRetry : callRetries) { offset = callRetry.getId(); RequestId requestId = new RequestId(callRetry.getSubscriptionId(), TIME_FORMATTER.print(timestamp)); if(split && subscriptionIdsJh.contains(callRetry.getSubscriptionId())) { writeSubscriptionRow( requestId.toString(), serviceIdFromOriginJh(false, callRetry.getSubscriptionOrigin()), callRetry.getMsisdn().toString(), HIGH_PRIORITY, callFlowUrl, callRetry.getContentFileName(), callRetry.getWeekId(), callRetry.getLanguageLocationCode(), callRetry.getCircle(), callRetry.getSubscriptionOrigin().getCode(), wr.get(Jh)); countJh++; } else { writeSubscriptionRow( requestId.toString(), serviceIdFromOrigin(false, callRetry.getSubscriptionOrigin()), callRetry.getMsisdn().toString(), NORMAL_PRIORITY, callFlowUrl, callRetry.getContentFileName(), callRetry.getWeekId(), callRetry.getLanguageLocationCode(), callRetry.getCircle(), callRetry.getSubscriptionOrigin().getCode(), wr.get(non_Jh)); count++; } } } while (true); LOGGER.info(WROTE+non_Jh+"Retry", count); retryCount.put(non_Jh, count); if(split) { LOGGER.info(WROTE+Jh+"Retry", countJh); retryCount.put(Jh, countJh); } return retryCount; } private File localObdDir() { return new File(settingsFacade.getProperty(LOCAL_OBD_DIR)); } @Transactional public HashMap<String, TargetFileNotification> generateTargetFile(boolean split) { LOGGER.info("generateTargetFile()"); DateTime today = DateTime.now(); String targetFileName = targetFileName(TIME_FORMATTER.print(today)); File localTargetDir = localObdDir(); String checksum; File targetFile = new File(localTargetDir, targetFileName); HashMap<String, Integer> recordCount; HashMap<String, Integer> recordCountRetry; int maxQueryBlock = Integer.parseInt(settingsFacade.getProperty(MAX_QUERY_BLOCK)); String callFlowUrl = settingsFacade.getProperty(TARGET_FILE_CALL_FLOW_URL); if (callFlowUrl == null) { //it's ok to have an empty call flow url - the spec says the default call flow will be used //whatever that is... callFlowUrl = ""; } HashMap<String, OutputStreamWriter> wr = new HashMap<>(); HashMap<String, TargetFileNotification> tfn = new HashMap<>(); if(split){ String targetFileNameJh = targetFileName(TIME_FORMATTER.print(today)+"JH"); File localTargetDirJh = localObdDir(); String checksumJh; File targetFileJh = new File(localTargetDirJh, targetFileNameJh); try { FileOutputStream fos = new FileOutputStream(targetFile); OutputStreamWriter writer = new OutputStreamWriter(fos); FileOutputStream fosJh = new FileOutputStream(targetFileJh); OutputStreamWriter writerJh = new OutputStreamWriter(fosJh); //Header writeHeader(writer); writeHeader(writerJh); List<String> subscriptionIdsJh = subscriptionService.findJhSubscriptionIds(); LOGGER.info("JH-Subscriptions-Number"+subscriptionIdsJh.size()); wr.put(Jh, writerJh); wr.put(non_Jh, writer); //Fresh calls recordCount = generateFreshCalls(today, maxQueryBlock, callFlowUrl, wr, subscriptionIdsJh, true); //Retry calls recordCountRetry = generateRetryCalls(today, maxQueryBlock, callFlowUrl, wr, subscriptionIdsJh, true); writer.close(); fos.close(); writerJh.close(); fosJh.close(); checksum = ChecksumHelper.checksum(targetFile); checksumJh = ChecksumHelper.checksum(targetFileJh); tfn.put(Jh, new TargetFileNotification(targetFileNameJh, checksumJh, recordCount.get(Jh)+recordCountRetry.get(Jh))); } catch (IOException e) { LOGGER.error(e.getMessage(),e); alert(targetFile.toString(), "targetFile", e.getMessage()); fileAuditRecordDataService.create(new FileAuditRecord(FileType.TARGET_FILE, targetFile.getName(), false, e.getMessage(), null, null)); return null; } } else{ try { FileOutputStream fos = new FileOutputStream(targetFile); OutputStreamWriter writer = new OutputStreamWriter(fos); //Header writeHeader(writer); wr.put(non_Jh, writer); //Fresh calls recordCount = generateFreshCalls(today, maxQueryBlock, callFlowUrl, wr, Collections.emptyList(), false); //Retry calls recordCountRetry = generateRetryCalls(today, maxQueryBlock, callFlowUrl, wr, Collections.emptyList(), false); writer.close(); fos.close(); checksum = ChecksumHelper.checksum(targetFile); } catch (IOException e) { LOGGER.error(e.getMessage(),e); alert(targetFile.toString(), "targetFile", e.getMessage()); fileAuditRecordDataService.create(new FileAuditRecord(FileType.TARGET_FILE, targetFile.getName(), false, e.getMessage(), null, null)); return null; } } tfn.put(non_Jh, new TargetFileNotification(targetFileName, checksum, recordCount.get(non_Jh)+recordCountRetry.get(non_Jh))); LOGGER.debug("TargetFileNotification = {}", tfn.toString()); //audit the success for(TargetFileNotification t: tfn.values()) { fileAuditRecordDataService.create(new FileAuditRecord(FileType.TARGET_FILE, t.getFileName(), true, null, t.getRecordsCount(), t.getChecksum())); } return tfn; } private void sendNotificationRequest(TargetFileNotification tfn) { String notificationUrl = settingsFacade.getProperty(TARGET_FILE_NOTIFICATION_URL); LOGGER.debug("Sending {} to {}", tfn, notificationUrl); ExponentialRetrySender sender = new ExponentialRetrySender(settingsFacade, alertService); HttpPost httpPost = new HttpPost(notificationUrl); ObjectMapper mapper = new ObjectMapper(); try { String requestJson = mapper.writeValueAsString(tfn); httpPost.setHeader("Content-type", "application/json"); httpPost.setHeader("Accept", "application/json"); httpPost.setEntity(new StringEntity(requestJson)); } catch (IOException e) { throw new InternalException(String.format("Unable to create targetFile notification request: %s", e.getMessage()), e); } sender.sendNotificationRequest(httpPost, HttpStatus.SC_ACCEPTED, tfn.getFileName(), "targetFile Notification Request"); } @MotechListener(subjects = { GENERATE_TARGET_FILE_EVENT }) @Transactional public void generateTargetFile(MotechEvent event) { LOGGER.debug(event.toString()); HashMap<String, TargetFileNotification> tfn = generateTargetFile(Boolean.valueOf(settingsFacade.getProperty(generateJhFile))); if (tfn != null) { // Copy the OBD file from the local imi.local_obd_dir to the remote imi.local_obd_dir network share ScpHelper scpHelper = new ScpHelper(settingsFacade); for(TargetFileNotification t: tfn.values()) { try { scpHelper.scpObdToRemote(t.getFileName()); } catch (ExecException e) { String error = String.format("Error copying target file %s: %s", t.getFileName(), e.getMessage()); LOGGER.error(error,e); fileAuditRecordDataService.create(new FileAuditRecord( FileType.TARGET_FILE, t.getFileName(), false, error, null, null )); alert(t.getFileName(), "targetFileName", error); return; } //notify the IVR system the file is ready sendNotificationRequest(t); } } } /** * Log & audit the fact that IMI processed the OBD file (successfully or not) * * @param request file name & status */ @Override public void handleFileProcessedStatusNotification(FileProcessedStatusRequest request) { fileAuditRecordDataService.create(new FileAuditRecord( FileType.TARGET_FILE, request.getFileName(), request.getFileProcessedStatus() == FileProcessedStatus.FILE_PROCESSED_SUCCESSFULLY, request.getFileProcessedStatus().getName(), null, null )); if (request.getFileProcessedStatus() != FileProcessedStatus.FILE_PROCESSED_SUCCESSFULLY) { LOGGER.error(request.toString()); //todo: IT check if alert was created alert(request.getFileName(), "targetFileName", String.format("Target File Processing Error: %s", request.getFailureReason())); } } }
imi/src/main/java/org/motechproject/nms/imi/service/impl/TargetFileServiceImpl.java
package org.motechproject.nms.imi.service.impl; import org.apache.commons.httpclient.HttpStatus; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import com.fasterxml.jackson.databind.ObjectMapper; import org.joda.time.DateTime; import org.joda.time.Days; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.motechproject.alerts.contract.AlertService; import org.motechproject.alerts.domain.AlertStatus; import org.motechproject.alerts.domain.AlertType; import org.motechproject.event.MotechEvent; import org.motechproject.event.listener.annotations.MotechListener; import org.motechproject.metrics.service.Timer; import org.motechproject.nms.imi.domain.FileAuditRecord; import org.motechproject.nms.imi.domain.FileProcessedStatus; import org.motechproject.nms.imi.domain.FileType; import org.motechproject.nms.imi.exception.ExecException; import org.motechproject.nms.imi.exception.InternalException; import org.motechproject.nms.imi.repository.FileAuditRecordDataService; import org.motechproject.nms.imi.service.TargetFileService; import org.motechproject.nms.imi.service.contract.TargetFileNotification; import org.motechproject.nms.imi.web.contract.FileProcessedStatusRequest; import org.motechproject.nms.kilkari.domain.CallRetry; import org.motechproject.nms.kilkari.domain.Subscriber; import org.motechproject.nms.kilkari.domain.Subscription; import org.motechproject.nms.kilkari.domain.SubscriptionOrigin; import org.motechproject.nms.kilkari.domain.SubscriptionPack; import org.motechproject.nms.kilkari.domain.SubscriptionPackMessage; import org.motechproject.nms.kilkari.service.CallRetryService; import org.motechproject.nms.kilkari.service.SubscriptionService; import org.motechproject.nms.props.domain.DayOfTheWeek; import org.motechproject.nms.props.domain.RequestId; import org.motechproject.scheduler.contract.RepeatingSchedulableJob; import org.motechproject.scheduler.service.MotechSchedulerService; import org.motechproject.server.config.SettingsFacade; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Collections; import java.util.HashMap; import java.util.List; @Service("targetFileService") public class TargetFileServiceImpl implements TargetFileService { private static final String LOCAL_OBD_DIR = "imi.local_obd_dir"; private static final String TARGET_FILE_TIME = "imi.target_file_time"; private static final String MAX_QUERY_BLOCK = "imi.max_query_block"; private static final String TARGET_FILE_SEC_INTERVAL = "imi.target_file_sec_interval"; private static final String TARGET_FILE_NOTIFICATION_URL = "imi.target_file_notification_url"; private static final String TARGET_FILE_CALL_FLOW_URL = "imi.target_file_call_flow_url"; private static final String NORMAL_PRIORITY = "0"; private static final String IMI_FRESH_CHECK_DND = "imi.fresh_check_dnd"; private static final String IMI_FRESH_NO_CHECK_DND = "imi.fresh_no_check_dnd"; private static final String IMI_RETRY_CHECK_DND = "imi.retry_check_dnd"; private static final String IMI_RETRY_NO_CHECK_DND = "imi.retry_no_check_dnd"; private static final String IMI_FRESH_CHECK_DND_JH = "imi.fresh_check_dnd_jh"; private static final String IMI_FRESH_NO_CHECK_DND_JH = "imi.fresh_no_check_dnd_jh"; private static final String IMI_RETRY_CHECK_DND_JH = "imi.retry_check_dnd_jh"; private static final String IMI_RETRY_NO_CHECK_DND_JH = "imi.retry_no_check_dnd_jh"; private static final String generateJhFile = "imi.obd_bifurcate"; private static final String Jh = "JH"; private static final String non_Jh = "NON-JH"; private static final int PROGRESS_INTERVAL = 10000; private static final String GENERATE_TARGET_FILE_EVENT = "nms.obd.generate_target_file"; private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormat.forPattern("yyyyMMddHHmmss"); private static final String DEFAULT_CIRCLE = "99"; // https://applab.atlassian.net/browse/NIP-64 public static final String WROTE = "Wrote {}"; private SettingsFacade settingsFacade; private MotechSchedulerService schedulerService; private AlertService alertService; private SubscriptionService subscriptionService; private CallRetryService callRetryService; private FileAuditRecordDataService fileAuditRecordDataService; private static String freshCheckDND; private static String freshNoCheckDND; private static String retryCheckDND; private static String retryNoCheckDND; private static String freshCheckDNDJh; private static String freshNoCheckDNDJh; private static String retryCheckDNDJh; private static String retryNoCheckDNDJh; private static final Logger LOGGER = LoggerFactory.getLogger(TargetFileServiceImpl.class); /** * Use the MOTECH scheduler to setup a repeating job * The job will start today at the time stored in imi.target_file_time in imi.properties * It will repeat every imi.target_file_sec_interval seconds (default value is a day) */ private void scheduleTargetFileGeneration() { //Calculate today's fire time DateTimeFormatter fmt = DateTimeFormat.forPattern("H:m"); String timeProp = settingsFacade.getProperty(TARGET_FILE_TIME); DateTime time = fmt.parseDateTime(timeProp); DateTime today = DateTime.now() // This means today's date... .withHourOfDay(time.getHourOfDay()) // ...at the hour... .withMinuteOfHour(time.getMinuteOfHour()) // ...and minute specified in imi.properties .withSecondOfMinute(0) .withMillisOfSecond(0); //Second interval between events String intervalProp = settingsFacade.getProperty(TARGET_FILE_SEC_INTERVAL); Integer secInterval = Integer.parseInt(intervalProp); if (secInterval < 1) { LOGGER.warn("{} is set to less than 1 second, no repeating schedule will be set to automatically generate " + "target files!", TARGET_FILE_SEC_INTERVAL); return; } LOGGER.debug(String.format("The %s message will be sent every %ss starting %s", GENERATE_TARGET_FILE_EVENT, secInterval.toString(), today.toString())); //Schedule repeating job MotechEvent event = new MotechEvent(GENERATE_TARGET_FILE_EVENT); RepeatingSchedulableJob job = new RepeatingSchedulableJob(event, //MOTECH event null, //repeatCount, null means infinity secInterval, //repeatIntervalInSeconds today.toDate(), //startTime null, //endTime, null means no end time true); //ignorePastFiresAtStart schedulerService.safeScheduleRepeatingJob(job); } @Autowired public TargetFileServiceImpl(@Qualifier("imiSettings") SettingsFacade settingsFacade, MotechSchedulerService schedulerService, AlertService alertService, SubscriptionService subscriptionService, CallRetryService callRetryService, FileAuditRecordDataService fileAuditRecordDataService) { this.schedulerService = schedulerService; this.settingsFacade = settingsFacade; this.alertService = alertService; this.subscriptionService = subscriptionService; this.callRetryService = callRetryService; this.fileAuditRecordDataService = fileAuditRecordDataService; scheduleTargetFileGeneration(); freshCheckDND = settingsFacade.getProperty(IMI_FRESH_CHECK_DND); freshNoCheckDND = settingsFacade.getProperty(IMI_FRESH_NO_CHECK_DND); retryCheckDND = settingsFacade.getProperty(IMI_RETRY_CHECK_DND); retryNoCheckDND = settingsFacade.getProperty(IMI_RETRY_NO_CHECK_DND); freshCheckDNDJh = settingsFacade.getProperty(IMI_FRESH_CHECK_DND_JH); freshNoCheckDNDJh = settingsFacade.getProperty(IMI_FRESH_NO_CHECK_DND_JH); retryCheckDNDJh = settingsFacade.getProperty(IMI_RETRY_CHECK_DND_JH); retryNoCheckDNDJh = settingsFacade.getProperty(IMI_RETRY_NO_CHECK_DND_JH); } public String serviceIdFromOrigin(boolean freshCall, SubscriptionOrigin origin) { if (origin == SubscriptionOrigin.MCTS_IMPORT || origin == SubscriptionOrigin.RCH_IMPORT) { return freshCall ? freshCheckDND : retryCheckDND; } if (origin == SubscriptionOrigin.IVR) { return freshCall ? freshNoCheckDND : retryNoCheckDND; } throw new IllegalStateException("Unexpected SubscriptionOrigin value"); } public String serviceIdFromOriginJh(boolean freshCall, SubscriptionOrigin origin) { if (origin == SubscriptionOrigin.MCTS_IMPORT || origin == SubscriptionOrigin.RCH_IMPORT) { return freshCall ? freshCheckDNDJh : retryCheckDNDJh; } if (origin == SubscriptionOrigin.IVR) { return freshCall ? freshNoCheckDNDJh : retryNoCheckDNDJh; } throw new IllegalStateException("Unexpected SubscriptionOrigin value"); } private String targetFileName(String timestamp) { return String.format("OBD_NMS_%s.csv", timestamp); } // Helper method that makes the code a bit cleaner private void alert(String id, String name, String description) { alertService.create(id, name, description, AlertType.CRITICAL, AlertStatus.NEW, 0, null); } private void writeHeader(OutputStreamWriter writer) throws IOException { /* * #1 RequestId * */ writer.write("RequestId"); writer.write(","); /* * #2 ServiceId * */ writer.write("ServiceId"); writer.write(","); /* * #3 Msisdn * */ writer.write("Msisdn"); writer.write(","); /* * #4 Cli * */ writer.write("Cli"); writer.write(","); /* * #5 Priority * */ writer.write("Priority"); writer.write(","); /* * #6 CallFlowURL * */ writer.write("CallFlowURL"); writer.write(","); /* * #7 ContentFileName * */ writer.write("ContentFileName"); writer.write(","); /* * #8 WeekId * */ writer.write("WeekId"); writer.write(","); /* * #9 LanguageLocationCode * */ writer.write("LanguageLocationCode"); writer.write(","); /* * #10 Circle * */ writer.write("Circle"); writer.write(","); /* * #11 subscription mode * */ writer.write("SubscriptionOrigin"); writer.write("\n"); } private void writeSubscriptionRow(String requestId, String serviceId, // NO CHECKSTYLE More than 7 parameters String msisdn, String priority, String callFlowUrl, String contentFileName, String weekId, String languageLocationCode, String circle, String subscriptionOrigin, OutputStreamWriter writer) throws IOException { /* * #1 RequestId * * A unique Request id for each obd record */ writer.write(requestId); writer.write(","); /* * #2 ServiceId * * Unique Id provided by IMImobile for a particular service */ writer.write(serviceId); writer.write(","); /* * #3 Msisdn * * 10 digit number to be dialed out */ writer.write(msisdn); writer.write(","); /* * #4 Cli * * 10 Digit number to be displayed as CLI for the call. If left blank, the default CLI of the service * shall be picked up. */ writer.write(""); // No idea why/what that field is: let's write nothing writer.write(","); /* * #5 Priority * * Specifies the priority with which the call is to be made. By default value is 0. * Possible Values: 0-Default, 1-Medium Priority, 2-High Priority */ writer.write(priority); //todo: priorities, what do we want to do? writer.write(","); /* * #6 CallFlowURL * * The URL of the VXML flow. If unspecified, default VXML URL specified for the service shall be picked up */ writer.write(callFlowUrl); writer.write(","); /* * #7 ContentFileName * * Content file to be played */ writer.write(contentFileName); writer.write(","); /* * #8 WeekId * * Week id of the messaged delivered in OBD */ writer.write(weekId); writer.write(","); /* * #9 LanguageLocationCode * * To identify the language */ writer.write(languageLocationCode); writer.write(","); /* * #10 Circle * * Circle of the beneficiary. */ if (circle != null && !circle.isEmpty()) { writer.write(circle); } else { writer.write(DEFAULT_CIRCLE); } writer.write(","); /* * #11 subscription mode * * I for IVR origin, M for MCTS origin */ writer.write(subscriptionOrigin); writer.write("\n"); } private HashMap<String, Integer> generateFreshCalls(DateTime timestamp, int maxQueryBlock, String callFlowUrl, HashMap<String, OutputStreamWriter> wr, List<String> subscriptionIdsJh, boolean split) throws IOException { LOGGER.info("generateFreshCallsObd({})", timestamp); int skippedrecords = 0; DayOfTheWeek dow = DayOfTheWeek.fromDateTime(timestamp); HashMap<String, Integer> recordsMap = new HashMap<>(); int recordsWritten = 0; int recordsWrittenJh = 0; Long offset = 0L; do { List<Subscription> subscriptions = subscriptionService.findActiveSubscriptionsForDay(dow, offset, maxQueryBlock); LOGGER.info("Subs_block_size" + subscriptions.size()); if (subscriptions.size() == 0) { break; } for (Subscription subscription : subscriptions) { LOGGER.debug("Handling Subscription " + subscription.getId()); offset = subscription.getId(); Subscriber subscriber = subscription.getSubscriber(); RequestId requestId = new RequestId(subscription.getSubscriptionId(), TIME_FORMATTER.print(timestamp)); try { SubscriptionPack pack = subscription.getSubscriptionPack(); int daysIntoPack = Days.daysBetween(subscription.getStartDate(), timestamp).getDays(); if (daysIntoPack == pack.getWeeks() * 7) { // // Do not add subscriptions on their last day to the fresh call list since we // will try to fetch message for current +1 week, which wouldn't exist // See https://applab.atlassian.net/browse/NMS-301 // LOGGER.debug("Ignoring last day for subscription {} from fresh calls.", subscription.getSubscriptionId()); skippedrecords++; continue; } SubscriptionPackMessage msg = subscription.nextScheduledMessage(timestamp); if(split && subscriptionIdsJh.contains(subscription.getSubscriptionId())) { writeSubscriptionRow( requestId.toString(), serviceIdFromOriginJh(true, subscription.getOrigin()), subscriber.getCallingNumber().toString(), NORMAL_PRIORITY, //todo: how do we choose a priority? callFlowUrl, msg.getMessageFileName(), msg.getWeekId(), // we are happy with empty language and circle since they are optional subscriber.getLanguage() == null ? "" : subscriber.getLanguage().getCode(), subscriber.getCircle() == null ? "" : subscriber.getCircle().getName(), subscription.getOrigin().getCode(), wr.get(Jh)); recordsWrittenJh++; } else { writeSubscriptionRow( requestId.toString(), serviceIdFromOrigin(true, subscription.getOrigin()), subscriber.getCallingNumber().toString(), NORMAL_PRIORITY, //todo: how do we choose a priority? callFlowUrl, msg.getMessageFileName(), msg.getWeekId(), // we are happy with empty language and circle since they are optional subscriber.getLanguage() == null ? "" : subscriber.getLanguage().getCode(), subscriber.getCircle() == null ? "" : subscriber.getCircle().getName(), subscription.getOrigin().getCode(), wr.get(non_Jh)); recordsWritten++; } } catch (IllegalStateException se) { String message = se.toString(); alertService.create(subscription.getSubscriptionId(), "IllegalStateException", message, AlertType.HIGH, AlertStatus.NEW, 0, null); LOGGER.error(message,se); } } } while (true); LOGGER.info(WROTE+non_Jh, recordsWritten); recordsMap.put(non_Jh, recordsWritten); if(split){ LOGGER.info(WROTE+Jh, recordsWrittenJh); recordsMap.put(Jh, recordsWrittenJh); } return recordsMap; } private HashMap<String, Integer> generateRetryCalls(DateTime timestamp, int maxQueryBlock, String callFlowUrl, HashMap<String, OutputStreamWriter> wr, List<String> subscriptionIdsJh, boolean split) throws IOException { LOGGER.info("generateRetryCallsObd({})", timestamp); int count = 0; int countJh = 0; HashMap<String, Integer> retryCount = new HashMap<>(); Long offset = 0L; do { // All calls are rescheduled for the next day which means that we should query for all CallRetry records List<CallRetry> callRetries = callRetryService.retrieveAll(offset, maxQueryBlock); LOGGER.info("Call_Retries"+callRetries.size()); if (callRetries.size() == 0) { break; } for (CallRetry callRetry : callRetries) { offset = callRetry.getId(); RequestId requestId = new RequestId(callRetry.getSubscriptionId(), TIME_FORMATTER.print(timestamp)); if(split && subscriptionIdsJh.contains(callRetry.getSubscriptionId())) { writeSubscriptionRow( requestId.toString(), serviceIdFromOriginJh(false, callRetry.getSubscriptionOrigin()), callRetry.getMsisdn().toString(), NORMAL_PRIORITY, callFlowUrl, callRetry.getContentFileName(), callRetry.getWeekId(), callRetry.getLanguageLocationCode(), callRetry.getCircle(), callRetry.getSubscriptionOrigin().getCode(), wr.get(Jh)); countJh++; } else { writeSubscriptionRow( requestId.toString(), serviceIdFromOrigin(false, callRetry.getSubscriptionOrigin()), callRetry.getMsisdn().toString(), NORMAL_PRIORITY, callFlowUrl, callRetry.getContentFileName(), callRetry.getWeekId(), callRetry.getLanguageLocationCode(), callRetry.getCircle(), callRetry.getSubscriptionOrigin().getCode(), wr.get(non_Jh)); count++; } } } while (true); LOGGER.info(WROTE+non_Jh+"Retry", count); retryCount.put(non_Jh, count); if(split) { LOGGER.info(WROTE+Jh+"Retry", countJh); retryCount.put(Jh, countJh); } return retryCount; } private File localObdDir() { return new File(settingsFacade.getProperty(LOCAL_OBD_DIR)); } @Transactional public HashMap<String, TargetFileNotification> generateTargetFile(boolean split) { LOGGER.info("generateTargetFile()"); DateTime today = DateTime.now(); String targetFileName = targetFileName(TIME_FORMATTER.print(today)); File localTargetDir = localObdDir(); String checksum; File targetFile = new File(localTargetDir, targetFileName); HashMap<String, Integer> recordCount; HashMap<String, Integer> recordCountRetry; int maxQueryBlock = Integer.parseInt(settingsFacade.getProperty(MAX_QUERY_BLOCK)); String callFlowUrl = settingsFacade.getProperty(TARGET_FILE_CALL_FLOW_URL); if (callFlowUrl == null) { //it's ok to have an empty call flow url - the spec says the default call flow will be used //whatever that is... callFlowUrl = ""; } HashMap<String, OutputStreamWriter> wr = new HashMap<>(); HashMap<String, TargetFileNotification> tfn = new HashMap<>(); if(split){ String targetFileNameJh = targetFileName(TIME_FORMATTER.print(today)+"JH"); File localTargetDirJh = localObdDir(); String checksumJh; File targetFileJh = new File(localTargetDirJh, targetFileNameJh); try { FileOutputStream fos = new FileOutputStream(targetFile); OutputStreamWriter writer = new OutputStreamWriter(fos); FileOutputStream fosJh = new FileOutputStream(targetFileJh); OutputStreamWriter writerJh = new OutputStreamWriter(fosJh); //Header writeHeader(writer); writeHeader(writerJh); List<String> subscriptionIdsJh = subscriptionService.findJhSubscriptionIds(); LOGGER.info("JH-Subscriptions-Number"+subscriptionIdsJh.size()); wr.put(Jh, writerJh); wr.put(non_Jh, writer); //Fresh calls recordCount = generateFreshCalls(today, maxQueryBlock, callFlowUrl, wr, subscriptionIdsJh, true); //Retry calls recordCountRetry = generateRetryCalls(today, maxQueryBlock, callFlowUrl, wr, subscriptionIdsJh, true); writer.close(); fos.close(); writerJh.close(); fosJh.close(); checksum = ChecksumHelper.checksum(targetFile); checksumJh = ChecksumHelper.checksum(targetFileJh); tfn.put(Jh, new TargetFileNotification(targetFileNameJh, checksumJh, recordCount.get(Jh)+recordCountRetry.get(Jh))); } catch (IOException e) { LOGGER.error(e.getMessage(),e); alert(targetFile.toString(), "targetFile", e.getMessage()); fileAuditRecordDataService.create(new FileAuditRecord(FileType.TARGET_FILE, targetFile.getName(), false, e.getMessage(), null, null)); return null; } } else{ try { FileOutputStream fos = new FileOutputStream(targetFile); OutputStreamWriter writer = new OutputStreamWriter(fos); //Header writeHeader(writer); wr.put(non_Jh, writer); //Fresh calls recordCount = generateFreshCalls(today, maxQueryBlock, callFlowUrl, wr, Collections.emptyList(), false); //Retry calls recordCountRetry = generateRetryCalls(today, maxQueryBlock, callFlowUrl, wr, Collections.emptyList(), false); writer.close(); fos.close(); checksum = ChecksumHelper.checksum(targetFile); } catch (IOException e) { LOGGER.error(e.getMessage(),e); alert(targetFile.toString(), "targetFile", e.getMessage()); fileAuditRecordDataService.create(new FileAuditRecord(FileType.TARGET_FILE, targetFile.getName(), false, e.getMessage(), null, null)); return null; } } tfn.put(non_Jh, new TargetFileNotification(targetFileName, checksum, recordCount.get(non_Jh)+recordCountRetry.get(non_Jh))); LOGGER.debug("TargetFileNotification = {}", tfn.toString()); //audit the success for(TargetFileNotification t: tfn.values()) { fileAuditRecordDataService.create(new FileAuditRecord(FileType.TARGET_FILE, t.getFileName(), true, null, t.getRecordsCount(), t.getChecksum())); } return tfn; } private void sendNotificationRequest(TargetFileNotification tfn) { String notificationUrl = settingsFacade.getProperty(TARGET_FILE_NOTIFICATION_URL); LOGGER.debug("Sending {} to {}", tfn, notificationUrl); ExponentialRetrySender sender = new ExponentialRetrySender(settingsFacade, alertService); HttpPost httpPost = new HttpPost(notificationUrl); ObjectMapper mapper = new ObjectMapper(); try { String requestJson = mapper.writeValueAsString(tfn); httpPost.setHeader("Content-type", "application/json"); httpPost.setHeader("Accept", "application/json"); httpPost.setEntity(new StringEntity(requestJson)); } catch (IOException e) { throw new InternalException(String.format("Unable to create targetFile notification request: %s", e.getMessage()), e); } sender.sendNotificationRequest(httpPost, HttpStatus.SC_ACCEPTED, tfn.getFileName(), "targetFile Notification Request"); } @MotechListener(subjects = { GENERATE_TARGET_FILE_EVENT }) @Transactional public void generateTargetFile(MotechEvent event) { LOGGER.debug(event.toString()); HashMap<String, TargetFileNotification> tfn = generateTargetFile(Boolean.valueOf(settingsFacade.getProperty(generateJhFile))); if (tfn != null) { // Copy the OBD file from the local imi.local_obd_dir to the remote imi.local_obd_dir network share ScpHelper scpHelper = new ScpHelper(settingsFacade); for(TargetFileNotification t: tfn.values()) { try { scpHelper.scpObdToRemote(t.getFileName()); } catch (ExecException e) { String error = String.format("Error copying target file %s: %s", t.getFileName(), e.getMessage()); LOGGER.error(error,e); fileAuditRecordDataService.create(new FileAuditRecord( FileType.TARGET_FILE, t.getFileName(), false, error, null, null )); alert(t.getFileName(), "targetFileName", error); return; } //notify the IVR system the file is ready sendNotificationRequest(t); } } } /** * Log & audit the fact that IMI processed the OBD file (successfully or not) * * @param request file name & status */ @Override public void handleFileProcessedStatusNotification(FileProcessedStatusRequest request) { fileAuditRecordDataService.create(new FileAuditRecord( FileType.TARGET_FILE, request.getFileName(), request.getFileProcessedStatus() == FileProcessedStatus.FILE_PROCESSED_SUCCESSFULLY, request.getFileProcessedStatus().getName(), null, null )); if (request.getFileProcessedStatus() != FileProcessedStatus.FILE_PROCESSED_SUCCESSFULLY) { LOGGER.error(request.toString()); //todo: IT check if alert was created alert(request.getFileName(), "targetFileName", String.format("Target File Processing Error: %s", request.getFailureReason())); } } }
setting high priority for Jhu obd records
imi/src/main/java/org/motechproject/nms/imi/service/impl/TargetFileServiceImpl.java
setting high priority for Jhu obd records
Java
mit
68727a3c96e41c6b2d36419c10b441c7ae4756a9
0
jongerrish/robolectric,jongerrish/robolectric,spotify/robolectric,spotify/robolectric,jongerrish/robolectric,jongerrish/robolectric,spotify/robolectric
package org.robolectric.shadows; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiEnterpriseConfig; import android.os.Build; import java.util.BitSet; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.annotation.RealObject; @Implements(WifiConfiguration.class) public class ShadowWifiConfiguration { @RealObject private WifiConfiguration realObject; public WifiConfiguration copy() { WifiConfiguration config = new WifiConfiguration(); config.networkId = realObject.networkId; config.SSID = realObject.SSID; config.BSSID = realObject.BSSID; config.preSharedKey = realObject.preSharedKey; config.wepTxKeyIndex = realObject.wepTxKeyIndex; config.status = realObject.status; config.priority = realObject.priority; config.hiddenSSID = realObject.hiddenSSID; config.allowedKeyManagement = (BitSet) realObject.allowedKeyManagement.clone(); config.allowedProtocols = (BitSet) realObject.allowedProtocols.clone(); config.allowedAuthAlgorithms = (BitSet) realObject.allowedAuthAlgorithms.clone(); config.allowedPairwiseCiphers = (BitSet) realObject.allowedPairwiseCiphers.clone(); config.allowedGroupCiphers = (BitSet) realObject.allowedGroupCiphers.clone(); config.wepKeys = new String[4]; System.arraycopy(realObject.wepKeys, 0, config.wepKeys, 0, config.wepKeys.length); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { config.creatorName = realObject.creatorName; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { config.creatorUid = realObject.creatorUid; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { config.enterpriseConfig = realObject.enterpriseConfig != null ? new WifiEnterpriseConfig(realObject.enterpriseConfig) : null; } return config; } // WifiConfiguration's toString() method crashes. @Override @Implementation public String toString() { return String.format("WifiConfiguration{ssid=%s}", realObject.SSID); } }
shadows/framework/src/main/java/org/robolectric/shadows/ShadowWifiConfiguration.java
package org.robolectric.shadows; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiEnterpriseConfig; import android.os.Build; import java.util.BitSet; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.annotation.RealObject; @Implements(WifiConfiguration.class) public class ShadowWifiConfiguration { @RealObject private WifiConfiguration realObject; @Implementation public void __constructor__() { realObject.networkId = -1; realObject.SSID = null; realObject.BSSID = null; realObject.priority = 0; realObject.hiddenSSID = false; realObject.allowedKeyManagement = new BitSet(); realObject.allowedProtocols = new BitSet(); realObject.allowedAuthAlgorithms = new BitSet(); realObject.allowedPairwiseCiphers = new BitSet(); realObject.allowedGroupCiphers = new BitSet(); realObject.wepKeys = new String[4]; for (int i = 0; i < realObject.wepKeys.length; i++) realObject.wepKeys[i] = null; // for (EnterpriseField field : realObject.enterpriseFields) { // field.setValue(null); // } } public WifiConfiguration copy() { WifiConfiguration config = new WifiConfiguration(); config.networkId = realObject.networkId; config.SSID = realObject.SSID; config.BSSID = realObject.BSSID; config.preSharedKey = realObject.preSharedKey; config.wepTxKeyIndex = realObject.wepTxKeyIndex; config.status = realObject.status; config.priority = realObject.priority; config.hiddenSSID = realObject.hiddenSSID; config.allowedKeyManagement = (BitSet) realObject.allowedKeyManagement.clone(); config.allowedProtocols = (BitSet) realObject.allowedProtocols.clone(); config.allowedAuthAlgorithms = (BitSet) realObject.allowedAuthAlgorithms.clone(); config.allowedPairwiseCiphers = (BitSet) realObject.allowedPairwiseCiphers.clone(); config.allowedGroupCiphers = (BitSet) realObject.allowedGroupCiphers.clone(); config.wepKeys = new String[4]; System.arraycopy(realObject.wepKeys, 0, config.wepKeys, 0, config.wepKeys.length); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { config.creatorName = realObject.creatorName; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { config.creatorUid = realObject.creatorUid; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { config.enterpriseConfig = realObject.enterpriseConfig != null ? new WifiEnterpriseConfig(realObject.enterpriseConfig) : null; } return config; } // WifiConfiguration's toString() method crashes. @Override @Implementation public String toString() { return String.format("WifiConfiguration{ssid=%s}", realObject.SSID); } }
Remove customized WifiConfiguration constructor in the ShadowWifiConfiguration The customized constructor is actually a subset of the original constructor. It is failing tests because the customized constructor doesn't set all fields, such as mIPConfiguration. PiperOrigin-RevId: 195809456
shadows/framework/src/main/java/org/robolectric/shadows/ShadowWifiConfiguration.java
Remove customized WifiConfiguration constructor in the ShadowWifiConfiguration
Java
mit
473e46ae178c574f2e8bed36c548d1291a256c73
0
greatman/legendarybot
/* * MIT License * * Copyright (c) Copyright (c) 2017-2017, Greatmancode * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.greatmancode.legendarybot.commands.ilvl; import com.greatmancode.legendarybot.api.commands.PublicCommand; import com.greatmancode.legendarybot.api.plugin.LegendaryBotPlugin; import com.greatmancode.legendarybot.api.utils.BattleNetAPIInterceptor; import com.greatmancode.legendarybot.api.utils.HeroClass; import com.greatmancode.legendarybot.api.utils.HeroRace; import com.greatmancode.legendarybot.api.utils.WoWUtils; import com.greatmancode.legendarybot.plugins.wowlink.utils.WowCommand; import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; import okhttp3.ConnectionPool; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.Request; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.pf4j.PluginWrapper; import java.io.IOException; import java.util.Map; import java.util.NavigableMap; import java.util.TreeMap; import java.util.concurrent.TimeUnit; /** * The !lookup command */ public class IlvlCommand extends LegendaryBotPlugin implements WowCommand, PublicCommand { /** * The OKHttp client */ private final OkHttpClient client = new OkHttpClient.Builder() .build(); OkHttpClient clientBattleNet = new OkHttpClient.Builder() .addInterceptor(new BattleNetAPIInterceptor(getBot())) .connectionPool(new ConnectionPool(300, 1, TimeUnit.SECONDS)) .build(); public IlvlCommand(PluginWrapper wrapper) { super(wrapper); } @Override public void start() { getBot().getCommandHandler().addCommand("lookup", this, "World of Warcraft"); getBot().getCommandHandler().addAlias("ilvl", "lookup"); getBot().getCommandHandler().addAlias("mplusrank", "lookup"); getBot().getCommandHandler().addAlias("raidrank", "lookup"); log.info("command !ilvl loaded"); } @Override public void stop() { getBot().getCommandHandler().removeCommand("lookup"); getBot().getCommandHandler().removeAlias("ilvl"); getBot().getCommandHandler().removeAlias("mplusrank"); getBot().getCommandHandler().removeAlias("raidrank"); log.info("command !ilvl unloaded"); } public void execute(MessageReceivedEvent event, String[] args) { String serverName = null; String region = null; try { if (args.length == 1) { serverName = getBot().getGuildSettings(event.getGuild()).getWowServerName(); region = getBot().getGuildSettings(event.getGuild()).getRegionName(); } else if (args.length == 2){ serverName = args[1]; region = getBot().getGuildSettings(event.getGuild()).getRegionName(); } else { //We got a long server name potentially if (args[args.length - 1].equalsIgnoreCase("US") || args[args.length - 1].equalsIgnoreCase("EU")) { //Last argument is the region, taking the rest for the realm info String[] argsend = new String[args.length - 2]; System.arraycopy(args,1,argsend,0,args.length - 2); StringBuilder builder = new StringBuilder(); for(String s : argsend) { builder.append(" ").append(s); } serverName = builder.toString().trim(); region = args[args.length - 1]; } else { String[] argsend = new String[args.length - 1]; System.arraycopy(args,1,argsend,0,args.length - 1); StringBuilder builder = new StringBuilder(); for(String s : argsend) { builder.append(" ").append(s); } serverName = builder.toString().trim(); region = getBot().getGuildSettings(event.getGuild()).getRegionName(); } } String realmData = WoWUtils.getRealmInformation(getBot(),region,serverName); if (realmData == null) { event.getChannel().sendMessage("Realm not found! Did you make a typo?").queue(); return; } JSONParser parser = new JSONParser(); JSONObject realmInformation = (JSONObject) parser.parse(realmData); String serverSlug = (String) realmInformation.get("slug"); HttpUrl url = new HttpUrl.Builder().scheme("https") .host("raider.io") .addPathSegments("api/v1/characters/profile") .addQueryParameter("region", region) .addQueryParameter("realm", serverSlug) .addQueryParameter("name", args[0]) .addQueryParameter("fields", "gear,raid_progression,mythic_plus_scores,previous_mythic_plus_scores,mythic_plus_best_runs") .build(); Request request = new Request.Builder().url(url).build(); String result = client.newCall(request).execute().body().string(); if (result != null) { JSONObject jsonObject = (JSONObject) parser.parse(result); if (!jsonObject.containsKey("error")) { EmbedBuilder eb = new EmbedBuilder(); if (jsonObject.get("name").equals("Pepyte") && jsonObject.get("realm").equals("Arthas")) { eb.setThumbnail("https://lumiere-a.akamaihd.net/v1/images/b5e11dc889c5696799a6bd3ec5d819c1f7dfe8b4.jpeg"); } else if (jsonObject.get("name").equals("Xdntgivitoya") && jsonObject.get("realm").equals("Arthas")) { eb.setThumbnail("https://cdn.discordapp.com/attachments/239729214004133889/389452254823841792/20171210_112359.jpg"); } else { eb.setThumbnail(jsonObject.get("thumbnail_url").toString()); } String className = jsonObject.get("class").toString().toLowerCase(); eb.setColor(WoWUtils.getClassColor(className)); StringBuilder titleBuilder = new StringBuilder(); titleBuilder.append(jsonObject.get("name")); titleBuilder.append(" "); titleBuilder.append(jsonObject.get("realm")); titleBuilder.append(" - "); titleBuilder.append(((String) jsonObject.get("region")).toUpperCase()); titleBuilder.append(" | "); titleBuilder.append(jsonObject.get("race")); titleBuilder.append(" "); titleBuilder.append(jsonObject.get("active_spec_name")); titleBuilder.append(" "); titleBuilder.append(jsonObject.get("class")); String wowLink = null; if (((String) jsonObject.get("region")).equalsIgnoreCase("us")) { wowLink = "https://worldofwarcraft.com/en-us/character/" + serverSlug + "/" + jsonObject.get("name"); } else { wowLink = "https://worldofwarcraft.com/en-gb/character/" + serverSlug + "/" + jsonObject.get("name"); } eb.setTitle(titleBuilder.toString(), wowLink); StringBuilder progressionBuilder = new StringBuilder(); JSONObject raidProgression = (JSONObject) jsonObject.get("raid_progression"); JSONObject emeraldNightmare = (JSONObject) raidProgression.get("the-emerald-nightmare"); JSONObject trialOfValor = (JSONObject) raidProgression.get("trial-of-valor"); JSONObject theNighthold = (JSONObject) raidProgression.get("the-nighthold"); JSONObject tombOfSargeras = (JSONObject) raidProgression.get("tomb-of-sargeras"); JSONObject antorus = (JSONObject) raidProgression.get("antorus-the-burning-throne"); progressionBuilder.append("**EN**: "); progressionBuilder.append(emeraldNightmare.get("summary")); progressionBuilder.append(" - "); progressionBuilder.append("**ToV**:"); progressionBuilder.append(trialOfValor.get("summary")); progressionBuilder.append(" - "); progressionBuilder.append("**NH**: "); progressionBuilder.append(theNighthold.get("summary")); progressionBuilder.append(" - "); progressionBuilder.append("**ToS**: "); progressionBuilder.append(tombOfSargeras.get("summary")); progressionBuilder.append("\n"); progressionBuilder.append("**Antorus**: "); progressionBuilder.append(antorus.get("summary")); eb.addField("Progression", progressionBuilder.toString(), false); //We fetch the Battle.net achivement record HttpUrl battleneturl = new HttpUrl.Builder().scheme("https") .host(region + ".api.battle.net") .addPathSegments("wow/character/"+serverSlug+"/" +args[0]) .addQueryParameter("fields", "achievements") .build(); Request battlenetRequest = new Request.Builder().url(battleneturl).build(); String battlenetResult = clientBattleNet.newCall(battlenetRequest).execute().body().string(); String apAmount = getAP(battlenetResult); JSONObject gear = (JSONObject) jsonObject.get("gear"); eb.addField("iLVL", gear.get("item_level_equipped") + "/" + gear.get("item_level_total"), true); if (apAmount != null) { eb.addField("Artifact Power", gear.get("artifact_traits").toString() + " / " + apAmount + " AP Gathered", true); } else { eb.addField("Artifact Power", gear.get("artifact_traits").toString(), true); } JSONObject mplusRank = (JSONObject) jsonObject.get("mythic_plus_scores"); eb.addField("Mythic+ Score", mplusRank.get("all").toString(), true); JSONObject lastMplusRank = (JSONObject) jsonObject.get("previous_mythic_plus_scores"); eb.addField("Last Season Mythic+ Score", lastMplusRank.get("all").toString(), true); StringBuilder runsBuilder = new StringBuilder(); JSONArray bestRuns = (JSONArray) jsonObject.get("mythic_plus_best_runs"); for (Object runObject : bestRuns) { JSONObject run = (JSONObject) runObject; runsBuilder.append("["); runsBuilder.append(run.get("dungeon")); runsBuilder.append(" **+"); runsBuilder.append(run.get("mythic_level")); runsBuilder.append("**]("); runsBuilder.append(run.get("url")); runsBuilder.append(")\n"); long time = (long) run.get("clear_time_ms"); long hours = TimeUnit.MILLISECONDS.toHours(time); long minutes = TimeUnit.MILLISECONDS.toMinutes(time); long seconds = TimeUnit.MILLISECONDS.toSeconds(time) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time)); runsBuilder.append(" "); if (hours >= 1) { runsBuilder.append(String.format("%d Hour(s) %d Minute(s), %d seconds", hours, minutes, seconds)); } else { runsBuilder.append(String.format("%d Minute(s), %d seconds", minutes, seconds)); } runsBuilder.append(" | "); runsBuilder.append(run.get("num_keystone_upgrades").toString()); runsBuilder.append(" Chest(s)\n\n"); } eb.addField("Best Mythic+ Runs", runsBuilder.toString(), false); eb.addField("WoWProgress", "[Click Here](https://www.wowprogress.com/character/"+region.toLowerCase()+"/"+serverSlug+"/"+jsonObject.get("name") + ")", true); eb.addField("Raider.IO", "[Click Here](https://raider.io/characters/"+region.toLowerCase()+"/"+serverSlug+"/"+jsonObject.get("name") + ")", true); eb.addField("WarcraftLogs","[Click Here](https://www.warcraftlogs.com/character/"+region.toLowerCase()+"/"+serverSlug+"/"+jsonObject.get("name") + ")", true); eb.setFooter("Information taken from https://raider.io",null); event.getChannel().sendMessage(eb.build()).queue(); } else { //We got an error from raider.io, maybe he was never added to the site. Let's try through battle.net HttpUrl battleneturl = new HttpUrl.Builder().scheme("https") .host(region + ".api.battle.net") .addPathSegments("wow/character/"+serverSlug+"/" +args[0]) .addQueryParameter("fields", "progression,items,achievements") .build(); Request battlenetRequest = new Request.Builder().url(battleneturl).build(); String battlenetResult = clientBattleNet.newCall(battlenetRequest).execute().body().string(); JSONObject battleNetObject = (JSONObject) parser.parse(battlenetResult); if (battleNetObject.containsKey("status")) { //Error event.getChannel().sendMessage("Character not found. Did you make an error?").queue(); return; } StringBuilder titleBuilder = new StringBuilder(); titleBuilder.append(battleNetObject.get("name")); titleBuilder.append(" "); titleBuilder.append(battleNetObject.get("realm")); titleBuilder.append(" - "); titleBuilder.append(region.toUpperCase()); titleBuilder.append(" | "); titleBuilder.append(HeroRace.values()[((Long) battleNetObject.get("race")).intValue()]); titleBuilder.append(" "); titleBuilder.append(HeroClass.values()[((Long) battleNetObject.get("class")).intValue()]); titleBuilder.append(" "); //event.getChannel().sendMessage(jsonObject.get("message").toString()).queue(); String wowLink = null; if (((String) jsonObject.get("region")).equalsIgnoreCase("us")) { wowLink = "https://worldofwarcraft.com/en-us/character/" + serverSlug + "/" + jsonObject.get("name"); } else { wowLink = "https://worldofwarcraft.com/en-gb/character/" + serverSlug + "/" + jsonObject.get("name"); } EmbedBuilder eb = new EmbedBuilder(); eb.setTitle(titleBuilder.toString(), wowLink); //http://render-api-us.worldofwarcraft.com/static-render/us/arthas/169/156057769-avatar.jpg http://render-us.worldofwarcraft.com/character/arthas/169/156057769-avatar.jpg System.out.println("http://render-" + region.toLowerCase() + ".worldofwarcraft.com/character/" + battleNetObject.get("thumbnail")); eb.setThumbnail("http://render-" + region.toLowerCase() + ".worldofwarcraft.com/character/" + battleNetObject.get("thumbnail")); String apAmount = getAP(battlenetResult); JSONObject gear = (JSONObject) battleNetObject.get("items"); eb.addField("iLVL", gear.get("averageItemLevelEquipped") + "/" + gear.get("averageItemLevel"), true); if (apAmount != null) { eb.addField("Artifact Power", apAmount + " AP Gathered", true); } eb.addField("WoWProgress", "[Click Here](https://www.wowprogress.com/character/"+region.toLowerCase()+"/"+serverSlug+"/"+battleNetObject.get("name") + ")", true); eb.addField("Raider.IO", "[Click Here](https://raider.io/characters/"+region.toLowerCase()+"/"+serverSlug+"/"+battleNetObject.get("name") + ")", true); eb.addField("WarcraftLogs","[Click Here](https://www.warcraftlogs.com/character/"+region.toLowerCase()+"/"+serverSlug+"/"+battleNetObject.get("name") + ")", true); eb.addField("Information", "Your character is not found on Raider.io. Limited information is available. Add it [Here](https://raider.io/add).", false); eb.setFooter("Information taken from https://us.battle.net/wow",null); event.getChannel().sendMessage(eb.build()).queue(); return; } } } catch (IOException e) { getBot().getStacktraceHandler().sendStacktrace(e, "serverName:" + serverName); event.getChannel().sendMessage("An error occured. Try again later!").queue(); } catch (ParseException e) { e.printStackTrace(); getBot().getStacktraceHandler().sendStacktrace(e, "serverName:" + serverName); event.getChannel().sendMessage("An error occured. Try again later!").queue(); } } public int minArgs() { return 1; } public int maxArgs() { return 99; } public String help() { return "Lookup a World of Warcraft character statistics.\n" + "**Format**: ``!lookup <Character Name> <Server Name> <Region>``\n\n" + "__Parameters__\n" + "**Character Name** (Required/Optional): A World of Warcraft character Name. This parameter is required if you don't have a main character set in this Discord server. Optional if you have one.\n" + "**Server Name** (Optional): The World of Warcraft realm you want to search on. If omitted, will take this Discord's default server.\n" + "**Region** (Optional): The Region you want to do the search in. If omitted, will take this Discord's default server.\n\n" + "**Example**: ``!lookup Kugruon Arthas US``"; } @Override public String shortDescription() { return "Lookup a character information (iLVL/Raid Progression/Mythic+)"; } private static final NavigableMap<Long, String> suffixes = new TreeMap<>(); static { suffixes.put(1_000L, "k"); suffixes.put(1_000_000L, " Million(s)"); suffixes.put(1_000_000_000L, " Billion(s)"); suffixes.put(1_000_000_000_000L, " Trillion(s)"); suffixes.put(1_000_000_000_000_000L, " Quadrillion(s)"); suffixes.put(1_000_000_000_000_000_000L, " Quintillion(s)"); } public static String format(long value) { //Long.MIN_VALUE == -Long.MIN_VALUE so we need an adjustment here if (value == Long.MIN_VALUE) return format(Long.MIN_VALUE + 1); if (value < 0) return "-" + format(-value); if (value < 1000) return Long.toString(value); //deal with easy case Map.Entry<Long, String> e = suffixes.floorEntry(value); Long divideBy = e.getKey(); String suffix = e.getValue(); long truncated = value / (divideBy / 10); //the number part of the output times 10 boolean hasDecimal = truncated < 100 && (truncated / 10d) != (truncated / 10); return hasDecimal ? (truncated / 10d) + suffix : (truncated / 10) + suffix; } public String getAP(String json) throws ParseException { long apAmount = -1; if (json != null) { JSONParser parser = new JSONParser(); JSONObject battleNetCharacter = (JSONObject) parser.parse(json); JSONObject achivements = (JSONObject) battleNetCharacter.get("achievements"); JSONArray criteriaObject = (JSONArray) achivements.get("criteria"); int criteriaNumber = -1; for (int i = 0; i < criteriaObject.size(); i++) { if ((long)criteriaObject.get(i) == 30103) { criteriaNumber = i; } } if (criteriaNumber != -1) { apAmount = (long) ((JSONArray)achivements.get("criteriaQuantity")).get(criteriaNumber); } } String result = null; if (apAmount != -1) { result = format(apAmount); } return result; } }
ilvlcommand/src/main/java/com/greatmancode/legendarybot/commands/ilvl/IlvlCommand.java
/* * MIT License * * Copyright (c) Copyright (c) 2017-2017, Greatmancode * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.greatmancode.legendarybot.commands.ilvl; import com.greatmancode.legendarybot.api.commands.PublicCommand; import com.greatmancode.legendarybot.api.plugin.LegendaryBotPlugin; import com.greatmancode.legendarybot.api.utils.BattleNetAPIInterceptor; import com.greatmancode.legendarybot.api.utils.HeroClass; import com.greatmancode.legendarybot.api.utils.HeroRace; import com.greatmancode.legendarybot.api.utils.WoWUtils; import com.greatmancode.legendarybot.plugins.wowlink.utils.WowCommand; import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; import okhttp3.ConnectionPool; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.Request; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.pf4j.PluginWrapper; import java.io.IOException; import java.util.Map; import java.util.NavigableMap; import java.util.TreeMap; import java.util.concurrent.TimeUnit; /** * The !lookup command */ public class IlvlCommand extends LegendaryBotPlugin implements WowCommand, PublicCommand { /** * The OKHttp client */ private final OkHttpClient client = new OkHttpClient.Builder() .build(); OkHttpClient clientBattleNet = new OkHttpClient.Builder() .addInterceptor(new BattleNetAPIInterceptor(getBot())) .connectionPool(new ConnectionPool(300, 1, TimeUnit.SECONDS)) .build(); public IlvlCommand(PluginWrapper wrapper) { super(wrapper); } @Override public void start() { getBot().getCommandHandler().addCommand("lookup", this, "World of Warcraft"); getBot().getCommandHandler().addAlias("ilvl", "lookup"); getBot().getCommandHandler().addAlias("mplusrank", "lookup"); getBot().getCommandHandler().addAlias("raidrank", "lookup"); log.info("command !ilvl loaded"); } @Override public void stop() { getBot().getCommandHandler().removeCommand("lookup"); getBot().getCommandHandler().removeAlias("ilvl"); getBot().getCommandHandler().removeAlias("mplusrank"); getBot().getCommandHandler().removeAlias("raidrank"); log.info("command !ilvl unloaded"); } public void execute(MessageReceivedEvent event, String[] args) { String serverName = null; String region = null; try { if (args.length == 1) { serverName = getBot().getGuildSettings(event.getGuild()).getWowServerName(); region = getBot().getGuildSettings(event.getGuild()).getRegionName(); } else if (args.length == 2){ serverName = args[1]; region = getBot().getGuildSettings(event.getGuild()).getRegionName(); } else { //We got a long server name potentially if (args[args.length - 1].equalsIgnoreCase("US") || args[args.length - 1].equalsIgnoreCase("EU")) { //Last argument is the region, taking the rest for the realm info String[] argsend = new String[args.length - 2]; System.arraycopy(args,1,argsend,0,args.length - 2); StringBuilder builder = new StringBuilder(); for(String s : argsend) { builder.append(" ").append(s); } serverName = builder.toString().trim(); region = args[args.length - 1]; } else { String[] argsend = new String[args.length - 1]; System.arraycopy(args,1,argsend,0,args.length - 1); StringBuilder builder = new StringBuilder(); for(String s : argsend) { builder.append(" ").append(s); } serverName = builder.toString().trim(); region = getBot().getGuildSettings(event.getGuild()).getRegionName(); } } String realmData = WoWUtils.getRealmInformation(getBot(),region,serverName); if (realmData == null) { event.getChannel().sendMessage("Realm not found! Did you make a typo?").queue(); return; } JSONParser parser = new JSONParser(); JSONObject realmInformation = (JSONObject) parser.parse(realmData); String serverSlug = (String) realmInformation.get("slug"); HttpUrl url = new HttpUrl.Builder().scheme("https") .host("raider.io") .addPathSegments("api/v1/characters/profile") .addQueryParameter("region", region) .addQueryParameter("realm", serverSlug) .addQueryParameter("name", args[0]) .addQueryParameter("fields", "gear,raid_progression,mythic_plus_scores,previous_mythic_plus_scores,mythic_plus_best_runs") .build(); Request request = new Request.Builder().url(url).build(); String result = client.newCall(request).execute().body().string(); if (result != null) { JSONObject jsonObject = (JSONObject) parser.parse(result); if (!jsonObject.containsKey("error")) { EmbedBuilder eb = new EmbedBuilder(); if (jsonObject.get("name").equals("Pepyte") && jsonObject.get("realm").equals("Arthas")) { eb.setThumbnail("https://lumiere-a.akamaihd.net/v1/images/b5e11dc889c5696799a6bd3ec5d819c1f7dfe8b4.jpeg"); } else if (jsonObject.get("name").equals("Xdntgivitoya") && jsonObject.get("realm").equals("Arthas")) { eb.setThumbnail("https://cdn.discordapp.com/attachments/239729214004133889/389452254823841792/20171210_112359.jpg"); } else { eb.setThumbnail(jsonObject.get("thumbnail_url").toString()); } String className = jsonObject.get("class").toString().toLowerCase(); eb.setColor(WoWUtils.getClassColor(className)); StringBuilder titleBuilder = new StringBuilder(); titleBuilder.append(jsonObject.get("name")); titleBuilder.append(" "); titleBuilder.append(jsonObject.get("realm")); titleBuilder.append(" - "); titleBuilder.append(((String) jsonObject.get("region")).toUpperCase()); titleBuilder.append(" | "); titleBuilder.append(jsonObject.get("race")); titleBuilder.append(" "); titleBuilder.append(jsonObject.get("active_spec_name")); titleBuilder.append(" "); titleBuilder.append(jsonObject.get("class")); String wowLink = null; if (((String) jsonObject.get("region")).equalsIgnoreCase("us")) { wowLink = "https://worldofwarcraft.com/en-us/character/" + serverSlug + "/" + jsonObject.get("name"); } else { wowLink = "https://worldofwarcraft.com/en-gb/character/" + serverSlug + "/" + jsonObject.get("name"); } eb.setTitle(titleBuilder.toString(), wowLink); StringBuilder progressionBuilder = new StringBuilder(); JSONObject raidProgression = (JSONObject) jsonObject.get("raid_progression"); JSONObject emeraldNightmare = (JSONObject) raidProgression.get("the-emerald-nightmare"); JSONObject trialOfValor = (JSONObject) raidProgression.get("trial-of-valor"); JSONObject theNighthold = (JSONObject) raidProgression.get("the-nighthold"); JSONObject tombOfSargeras = (JSONObject) raidProgression.get("tomb-of-sargeras"); JSONObject antorus = (JSONObject) raidProgression.get("antorus-the-burning-throne"); progressionBuilder.append("**EN**: "); progressionBuilder.append(emeraldNightmare.get("summary")); progressionBuilder.append(" - "); progressionBuilder.append("**ToV**:"); progressionBuilder.append(trialOfValor.get("summary")); progressionBuilder.append(" - "); progressionBuilder.append("**NH**: "); progressionBuilder.append(theNighthold.get("summary")); progressionBuilder.append(" - "); progressionBuilder.append("**ToS**: "); progressionBuilder.append(tombOfSargeras.get("summary")); progressionBuilder.append("\n"); progressionBuilder.append("**Antorus**: "); progressionBuilder.append(antorus.get("summary")); eb.addField("Progression", progressionBuilder.toString(), false); //We fetch the Battle.net achivement record HttpUrl battleneturl = new HttpUrl.Builder().scheme("https") .host(region + ".api.battle.net") .addPathSegments("wow/character/"+serverSlug+"/" +args[0]) .addQueryParameter("fields", "achievements") .build(); Request battlenetRequest = new Request.Builder().url(battleneturl).build(); String battlenetResult = clientBattleNet.newCall(battlenetRequest).execute().body().string(); String apAmount = getAP(battlenetResult); JSONObject gear = (JSONObject) jsonObject.get("gear"); eb.addField("iLVL", gear.get("item_level_equipped") + "/" + gear.get("item_level_total"), true); if (apAmount != null) { eb.addField("Artifact Power", gear.get("artifact_traits").toString() + " / " + apAmount + " AP Gathered", true); } else { eb.addField("Artifact Power", gear.get("artifact_traits").toString(), true); } JSONObject mplusRank = (JSONObject) jsonObject.get("mythic_plus_scores"); eb.addField("Mythic+ Score", mplusRank.get("all").toString(), true); JSONObject lastMplusRank = (JSONObject) jsonObject.get("previous_mythic_plus_scores"); eb.addField("Last Season Mythic+ Score", lastMplusRank.get("all").toString(), true); StringBuilder runsBuilder = new StringBuilder(); JSONArray bestRuns = (JSONArray) jsonObject.get("mythic_plus_best_runs"); for (Object runObject : bestRuns) { JSONObject run = (JSONObject) runObject; runsBuilder.append("["); runsBuilder.append(run.get("dungeon")); runsBuilder.append(" **+"); runsBuilder.append(run.get("mythic_level")); runsBuilder.append("**]("); runsBuilder.append(run.get("url")); runsBuilder.append(")\n"); long time = (long) run.get("clear_time_ms"); long hours = TimeUnit.MILLISECONDS.toHours(time); long minutes = TimeUnit.MILLISECONDS.toMinutes(time); long seconds = TimeUnit.MILLISECONDS.toSeconds(time) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time)); runsBuilder.append(" "); if (hours >= 1) { runsBuilder.append(String.format("%d Hour(s) %d Minute(s), %d seconds", hours, minutes, seconds)); } else { runsBuilder.append(String.format("%d Minute(s), %d seconds", minutes, seconds)); } runsBuilder.append(" | "); runsBuilder.append(run.get("num_keystone_upgrades").toString()); runsBuilder.append(" Chest(s)\n\n"); } eb.addField("Best Mythic+ Runs", runsBuilder.toString(), false); eb.addField("WoWProgress", "[Click Here](https://www.wowprogress.com/character/"+region.toLowerCase()+"/"+serverSlug+"/"+jsonObject.get("name") + ")", true); eb.addField("Raider.IO", "[Click Here](https://raider.io/characters/"+region.toLowerCase()+"/"+serverSlug+"/"+jsonObject.get("name") + ")", true); eb.addField("WarcraftLogs","[Click Here](https://www.warcraftlogs.com/character/"+region.toLowerCase()+"/"+serverSlug+"/"+jsonObject.get("name") + ")", true); eb.setFooter("Information taken from https://raider.io",null); event.getChannel().sendMessage(eb.build()).queue(); } else { //We got an error from raider.io, maybe he was never added to the site. Let's try through battle.net HttpUrl battleneturl = new HttpUrl.Builder().scheme("https") .host(region + ".api.battle.net") .addPathSegments("wow/character/"+serverSlug+"/" +args[0]) .addQueryParameter("fields", "progression,items,achievements") .build(); Request battlenetRequest = new Request.Builder().url(battleneturl).build(); String battlenetResult = clientBattleNet.newCall(battlenetRequest).execute().body().string(); JSONObject battleNetObject = (JSONObject) parser.parse(battlenetResult); if (battleNetObject.containsKey("status")) { //Error event.getChannel().sendMessage("Character not found. Did you make an error?").queue(); return; } StringBuilder titleBuilder = new StringBuilder(); titleBuilder.append(battleNetObject.get("name")); titleBuilder.append(" "); titleBuilder.append(battleNetObject.get("realm")); titleBuilder.append(" - "); titleBuilder.append(region.toUpperCase()); titleBuilder.append(" | "); titleBuilder.append(HeroRace.values()[((Long) battleNetObject.get("race")).intValue()]); titleBuilder.append(" "); titleBuilder.append(HeroClass.values()[((Long) battleNetObject.get("class")).intValue()]); titleBuilder.append(" "); //event.getChannel().sendMessage(jsonObject.get("message").toString()).queue(); String wowLink = null; if (((String) jsonObject.get("region")).equalsIgnoreCase("us")) { wowLink = "https://worldofwarcraft.com/en-us/character/" + serverSlug + "/" + jsonObject.get("name"); } else { wowLink = "https://worldofwarcraft.com/en-gb/character/" + serverSlug + "/" + jsonObject.get("name"); } EmbedBuilder eb = new EmbedBuilder(); eb.setTitle(titleBuilder.toString(), wowLink); //http://render-api-us.worldofwarcraft.com/static-render/us/arthas/169/156057769-avatar.jpg System.out.println("http://render-api-" + region.toLowerCase() + ".worldofwarcraft.com/static-render/" + region.toLowerCase() + "/" + battleNetObject.get("thumbnail")); eb.setThumbnail("http://render-api-" + region.toLowerCase() + ".worldofwarcraft.com/static-render/" + region.toLowerCase() + "/" + battleNetObject.get("thumbnail")); String apAmount = getAP(battlenetResult); JSONObject gear = (JSONObject) battleNetObject.get("items"); eb.addField("iLVL", gear.get("averageItemLevelEquipped") + "/" + gear.get("averageItemLevel"), true); if (apAmount != null) { eb.addField("Artifact Power", apAmount + " AP Gathered", true); } eb.addField("WoWProgress", "[Click Here](https://www.wowprogress.com/character/"+region.toLowerCase()+"/"+serverSlug+"/"+battleNetObject.get("name") + ")", true); eb.addField("Raider.IO", "[Click Here](https://raider.io/characters/"+region.toLowerCase()+"/"+serverSlug+"/"+battleNetObject.get("name") + ")", true); eb.addField("WarcraftLogs","[Click Here](https://www.warcraftlogs.com/character/"+region.toLowerCase()+"/"+serverSlug+"/"+battleNetObject.get("name") + ")", true); eb.addField("Information", "Your character is not found on Raider.io. Limited information is available. Add it [Here](https://raider.io/add).", false); eb.setFooter("Information taken from https://us.battle.net/wow",null); event.getChannel().sendMessage(eb.build()).queue(); return; } } } catch (IOException e) { getBot().getStacktraceHandler().sendStacktrace(e, "serverName:" + serverName); event.getChannel().sendMessage("An error occured. Try again later!").queue(); } catch (ParseException e) { e.printStackTrace(); getBot().getStacktraceHandler().sendStacktrace(e, "serverName:" + serverName); event.getChannel().sendMessage("An error occured. Try again later!").queue(); } } public int minArgs() { return 1; } public int maxArgs() { return 99; } public String help() { return "Lookup a World of Warcraft character statistics.\n" + "**Format**: ``!lookup <Character Name> <Server Name> <Region>``\n\n" + "__Parameters__\n" + "**Character Name** (Required/Optional): A World of Warcraft character Name. This parameter is required if you don't have a main character set in this Discord server. Optional if you have one.\n" + "**Server Name** (Optional): The World of Warcraft realm you want to search on. If omitted, will take this Discord's default server.\n" + "**Region** (Optional): The Region you want to do the search in. If omitted, will take this Discord's default server.\n\n" + "**Example**: ``!lookup Kugruon Arthas US``"; } @Override public String shortDescription() { return "Lookup a character information (iLVL/Raid Progression/Mythic+)"; } private static final NavigableMap<Long, String> suffixes = new TreeMap<>(); static { suffixes.put(1_000L, "k"); suffixes.put(1_000_000L, " Million(s)"); suffixes.put(1_000_000_000L, " Billion(s)"); suffixes.put(1_000_000_000_000L, " Trillion(s)"); suffixes.put(1_000_000_000_000_000L, " Quadrillion(s)"); suffixes.put(1_000_000_000_000_000_000L, " Quintillion(s)"); } public static String format(long value) { //Long.MIN_VALUE == -Long.MIN_VALUE so we need an adjustment here if (value == Long.MIN_VALUE) return format(Long.MIN_VALUE + 1); if (value < 0) return "-" + format(-value); if (value < 1000) return Long.toString(value); //deal with easy case Map.Entry<Long, String> e = suffixes.floorEntry(value); Long divideBy = e.getKey(); String suffix = e.getValue(); long truncated = value / (divideBy / 10); //the number part of the output times 10 boolean hasDecimal = truncated < 100 && (truncated / 10d) != (truncated / 10); return hasDecimal ? (truncated / 10d) + suffix : (truncated / 10) + suffix; } public String getAP(String json) throws ParseException { long apAmount = -1; if (json != null) { JSONParser parser = new JSONParser(); JSONObject battleNetCharacter = (JSONObject) parser.parse(json); JSONObject achivements = (JSONObject) battleNetCharacter.get("achievements"); JSONArray criteriaObject = (JSONArray) achivements.get("criteria"); int criteriaNumber = -1; for (int i = 0; i < criteriaObject.size(); i++) { if ((long)criteriaObject.get(i) == 30103) { criteriaNumber = i; } } if (criteriaNumber != -1) { apAmount = (long) ((JSONArray)achivements.get("criteriaQuantity")).get(criteriaNumber); } } String result = null; if (apAmount != -1) { result = format(apAmount); } return result; } }
Change URL for the avatar. Was using the old one.
ilvlcommand/src/main/java/com/greatmancode/legendarybot/commands/ilvl/IlvlCommand.java
Change URL for the avatar. Was using the old one.
Java
mit
1ff887b161f31b41927592d925dea5910c39b507
0
codylieu/oogasalad_OOGALoompas,dennis-park/OOGALoompas,jordanly/oogasalad_OOGALoompas,sdh31/tower_defense,dianwen/oogasalad_TowerDefense,garysheng/tower-defense-game-engine,kevinkdo/oogasalad_OOGALoompas
package main.java.author.view.tabs.terrain; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.io.File; import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.imageio.ImageIO; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import main.java.author.controller.TabController; import main.java.author.controller.tabbed_controllers.TerrainController; import main.java.author.view.tabs.EditorTab; import main.java.exceptions.engine.InvalidParameterForConcreteTypeException; import main.java.schema.GameMap; import main.java.schema.TileMapSchema; import main.java.schema.TileSchema; import static main.java.author.util.ActionListenerUtil.actionListener; public class TerrainEditorTab extends EditorTab { private static final String CLEAR = "Clear Tiles"; private static final String EDIT_TILE = "Edit Tile"; private static final String SAVE_MAP = "Save Map"; private static final String ADD_TILEMAP = "Import Image File"; private static final String PIXEL_QUERY = "How many pixels are in the bitmap?"; private static final String ROW_QUERY = "Enter Row Count"; private static final String COL_QUERY = "Enter Column Count"; private static final String PIXEL_RANGE = "Pixel size must be between 10 and 40"; private static final String IMAGE_FILTER_DIALOGUE = ".GIF,.PNG,.BMP Images"; private static final String USER_INIT_MESSAGE = "Begin Terrain Editing"; private JFileChooser fileChooser; private TileSelectionManager myTileSelectionManager; private Map<String, JButton> buttonDisplayOptions; private Canvas myCanvas; public TerrainEditorTab(TabController controller){ super(controller); JButton initTerrainButton = new JButton(USER_INIT_MESSAGE); initTerrainButton.addActionListener(actionListener(this, "initTerrainTab")); add(initTerrainButton); setPreferredSize(new Dimension(1200, 800)); } /** * Initializes the terrain tab if the user has entered proper row/column * information. If the user enters poor information, nothing happens. */ public void initTerrainTab(ActionEvent e) { boolean isCanvasInitialized = initCanvas(); if (!isCanvasInitialized) { return; } remove((JButton) e.getSource()); myTileSelectionManager = new TileSelectionManager(myCanvas); add(myTileSelectionManager.getTileDisplayTabs(), BorderLayout.EAST); add(myCanvas, BorderLayout.CENTER); constructButtonDisplay(); } /** * Obtains information from the user about the row and column size of the * terrain map, and creates the Canvas representing the terrain map * * @return true if the row and column entries contain valid information, * otherwise false */ private boolean initCanvas() { boolean isInitialized = false; String numRows = queryUser(ROW_QUERY); String numCols = queryUser(COL_QUERY); try { int rowCount = Integer.parseInt(numRows); int colCount = Integer.parseInt(numCols); myCanvas = new Canvas(rowCount, colCount); isInitialized = true; } catch (NumberFormatException e) {} return isInitialized; } /** * Initializes different buttons that give the user various options * when constructing the terrain map. These include clearing the canvas, * editing tiles, saving the current map, and adding new images for future * use. */ private void constructButtonDisplay() { buttonDisplayOptions = new HashMap<String, JButton>(); buttonDisplayOptions.put(CLEAR, initClearButton()); buttonDisplayOptions.put(EDIT_TILE, initEditorButton()); buttonDisplayOptions.put(SAVE_MAP, initSaveButton()); buttonDisplayOptions.put(ADD_TILEMAP, initNewTileMap()); JPanel buttonDisplayPanel = new JPanel(); buttonDisplayPanel.setBackground(new Color(50, 50, 50)); buttonDisplayPanel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridy = 0; for (JButton buttonDisplay : buttonDisplayOptions.values()) { buttonDisplayPanel.add(buttonDisplay, c); c.gridy++; } add(buttonDisplayPanel, BorderLayout.WEST); revalidate(); repaint(); } /** * Constructs a JButton that allows the user to enter a image map, * which can then be parsed into smaller images */ private JButton initNewTileMap() { JButton createTileMap = new JButton(ADD_TILEMAP); createTileMap.addActionListener(actionListener(this, "importTileMap")); return createTileMap; } /** * Constructs a JButton that allows the user to save the current * state of the terrain map */ private JButton initSaveButton() { JButton saveButton = new JButton(SAVE_MAP); saveButton.addActionListener(actionListener(this, "saveMap")); return saveButton; } /** * Constructs a JButton that allows the user to clear the terrain map */ private JButton initClearButton() { JButton clearButton = new JButton(CLEAR); clearButton.addActionListener(actionListener(this, "clearCanvasTiles")); return clearButton; } /** * Constructs a JButton that allows the user to edit the features of an image */ private JButton initEditorButton() { JButton openBGTiles = new JButton(EDIT_TILE); openBGTiles.addActionListener(actionListener(this, "openEditorWindow")); openBGTiles.setEnabled(false); return openBGTiles; } /** * Allows the user to enter a grid of images that they would like to use, * which can then be parsed based on the pixel size of each image within * the grid. * * @param e */ public void importTileMap(ActionEvent e) { fileChooser = new JFileChooser(new File(System.getProperty("user.dir"))); FileFilter imageFilter = new FileNameExtensionFilter(IMAGE_FILTER_DIALOGUE, "png", "gif", "bmp"); fileChooser.setFileFilter(imageFilter); int fileReturn = fileChooser.showOpenDialog(this); if (fileReturn == JFileChooser.APPROVE_OPTION) { addTileDisplay(fileChooser.getSelectedFile()); buttonDisplayOptions.get(EDIT_TILE).setEnabled(true); revalidate(); repaint(); } } /** * Allows the current tiles on the canvas to be saved. TileSchemas represent * the information behind Tile objects, while TileMapSchemas represent * information about an image file imported by the user. Both are necessary * in transferring information to the engine team. * * @param e */ public void saveMap(ActionEvent e) { ((JButton) e.getSource()).setEnabled(false); GameMap myCompletedMap = new GameMap(); List<Tile> gameTiles = myCanvas.getTiles(); List<TileSchema> gameTileSchemas = new ArrayList<TileSchema>(); for (Tile tile : gameTiles) { TileSchema tileSchema = new TileSchema(); populateTileSchema(tileSchema, tile); gameTileSchemas.add(tileSchema); } List<TileDisplay> tileDisplays = myTileSelectionManager.getAllTileDisplays(); List<TileMapSchema> gameTileMapSchemas = new ArrayList<TileMapSchema>(); for (TileDisplay tileDisp : tileDisplays) { TileMapSchema tileMapSchema = new TileMapSchema(); populateTileMapSchema(tileMapSchema, tileDisp); gameTileMapSchemas.add(tileMapSchema); } myCompletedMap.setTileSchemas(gameTileSchemas); myCompletedMap.setTileMapSchemas(gameTileMapSchemas); TerrainController myControl = (TerrainController) myController; myControl.addMap(myCompletedMap); //writeMapToFile(myCompletedMap); } /** * Transfers information about a Tile into a TileSchema object * * @param tileSchema * @param tile */ private void populateTileSchema(TileSchema tileSchema, Tile tile) { tileSchema.addAttribute(TileSchema.CANVAS_ROW, tile.getRow()); tileSchema.addAttribute(TileSchema.CANVAS_COL, tile.getCol()); tileSchema.addAttribute(TileSchema.TILEMAP_ROW, tile.getMyMapYIndex()); tileSchema.addAttribute(TileSchema.TILEMAP_COL, tile.getMyMapXIndex()); tileSchema.addAttribute(TileSchema.TILEMAP_FILE_NAME, tile.getMyTileMapFileName()); tileSchema.addAttribute(TileSchema.TILE_CID, tile.getPassIndex()); } /** * Transfers information about a TileDisplay into a TileMapSchema object * @param tileMapSchema * @param tileDisp */ private void populateTileMapSchema(TileMapSchema tileMapSchema, TileDisplay tileDisp) { tileMapSchema.addAttribute(TileMapSchema.NUM_ROWS, tileDisp.getNumRows()); tileMapSchema.addAttribute(TileMapSchema.NUM_COLS, tileDisp.getNumCols()); tileMapSchema.addAttribute(TileMapSchema.PIXEL_SIZE, tileDisp.getMyPixelSize()); tileMapSchema.addAttribute(TileMapSchema.TILEMAP_FILE_NAME, tileDisp.getTileMapFile()); } /** * Serializes a 'GameMap' which contains multiple TileSchemas and * TileMapSchemas. * * @param map */ private void writeMapToFile(GameMap map) { JFileChooser saveFileChooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("SER Files", "ser"); saveFileChooser.setFileFilter(filter); int returnVal = saveFileChooser.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { try { FileOutputStream fout = new FileOutputStream(saveFileChooser.getSelectedFile().getAbsolutePath() + ".ser"); ObjectOutputStream oos = new ObjectOutputStream(fout); oos.writeObject(map); oos.close(); } catch(Exception ex){ ex.printStackTrace(); } } } /** * Clears the canvas of all user placed Tiles */ public void clearCanvasTiles(ActionEvent e) { myCanvas.clearTiles(); } private void addTileDisplay(File f) { String pixels = queryUser(PIXEL_QUERY); try { int pixelCount = Integer.parseInt(pixels); if (pixelCount < 40 && pixelCount > 10) { myTileSelectionManager.addTileDisplay(f, pixelCount); } else { JOptionPane.showMessageDialog(this, PIXEL_RANGE); } } catch (NumberFormatException e) { e.printStackTrace(); } } private String queryUser(String query) { return JOptionPane.showInputDialog(query); } /** * Opens a window that allows the user to edit information about * the selected Tile */ public void openEditorWindow(ActionEvent e) { JFrame selectionFrame = new JFrame(); selectionFrame.add(myTileSelectionManager.getTileEditPanel(), BorderLayout.CENTER); selectionFrame.setLocation(this.getWidth() + 25, 0); selectionFrame.pack(); selectionFrame.setVisible(true); } }
src/main/java/author/view/tabs/terrain/TerrainEditorTab.java
package main.java.author.view.tabs.terrain; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.io.File; import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.imageio.ImageIO; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import main.java.author.controller.TabController; import main.java.author.controller.tabbed_controllers.TerrainController; import main.java.author.view.tabs.EditorTab; import main.java.exceptions.engine.InvalidParameterForConcreteTypeException; import main.java.schema.GameMap; import main.java.schema.TileMapSchema; import main.java.schema.TileSchema; import static main.java.author.util.ActionListenerUtil.actionListener; public class TerrainEditorTab extends EditorTab { private static final String CLEAR = "Clear Tiles"; private static final String EDIT_TILE = "Edit Tile"; private static final String SAVE_MAP = "Save Map"; private static final String ADD_TILEMAP = "Import Image File"; private static final String PIXEL_QUERY = "How many pixels are in the bitmap?"; private static final String ROW_QUERY = "Enter Row Count"; private static final String COL_QUERY = "Enter Column Count"; private static final String PIXEL_RANGE = "Pixel size must be between 10 and 40"; private static final String IMAGE_FILTER_DIALOGUE = ".GIF,.PNG,.BMP Images"; private static final String USER_INIT_MESSAGE = "Begin Terrain Editing"; private JFileChooser fileChooser; private TileSelectionManager myTileSelectionManager; private Map<String, JButton> buttonDisplayOptions; private Canvas myCanvas; public TerrainEditorTab(TabController controller){ super(controller); JButton initTerrainButton = new JButton(USER_INIT_MESSAGE); initTerrainButton.addActionListener(actionListener(this, "initTerrainTab")); add(initTerrainButton); setPreferredSize(new Dimension(1200, 800)); } /** * Initializes the terrain tab if the user has entered proper row/column * information. If the user enters poor information, nothing happens. */ public void initTerrainTab(ActionEvent e) { boolean isCanvasInitialized = initCanvas(); if (!isCanvasInitialized) { return; } remove((JButton) e.getSource()); myTileSelectionManager = new TileSelectionManager(myCanvas); add(myTileSelectionManager.getTileDisplayTabs(), BorderLayout.EAST); add(myCanvas, BorderLayout.CENTER); constructButtonDisplay(); } /** * Obtains information from the user about the row and column size of the * terrain map, and creates the Canvas representing the terrain map * * @return true if the row and column entries contain valid information, * otherwise false */ private boolean initCanvas() { boolean isInitialized = false; String numRows = queryUser(ROW_QUERY); String numCols = queryUser(COL_QUERY); try { int rowCount = Integer.parseInt(numRows); int colCount = Integer.parseInt(numCols); myCanvas = new Canvas(rowCount, colCount); isInitialized = true; } catch (NumberFormatException e) {} return isInitialized; } /** * Initializes different buttons that give the user various options * when constructing the terrain map. These include clearing the canvas, * editing tiles, saving the current map, and adding new images for future * use. */ private void constructButtonDisplay() { buttonDisplayOptions = new HashMap<String, JButton>(); buttonDisplayOptions.put(CLEAR, initClearButton()); buttonDisplayOptions.put(EDIT_TILE, initEditorButton()); buttonDisplayOptions.put(SAVE_MAP, initSaveButton()); buttonDisplayOptions.put(ADD_TILEMAP, initNewTileMap()); JPanel buttonDisplayPanel = new JPanel(); buttonDisplayPanel.setBackground(new Color(50, 50, 50)); buttonDisplayPanel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridy = 0; for (JButton buttonDisplay : buttonDisplayOptions.values()) { buttonDisplayPanel.add(buttonDisplay, c); c.gridy++; } add(buttonDisplayPanel, BorderLayout.WEST); revalidate(); repaint(); } /** * Constructs a JButton that allows the user to enter a image map, * which can then be parsed into smaller images */ private JButton initNewTileMap() { JButton createTileMap = new JButton(ADD_TILEMAP); createTileMap.addActionListener(actionListener(this, "importTileMap")); return createTileMap; } /** * Constructs a JButton that allows the user to save the current * state of the terrain map */ private JButton initSaveButton() { JButton saveButton = new JButton(SAVE_MAP); saveButton.addActionListener(actionListener(this, "saveMap")); return saveButton; } /** * Constructs a JButton that allows the user to clear the terrain map */ private JButton initClearButton() { JButton clearButton = new JButton(CLEAR); clearButton.addActionListener(actionListener(this, "clearCanvasTiles")); return clearButton; } /** * Constructs a JButton that allows the user to edit the features of an image */ private JButton initEditorButton() { JButton openBGTiles = new JButton(EDIT_TILE); openBGTiles.addActionListener(actionListener(this, "openEditorWindow")); openBGTiles.setEnabled(false); return openBGTiles; } /** * Allows the user to enter a grid of images that they would like to use, * which can then be parsed based on the pixel size of each image within * the grid. * * @param e */ public void importTileMap(ActionEvent e) { fileChooser = new JFileChooser(new File(System.getProperty("user.dir"))); FileFilter imageFilter = new FileNameExtensionFilter(IMAGE_FILTER_DIALOGUE, ".png", ".gif", ".bmp"); fileChooser.setFileFilter(imageFilter); int fileReturn = fileChooser.showOpenDialog(this); if (fileReturn == JFileChooser.APPROVE_OPTION) { addTileDisplay(fileChooser.getSelectedFile()); buttonDisplayOptions.get(EDIT_TILE).setEnabled(true); revalidate(); repaint(); } } /** * Allows the current tiles on the canvas to be saved. TileSchemas represent * the information behind Tile objects, while TileMapSchemas represent * information about an image file imported by the user. Both are necessary * in transferring information to the engine team. * * @param e */ public void saveMap(ActionEvent e) { GameMap myCompletedMap = new GameMap(); List<Tile> gameTiles = myCanvas.getTiles(); List<TileSchema> gameTileSchemas = new ArrayList<TileSchema>(); for (Tile tile : gameTiles) { TileSchema tileSchema = new TileSchema(); populateTileSchema(tileSchema, tile); gameTileSchemas.add(tileSchema); } List<TileDisplay> tileDisplays = myTileSelectionManager.getAllTileDisplays(); List<TileMapSchema> gameTileMapSchemas = new ArrayList<TileMapSchema>(); for (TileDisplay tileDisp : tileDisplays) { TileMapSchema tileMapSchema = new TileMapSchema(); populateTileMapSchema(tileMapSchema, tileDisp); gameTileMapSchemas.add(tileMapSchema); } myCompletedMap.setTileSchemas(gameTileSchemas); myCompletedMap.setTileMapSchemas(gameTileMapSchemas); TerrainController myControl = (TerrainController) myController; myControl.addMap(myCompletedMap); //writeMapToFile(myCompletedMap); } /** * Transfers information about a Tile into a TileSchema object * * @param tileSchema * @param tile */ private void populateTileSchema(TileSchema tileSchema, Tile tile) { tileSchema.addAttribute(TileSchema.CANVAS_ROW, tile.getRow()); tileSchema.addAttribute(TileSchema.CANVAS_COL, tile.getCol()); tileSchema.addAttribute(TileSchema.TILEMAP_ROW, tile.getMyMapYIndex()); tileSchema.addAttribute(TileSchema.TILEMAP_COL, tile.getMyMapXIndex()); tileSchema.addAttribute(TileSchema.TILEMAP_FILE_NAME, tile.getMyTileMapFileName()); tileSchema.addAttribute(TileSchema.TILE_CID, tile.getPassIndex()); } /** * Transfers information about a TileDisplay into a TileMapSchema object * @param tileMapSchema * @param tileDisp */ private void populateTileMapSchema(TileMapSchema tileMapSchema, TileDisplay tileDisp) { tileMapSchema.addAttribute(TileMapSchema.NUM_ROWS, tileDisp.getNumRows()); tileMapSchema.addAttribute(TileMapSchema.NUM_COLS, tileDisp.getNumCols()); tileMapSchema.addAttribute(TileMapSchema.PIXEL_SIZE, tileDisp.getMyPixelSize()); tileMapSchema.addAttribute(TileMapSchema.TILEMAP_FILE_NAME, tileDisp.getTileMapFile()); } /** * Serializes a 'GameMap' which contains multiple TileSchemas and * TileMapSchemas. * * @param map */ private void writeMapToFile(GameMap map) { JFileChooser saveFileChooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("SER Files", "ser"); saveFileChooser.setFileFilter(filter); int returnVal = saveFileChooser.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { try { FileOutputStream fout = new FileOutputStream(saveFileChooser.getSelectedFile().getAbsolutePath() + ".ser"); ObjectOutputStream oos = new ObjectOutputStream(fout); oos.writeObject(map); oos.close(); } catch(Exception ex){ ex.printStackTrace(); } } } /** * Clears the canvas of all user placed Tiles */ public void clearCanvasTiles(ActionEvent e) { myCanvas.clearTiles(); } private void addTileDisplay(File f) { String pixels = queryUser(PIXEL_QUERY); try { int pixelCount = Integer.parseInt(pixels); if (pixelCount < 40 && pixelCount > 10) { myTileSelectionManager.addTileDisplay(f, pixelCount); } else { JOptionPane.showMessageDialog(this, PIXEL_RANGE); } } catch (NumberFormatException e) { e.printStackTrace(); } } private String queryUser(String query) { return JOptionPane.showInputDialog(query); } /** * Opens a window that allows the user to edit information about * the selected Tile */ public void openEditorWindow(ActionEvent e) { JFrame selectionFrame = new JFrame(); selectionFrame.add(myTileSelectionManager.getTileEditPanel(), BorderLayout.CENTER); selectionFrame.setLocation(this.getWidth() + 25, 0); selectionFrame.pack(); selectionFrame.setVisible(true); } }
minor updates
src/main/java/author/view/tabs/terrain/TerrainEditorTab.java
minor updates
Java
mit
7ce016545a334ddfbd0a10874f49e4fb96c22d40
0
dmazinanian/css-analyser
package ca.concordia.cssanalyser.cssmodel.declaration.value; import ca.concordia.cssanalyser.csshelper.ColorHelper; import ca.concordia.cssanalyser.csshelper.NamedColorsHelper; import ca.concordia.cssanalyser.cssmodel.declaration.Declaration; /** * This class is used to add equivalent values to a value. * The {@link #getDeclarationValue(String, String, ValueType)} method * returns either a {@link DeclarationValue} or {@link DeclarationEquivalentValue}. * @author Davood Mazinanian * */ public class DeclarationValueFactory { public static DeclarationValue getDeclarationValue(String forProperty, String value, ValueType type) { //return new DeclarationValue(value, type); forProperty = Declaration.getNonVendorProperty(Declaration.getNonHackedProperty(forProperty.toLowerCase())); value = value.trim(); switch (type) { case IDENT: { if (NamedColorsHelper.isNamedColor(value)) return new DeclarationEquivalentValue(value, NamedColorsHelper.getRGBAColor(value), ValueType.COLOR); switch (value.toLowerCase()) { case "currentcolor": return new DeclarationValue(value, ValueType.COLOR); case "none": return new DeclarationEquivalentValue(value, value, ValueType.IDENT); case "left": case "top": switch (forProperty) { case "background-position": case "background": case "perspective-origin": case "transform-origin": return new DeclarationEquivalentValue(value, "0px", ValueType.LENGTH); } break; case "right": case "bottom": switch (forProperty) { case "background-position": case "background": case "perspective-origin": case "transform-origin": return new DeclarationEquivalentValue(value, "100%", ValueType.LENGTH); } break; case "center": switch (forProperty) { case "background-position": case "background": case "perspective-origin": case "transform-origin": return new DeclarationEquivalentValue(value, "50%", ValueType.LENGTH); } break; case "bold": return new DeclarationEquivalentValue(value, "700", ValueType.INTEGER); case "normal": if (forProperty.equals("font-weight")) return new DeclarationEquivalentValue(value, "400", ValueType.INTEGER); // What should we do for font shorthand property?! } break; } case INTEGER: { if ("0".equals(value)) { switch (forProperty) { case "margin": case "margin-left": case "margin-right": case "margin-top": case "margin-bottom": case "padding": case "padding-left": case "padding-right": case "padding-bottom": case "padding-top": case "top": case "left": case "bottom": case "right": case "height": case "width": case "max-height": case "max-width": case "min-height": case "min-width": case "background-position": case "background-size": case "background": case "border": case "border-bottom": case "border-left": case "border-right": case "border-top": case "outline": case "border-top-width": case "border-bottom-width": case "border-left-width": case "border-right-width": case "border-width": case "outline-width": case "border-radius": case "border-bottom-left-radius": case "border-bottom-right-radius": case "border-top-left-radius": case "border-top-right-radius": case "column-width": case "column-rule-width": case "column-gap": case "perspective-origin": case "text-shadow": case "box-shadow": case "transform-origin": return new DeclarationEquivalentValue(value, "0px", ValueType.LENGTH); } } break; } case PERCENTAGE: { String eqVal = handlePointWithoutZero(value); if ("0%".equals(value)) { switch (forProperty) { case "background-position": case "background-size": case "border-radius": case "border-bottom-left-radius": case "border-bottom-right-radius": case "border-bottom-top-radius": case "border-bottom-bottom-radius": case "transform-origin": eqVal = "0px"; break; case "rgb": case "rgba": case "hsl": case "hsla": eqVal = "0"; } } return new DeclarationEquivalentValue(value, eqVal, ValueType.PERCENTAGE); } case COLOR: { String eqValue = ""; if (value.startsWith("#")) { try { eqValue = ColorHelper.RGBAFromHEX(value.substring(1)); } catch (Exception e) { } } else if (value.startsWith("rgb")) { String[] values = getCommaSeparatedValueParts(value); float a = 1F; if (value.startsWith("rgba")) { if (values.length != 4) throw new RuntimeException("Invalid rgba color: " + value); a = Math.min(Float.valueOf(values[3]), 1); } else { if (values.length != 3) throw new RuntimeException("Invalid rgb color: " + value); } int r = getRgbComponentValue(values[0]); int g = getRgbComponentValue(values[1]); int b = getRgbComponentValue(values[2]); eqValue = ColorHelper.RGBA(r, g, b, a); } else if (value.startsWith("hsl")) { String[] values = getCommaSeparatedValueParts(value); float a = 1F; if (value.startsWith("hsla")) { if (values.length != 4) throw new RuntimeException("Invalid hsla color: " + value); a = Math.min(Float.valueOf(values[3]), 1); } else { if (values.length != 3) throw new RuntimeException("Invalid hsl color: " + value); } float h = Math.min(Integer.valueOf(values[0]), 360) / 360F; float s,l; try { s = getPercentageValue(values[1]); l = getPercentageValue(values[2]); } catch (IllegalArgumentException e) { throw new RuntimeException("Invalud percentage value in " + value); } eqValue = ColorHelper.RGBAFromHSLA(h, s, l, a); } return new DeclarationEquivalentValue(value, eqValue, ValueType.COLOR); } case LENGTH: { String postfix = value.substring(value.length() - 2); float floatVal = Float.valueOf(value.replace(postfix, "")); String eqVal = ""; String originalVal = value; value = handlePointWithoutZero(value); switch(postfix) { case "pc": { // 1pc = 12pt = 16px eqVal = formatDouble(floatVal * 16) + "px"; break; } case "pt": { // 72pt is 96px eqVal = formatDouble(floatVal / 72F * 96F) + "px"; break; } case "in": { // Every inch is 96px eqVal = formatDouble(floatVal * 96F) + "px"; break; } case "cm": { // Every cm is (2.54^-1 * 96)px // In browser, every cm is about 38px eqVal = formatDouble(floatVal * 38F) + "px"; break; } case "mm": { //every mm is 0.01 cm eqVal = formatDouble(floatVal * 38F / 100F) + "px"; break; } case "px": { eqVal = value; break; } case "em": { // 1em = 100%, if we are talking about font if ("font".equals(forProperty) || "font-size".equals(forProperty) || "line-height".equals(forProperty)) { eqVal = formatDouble(floatVal * 100) + "%"; } else { return new DeclarationValue(value, ValueType.LENGTH); } break; } } if (!"".equals(eqVal)) return new DeclarationEquivalentValue(originalVal, eqVal, ValueType.LENGTH); break; } case ANGLE: { String originalValue = value; value = handlePointWithoutZero(value); String eqVal = ""; if (value.endsWith("grad")) { // 1grad = 0.9deg eqVal = formatDouble(Float.valueOf(value.replace("grad", "")) * 0.9F) + "deg"; } else if (value.endsWith("rad")) { // 2pi rad = 360deg eqVal = formatDouble(Float.valueOf(value.replace("rad", "")) / (2 * 3.1415926F) * 360) + "deg"; } else if (value.endsWith("turn")) { // 1turn = 360deg eqVal = formatDouble(Float.valueOf(value.replace("turn", "")) * 360) + "deg"; } else if (value.endsWith("deg")) { eqVal = value; } return new DeclarationEquivalentValue(originalValue, eqVal, type); } case FREQUENCY: { String originalValue = value; value = handlePointWithoutZero(value); String eqVal = value; // 1KHz = 1000Hz if (value.endsWith("khz")) { eqVal = formatDouble(Float.valueOf(value.replace("khz", "")) * 1000) + "hz"; } return new DeclarationEquivalentValue(originalValue, eqVal, ValueType.FREQUENCY); } case TIME: { String originalValue = value; // Each second is 1000 ms value = handlePointWithoutZero(value); String eqVal = value; if (value.endsWith("ms")) { eqVal = formatDouble(Float.valueOf(value.replace("ms", "")) * 1000) + "ms"; } return new DeclarationEquivalentValue(originalValue, eqVal, ValueType.TIME); } case URL: { if ("url('')".equals(value)) return new DeclarationEquivalentValue(value, "none", ValueType.URL); return new DeclarationValue(value, ValueType.URL); } default: break; } return new DeclarationValue(value, type); } private static String handlePointWithoutZero(String value) { if (value.startsWith(".")) return "0" + value; else if (value.startsWith("-.")) return value.replace("-.", "-0."); return value; } protected static float getPercentageValue(String string) throws IllegalArgumentException { float s = 0; if (string.endsWith("%")) s = Math.min(Integer.valueOf(string.substring(0, string.length() - 1)), 100) / 100F; else if ("0".equals(string)) s = 0; else throw new IllegalArgumentException("Invalid percent value"); return s; } protected static String[] getCommaSeparatedValueParts(String value) { String[] values = value.substring(value.indexOf("(") + 1, value.indexOf(")")).split(","); for (int i = 0; i < values.length; i++) values[i] = values[i].trim(); return values; } /** * Returns a color component value (like red value) in 255 scale. * (it might be percent or integer, like rgb(100%, 50%, 40%) ) * @param color * @return */ private static int getRgbComponentValue(String value) { if (value.endsWith("%")) return (int) Math.min(Integer.valueOf(value.substring(0, value.length() - 1)) * 255, 255); else return Math.min(Integer.valueOf(value), 255); } public static String formatDouble(double d) { if(d == (long) d) return String.format("%d", (long)d); else return String.format("%s", d); } public static DeclarationValue getFontValue(String propertyName, float value, String unit) { String val = formatDouble(value) + unit; return getDeclarationValue(propertyName, val, ValueType.LENGTH); } }
src/main/java/ca/concordia/cssanalyser/cssmodel/declaration/value/DeclarationValueFactory.java
package ca.concordia.cssanalyser.cssmodel.declaration.value; import ca.concordia.cssanalyser.csshelper.ColorHelper; import ca.concordia.cssanalyser.csshelper.NamedColorsHelper; import ca.concordia.cssanalyser.cssmodel.declaration.Declaration; /** * This class is used to add equivalent values to a value. * The {@link #getDeclarationValue(String, String, ValueType)} method * returns either a {@link DeclarationValue} or {@link DeclarationEquivalentValue}. * @author Davood Mazinanian * */ public class DeclarationValueFactory { public static DeclarationValue getDeclarationValue(String forProperty, String value, ValueType type) { //return new DeclarationValue(value, type); forProperty = Declaration.getNonVendorProperty(Declaration.getNonHackedProperty(forProperty.toLowerCase())); value = value.trim(); switch (type) { case IDENT: { if (NamedColorsHelper.isNamedColor(value)) return new DeclarationEquivalentValue(value, NamedColorsHelper.getRGBAColor(value), ValueType.COLOR); switch (value.toLowerCase()) { case "currentcolor": return new DeclarationValue(value, ValueType.COLOR); case "none": return new DeclarationEquivalentValue(value, value, ValueType.IDENT); case "left": case "top": switch (forProperty) { case "background-position": case "background": case "perspective-origin": case "transform-origin": return new DeclarationEquivalentValue(value, "0px", ValueType.LENGTH); } break; case "right": case "bottom": switch (forProperty) { case "background-position": case "background": case "perspective-origin": case "transform-origin": return new DeclarationEquivalentValue(value, "100%", ValueType.LENGTH); } break; case "center": switch (forProperty) { case "background-position": case "background": case "perspective-origin": case "transform-origin": return new DeclarationEquivalentValue(value, "50%", ValueType.LENGTH); } break; case "bold": return new DeclarationEquivalentValue(value, "700", ValueType.INTEGER); case "normal": if (forProperty.equals("font-weight")) return new DeclarationEquivalentValue(value, "400", ValueType.INTEGER); // What should we do for font shorthand property?! } break; } case INTEGER: { if ("0".equals(value)) { switch (forProperty) { case "margin": case "margin-left": case "margin-right": case "margin-top": case "margin-bottom": case "padding": case "padding-left": case "padding-right": case "padding-bottom": case "padding-top": case "top": case "left": case "bottom": case "right": case "height": case "width": case "max-height": case "max-width": case "min-height": case "min-width": case "background-position": case "background-size": case "background": case "border": case "border-bottom": case "border-left": case "border-right": case "border-top": case "outline": case "border-top-width": case "border-bottom-width": case "border-left-width": case "border-right-width": case "border-width": case "outline-width": case "border-radius": case "border-bottom-left-radius": case "border-bottom-right-radius": case "border-top-left-radius": case "border-top-right-radius": case "column-width": case "column-rule-width": case "column-gap": case "perspective-origin": case "text-shadow": case "box-shadow": /* * Dangerous to do! * case "transform-origin": * case "-ms-transform-origin": * case "-webkit-transform-origin": */ return new DeclarationEquivalentValue(value, "0px", ValueType.LENGTH); } } break; } case PERCENTAGE: { String eqVal = handlePointWithoutZero(value); if ("0".equals(value)) { switch (forProperty) { case "background-position": case "background-size": case "border-radius": case "-webkit-border-radius": case "-moz-border-radius": case "border-bottom-left-radius": case "border-bottom-right-radius": case "border-bottom-top-radius": case "border-bottom-bottom-radius": case "transform-origin": eqVal = "0px"; break; case "rgb": case "rgba": case "hsl": case "hsla": eqVal = "0"; } } return new DeclarationEquivalentValue(value, eqVal, ValueType.PERCENTAGE); } case COLOR: { String eqValue = ""; if (value.startsWith("#")) { try { eqValue = ColorHelper.RGBAFromHEX(value.substring(1)); } catch (Exception e) { } } else if (value.startsWith("rgb")) { String[] values = getCommaSeparatedValueParts(value); float a = 1F; if (value.startsWith("rgba")) { if (values.length != 4) throw new RuntimeException("Invalid rgba color: " + value); a = Math.min(Float.valueOf(values[3]), 1); } else { if (values.length != 3) throw new RuntimeException("Invalid rgb color: " + value); } int r = getRgbComponentValue(values[0]); int g = getRgbComponentValue(values[1]); int b = getRgbComponentValue(values[2]); eqValue = ColorHelper.RGBA(r, g, b, a); } else if (value.startsWith("hsl")) { String[] values = getCommaSeparatedValueParts(value); float a = 1F; if (value.startsWith("hsla")) { if (values.length != 4) throw new RuntimeException("Invalid hsla color: " + value); a = Math.min(Float.valueOf(values[3]), 1); } else { if (values.length != 3) throw new RuntimeException("Invalid hsl color: " + value); } float h = Math.min(Integer.valueOf(values[0]), 360) / 360F; float s,l; try { s = getPercentageValue(values[1]); l = getPercentageValue(values[2]); } catch (IllegalArgumentException e) { throw new RuntimeException("Invalud percentage value in " + value); } eqValue = ColorHelper.RGBAFromHSLA(h, s, l, a); } return new DeclarationEquivalentValue(value, eqValue, ValueType.COLOR); } case LENGTH: { String postfix = value.substring(value.length() - 2); float floatVal = Float.valueOf(value.replace(postfix, "")); String eqVal = ""; String originalVal = value; value = handlePointWithoutZero(value); switch(postfix) { case "pc": { // 1pc = 12pt = 16px eqVal = formatDouble(floatVal * 16) + "px"; break; } case "pt": { // 72pt is 96px eqVal = formatDouble(floatVal / 72F * 96F) + "px"; break; } case "in": { // Every inch is 96px eqVal = formatDouble(floatVal * 96F) + "px"; break; } case "cm": { // Every cm is (2.54^-1 * 96)px // In browser, every cm is about 38px eqVal = formatDouble(floatVal * 38F) + "px"; break; } case "mm": { //every mm is 0.01 cm eqVal = formatDouble(floatVal * 38F / 100F) + "px"; break; } case "px": { eqVal = value; break; } case "em": { // 1em = 100%, if we are talking about font if ("font".equals(forProperty) || "font-size".equals(forProperty) || "line-height".equals(forProperty)) { eqVal = formatDouble(floatVal * 100) + "%"; } else { return new DeclarationValue(value, ValueType.LENGTH); } break; } } if (!"".equals(eqVal)) return new DeclarationEquivalentValue(originalVal, eqVal, ValueType.LENGTH); break; } case ANGLE: { String originalValue = value; value = handlePointWithoutZero(value); String eqVal = ""; if (value.endsWith("grad")) { // 1grad = 0.9deg eqVal = formatDouble(Float.valueOf(value.replace("grad", "")) * 0.9F) + "deg"; } else if (value.endsWith("rad")) { // 2pi rad = 360deg eqVal = formatDouble(Float.valueOf(value.replace("rad", "")) / (2 * 3.1415926F) * 360) + "deg"; } else if (value.endsWith("turn")) { // 1turn = 360deg eqVal = formatDouble(Float.valueOf(value.replace("turn", "")) * 360) + "deg"; } else if (value.endsWith("deg")) { eqVal = value; } return new DeclarationEquivalentValue(originalValue, eqVal, type); } case FREQUENCY: { String originalValue = value; value = handlePointWithoutZero(value); String eqVal = value; // 1KHz = 1000Hz if (value.endsWith("khz")) { eqVal = formatDouble(Float.valueOf(value.replace("khz", "")) * 1000) + "hz"; } return new DeclarationEquivalentValue(originalValue, eqVal, ValueType.FREQUENCY); } case TIME: { String originalValue = value; // Each second is 1000 ms value = handlePointWithoutZero(value); String eqVal = value; if (value.endsWith("ms")) { eqVal = formatDouble(Float.valueOf(value.replace("ms", "")) * 1000) + "ms"; } return new DeclarationEquivalentValue(originalValue, eqVal, ValueType.TIME); } case URL: { if ("url('')".equals(value)) return new DeclarationEquivalentValue(value, "none", ValueType.URL); return new DeclarationValue(value, ValueType.URL); } default: break; } return new DeclarationValue(value, type); } private static String handlePointWithoutZero(String value) { if (value.startsWith(".")) return "0" + value; else if (value.startsWith("-.")) return value.replace("-.", "-0."); return value; } protected static float getPercentageValue(String string) throws IllegalArgumentException { float s = 0; if (string.endsWith("%")) s = Math.min(Integer.valueOf(string.substring(0, string.length() - 1)), 100) / 100F; else if ("0".equals(string)) s = 0; else throw new IllegalArgumentException("Invalid percent value"); return s; } protected static String[] getCommaSeparatedValueParts(String value) { String[] values = value.substring(value.indexOf("(") + 1, value.indexOf(")")).split(","); for (int i = 0; i < values.length; i++) values[i] = values[i].trim(); return values; } /** * Returns a color component value (like red value) in 255 scale. * (it might be percent or integer, like rgb(100%, 50%, 40%) ) * @param color * @return */ private static int getRgbComponentValue(String value) { if (value.endsWith("%")) return (int) Math.min(Integer.valueOf(value.substring(0, value.length() - 1)) * 255, 255); else return Math.min(Integer.valueOf(value), 255); } public static String formatDouble(double d) { if(d == (long) d) return String.format("%d", (long)d); else return String.format("%s", d); } public static DeclarationValue getFontValue(String propertyName, float value, String unit) { String val = formatDouble(value) + unit; return getDeclarationValue(propertyName, val, ValueType.LENGTH); } }
Fixed the problem with equivalent percent values
src/main/java/ca/concordia/cssanalyser/cssmodel/declaration/value/DeclarationValueFactory.java
Fixed the problem with equivalent percent values
Java
epl-1.0
e689e2246a2d2d2cab43219ebf4c78483f2c01fc
0
wuellueb/openhab,Snickermicker/openhab,gregfinley/openhab,mvolaart/openhab,querdenker2k/openhab,dominicdesu/openhab,JensErat/openhab,clinique/openhab,saydulk/openhab,mrguessed/openhab,savageautomate/openhab,bakrus/openhab,svenschaefer74/openhab,richbeales/openhab,tinnerm/openhab,gregfinley/openhab,tomtrath/openhab,saydulk/openhab,aruder77/openhab,sytone/openhab,jowi24/openhab,gunthor/openhab,TheNetStriker/openhab,evansj/openhab,idserda/openhab,joek/openhab1-addons,netwolfuk/openhab,docbender/openhab,computergeek1507/openhab,evansj/openhab,JoeCob/openhab,rmayr/openhab,coolweb/openhab,starwarsfan/openhab,andrey-desman/openhab-hdl,stefanroellin/openhab,docbender/openhab,andrey-desman/openhab-hdl,Gerguis/openhab2,seebag/openhab,beowulfe/openhab,PlegmaLabs/openhab,watou/openhab,QuailAutomation/openhab,robbyb67/openhab,gilhmauy/openhab,innoq/openhab,mdbergmann/openhab,hemantsangwan/openhab,Gecko33/openhab,wurtzel/openhab,vgoldman/openhab,starwarsfan/openhab,dfliess/openhab,wep4you/openhab,computergeek1507/openhab,dvanherbergen/openhab,innoq/openhab,resetnow/openhab,Snickermicker/openhab,CondormanFr/openhab,sedstef/openhab,sitewhere/openhab,johkin/openhab,gilhmauy/openhab,kgoderis/openhab,lewie/openhab,maraszm/openhab,paulianttila/openhab,taupinfada/openhab,paolodenti/openhab,druciak/openhab,Mike-Petersen/openhab,mroeckl/openhab,dbadia/openhab,andreasgebauer/openhab,aruder77/openhab,robbyb67/openhab,holgercn/openhab,marcelerkel/openhab,LaurensVanAcker/openhab,saydulk/openhab,taupinfada/openhab,cslauritsen/openhab,svenschreier/openhab,aidanom1/openhab,MitchSUEW/openhab,docbender/openhab,digitaldan/openhab,wurtzel/openhab,kuijp/openhab,swatchy2dot0/openhab,gilhmauy/openhab,jenskastensson/openhab,mdbergmann/openhab,joek/openhab1-addons,johkin/openhab,Gecko33/openhab,mash0304/openhab,querdenker2k/openhab,mvolaart/openhab,gernoteger/openhab_contributions,JensErat/openhab,dereulenspiegel/openhab,paphko/openhab,gunthor/openhab,robbyb67/openhab,curtisstpierre/openhab,hemantsangwan/openhab,MitchSUEW/openhab,bbesser/openhab1-addons,berndpfrommer/openhab,mjsolidarios/openhab,Jakey69/openhab,pravinw/openhab,aruder77/openhab,mvolaart/openhab,cvanorman/openhab,RafalLukawiecki/openhab1-addons,gilhmauy/openhab,peuter/openhab,coolweb/openhab,TheOriginalAndrobot/openhab,xsnrg/openhab,JensErat/openhab,Gecko33/openhab,cslauritsen/openhab,cslauritsen/openhab,gerrieg/openhab,vgoldman/openhab,robnielsen/openhab,innoq/openhab,Gerguis/openhab2,wojtus/openhab,ollie-dev/openhab,ShanksSGV/openhab,revenz/openhab,CondormanFr/openhab,Gerguis/open,taupinfada/openhab,aidanom1/openhab,dbadia/openhab,digitaldan/openhab,gerrieg/openhab,TheOriginalAndrobot/openhab,curtisstpierre/openhab,stefanroellin/openhab,savageautomate/openhab,peuter/openhab,mleegwt/openhab,robbyb67/openhab,bakrus/openhab,MCherifiOSS/openhab,georgwiltschek/openhab,cslauritsen/openhab,gerrieg/openhab,CrackerStealth/openhab,tomtrath/openhab,revenz/openhab,kaikreuzer/openhab,falkena/openhab,ivanfmartinez/openhab,hmerk/openhab,lewie/openhab,sedstef/openhab,ollie-dev/openhab,Mike-Petersen/openhab,g8kmh/openhab,aruder77/openhab,aidanom1/openhab,eschava/openhab,computergeek1507/openhab,richbeales/openhab,QuailAutomation/openhab,robbyb67/openhab,idserda/openhab,Greblys/openhab,mleegwt/openhab,cschneider/openhab,sitewhere/openhab,Gecko33/openhab,cyclingengineer/openhab,kgoderis/openhab,smerschjohann/openhab,eschava/openhab,clinique/openhab,wojtus/openhab,sibbi77/openhab,mdbergmann/openhab,hemantsangwan/openhab,joek/openhab1-addons,aruder77/openhab,gernoteger/openhab_contributions,svenschreier/openhab,gregfinley/openhab,bbesser/openhab1-addons,robbyb67/openhab,mjsolidarios/openhab,AutoMates/openhab,clinique/openhab,Gecko33/openhab,marcelrv/openhab,vgoldman/openhab,dbadia/openhab,robnielsen/openhab,Snickermicker/openhab,steve-bate/openhab,PolymorhicCode/openhab,CondormanFr/openhab,svenschaefer74/openhab,taimos/openhab,SwissKid/openhab,AutoMates/openhab,dereulenspiegel/openhab,sitewhere/openhab,mroeckl/openhab,beowulfe/openhab,rmayr/openhab,MitchSUEW/openhab,maraszm/openhab,druciak/openhab,sumnerboy12/openhab,swatchy2dot0/openhab,doubled-ca/openhab1-addons,svenschreier/openhab,sja/openhab,eschava/openhab,dfliess/openhab,LaurensVanAcker/openhab,Mixajlo/openhab,mattnl/openhab,JoeCob/openhab,TheNetStriker/openhab,sytone/openhab,revenz/openhab,taimos/openhab,magcode/openhab,idserda/openhab,stefanroellin/openhab,falkena/openhab,jhonpaulrocha/openhabss,theoweiss/openhab,Gerguis/openhab2,MitchSUEW/openhab,mroeckl/openhab,docbender/openhab,jowiho/openhab,g8kmh/openhab,seebag/openhab,seebag/openhab,magcode/openhab,abrenk/openhab,rmayr/openhab,JensErat/openhab,cesarmarinhorj/openhab,andreasgebauer/openhab,hemantsangwan/openhab,elifesy/openhab,dominicdesu/openhab,jowi24/openhab,starwarsfan/openhab,svenschaefer74/openhab,CondormanFr/openhab,stefanroellin/openhab,cschneider/openhab,marcelerkel/openhab,TheNetStriker/openhab,gilhmauy/openhab,starwarsfan/openhab,cschneider/openhab,falkena/openhab,resetnow/openhab,jenskastensson/openhab,MCherifiOSS/openhab,dodger777/openhabMod,sja/openhab,gernoteger/openhab_contributions,kgoderis/openhab,jowi24/openhab,richbeales/openhab,Gerguis/open,richbeales/openhab,sumnerboy12/openhab,pravinw/openhab,MitchSUEW/openhab,ShanksSGV/openhab,kaikreuzer/openhab,jowi24/openhab,tomtrath/openhab,dodger777/openhabMod,richbeales/openhab,AutoMates/openhab,evansj/openhab,sja/openhab,computergeek1507/openhab,jforge/openhab,elifesy/openhab,resetnow/openhab,pravinw/openhab,gunthor/openhab,theoweiss/openhab,tomtrath/openhab,dvanherbergen/openhab,watou/openhab,sitewhere/openhab,MCherifiOSS/openhab,dmize/openhab,tdiekmann/openhab,magcode/openhab,tdiekmann/openhab,MCherifiOSS/openhab,Snickermicker/openhab,sumnerboy12/openhab,Mixajlo/openhab,frami/openhab,robnielsen/openhab,abrenk/openhab,juri8/openhab,QuailAutomation/openhab,taimos/openhab,mash0304/openhab,tisoft/openhab,ssalonen/openhab,kreutpet/openhab,marcelerkel/openhab,juri8/openhab,bbesser/openhab1-addons,taimos/openhab,peuter/openhab,g8kmh/openhab,beowulfe/openhab,Mike-Petersen/openhab,juri8/openhab,paulianttila/openhab,peuter/openhab,sibbi77/openhab,tomtrath/openhab,gregfinley/openhab,computergeek1507/openhab,bakrus/openhab,joek/openhab1-addons,mash0304/openhab,jhonpaulrocha/openhabss,saydulk/openhab,clanko8285/openhab,gilhmauy/openhab,sytone/openhab,marcelerkel/openhab,peuter/openhab,PolymorhicCode/openhab,mjsolidarios/openhab,Jakey69/openhab,andreasgebauer/openhab,wojtus/openhab,dodger777/openhabMod,johkin/openhab,JoeCob/openhab,marcelerkel/openhab,sja/openhab,mroeckl/openhab,druciak/openhab,jforge/openhab,tdiekmann/openhab,juri8/openhab,sibbi77/openhab,kbialek/openhab,frami/openhab,sja/openhab,cschneider/openhab,teichsta/openhab,paolodenti/openhab,magcode/openhab,cslauritsen/openhab,Jakey69/openhab,idserda/openhab,seebag/openhab,resetnow/openhab,beowulfe/openhab,dodger777/openhabMod,gerrieg/openhab,steve-bate/openhab,johkin/openhab,aschor/openhab,dfliess/openhab,cvanorman/openhab,smerschjohann/openhab,ivanfmartinez/openhab,wojtus/openhab,Mixajlo/openhab,mroeckl/openhab,georgwiltschek/openhab,robnielsen/openhab,kgoderis/openhab,hmerk/openhab,dereulenspiegel/openhab,pravinw/openhab,sibbi77/openhab,saydulk/openhab,JoeCob/openhab,QuailAutomation/openhab,ivanfmartinez/openhab,mrguessed/openhab,dominicdesu/openhab,mdbergmann/openhab,starwarsfan/openhab,sitewhere/openhab,doubled-ca/openhab1-addons,peuter/openhab,paphko/openhab,marcelrv/openhab,maraszm/openhab,sytone/openhab,cdjackson/openhab,gregfinley/openhab,johkin/openhab,wuellueb/openhab,magcode/openhab,xsnrg/openhab,g8kmh/openhab,lewie/openhab,openhab/openhab,jowi24/openhab,fbeke/openhab,dominicdesu/openhab,CrackerStealth/openhab,steintore/openhab,openhab/openhab,Mike-Petersen/openhab,kuijp/openhab,georgwiltschek/openhab,maraszm/openhab,jowiho/openhab,Jakey69/openhab,eschava/openhab,bbesser/openhab1-addons,doubled-ca/openhab1-addons,aidanom1/openhab,teichsta/openhab,PolymorhicCode/openhab,dmize/openhab,JoeCob/openhab,Greblys/openhab,aschor/openhab,wep4you/openhab,lewie/openhab,xsnrg/openhab,jenskastensson/openhab,rmayr/openhab,wurtzel/openhab,tisoft/openhab,dmize/openhab,cschneider/openhab,Mike-Petersen/openhab,andreasgebauer/openhab,teichsta/openhab,openhab/openhab,paolodenti/openhab,Gecko33/openhab,johkin/openhab,foxy82/openhab,paphko/openhab,PlegmaLabs/openhab,dfliess/openhab,Gerguis/open,lmaertin/openhab,druciak/openhab,revenz/openhab,MCherifiOSS/openhab,joek/openhab1-addons,fbeke/openhab,clanko8285/openhab,jowi24/openhab,foxy82/openhab,mdbergmann/openhab,abrenk/openhab,xsnrg/openhab,tarioch/openhab,aidanom1/openhab,marcelrv/openhab,sibbi77/openhab,teichsta/openhab,doubled-ca/openhab1-addons,pravinw/openhab,elifesy/openhab,wojtus/openhab,mrguessed/openhab,watou/openhab,bakrus/openhab,basriram/openhab,seebag/openhab,teichsta/openhab,jhonpaulrocha/openhabss,jforge/openhab,basriram/openhab,wurtzel/openhab,wep4you/openhab,resetnow/openhab,querdenker2k/openhab,netwolfuk/openhab,savageautomate/openhab,taimos/openhab,swatchy2dot0/openhab,aschor/openhab,AutoMates/openhab,SwissKid/openhab,tarioch/openhab,kbialek/openhab,tarioch/openhab,maraszm/openhab,mvolaart/openhab,cschneider/openhab,jhonpaulrocha/openhabss,mrguessed/openhab,docbender/openhab,beowulfe/openhab,seebag/openhab,Gerguis/open,abrenk/openhab,falkena/openhab,revenz/openhab,aidanom1/openhab,vgoldman/openhab,taimos/openhab,teichsta/openhab,Gerguis/open,saydulk/openhab,tinnerm/openhab,jowiho/openhab,wurtzel/openhab,steintore/openhab,kgoderis/openhab,tarioch/openhab,watou/openhab,mrguessed/openhab,coolweb/openhab,craigham/openhab,paixaop/openhab,theoweiss/openhab,steve-bate/openhab,clinique/openhab,berndpfrommer/openhab,paolodenti/openhab,clinique/openhab,teichsta/openhab,elifesy/openhab,tisoft/openhab,mjsolidarios/openhab,kuijp/openhab,JoeCob/openhab,paixaop/openhab,RafalLukawiecki/openhab1-addons,bakrus/openhab,dereulenspiegel/openhab,stefanroellin/openhab,paixaop/openhab,georgwiltschek/openhab,cslauritsen/openhab,kbialek/openhab,dvanherbergen/openhab,sedstef/openhab,QuailAutomation/openhab,tinnerm/openhab,tinnerm/openhab,taimos/openhab,wurtzel/openhab,ssalonen/openhab,lmaertin/openhab,dereulenspiegel/openhab,wuellueb/openhab,Greblys/openhab,jforge/openhab,jhonpaulrocha/openhabss,paixaop/openhab,dodger777/openhabMod,docbender/openhab,LaurensVanAcker/openhab,querdenker2k/openhab,theoweiss/openhab,evansj/openhab,richbeales/openhab,LaurensVanAcker/openhab,PolymorhicCode/openhab,RafalLukawiecki/openhab1-addons,Snickermicker/openhab,johkin/openhab,mleegwt/openhab,cyclingengineer/openhab,mleegwt/openhab,mrguessed/openhab,dominicdesu/openhab,lmaertin/openhab,revenz/openhab,wuellueb/openhab,PolymorhicCode/openhab,QuailAutomation/openhab,hemantsangwan/openhab,ivanfmartinez/openhab,holgercn/openhab,cdjackson/openhab,rmayr/openhab,CondormanFr/openhab,kgoderis/openhab,svenschreier/openhab,wurtzel/openhab,maraszm/openhab,stefanroellin/openhab,andrey-desman/openhab-hdl,TheNetStriker/openhab,georgwiltschek/openhab,frami/openhab,steve-bate/openhab,ollie-dev/openhab,smerschjohann/openhab,bakrus/openhab,ivanfmartinez/openhab,mattnl/openhab,dfliess/openhab,hmerk/openhab,basriram/openhab,starwarsfan/openhab,juri8/openhab,frami/openhab,elifesy/openhab,aschor/openhab,TheOriginalAndrobot/openhab,gunthor/openhab,kreutpet/openhab,hemantsangwan/openhab,lewie/openhab,cdjackson/openhab,idserda/openhab,fbeke/openhab,mroeckl/openhab,cvanorman/openhab,smerschjohann/openhab,paphko/openhab,TheOriginalAndrobot/openhab,kuijp/openhab,curtisstpierre/openhab,hmerk/openhab,paixaop/openhab,xsnrg/openhab,cdjackson/openhab,cesarmarinhorj/openhab,AutoMates/openhab,ShanksSGV/openhab,berndpfrommer/openhab,jenskastensson/openhab,robbyb67/openhab,SwissKid/openhab,AutoMates/openhab,Gecko33/openhab,juri8/openhab,hmerk/openhab,aruder77/openhab,paulianttila/openhab,dodger777/openhabMod,LaurensVanAcker/openhab,jowi24/openhab,LaurensVanAcker/openhab,jforge/openhab,tinnerm/openhab,fbeke/openhab,basriram/openhab,fbeke/openhab,curtisstpierre/openhab,druciak/openhab,openhab/openhab,savageautomate/openhab,kaikreuzer/openhab,mleegwt/openhab,taupinfada/openhab,ssalonen/openhab,ivanfmartinez/openhab,andreasgebauer/openhab,Snickermicker/openhab,mvolaart/openhab,tdiekmann/openhab,Mixajlo/openhab,abrenk/openhab,cyclingengineer/openhab,gunthor/openhab,tomtrath/openhab,frami/openhab,sytone/openhab,foxy82/openhab,paixaop/openhab,Mixajlo/openhab,clinique/openhab,ssalonen/openhab,falkena/openhab,andrey-desman/openhab-hdl,dvanherbergen/openhab,sumnerboy12/openhab,kreutpet/openhab,Gerguis/openhab2,taupinfada/openhab,druciak/openhab,SwissKid/openhab,craigham/openhab,tinnerm/openhab,paphko/openhab,mvolaart/openhab,evansj/openhab,kbialek/openhab,sedstef/openhab,Gerguis/open,sumnerboy12/openhab,teichsta/openhab,RafalLukawiecki/openhab1-addons,doubled-ca/openhab1-addons,foxy82/openhab,dodger777/openhabMod,innoq/openhab,mash0304/openhab,sytone/openhab,gerrieg/openhab,TheNetStriker/openhab,bbesser/openhab1-addons,cesarmarinhorj/openhab,ShanksSGV/openhab,Greblys/openhab,AutoMates/openhab,querdenker2k/openhab,digitaldan/openhab,ssalonen/openhab,tisoft/openhab,digitaldan/openhab,CondormanFr/openhab,CrackerStealth/openhab,abrenk/openhab,Mike-Petersen/openhab,JoeCob/openhab,querdenker2k/openhab,jhonpaulrocha/openhabss,mattnl/openhab,tarioch/openhab,jenskastensson/openhab,mroeckl/openhab,watou/openhab,holgercn/openhab,curtisstpierre/openhab,Gerguis/openhab2,starwarsfan/openhab,steve-bate/openhab,MitchSUEW/openhab,PolymorhicCode/openhab,marcelrv/openhab,MitchSUEW/openhab,eschava/openhab,watou/openhab,wep4you/openhab,wep4you/openhab,jhonpaulrocha/openhabss,paulianttila/openhab,cslauritsen/openhab,dodger777/openhabMod,Greblys/openhab,kbialek/openhab,gernoteger/openhab_contributions,netwolfuk/openhab,svenschreier/openhab,gunthor/openhab,MCherifiOSS/openhab,gerrieg/openhab,PlegmaLabs/openhab,holgercn/openhab,holgercn/openhab,curtisstpierre/openhab,Mixajlo/openhab,berndpfrommer/openhab,savageautomate/openhab,paixaop/openhab,openhab/openhab,hemantsangwan/openhab,Jakey69/openhab,bbesser/openhab1-addons,PlegmaLabs/openhab,mjsolidarios/openhab,cvanorman/openhab,kaikreuzer/openhab,cesarmarinhorj/openhab,doubled-ca/openhab1-addons,marcelerkel/openhab,svenschreier/openhab,swatchy2dot0/openhab,tarioch/openhab,elifesy/openhab,gernoteger/openhab_contributions,PolymorhicCode/openhab,evansj/openhab,SwissKid/openhab,mroeckl/openhab,kuijp/openhab,smerschjohann/openhab,PlegmaLabs/openhab,magcode/openhab,mleegwt/openhab,paphko/openhab,berndpfrommer/openhab,magcode/openhab,sitewhere/openhab,abrenk/openhab,marcelerkel/openhab,dmize/openhab,ShanksSGV/openhab,robnielsen/openhab,wojtus/openhab,gilhmauy/openhab,g8kmh/openhab,coolweb/openhab,g8kmh/openhab,kaikreuzer/openhab,cyclingengineer/openhab,clanko8285/openhab,beowulfe/openhab,sedstef/openhab,watou/openhab,revenz/openhab,taupinfada/openhab,robnielsen/openhab,saydulk/openhab,marcelrv/openhab,mleegwt/openhab,MCherifiOSS/openhab,tomtrath/openhab,innoq/openhab,cesarmarinhorj/openhab,andreasgebauer/openhab,jforge/openhab,coolweb/openhab,wojtus/openhab,andrey-desman/openhab-hdl,tdiekmann/openhab,clanko8285/openhab,jowiho/openhab,foxy82/openhab,andrey-desman/openhab-hdl,sitewhere/openhab,mattnl/openhab,tomtrath/openhab,swatchy2dot0/openhab,digitaldan/openhab,tisoft/openhab,mjsolidarios/openhab,cvanorman/openhab,curtisstpierre/openhab,mash0304/openhab,dvanherbergen/openhab,openhab/openhab,pravinw/openhab,lmaertin/openhab,RafalLukawiecki/openhab1-addons,resetnow/openhab,mash0304/openhab,ssalonen/openhab,ollie-dev/openhab,TheNetStriker/openhab,CrackerStealth/openhab,lewie/openhab,dmize/openhab,kgoderis/openhab,cschneider/openhab,craigham/openhab,digitaldan/openhab,basriram/openhab,smerschjohann/openhab,Greblys/openhab,ollie-dev/openhab,svenschaefer74/openhab,tdiekmann/openhab,vgoldman/openhab,xsnrg/openhab,bakrus/openhab,peuter/openhab,Mike-Petersen/openhab,steintore/openhab,craigham/openhab,SwissKid/openhab,JensErat/openhab,marcelrv/openhab,cesarmarinhorj/openhab,holgercn/openhab,tisoft/openhab,dmize/openhab,dfliess/openhab,craigham/openhab,TheOriginalAndrobot/openhab,kbialek/openhab,dbadia/openhab,steintore/openhab,JensErat/openhab,vgoldman/openhab,sedstef/openhab,eschava/openhab,jowiho/openhab,coolweb/openhab,CrackerStealth/openhab,clanko8285/openhab,cesarmarinhorj/openhab,sja/openhab,cyclingengineer/openhab,kreutpet/openhab,sibbi77/openhab,falkena/openhab,computergeek1507/openhab,TheNetStriker/openhab,berndpfrommer/openhab,paolodenti/openhab,bakrus/openhab,steintore/openhab,cdjackson/openhab,richbeales/openhab,sumnerboy12/openhab,georgwiltschek/openhab,cvanorman/openhab,mash0304/openhab,marcelrv/openhab,lmaertin/openhab,kbialek/openhab,Gerguis/openhab2,gunthor/openhab,aschor/openhab,holgercn/openhab,Greblys/openhab,coolweb/openhab,lewie/openhab,xsnrg/openhab,ShanksSGV/openhab,foxy82/openhab,Gerguis/open,paolodenti/openhab,hmerk/openhab,gernoteger/openhab_contributions,AutoMates/openhab,TheOriginalAndrobot/openhab,lmaertin/openhab,paulianttila/openhab,juri8/openhab,dfliess/openhab,smerschjohann/openhab,maraszm/openhab,paulianttila/openhab,Jakey69/openhab,dbadia/openhab,idserda/openhab,kreutpet/openhab,fbeke/openhab,jenskastensson/openhab,ShanksSGV/openhab,robbyb67/openhab,wuellueb/openhab,theoweiss/openhab,wuellueb/openhab,rmayr/openhab,PlegmaLabs/openhab,PlegmaLabs/openhab,dereulenspiegel/openhab,jowiho/openhab,cyclingengineer/openhab,kuijp/openhab,g8kmh/openhab,aidanom1/openhab,andrey-desman/openhab-hdl,aschor/openhab,cyclingengineer/openhab,steve-bate/openhab,Gerguis/openhab2,docbender/openhab,jenskastensson/openhab,RafalLukawiecki/openhab1-addons,dbadia/openhab,mjsolidarios/openhab,stefanroellin/openhab,joek/openhab1-addons,sja/openhab,clanko8285/openhab,steintore/openhab,kreutpet/openhab,digitaldan/openhab,innoq/openhab,frami/openhab,mattnl/openhab,dvanherbergen/openhab,netwolfuk/openhab,maraszm/openhab,resetnow/openhab,cdjackson/openhab,georgwiltschek/openhab,svenschaefer74/openhab,foxy82/openhab,craigham/openhab,gregfinley/openhab,craigham/openhab,fbeke/openhab,savageautomate/openhab,kaikreuzer/openhab,lmaertin/openhab,CondormanFr/openhab,svenschaefer74/openhab,paixaop/openhab,netwolfuk/openhab,JensErat/openhab,elifesy/openhab,basriram/openhab,netwolfuk/openhab,clinique/openhab,mdbergmann/openhab,swatchy2dot0/openhab,andreasgebauer/openhab,mattnl/openhab,falkena/openhab,wep4you/openhab,digitaldan/openhab,mdbergmann/openhab,jforge/openhab,Jakey69/openhab,theoweiss/openhab,dominicdesu/openhab,cschneider/openhab,eschava/openhab,ollie-dev/openhab,tinnerm/openhab,CrackerStealth/openhab,gernoteger/openhab_contributions
/** * openHAB, the open Home Automation Bus. * Copyright (C) 2010-2012, openHAB.org <[email protected]> * * See the contributors.txt file in the distribution for a * full listing of individual contributors. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or * combining it with Eclipse (or a modified version of that library), * containing parts covered by the terms of the Eclipse Public License * (EPL), the licensors of this Program grant you additional permission * to convey the resulting work. */ package org.openhab.library.tel.types; import java.util.Formatter; import java.util.SortedMap; import java.util.TreeMap; import org.apache.commons.lang.StringUtils; import org.openhab.core.library.types.StringType; import org.openhab.core.types.Command; import org.openhab.core.types.ComplexType; import org.openhab.core.types.PrimitiveType; import org.openhab.core.types.State; /** * This type can be used for items that are dealing with telephony functionality. * * @author Thomas.Eichstaedt-Engelen * @since 0.9.0 * */ public class CallType implements ComplexType, Command, State { protected static final String DEST_NUM = "destNum"; protected static final String ORIG_NUM = "origNum"; private static final String SEPARATOR = "##"; private SortedMap<String, PrimitiveType> callDetails; public static final State EMPTY = new CallType(new StringType(""), new StringType("")); public CallType() { callDetails = new TreeMap<String, PrimitiveType>(); } public CallType(String value) { this(); if (StringUtils.isNotBlank(value)) { String[] elements = value.split(SEPARATOR); if (elements.length == 2) { callDetails.put(DEST_NUM, new StringType(elements[0])); callDetails.put(ORIG_NUM, new StringType(elements[1])); } } } public CallType(String origNum, String destNum) { this(new StringType(origNum), new StringType(destNum)); } public CallType(StringType origNum, StringType destNum) { this(); callDetails.put(DEST_NUM, destNum); callDetails.put(ORIG_NUM, origNum); } public SortedMap<String, PrimitiveType> getConstituents() { return callDetails; } public PrimitiveType getDestNum() { return callDetails.get(DEST_NUM); } public PrimitiveType getOrigNum() { return callDetails.get(ORIG_NUM); } /** * <p>Formats the value of this type according to a pattern (@see * {@link Formatter}). One single value of this type can be referenced * by the pattern using an index. The item order is defined by the natural * (alphabetical) order of their keys.</p> * * <p>Index '1' will reference the call's destination number and index '2' * will reference the call's origination number.</p> * * @param pattern the pattern to use containing indexes to reference the * single elements of this type. */ public String format(String pattern) { return String.format(pattern, callDetails.values().toArray()); } public CallType valueOf(String value) { return new CallType(value); } @Override public String toString() { return getOrigNum() + SEPARATOR + getDestNum(); } }
bundles/library/org.openhab.library.tel/src/main/java/org/openhab/library/tel/types/CallType.java
/** * openHAB, the open Home Automation Bus. * Copyright (C) 2010-2012, openHAB.org <[email protected]> * * See the contributors.txt file in the distribution for a * full listing of individual contributors. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or * combining it with Eclipse (or a modified version of that library), * containing parts covered by the terms of the Eclipse Public License * (EPL), the licensors of this Program grant you additional permission * to convey the resulting work. */ package org.openhab.library.tel.types; import java.util.Formatter; import java.util.SortedMap; import java.util.TreeMap; import org.openhab.core.library.types.StringType; import org.openhab.core.types.Command; import org.openhab.core.types.ComplexType; import org.openhab.core.types.PrimitiveType; import org.openhab.core.types.State; /** * This type can be used for items that are dealing with telephony functionality. * * @author Thomas.Eichstaedt-Engelen * @since 0.9.0 * */ public class CallType implements ComplexType, Command, State { protected static final String DEST_NUM = "destNum"; protected static final String ORIG_NUM = "origNum"; private SortedMap<String, PrimitiveType> callDetails; public static final State EMPTY = new CallType(new StringType(""), new StringType("")); public CallType(String origNum, String destNum) { this(new StringType(origNum), new StringType(destNum)); } public CallType(StringType origNum, StringType destNum) { callDetails = new TreeMap<String, PrimitiveType>(); callDetails.put(DEST_NUM, destNum); callDetails.put(ORIG_NUM, origNum); } public SortedMap<String, PrimitiveType> getConstituents() { return callDetails; } public PrimitiveType getDestNum() { return callDetails.get(DEST_NUM); } public PrimitiveType getOrigNum() { return callDetails.get(ORIG_NUM); } /** * <p>Formats the value of this type according to a pattern (@see * {@link Formatter}). One single value of this type can be referenced * by the pattern using an index. The item order is defined by the natural * (alphabetical) order of their keys.</p> * * <p>Index '1' will reference the call's destination number and index '2' * will reference the call's origination number.</p> * * @param pattern the pattern to use containing indexes to reference the * single elements of this type. */ public String format(String pattern) { return String.format(pattern, callDetails.values().toArray()); } @Override public String toString() { return "CallType [callDetails=" + callDetails + "]"; } }
changed toString() added valueOf - a CallType can now be created with String separated by a '##'
bundles/library/org.openhab.library.tel/src/main/java/org/openhab/library/tel/types/CallType.java
changed toString() added valueOf - a CallType can now be created with String separated by a '##'
Java
epl-1.0
c86782d9682f49fdd97f7c7f3751ee2cef9c7801
0
ELTE-Soft/xUML-RT-Executor
package hu.eltesoft.modelexecution.filemanager; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Paths; /** * Manager class to write, update and delete Java files according to package * hierarchy under a specified root directory. */ public class FileManager { private String rootDirectory; private static final String DEFAULT_ROOT_DIRECTORY = ""; /** * @param rootDirectory * Root directory of the package hierarchy to be created. * Warning: Empty path is set as default if this parameter is * null. */ public FileManager(String rootDirectory) { this.rootDirectory = rootDirectory; if (null == this.rootDirectory) { this.rootDirectory = DEFAULT_ROOT_DIRECTORY; } } /** * @param qualifiedName * A fully qualified class name like a.b.cc.Ddd or Aaa * @param content * The content to be written in the file. */ public void addOrUpdate(String qualifiedName, String content) throws IOException { if (null == qualifiedName) { return; } File outFile = qualifiedNameToFile(qualifiedName); createDirectoryForFile(outFile); try (FileWriter writer = new FileWriter(outFile)) { writer.write(content); } } /** * Removes a Java file if possible. * * @param qualifiedName * Fully qualified class name of the Java file to be deleted. */ public void remove(String qualifiedName) { if (null == qualifiedName) { return; } File toDelete = qualifiedNameToFile(qualifiedName); toDelete.delete(); } /** * Remove all files and directories under the root. */ public void cleanup() { File root = new File(rootDirectory); for (File file : root.listFiles()) { delete(file); } } private static void delete(File toDelete) { if (toDelete.exists()) { if (toDelete.isDirectory()) { File[] files = toDelete.listFiles(); for (File file : files) { delete(file); } } toDelete.delete(); } } private File qualifiedNameToFile(String qualifiedName) { String[] parts = qualifiedName.split("\\."); if (parts.length > 0) { parts[parts.length - 1] += ".java"; } return Paths.get(rootDirectory, parts).toFile(); } private static void createDirectoryForFile(File outFile) { File parent = outFile.getParentFile(); if (null != parent) { parent.mkdirs(); } } }
hu.eltesoft.modelexecution.filemanager/src/hu/eltesoft/modelexecution/filemanager/FileManager.java
package hu.eltesoft.modelexecution.filemanager; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Paths; /** * Manager class to write, update and delete Java files according to package * hierarchy under a specified root directory. */ public class FileManager { private String rootDirectory; private static final String DEFAULT_ROOT_DIRECTORY = ""; /** * @param rootDirectory * Root directory of the package hierarchy to be created. */ public FileManager(String rootDirectory) { this.rootDirectory = rootDirectory; if (null == this.rootDirectory) { this.rootDirectory = DEFAULT_ROOT_DIRECTORY; } } /** * @param qualifiedName * A fully qualified class name like a.b.cc.Ddd or Aaa * @param content * The content to be written in the file. */ public void addOrUpdate(String qualifiedName, String content) throws IOException { if (null == qualifiedName) { return; } File outFile = qualifiedNameToFile(qualifiedName); File parent = outFile.getParentFile(); if (null != parent) { parent.mkdirs(); } try(FileWriter writer = new FileWriter(outFile)) { writer.write(content); } } /** * Removes a Java file if possible. * * @param qualifiedName * Fully qualified class name of the Java file to be deleted. */ public void remove(String qualifiedName) { if (null == qualifiedName) { return; } File toDelete = qualifiedNameToFile(qualifiedName); toDelete.delete(); } /** * Remove all files and directories under the root. */ public void cleanup() { File root = new File(rootDirectory); for (File file : root.listFiles()) { delete(file); } } private static void delete(File toDelete) { if (toDelete.exists()) { if (toDelete.isDirectory()) { File[] files = toDelete.listFiles(); for (File file : files) { delete(file); } } toDelete.delete(); } } private File qualifiedNameToFile(String qualifiedName) { String[] parts = qualifiedName.split("\\."); if (parts.length > 0) { parts[parts.length - 1] += ".java"; } return Paths.get(rootDirectory, parts).toFile(); } }
File manager: extract method; more details in a comment
hu.eltesoft.modelexecution.filemanager/src/hu/eltesoft/modelexecution/filemanager/FileManager.java
File manager: extract method; more details in a comment
Java
epl-1.0
8f9a8f34c33cab1e6c691c9f77997acfba6954e2
0
tectronics/mercurialeclipse,leinier/mercurialeclipse,boa0332/mercurialeclipse,naidu/mercurialeclipse
/******************************************************************************* * Copyright (c) 2006, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Andrei Loskutov - adopting to hg * Soren Mathiasen - implemented multiple repositories * Martin Olsen - implemented multiple repositories *******************************************************************************/ package com.vectrace.MercurialEclipse.synchronize.cs; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Observer; import java.util.Set; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.resources.mapping.ResourceTraversal; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.team.core.diff.IDiffChangeEvent; import org.eclipse.team.core.mapping.ISynchronizationContext; import org.eclipse.team.internal.core.subscribers.BatchingChangeSetManager; import org.eclipse.team.internal.core.subscribers.BatchingChangeSetManager.CollectorChangeEvent; import org.eclipse.team.internal.core.subscribers.IChangeSetChangeListener; import org.eclipse.team.internal.ui.Utils; import org.eclipse.team.internal.ui.synchronize.ChangeSetCapability; import org.eclipse.team.internal.ui.synchronize.IChangeSetProvider; import org.eclipse.team.ui.mapping.SynchronizationContentProvider; import org.eclipse.team.ui.synchronize.ISynchronizePageConfiguration; import org.eclipse.team.ui.synchronize.ISynchronizeParticipant; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.navigator.ICommonContentExtensionSite; import org.eclipse.ui.navigator.INavigatorContentExtension; import org.eclipse.ui.navigator.INavigatorContentService; import org.eclipse.ui.navigator.INavigatorSorterService; import com.vectrace.MercurialEclipse.MercurialEclipsePlugin; import com.vectrace.MercurialEclipse.model.ChangeSet; import com.vectrace.MercurialEclipse.model.ChangeSet.Direction; import com.vectrace.MercurialEclipse.model.FileFromChangeSet; import com.vectrace.MercurialEclipse.model.IHgRepositoryLocation; import com.vectrace.MercurialEclipse.model.PathFromChangeSet; import com.vectrace.MercurialEclipse.model.UncommittedChangeSet; import com.vectrace.MercurialEclipse.model.WorkingChangeSet; import com.vectrace.MercurialEclipse.preferences.MercurialPreferenceConstants; import com.vectrace.MercurialEclipse.synchronize.HgDragAdapterAssistant; import com.vectrace.MercurialEclipse.synchronize.HgSubscriberMergeContext; import com.vectrace.MercurialEclipse.synchronize.MercurialSynchronizeParticipant; import com.vectrace.MercurialEclipse.synchronize.MercurialSynchronizeSubscriber; import com.vectrace.MercurialEclipse.synchronize.PresentationMode; import com.vectrace.MercurialEclipse.synchronize.RepositorySynchronizationScope.RepositoryLocationMap; import com.vectrace.MercurialEclipse.team.cache.MercurialStatusCache; import com.vectrace.MercurialEclipse.utils.ResourceUtils; @SuppressWarnings("restriction") public class HgChangeSetContentProvider extends SynchronizationContentProvider { public static final String ID = "com.vectrace.MercurialEclipse.changeSetContent"; private static final MercurialStatusCache STATUS_CACHE = MercurialStatusCache.getInstance(); private final class UcommittedSetListener implements IPropertyChangeListener { public void propertyChange(PropertyChangeEvent event) { Object input = getTreeViewer().getInput(); if (input instanceof HgChangeSetModelProvider) { Utils.asyncExec(new Runnable() { public void run() { TreeViewer treeViewer = getTreeViewer(); treeViewer.getTree().setRedraw(false); treeViewer.refresh(uncommitted, true); if (uncommitted instanceof ChangesetGroup) { for (ChangeSet cs : ((ChangesetGroup) uncommitted).getChangesets()) { treeViewer.refresh(cs, true); } } treeViewer.getTree().setRedraw(true); } }, getTreeViewer()); } } } private final class PreferenceListener implements IPropertyChangeListener { public void propertyChange(PropertyChangeEvent event) { Object input = getTreeViewer().getInput(); String property = event.getProperty(); final boolean bLocal = property .equals(MercurialPreferenceConstants.PREF_SYNC_ENABLE_LOCAL_CHANGESETS); if ((property.equals(PresentationMode.PREFERENCE_KEY) || bLocal || property.equals(MercurialPreferenceConstants.PREF_SYNC_SHOW_EMPTY_GROUPS)) && input instanceof HgChangeSetModelProvider) { Utils.asyncExec(new Runnable() { public void run() { TreeViewer treeViewer = getTreeViewer(); if (bLocal) { recreateUncommittedEntry(treeViewer); } else { treeViewer.getTree().setRedraw(false); treeViewer.refresh(uncommitted, true); for(RepositoryChangesetGroup sg : projectGroup) { treeViewer.refresh(sg.getOutgoing(), true); treeViewer.refresh(sg.getIncoming(), true); } treeViewer.getTree().setRedraw(true); treeViewer.refresh(); // TODO: this is unnecessary? } } }, getTreeViewer()); } } } private final class CollectorListener implements IChangeSetChangeListener, BatchingChangeSetManager.IChangeSetCollectorChangeListener { public void setAdded(final org.eclipse.team.internal.core.subscribers.ChangeSet cs) { ChangeSet set = (ChangeSet)cs; if (isVisibleInMode(set)) { final ChangesetGroup toRefresh = findChangeSetInProjects(cs); if(toRefresh != null) { boolean added = toRefresh.getChangesets().add(set); if (added) { Utils.asyncExec(new Runnable() { public void run() { getTreeViewer().refresh(toRefresh, true); } }, getTreeViewer()); } } } } public void setRemoved(final org.eclipse.team.internal.core.subscribers.ChangeSet cs) { ChangeSet set = (ChangeSet)cs; if (isVisibleInMode(set)) { final ChangesetGroup toRefresh = findChangeSetInProjects(cs); boolean removed = toRefresh.getChangesets().remove(set); if(removed) { Utils.asyncExec(new Runnable() { public void run() { getTreeViewer().refresh(toRefresh, true); } }, getTreeViewer()); } } } private ChangesetGroup findChangeSetInProjects(final org.eclipse.team.internal.core.subscribers.ChangeSet cs) { ChangeSet set = (ChangeSet) cs; for (RepositoryChangesetGroup sg : projectGroup) { if (set.getRepository().equals(sg.getLocation())) { if (set.getDirection() == Direction.INCOMING) { return sg.getIncoming(); } if (set.getDirection() == Direction.OUTGOING) { return sg.getOutgoing(); } } } return null; } public void defaultSetChanged(final org.eclipse.team.internal.core.subscribers.ChangeSet previousDefault, final org.eclipse.team.internal.core.subscribers.ChangeSet set) { // user has requested a manual refresh: simply refresh root elements getRootElements(); } public void nameChanged(final org.eclipse.team.internal.core.subscribers.ChangeSet set) { // ignored } public void resourcesChanged(final org.eclipse.team.internal.core.subscribers.ChangeSet set, final IPath[] paths) { // ignored } public void changeSetChanges(final CollectorChangeEvent event, IProgressMonitor monitor) { // ignored } } private HgChangesetsCollector csCollector; private boolean collectorInitialized; private final IChangeSetChangeListener collectorListener; private final IPropertyChangeListener uncommittedSetListener; private final IPropertyChangeListener preferenceListener; private final List<RepositoryChangesetGroup> projectGroup; private WorkbenchContentProvider provider; private IUncommitted uncommitted; public HgChangeSetContentProvider() { super(); projectGroup = new ArrayList<RepositoryChangesetGroup>(); collectorListener = new CollectorListener(); uncommittedSetListener = new UcommittedSetListener(); preferenceListener = new PreferenceListener(); MercurialEclipsePlugin.getDefault().getPreferenceStore().addPropertyChangeListener(preferenceListener); uncommitted = makeUncommittedEntry(); } private static IUncommitted makeUncommittedEntry() { if (MercurialEclipsePlugin.getDefault().getPreferenceStore().getBoolean( MercurialPreferenceConstants.PREF_SYNC_ENABLE_LOCAL_CHANGESETS)) { return new UncommittedChangesetGroup(); } return new UncommittedChangeSet(); } @Override protected String getModelProviderId() { return HgChangeSetModelProvider.ID; } private boolean isOutgoingVisible(){ return getConfiguration().getMode() != ISynchronizePageConfiguration.INCOMING_MODE; } private boolean isIncomingVisible(){ return getConfiguration().getMode() != ISynchronizePageConfiguration.OUTGOING_MODE; } private boolean isEnabled() { final Object input = getViewer().getInput(); return input instanceof HgChangeSetModelProvider; } @Override public Object[] getChildren(Object parent) { return getElements(parent); } @Override public Object[] getElements(Object parent) { if (parent instanceof ISynchronizationContext) { // Do not show change sets when all models are visible because // model providers that override the resource content may cause // problems for the change set content provider return new Object[0]; } if(isEnabled()){ if(!((HgChangeSetModelProvider) getViewer().getInput()).isParticipantCreated()){ initCollector(); // on startup, do not start to show anything for the first time: // show "reminder" page which allows user to choose synchronize or not // return new Object[0]; // TODO right now it doesn't make sense to show "reminder page" as we // connect to the remote servers automatically as soon as the sync view // shows up. } } if (parent == getModelProvider()) { return getRootElements(); } else if (parent instanceof ChangesetGroup) { ChangesetGroup group = (ChangesetGroup) parent; Direction direction = group.getDirection(); if (isOutgoing(direction)) { if (isOutgoingVisible()) { return group.getChangesets().toArray(); } return new Object[] { new FilteredPlaceholder() }; } if(direction == Direction.INCOMING){ if (isIncomingVisible()) { return group.getChangesets().toArray(); } return new Object[] {new FilteredPlaceholder()}; } if(direction == Direction.LOCAL){ return group.getChangesets().toArray(); } } else if (parent instanceof RepositoryChangesetGroup) { // added groups to view boolean showEmpty = MercurialEclipsePlugin.getDefault().getPreferenceStore() .getBoolean(MercurialPreferenceConstants.PREF_SYNC_SHOW_EMPTY_GROUPS); RepositoryChangesetGroup supergroup = (RepositoryChangesetGroup) parent; ArrayList<Object> groups =new ArrayList<Object>(); if(supergroup.getIncoming().getChangesets().size() > 0) { groups.add(supergroup.getIncoming()); } else if(showEmpty) { groups.add(supergroup.getIncoming()); } if(supergroup.getOutgoing().getChangesets().size() > 0) { groups.add(supergroup.getOutgoing()); } else if(showEmpty) { groups.add(supergroup.getOutgoing()); } return groups.toArray(); } else if (parent instanceof ChangeSet) { FileFromChangeSet[] files = ((ChangeSet) parent).getChangesetFiles(); if (files.length != 0) { switch (PresentationMode.get()) { case FLAT: return files; case TREE: return collectTree(parent, files); case COMPRESSED_TREE: return collectCompressedTree(parent, files); } } } else if (parent instanceof PathFromChangeSet) { return ((PathFromChangeSet) parent).getChildren(); } return new Object[0]; } private synchronized void initProjects(MercurialSynchronizeSubscriber subscriber) { RepositoryLocationMap locations = subscriber.getParticipant().getRepositoryLocations(); for (IHgRepositoryLocation repoLocation : locations.getLocations()) { RepositoryChangesetGroup scg = new RepositoryChangesetGroup( locations.getRoot(repoLocation), repoLocation); scg.setIncoming(new ChangesetGroup("Incoming", Direction.INCOMING)); scg.setOutgoing(new ChangesetGroup("Outgoing", Direction.OUTGOING)); scg.setProjects(Arrays.asList(locations.getProjects(repoLocation))); projectGroup.add(scg); } } private Object[] collectTree(Object parent, FileFromChangeSet[] files) { List<Object> out = new ArrayList<Object>(files.length * 2); for (FileFromChangeSet file : files) { IPath path = file.getPath(); if(path == null) { out.add(Path.EMPTY); } else { out.add(path.removeLastSegments(1)); } out.add(file); } return collectTree(parent, out); } private Object[] collectTree(Object parent, List<Object> files) { HashMap<String, List<Object>> map = new HashMap<String, List<Object>>(); List<Object> out = new ArrayList<Object>(); for (Iterator<Object> it = files.iterator(); it.hasNext();) { IPath path = (IPath) it.next(); FileFromChangeSet file = (FileFromChangeSet) it.next(); if (path == null || 0 == path.segmentCount()) { out.add(file); } else { String seg = path.segment(0); List<Object> l = map.get(seg); if (l == null) { map.put(seg, l = new ArrayList<Object>()); } l.add(path.removeFirstSegments(1)); l.add(file); } } for (String seg : map.keySet()) { out.add(new TreePathFromChangeSet(parent, seg, map.get(seg))); } return out.toArray(new Object[out.size()]); } private Object[] collectCompressedTree(Object parent, FileFromChangeSet[] files) { HashMap<IPath, List<FileFromChangeSet>> map = new HashMap<IPath, List<FileFromChangeSet>>(); List<Object> out = new ArrayList<Object>(); for (FileFromChangeSet file : files) { IPath path = file.getPath(); path = (path == null) ? Path.EMPTY : path.removeLastSegments(1); List<FileFromChangeSet> l = map.get(path); if (l == null) { map.put(path, l = new ArrayList<FileFromChangeSet>()); } l.add(file); } for (IPath path : map.keySet()) { final List<FileFromChangeSet> data = map.get(path); if (path.isEmpty()) { out.addAll(data); } else { out.add(new CompressedTreePathFromChangeSet(parent, path.toString(), data)); } } return out.toArray(new Object[out.size()]); } private void ensureRootsAdded() { TreeViewer viewer = getTreeViewer(); TreeItem[] children = viewer.getTree().getItems(); if(children.length == 0) { viewer.add(viewer.getInput(), getRootElements()); } } // traverse through elements and add them to the correct group private Object[] getRootElements() { initCollector(); List<ChangeSet> result = new ArrayList<ChangeSet>(); Collection<ChangeSet> allSets = getAllSets(); for (ChangeSet set : allSets) { if (hasChildren(set)) { result.add(set); } } boolean showOutgoing = isOutgoingVisible(); boolean showIncoming = isIncomingVisible(); for (ChangeSet set : result) { for (RepositoryChangesetGroup group : projectGroup) { if (set.getRepository().equals(group.getLocation())) { Direction direction = set.getDirection(); if (showOutgoing && (isOutgoing(direction))) { group.getOutgoing().getChangesets().add(set); } if (showIncoming && direction == Direction.INCOMING) { group.getIncoming().getChangesets().add(set); } } } } uncommitted.update(STATUS_CACHE, null); List<Object> itemsToShow = new ArrayList<Object>(); itemsToShow.add(uncommitted); if (projectGroup.size() == 1) { itemsToShow.addAll(Arrays.asList(getElements(projectGroup.get(0)))); } else { itemsToShow.addAll(projectGroup); } return itemsToShow.toArray(); } private synchronized void initCollector() { if (!collectorInitialized) { initializeChangeSets(getChangeSetCapability()); collectorInitialized = true; } } @Override protected ResourceTraversal[] getTraversals( ISynchronizationContext context, Object object) { if (object instanceof ChangeSet) { ChangeSet set = (ChangeSet) object; IResource[] resources = set.getResources(); return new ResourceTraversal[] { new ResourceTraversal(resources, IResource.DEPTH_ZERO, IResource.NONE) }; } if(object instanceof IResource){ IResource[] resources = new IResource[]{(IResource) object}; return new ResourceTraversal[] { new ResourceTraversal(resources, IResource.DEPTH_ZERO, IResource.NONE) }; } if(object instanceof ChangesetGroup){ ChangesetGroup group = (ChangesetGroup) object; Set<ChangeSet> changesets = group.getChangesets(); Set<IFile> all = new HashSet<IFile>(); for (ChangeSet changeSet : changesets) { all.addAll(changeSet.getFiles()); } IResource[] resources = all.toArray(new IResource[0]); return new ResourceTraversal[] { new ResourceTraversal(resources, IResource.DEPTH_ZERO, IResource.NONE) }; } if(object instanceof RepositoryChangesetGroup){ RepositoryChangesetGroup supergroup = (RepositoryChangesetGroup) object; Set<IFile> all = new HashSet<IFile>(); Set<ChangeSet> changesets = supergroup.getIncoming().getChangesets(); for (ChangeSet changeSet : changesets) { all.addAll(changeSet.getFiles()); } changesets = supergroup.getOutgoing().getChangesets(); for (ChangeSet changeSet : changesets) { all.addAll(changeSet.getFiles()); } IResource[] resources = all.toArray(new IResource[0]); return new ResourceTraversal[] { new ResourceTraversal(resources, IResource.DEPTH_ZERO, IResource.NONE) }; } return new ResourceTraversal[0]; } /** * @see org.eclipse.team.ui.mapping.SynchronizationContentProvider#hasChildrenInContext(org.eclipse.team.core.mapping.ISynchronizationContext, * java.lang.Object) */ @Override protected boolean hasChildrenInContext(ISynchronizationContext context, Object element) { if (element instanceof ChangeSet) { return hasChildren((ChangeSet) element); } else if (element instanceof ChangesetGroup) { ChangesetGroup group = (ChangesetGroup) element; Direction direction = group.getDirection(); if (isOutgoingVisible() && isOutgoing(direction)) { return true; } if(isIncomingVisible() && direction == Direction.INCOMING){ return true; } } else if (element instanceof RepositoryChangesetGroup) { boolean showEmptyGroups = MercurialEclipsePlugin.getDefault().getPreferenceStore().getBoolean(MercurialPreferenceConstants.PREF_SYNC_SHOW_EMPTY_GROUPS); RepositoryChangesetGroup supergroup = (RepositoryChangesetGroup) element; if (isOutgoingVisible() && (showEmptyGroups || supergroup.getOutgoing().getChangesets().size() > 0)) { return true; } if (isIncomingVisible() && (showEmptyGroups || supergroup.getIncoming().getChangesets().size() > 0)) { return true; } } else if (element instanceof PathFromChangeSet) { return true; } return false; } private boolean isVisibleInMode(ChangeSet cs) { int mode = getConfiguration().getMode(); if (cs != null) { switch (mode) { case ISynchronizePageConfiguration.BOTH_MODE: return true; case ISynchronizePageConfiguration.CONFLICTING_MODE: return containsConflicts(cs); case ISynchronizePageConfiguration.INCOMING_MODE: return cs.getDirection() == Direction.INCOMING; case ISynchronizePageConfiguration.OUTGOING_MODE: return hasConflicts(cs) || isOutgoing(cs.getDirection()); default: break; } } return true; } private static boolean isOutgoing(Direction direction) { return direction == Direction.OUTGOING || direction == Direction.LOCAL; } private static boolean hasConflicts(ChangeSet cs) { // Conflict mode not meaningful in a DVCS return false; } private static boolean containsConflicts(ChangeSet cs) { // Conflict mode not meaningful in a DVCS return false; } private boolean hasChildren(ChangeSet changeset) { return isVisibleInMode(changeset) && (!changeset.getFiles().isEmpty() || changeset.getChangesetFiles().length > 0); } /** * Return all the change sets (incoming and outgoing). This * list must not include the unassigned set. * @return all the change sets (incoming and outgoing) */ private Collection<ChangeSet> getAllSets() { if (csCollector != null) { return csCollector.getChangeSets(); } return new HashSet<ChangeSet>(); } @Override public void init(ICommonContentExtensionSite site) { super.init(site); HgChangeSetSorter sorter = getSorter(); if (sorter != null) { sorter.setConfiguration(getConfiguration()); } MercurialSynchronizeParticipant participant = (MercurialSynchronizeParticipant) getConfiguration().getParticipant(); getExtensionSite().getService().getDnDService().bindDragAssistant(new HgDragAdapterAssistant()); uncommitted.setContext((HgSubscriberMergeContext) participant.getContext()); } private HgChangeSetSorter getSorter() { INavigatorContentService contentService = getExtensionSite().getService(); INavigatorSorterService sortingService = contentService.getSorterService(); INavigatorContentExtension extension = getExtensionSite().getExtension(); if (extension != null) { ViewerSorter sorter = sortingService.findSorter(extension.getDescriptor(), getModelProvider(), null, null); // incoming, incoming // TODO: sorting if (sorter instanceof HgChangeSetSorter) { return (HgChangeSetSorter) sorter; } } return null; } private void initializeChangeSets(ChangeSetCapability csc) { if (csc.supportsCheckedInChangeSets()) { csCollector = ((HgChangeSetCapability) csc).createSyncInfoSetChangeSetCollector(getConfiguration()); csCollector.addListener(collectorListener); initializeUncommittedEntry(csCollector.getSubscriber().getProjects()); initProjects(csCollector.getSubscriber()); } } private void initializeUncommittedEntry(IProject[] projects) { uncommitted.setProjects(projects); uncommitted.addListener(uncommittedSetListener); STATUS_CACHE.addObserver(uncommitted); } @Override public void dispose() { if (csCollector != null) { csCollector.removeListener(collectorListener); csCollector.dispose(); } MercurialEclipsePlugin.getDefault().getPreferenceStore().removePropertyChangeListener(preferenceListener); disposeUncommittedEntry(); for(RepositoryChangesetGroup sg : projectGroup) { sg.getOutgoing().getChangesets().clear(); sg.getIncoming().getChangesets().clear(); } projectGroup.clear(); super.dispose(); } private void disposeUncommittedEntry() { uncommitted.removeListener(uncommittedSetListener); STATUS_CACHE.deleteObserver(uncommitted); uncommitted.dispose(); uncommitted = null; } protected void recreateUncommittedEntry(TreeViewer tree) { IProject[] projects = uncommitted.getProjects(); HgSubscriberMergeContext ctx = uncommitted.getContext(); disposeUncommittedEntry(); uncommitted = makeUncommittedEntry(); uncommitted.setContext(ctx); if (collectorInitialized) { initializeUncommittedEntry(projects); } tree.refresh(); } @Override public void diffsChanged(IDiffChangeEvent event, IProgressMonitor monitor) { Utils.asyncExec(new Runnable() { public void run() { ensureRootsAdded(); } }, getTreeViewer()); if (csCollector != null) { csCollector.handleChange(event); } // no other updates here, as it simply doesn't fit into the changeset concept. } private ChangeSetCapability getChangeSetCapability() { ISynchronizeParticipant participant = getConfiguration().getParticipant(); if (participant instanceof IChangeSetProvider) { IChangeSetProvider csProvider = (IChangeSetProvider) participant; return csProvider.getChangeSetCapability(); } return null; } private TreeViewer getTreeViewer() { return (TreeViewer) getViewer(); } @Override protected ITreeContentProvider getDelegateContentProvider() { if (provider == null) { provider = new WorkbenchContentProvider(); } return provider; } @Override protected Object getModelRoot() { return ResourcesPlugin.getWorkspace().getRoot(); } /** * * @param file may be null * @return may return null, if the given file is null, not selected or is not contained * in any selected changesets */ public ChangeSet getParentOfSelection(FileFromChangeSet file){ TreeItem[] selection = getTreeViewer().getTree().getSelection(); for (TreeItem treeItem : selection) { if(treeItem.getData() != file){ continue; } TreeItem parentItem = treeItem.getParentItem(); while (parentItem != null && !(parentItem.getData() instanceof ChangeSet)) { parentItem = parentItem.getParentItem(); } if (parentItem != null) { return (ChangeSet) parentItem.getData(); } } return null; } /** * @param changeset may be null * @return may return null */ public ChangesetGroup getParentGroup(ChangeSet changeset){ if(changeset == null || changeset instanceof WorkingChangeSet){ return null; } boolean incoming = changeset.getDirection() == Direction.INCOMING; for (RepositoryChangesetGroup group : projectGroup) { ChangesetGroup g = incoming ? group.getIncoming() : group.getOutgoing(); if (g.getChangesets().contains(changeset)) { return g; } } return null; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("HgChangeSetContentProvider [collectorInitialized="); builder.append(collectorInitialized); builder.append(", "); if (csCollector != null) { builder.append("csCollector="); builder.append(csCollector); builder.append(", "); } if (provider != null) { builder.append("provider="); builder.append(provider); builder.append(", "); } builder.append("]"); return builder.toString(); } public IUncommitted getUncommittedEntry() { return uncommitted; } private class CompressedTreePathFromChangeSet extends PathFromChangeSet { protected final List<FileFromChangeSet> data; public CompressedTreePathFromChangeSet(Object prnt, String seg, List<FileFromChangeSet> data) { super(prnt, seg); this.data = data; if (data != null && data.size() > 0) { IFile file = data.get(0).getFile(); this.resource = file != null? file.getParent() : null; } } @Override public Object[] getChildren() { return data.toArray(new FileFromChangeSet[data.size()]); } @Override public Set<FileFromChangeSet> getFiles() { return new LinkedHashSet<FileFromChangeSet>(data); } } private class TreePathFromChangeSet extends PathFromChangeSet { protected final List<Object> data; public TreePathFromChangeSet(Object prnt, String seg, List<Object> data) { super(prnt, seg); this.data = data; this.resource = getResource(); } @Override public Object[] getChildren() { return collectTree(HgChangeSetContentProvider.this, data); } private IResource getResource() { IResource result = null; if (data.size() > 1) { // first object must be an IPath Object o1 = data.get(0); // and second must be FileFromChangeSet Object o2 = data.get(1); if (o1 instanceof IPath && o2 instanceof FileFromChangeSet) { FileFromChangeSet fcs = (FileFromChangeSet) o2; IResource childResource = ResourceUtils.getResource(fcs); if(childResource != null) { IPath folderPath = ResourceUtils.getPath(childResource).removeLastSegments( ((IPath) o1).segmentCount() + 1); return ResourcesPlugin.getWorkspace().getRoot().getContainerForLocation( folderPath); } } } return result; } @Override public Set<FileFromChangeSet> getFiles() { Set<FileFromChangeSet> files = new LinkedHashSet<FileFromChangeSet>(); for (Object o : data) { if(o instanceof FileFromChangeSet) { files.add((FileFromChangeSet) o); } } return files; } } protected static class FilteredPlaceholder { /** * @see java.lang.Object#toString() */ @Override public String toString() { return "<Filtered>"; } } public interface IUncommitted extends Observer { void setProjects(IProject[] projects); IProject[] getProjects(); void dispose(); void removeListener(IPropertyChangeListener listener); void addListener(IPropertyChangeListener listener); void setContext(HgSubscriberMergeContext context); HgSubscriberMergeContext getContext(); } }
plugin/src/com/vectrace/MercurialEclipse/synchronize/cs/HgChangeSetContentProvider.java
/******************************************************************************* * Copyright (c) 2006, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Andrei Loskutov - adopting to hg * Soren Mathiasen - implemented multiple repositories * Martin Olsen - implemented multiple repositories *******************************************************************************/ package com.vectrace.MercurialEclipse.synchronize.cs; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Observer; import java.util.Set; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.resources.mapping.ResourceTraversal; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.team.core.diff.IDiffChangeEvent; import org.eclipse.team.core.mapping.ISynchronizationContext; import org.eclipse.team.internal.core.subscribers.BatchingChangeSetManager; import org.eclipse.team.internal.core.subscribers.BatchingChangeSetManager.CollectorChangeEvent; import org.eclipse.team.internal.core.subscribers.IChangeSetChangeListener; import org.eclipse.team.internal.ui.Utils; import org.eclipse.team.internal.ui.synchronize.ChangeSetCapability; import org.eclipse.team.internal.ui.synchronize.IChangeSetProvider; import org.eclipse.team.ui.mapping.SynchronizationContentProvider; import org.eclipse.team.ui.synchronize.ISynchronizePageConfiguration; import org.eclipse.team.ui.synchronize.ISynchronizeParticipant; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.navigator.ICommonContentExtensionSite; import org.eclipse.ui.navigator.INavigatorContentExtension; import org.eclipse.ui.navigator.INavigatorContentService; import org.eclipse.ui.navigator.INavigatorSorterService; import com.vectrace.MercurialEclipse.MercurialEclipsePlugin; import com.vectrace.MercurialEclipse.model.ChangeSet; import com.vectrace.MercurialEclipse.model.ChangeSet.Direction; import com.vectrace.MercurialEclipse.model.FileFromChangeSet; import com.vectrace.MercurialEclipse.model.IHgRepositoryLocation; import com.vectrace.MercurialEclipse.model.PathFromChangeSet; import com.vectrace.MercurialEclipse.model.UncommittedChangeSet; import com.vectrace.MercurialEclipse.model.WorkingChangeSet; import com.vectrace.MercurialEclipse.preferences.MercurialPreferenceConstants; import com.vectrace.MercurialEclipse.synchronize.HgDragAdapterAssistant; import com.vectrace.MercurialEclipse.synchronize.HgSubscriberMergeContext; import com.vectrace.MercurialEclipse.synchronize.MercurialSynchronizeParticipant; import com.vectrace.MercurialEclipse.synchronize.MercurialSynchronizeSubscriber; import com.vectrace.MercurialEclipse.synchronize.PresentationMode; import com.vectrace.MercurialEclipse.synchronize.RepositorySynchronizationScope.RepositoryLocationMap; import com.vectrace.MercurialEclipse.team.cache.MercurialStatusCache; import com.vectrace.MercurialEclipse.utils.ResourceUtils; @SuppressWarnings("restriction") public class HgChangeSetContentProvider extends SynchronizationContentProvider { public static final String ID = "com.vectrace.MercurialEclipse.changeSetContent"; private static final MercurialStatusCache STATUS_CACHE = MercurialStatusCache.getInstance(); private final class UcommittedSetListener implements IPropertyChangeListener { public void propertyChange(PropertyChangeEvent event) { Object input = getTreeViewer().getInput(); if (input instanceof HgChangeSetModelProvider) { Utils.asyncExec(new Runnable() { public void run() { TreeViewer treeViewer = getTreeViewer(); treeViewer.getTree().setRedraw(false); treeViewer.refresh(uncommitted, true); if (uncommitted instanceof ChangesetGroup) { for (ChangeSet cs : ((ChangesetGroup) uncommitted).getChangesets()) { treeViewer.refresh(cs, true); } } treeViewer.getTree().setRedraw(true); } }, getTreeViewer()); } } } private final class PreferenceListener implements IPropertyChangeListener { public void propertyChange(PropertyChangeEvent event) { Object input = getTreeViewer().getInput(); String property = event.getProperty(); final boolean bLocal = property .equals(MercurialPreferenceConstants.PREF_SYNC_ENABLE_LOCAL_CHANGESETS); if ((property.equals(PresentationMode.PREFERENCE_KEY) || bLocal || property.equals(MercurialPreferenceConstants.PREF_SYNC_SHOW_EMPTY_GROUPS)) && input instanceof HgChangeSetModelProvider) { Utils.asyncExec(new Runnable() { public void run() { TreeViewer treeViewer = getTreeViewer(); if (bLocal) { recreateUncommittedEntry(treeViewer); } else { treeViewer.getTree().setRedraw(false); treeViewer.refresh(uncommitted, true); for(RepositoryChangesetGroup sg : projectGroup) { treeViewer.refresh(sg.getOutgoing(), true); treeViewer.refresh(sg.getIncoming(), true); } treeViewer.getTree().setRedraw(true); treeViewer.refresh(); // TODO: this is unnecessary? } } }, getTreeViewer()); } } } private final class CollectorListener implements IChangeSetChangeListener, BatchingChangeSetManager.IChangeSetCollectorChangeListener { public void setAdded(final org.eclipse.team.internal.core.subscribers.ChangeSet cs) { ChangeSet set = (ChangeSet)cs; if (isVisibleInMode(set)) { final ChangesetGroup toRefresh = findChangeSetInProjects(cs); if(toRefresh != null) { boolean added = toRefresh.getChangesets().add(set); if (added) { Utils.asyncExec(new Runnable() { public void run() { getTreeViewer().refresh(toRefresh, true); } }, getTreeViewer()); } } } } public void setRemoved(final org.eclipse.team.internal.core.subscribers.ChangeSet cs) { ChangeSet set = (ChangeSet)cs; if (isVisibleInMode(set)) { final ChangesetGroup toRefresh = findChangeSetInProjects(cs); boolean removed = toRefresh.getChangesets().remove(set); if(removed) { Utils.asyncExec(new Runnable() { public void run() { getTreeViewer().refresh(toRefresh, true); } }, getTreeViewer()); } } } private ChangesetGroup findChangeSetInProjects(final org.eclipse.team.internal.core.subscribers.ChangeSet cs) { ChangeSet set = (ChangeSet) cs; for (RepositoryChangesetGroup sg : projectGroup) { if (set.getRepository().equals(sg.getLocation())) { if (set.getDirection() == Direction.INCOMING) { return sg.getIncoming(); } if (set.getDirection() == Direction.OUTGOING) { return sg.getOutgoing(); } } } return null; } public void defaultSetChanged(final org.eclipse.team.internal.core.subscribers.ChangeSet previousDefault, final org.eclipse.team.internal.core.subscribers.ChangeSet set) { // user has requested a manual refresh: simply refresh root elements getRootElements(); } public void nameChanged(final org.eclipse.team.internal.core.subscribers.ChangeSet set) { // ignored } public void resourcesChanged(final org.eclipse.team.internal.core.subscribers.ChangeSet set, final IPath[] paths) { // ignored } public void changeSetChanges(final CollectorChangeEvent event, IProgressMonitor monitor) { // ignored } } private HgChangesetsCollector csCollector; private boolean collectorInitialized; private final IChangeSetChangeListener collectorListener; private final IPropertyChangeListener uncommittedSetListener; private final IPropertyChangeListener preferenceListener; private final List<RepositoryChangesetGroup> projectGroup; private WorkbenchContentProvider provider; private IUncommitted uncommitted; public HgChangeSetContentProvider() { super(); projectGroup = new ArrayList<RepositoryChangesetGroup>(); collectorListener = new CollectorListener(); uncommittedSetListener = new UcommittedSetListener(); preferenceListener = new PreferenceListener(); MercurialEclipsePlugin.getDefault().getPreferenceStore().addPropertyChangeListener(preferenceListener); uncommitted = makeUncommittedEntry(); } private static IUncommitted makeUncommittedEntry() { if (MercurialEclipsePlugin.getDefault().getPreferenceStore().getBoolean( MercurialPreferenceConstants.PREF_SYNC_ENABLE_LOCAL_CHANGESETS)) { return new UncommittedChangesetGroup(); } return new UncommittedChangeSet(); } @Override protected String getModelProviderId() { return HgChangeSetModelProvider.ID; } private boolean isOutgoingVisible(){ return getConfiguration().getMode() != ISynchronizePageConfiguration.INCOMING_MODE; } private boolean isIncomingVisible(){ return getConfiguration().getMode() != ISynchronizePageConfiguration.OUTGOING_MODE; } private boolean isEnabled() { final Object input = getViewer().getInput(); return input instanceof HgChangeSetModelProvider; } @Override public Object[] getChildren(Object parent) { return getElements(parent); } @Override public Object[] getElements(Object parent) { if (parent instanceof ISynchronizationContext) { // Do not show change sets when all models are visible because // model providers that override the resource content may cause // problems for the change set content provider return new Object[0]; } if(isEnabled()){ if(!((HgChangeSetModelProvider) getViewer().getInput()).isParticipantCreated()){ initCollector(); // on startup, do not start to show anything for the first time: // show "reminder" page which allows user to choose synchronize or not // return new Object[0]; // TODO right now it doesn't make sense to show "reminder page" as we // connect to the remote servers automatically as soon as the sync view // shows up. } } if (parent == getModelProvider()) { return getRootElements(); } else if (parent instanceof ChangesetGroup) { ChangesetGroup group = (ChangesetGroup) parent; Direction direction = group.getDirection(); if (isOutgoing(direction)) { if (isOutgoingVisible()) { return group.getChangesets().toArray(); } return new Object[] {new FilteredPlaceholder()}; } if(direction == Direction.INCOMING){ if (isIncomingVisible()) { return group.getChangesets().toArray(); } return new Object[] {new FilteredPlaceholder()}; } if(direction == Direction.LOCAL){ return group.getChangesets().toArray(); } } else if (parent instanceof RepositoryChangesetGroup) { // added groups to view boolean showEmpty = MercurialEclipsePlugin.getDefault().getPreferenceStore().getBoolean(MercurialPreferenceConstants.PREF_SYNC_SHOW_EMPTY_GROUPS); // showEmpty = true; RepositoryChangesetGroup supergroup = (RepositoryChangesetGroup) parent; ArrayList<Object> groups =new ArrayList<Object>(); if(supergroup.getIncoming().getChangesets().size() > 0) { groups.add(supergroup.getIncoming()); } else if(showEmpty) { groups.add(supergroup.getIncoming()); } if(supergroup.getOutgoing().getChangesets().size() > 0) { groups.add(supergroup.getOutgoing()); } else if(showEmpty) { groups.add(supergroup.getOutgoing()); } return groups.toArray(); } else if (parent instanceof ChangeSet) { FileFromChangeSet[] files = ((ChangeSet) parent).getChangesetFiles(); if (files.length != 0) { switch (PresentationMode.get()) { case FLAT: return files; case TREE: return collectTree(parent, files); case COMPRESSED_TREE: return collectCompressedTree(parent, files); } } } else if (parent instanceof PathFromChangeSet) { return ((PathFromChangeSet) parent).getChildren(); } return new Object[0]; } private synchronized void initProjects(MercurialSynchronizeSubscriber subscriber) { RepositoryLocationMap locations = subscriber.getParticipant().getRepositoryLocations(); for (IHgRepositoryLocation repoLocation : locations.getLocations()) { RepositoryChangesetGroup scg = new RepositoryChangesetGroup( locations.getRoot(repoLocation), repoLocation); scg.setIncoming(new ChangesetGroup("Incoming", Direction.INCOMING)); scg.setOutgoing(new ChangesetGroup("Outgoing", Direction.OUTGOING)); scg.setProjects(Arrays.asList(locations.getProjects(repoLocation))); projectGroup.add(scg); } } private Object[] collectTree(Object parent, FileFromChangeSet[] files) { List<Object> out = new ArrayList<Object>(files.length * 2); for (FileFromChangeSet file : files) { IPath path = file.getPath(); if(path == null) { out.add(Path.EMPTY); } else { out.add(path.removeLastSegments(1)); } out.add(file); } return collectTree(parent, out); } private Object[] collectTree(Object parent, List<Object> files) { HashMap<String, List<Object>> map = new HashMap<String, List<Object>>(); List<Object> out = new ArrayList<Object>(); for (Iterator<Object> it = files.iterator(); it.hasNext();) { IPath path = (IPath) it.next(); FileFromChangeSet file = (FileFromChangeSet) it.next(); if (path == null || 0 == path.segmentCount()) { out.add(file); } else { String seg = path.segment(0); List<Object> l = map.get(seg); if (l == null) { map.put(seg, l = new ArrayList<Object>()); } l.add(path.removeFirstSegments(1)); l.add(file); } } for (String seg : map.keySet()) { out.add(new TreePathFromChangeSet(parent, seg, map.get(seg))); } return out.toArray(new Object[out.size()]); } private Object[] collectCompressedTree(Object parent, FileFromChangeSet[] files) { HashMap<IPath, List<FileFromChangeSet>> map = new HashMap<IPath, List<FileFromChangeSet>>(); List<Object> out = new ArrayList<Object>(); for (FileFromChangeSet file : files) { IPath path; if(file.getPath() == null) { path = Path.EMPTY; } else { path = file.getPath().removeLastSegments(1); } List<FileFromChangeSet> l = map.get(path); if (l == null) { map.put(path, l = new ArrayList<FileFromChangeSet>()); } l.add(file); } for (IPath path : map.keySet()) { final List<FileFromChangeSet> data = map.get(path); if (path.isEmpty()) { out.addAll(data); } else { out.add(new CompressedTreePathFromChangeSet(parent, path.toString(), data)); } } return out.toArray(new Object[out.size()]); } private void ensureRootsAdded() { TreeViewer viewer = getTreeViewer(); TreeItem[] children = viewer.getTree().getItems(); if(children.length == 0) { viewer.add(viewer.getInput(), getRootElements()); } } // traverse through elements and add them to the correct group private Object[] getRootElements() { initCollector(); List<ChangeSet> result = new ArrayList<ChangeSet>(); Collection<ChangeSet> allSets = getAllSets(); for (ChangeSet set : allSets) { if (hasChildren(set)) { result.add(set); } } boolean showOutgoing = isOutgoingVisible(); boolean showIncoming = isIncomingVisible(); for (ChangeSet set : result) { for (RepositoryChangesetGroup group : projectGroup) { if (set.getRepository().equals(group.getLocation())) { Direction direction = set.getDirection(); if (showOutgoing && (isOutgoing(direction))) { group.getOutgoing().getChangesets().add(set); } if (showIncoming && direction == Direction.INCOMING) { group.getIncoming().getChangesets().add(set); } } } } uncommitted.update(STATUS_CACHE, null); List<Object> itemsToShow = new ArrayList<Object>(); itemsToShow.add(uncommitted); if (projectGroup.size() == 1) { itemsToShow.addAll(Arrays.asList(getElements(projectGroup.get(0)))); } else { itemsToShow.addAll(projectGroup); } return itemsToShow.toArray(); } private synchronized void initCollector() { if (!collectorInitialized) { initializeChangeSets(getChangeSetCapability()); collectorInitialized = true; } } @Override protected ResourceTraversal[] getTraversals( ISynchronizationContext context, Object object) { if (object instanceof ChangeSet) { ChangeSet set = (ChangeSet) object; IResource[] resources = set.getResources(); return new ResourceTraversal[] { new ResourceTraversal(resources, IResource.DEPTH_ZERO, IResource.NONE) }; } if(object instanceof IResource){ IResource[] resources = new IResource[]{(IResource) object}; return new ResourceTraversal[] { new ResourceTraversal(resources, IResource.DEPTH_ZERO, IResource.NONE) }; } if(object instanceof ChangesetGroup){ ChangesetGroup group = (ChangesetGroup) object; Set<ChangeSet> changesets = group.getChangesets(); Set<IFile> all = new HashSet<IFile>(); for (ChangeSet changeSet : changesets) { all.addAll(changeSet.getFiles()); } IResource[] resources = all.toArray(new IResource[0]); return new ResourceTraversal[] { new ResourceTraversal(resources, IResource.DEPTH_ZERO, IResource.NONE) }; } if(object instanceof RepositoryChangesetGroup){ RepositoryChangesetGroup supergroup = (RepositoryChangesetGroup) object; Set<IFile> all = new HashSet<IFile>(); Set<ChangeSet> changesets = supergroup.getIncoming().getChangesets(); for (ChangeSet changeSet : changesets) { all.addAll(changeSet.getFiles()); } changesets = supergroup.getOutgoing().getChangesets(); for (ChangeSet changeSet : changesets) { all.addAll(changeSet.getFiles()); } IResource[] resources = all.toArray(new IResource[0]); return new ResourceTraversal[] { new ResourceTraversal(resources, IResource.DEPTH_ZERO, IResource.NONE) }; } return new ResourceTraversal[0]; } /** * @see org.eclipse.team.ui.mapping.SynchronizationContentProvider#hasChildrenInContext(org.eclipse.team.core.mapping.ISynchronizationContext, * java.lang.Object) */ @Override protected boolean hasChildrenInContext(ISynchronizationContext context, Object element) { if (element instanceof ChangeSet) { return hasChildren((ChangeSet) element); } else if (element instanceof ChangesetGroup) { ChangesetGroup group = (ChangesetGroup) element; Direction direction = group.getDirection(); if (isOutgoingVisible() && isOutgoing(direction)) { return true; } if(isIncomingVisible() && direction == Direction.INCOMING){ return true; } } else if (element instanceof RepositoryChangesetGroup) { boolean showEmptyGroups = MercurialEclipsePlugin.getDefault().getPreferenceStore().getBoolean(MercurialPreferenceConstants.PREF_SYNC_SHOW_EMPTY_GROUPS); RepositoryChangesetGroup supergroup = (RepositoryChangesetGroup) element; if (isOutgoingVisible() && (showEmptyGroups || supergroup.getOutgoing().getChangesets().size() > 0)) { return true; } if (isIncomingVisible() && (showEmptyGroups || supergroup.getIncoming().getChangesets().size() > 0)) { return true; } } else if (element instanceof PathFromChangeSet) { return true; } return false; } private boolean isVisibleInMode(ChangeSet cs) { int mode = getConfiguration().getMode(); if (cs != null) { switch (mode) { case ISynchronizePageConfiguration.BOTH_MODE: return true; case ISynchronizePageConfiguration.CONFLICTING_MODE: return containsConflicts(cs); case ISynchronizePageConfiguration.INCOMING_MODE: return cs.getDirection() == Direction.INCOMING; case ISynchronizePageConfiguration.OUTGOING_MODE: return hasConflicts(cs) || isOutgoing(cs.getDirection()); default: break; } } return true; } private static boolean isOutgoing(Direction direction) { return direction == Direction.OUTGOING || direction == Direction.LOCAL; } private static boolean hasConflicts(ChangeSet cs) { // Conflict mode not meaningful in a DVCS return false; } private static boolean containsConflicts(ChangeSet cs) { // Conflict mode not meaningful in a DVCS return false; } private boolean hasChildren(ChangeSet changeset) { return isVisibleInMode(changeset) && (!changeset.getFiles().isEmpty() || changeset.getChangesetFiles().length > 0); } /** * Return all the change sets (incoming and outgoing). This * list must not include the unassigned set. * @return all the change sets (incoming and outgoing) */ private Collection<ChangeSet> getAllSets() { if (csCollector != null) { return csCollector.getChangeSets(); } return new HashSet<ChangeSet>(); } @Override public void init(ICommonContentExtensionSite site) { super.init(site); HgChangeSetSorter sorter = getSorter(); if (sorter != null) { sorter.setConfiguration(getConfiguration()); } MercurialSynchronizeParticipant participant = (MercurialSynchronizeParticipant) getConfiguration().getParticipant(); getExtensionSite().getService().getDnDService().bindDragAssistant(new HgDragAdapterAssistant()); uncommitted.setContext((HgSubscriberMergeContext) participant.getContext()); } private HgChangeSetSorter getSorter() { INavigatorContentService contentService = getExtensionSite().getService(); INavigatorSorterService sortingService = contentService.getSorterService(); INavigatorContentExtension extension = getExtensionSite().getExtension(); if (extension != null) { ViewerSorter sorter = sortingService.findSorter(extension.getDescriptor(), getModelProvider(), null, null); // incoming, incoming // TODO: sorting if (sorter instanceof HgChangeSetSorter) { return (HgChangeSetSorter) sorter; } } return null; } private void initializeChangeSets(ChangeSetCapability csc) { if (csc.supportsCheckedInChangeSets()) { csCollector = ((HgChangeSetCapability) csc).createSyncInfoSetChangeSetCollector(getConfiguration()); csCollector.addListener(collectorListener); initializeUncommittedEntry(csCollector.getSubscriber().getProjects()); initProjects(csCollector.getSubscriber()); } } private void initializeUncommittedEntry(IProject[] projects) { uncommitted.setProjects(projects); uncommitted.addListener(uncommittedSetListener); STATUS_CACHE.addObserver(uncommitted); } @Override public void dispose() { if (csCollector != null) { csCollector.removeListener(collectorListener); csCollector.dispose(); } MercurialEclipsePlugin.getDefault().getPreferenceStore().removePropertyChangeListener(preferenceListener); disposeUncommittedEntry(); for(RepositoryChangesetGroup sg : projectGroup) { sg.getOutgoing().getChangesets().clear(); sg.getIncoming().getChangesets().clear(); } projectGroup.clear(); super.dispose(); } private void disposeUncommittedEntry() { uncommitted.removeListener(uncommittedSetListener); STATUS_CACHE.deleteObserver(uncommitted); uncommitted.dispose(); uncommitted = null; } protected void recreateUncommittedEntry(TreeViewer tree) { IProject[] projects = uncommitted.getProjects(); HgSubscriberMergeContext ctx = uncommitted.getContext(); disposeUncommittedEntry(); uncommitted = makeUncommittedEntry(); uncommitted.setContext(ctx); if (collectorInitialized) { initializeUncommittedEntry(projects); } tree.refresh(); } @Override public void diffsChanged(IDiffChangeEvent event, IProgressMonitor monitor) { Utils.asyncExec(new Runnable() { public void run() { ensureRootsAdded(); } }, getTreeViewer()); if (csCollector != null) { csCollector.handleChange(event); } // no other updates here, as it simply doesn't fit into the changeset concept. } private ChangeSetCapability getChangeSetCapability() { ISynchronizeParticipant participant = getConfiguration().getParticipant(); if (participant instanceof IChangeSetProvider) { IChangeSetProvider csProvider = (IChangeSetProvider) participant; return csProvider.getChangeSetCapability(); } return null; } private TreeViewer getTreeViewer() { return (TreeViewer) getViewer(); } @Override protected ITreeContentProvider getDelegateContentProvider() { if (provider == null) { provider = new WorkbenchContentProvider(); } return provider; } @Override protected Object getModelRoot() { return ResourcesPlugin.getWorkspace().getRoot(); } /** * * @param file may be null * @return may return null, if the given file is null, not selected or is not contained * in any selected changesets */ public ChangeSet getParentOfSelection(FileFromChangeSet file){ TreeItem[] selection = getTreeViewer().getTree().getSelection(); for (TreeItem treeItem : selection) { if(treeItem.getData() != file){ continue; } TreeItem parentItem = treeItem.getParentItem(); while (parentItem != null && !(parentItem.getData() instanceof ChangeSet)) { parentItem = parentItem.getParentItem(); } if (parentItem != null) { return (ChangeSet) parentItem.getData(); } } return null; } /** * @param changeset may be null * @return may return null */ public ChangesetGroup getParentGroup(ChangeSet changeset){ if(changeset == null || changeset instanceof WorkingChangeSet){ return null; } boolean incoming = changeset.getDirection() == Direction.INCOMING; for (RepositoryChangesetGroup group : projectGroup) { ChangesetGroup g = incoming ? group.getIncoming() : group.getOutgoing(); if (g.getChangesets().contains(changeset)) { return g; } } return null; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("HgChangeSetContentProvider [collectorInitialized="); builder.append(collectorInitialized); builder.append(", "); if (csCollector != null) { builder.append("csCollector="); builder.append(csCollector); builder.append(", "); } if (provider != null) { builder.append("provider="); builder.append(provider); builder.append(", "); } builder.append("]"); return builder.toString(); } public IUncommitted getUncommittedEntry() { return uncommitted; } private class CompressedTreePathFromChangeSet extends PathFromChangeSet { protected final List<FileFromChangeSet> data; public CompressedTreePathFromChangeSet(Object prnt, String seg, List<FileFromChangeSet> data) { super(prnt, seg); this.data = data; if (data != null && data.size() > 0) { IFile file = data.get(0).getFile(); this.resource = file != null? file.getParent() : null; } } @Override public Object[] getChildren() { return data.toArray(new FileFromChangeSet[data.size()]); } @Override public Set<FileFromChangeSet> getFiles() { return new LinkedHashSet<FileFromChangeSet>(data); } } private class TreePathFromChangeSet extends PathFromChangeSet { protected final List<Object> data; public TreePathFromChangeSet(Object prnt, String seg, List<Object> data) { super(prnt, seg); this.data = data; this.resource = getResource(); } @Override public Object[] getChildren() { return collectTree(HgChangeSetContentProvider.this, data); } private IResource getResource() { IResource result = null; if (data.size() > 1) { // first object must be an IPath Object o1 = data.get(0); // and second must be FileFromChangeSet Object o2 = data.get(1); if (o1 instanceof IPath && o2 instanceof FileFromChangeSet) { FileFromChangeSet fcs = (FileFromChangeSet) o2; IResource childResource = ResourceUtils.getResource(fcs); if(childResource != null) { IPath folderPath = ResourceUtils.getPath(childResource).removeLastSegments( ((IPath) o1).segmentCount() + 1); return ResourcesPlugin.getWorkspace().getRoot().getContainerForLocation( folderPath); } } } return result; } @Override public Set<FileFromChangeSet> getFiles() { Set<FileFromChangeSet> files = new LinkedHashSet<FileFromChangeSet>(); for (Object o : data) { if(o instanceof FileFromChangeSet) { files.add((FileFromChangeSet) o); } } return files; } } protected static class FilteredPlaceholder { /** * @see java.lang.Object#toString() */ @Override public String toString() { return "<Filtered>"; } } public interface IUncommitted extends Observer { void setProjects(IProject[] projects); IProject[] getProjects(); void dispose(); void removeListener(IPropertyChangeListener listener); void addListener(IPropertyChangeListener listener); void setContext(HgSubscriberMergeContext context); HgSubscriberMergeContext getContext(); } }
Formatting and minor optimization
plugin/src/com/vectrace/MercurialEclipse/synchronize/cs/HgChangeSetContentProvider.java
Formatting and minor optimization
Java
agpl-3.0
4c6802e630930e0323a1fa08d5cb204c1ac8d6a8
0
vimsvarcode/elmis,OpenLMIS/open-lmis,joshzamor/open-lmis,jasolangi/jasolangi.github.io,kelvinmbwilo/vims,vimsvarcode/elmis,kelvinmbwilo/vims,jasolangi/jasolangi.github.io,USAID-DELIVER-PROJECT/elmis,OpenLMIS/open-lmis,USAID-DELIVER-PROJECT/elmis,USAID-DELIVER-PROJECT/elmis,vimsvarcode/elmis,joshzamor/open-lmis,kelvinmbwilo/vims,kelvinmbwilo/vims,OpenLMIS/open-lmis,joshzamor/open-lmis,vimsvarcode/elmis,OpenLMIS/open-lmis,USAID-DELIVER-PROJECT/elmis,jasolangi/jasolangi.github.io,vimsvarcode/elmis,joshzamor/open-lmis
/* * * * This program is part of the OpenLMIS logistics management information system platform software. * * Copyright © 2013 VillageReach * * * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * *   * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program.  If not, see http://www.gnu.org/licenses.  For additional information contact [email protected].  * */ package org.openlmis.functional; import org.openlmis.UiUtils.TestCaseHelper; import org.openlmis.UiUtils.TestWebDriver; import org.openlmis.pageobjects.*; import org.openqa.selenium.JavascriptExecutor; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.thoughtworks.selenium.SeleneseTestBase.assertTrue; import static java.util.Arrays.asList; public class DistributionRefrigeratorSyncTest extends TestCaseHelper { public static final String USER = "user"; public static final String PASSWORD = "password"; public static final String FIRST_DELIVERY_ZONE_CODE = "firstDeliveryZoneCode"; public static final String SECOND_DELIVERY_ZONE_CODE = "secondDeliveryZoneCode"; public static final String FIRST_DELIVERY_ZONE_NAME = "firstDeliveryZoneName"; public static final String SECOND_DELIVERY_ZONE_NAME = "secondDeliveryZoneName"; public static final String FIRST_FACILITY_CODE = "firstFacilityCode"; public static final String SECOND_FACILITY_CODE = "secondFacilityCode"; public static final String VACCINES_PROGRAM = "vaccinesProgram"; public static final String TB_PROGRAM = "secondProgram"; public static final String SCHEDULE = "schedule"; public static final String PRODUCT_GROUP_CODE = "productGroupName"; LoginPage loginPage; FacilityListPage facilityListPage; public Map<String, String> refrigeratorTestData = new HashMap<String, String>() {{ put(USER, "fieldCoordinator"); put(PASSWORD, "Admin123"); put(FIRST_DELIVERY_ZONE_CODE, "DZ1"); put(SECOND_DELIVERY_ZONE_CODE, "DZ2"); put(FIRST_DELIVERY_ZONE_NAME, "Delivery Zone First"); put(SECOND_DELIVERY_ZONE_NAME, "Delivery Zone Second"); put(FIRST_FACILITY_CODE, "F10"); put(SECOND_FACILITY_CODE, "F11"); put(VACCINES_PROGRAM, "VACCINES"); put(TB_PROGRAM, "TB"); put(SCHEDULE, "M"); put(PRODUCT_GROUP_CODE, "PG1"); }}; @BeforeMethod(groups = {"distribution"}) public void setUp() throws Exception { super.setup(); loginPage = new LoginPage(testWebDriver, baseUrlGlobal); facilityListPage = new FacilityListPage(testWebDriver); Map<String, String> dataMap = refrigeratorTestData; setupDataForDistributionTest(dataMap.get(USER), dataMap.get(FIRST_DELIVERY_ZONE_CODE), dataMap.get(SECOND_DELIVERY_ZONE_CODE), dataMap.get(FIRST_DELIVERY_ZONE_NAME), dataMap.get(SECOND_DELIVERY_ZONE_NAME), dataMap.get(FIRST_FACILITY_CODE), dataMap.get(SECOND_FACILITY_CODE), dataMap.get(VACCINES_PROGRAM), dataMap.get(TB_PROGRAM), dataMap.get(SCHEDULE), dataMap.get(PRODUCT_GROUP_CODE)); } @Test(groups = {"distribution"}) public void testRefrigeratorPageSyncWith2Refrigerators() throws Exception { dbWrapper.addRefrigeratorToFacility("LG", "800L1", "TGNR7878", "F10"); HomePage homePage = loginPage.loginAs(refrigeratorTestData.get(USER), refrigeratorTestData.get(PASSWORD)); initiateDistribution(refrigeratorTestData.get(FIRST_DELIVERY_ZONE_NAME), refrigeratorTestData.get(VACCINES_PROGRAM)); GeneralObservationPage generalObservationPage = facilityListPage.selectFacility(refrigeratorTestData.get(FIRST_FACILITY_CODE)); generalObservationPage.enterDataWhenFacilityVisited("some observations", "samuel", "Doe", "Verifier", "XYZ"); RefrigeratorPage refrigeratorPage = generalObservationPage.navigateToRefrigerators(); refrigeratorPage.clickShowForRefrigerator1(); refrigeratorPage.verifyRefrigeratorColor("individual", "RED"); refrigeratorPage.enterValueInRefrigeratorTemperature("999.9"); refrigeratorPage.verifyRefrigeratorColor("overall", "AMBER"); refrigeratorPage.verifyRefrigeratorColor("individual", "AMBER"); refrigeratorPage.clickFunctioningCorrectlyYesRadio(); refrigeratorPage.enterValueInLowAlarmEvents("1"); refrigeratorPage.enterValueInHighAlarmEvents("0"); refrigeratorPage.clickProblemSinceLastVisitDontKnowRadio(); refrigeratorPage.enterValueInNotesTextArea("miscellaneous"); refrigeratorPage.clickDone(); refrigeratorPage.verifyRefrigeratorColor("individual", "GREEN"); refrigeratorPage.verifyRefrigeratorColor("overall", "AMBER"); refrigeratorPage.clickShowForRefrigerator2(); refrigeratorPage.enterValueInRefrigeratorTemperatureForSecondRefrigerator("5"); refrigeratorPage.clickFunctioningCorrectlyNoRadioForSecondRefrigerator(); refrigeratorPage.enterValueInLowAlarmEventsForSecondRefrigerator("10"); refrigeratorPage.enterValueInHighAlarmEventsForSecondRefrigerator("05"); refrigeratorPage.clickProblemSinceLastVisitNoRadioForSecondRefrigerator(); refrigeratorPage.verifyRefrigeratorColor("individual", "GREEN"); refrigeratorPage.verifyRefrigeratorColor("overall", "GREEN"); EPIUsePage epiUsePage = refrigeratorPage.navigateToEpiUse(); epiUsePage.enterData(10, 20, 30, 40, 50, "10/2011", 1); FullCoveragePage fullCoveragePage = epiUsePage.navigateToFullCoverage(); fullCoveragePage.enterData(45, 67, 89, "90"); fullCoveragePage.navigateToEpiInventory(); fillEpiInventoryWithOnlyDeliveredQuantity("2", "4", "6"); DistributionPage distributionPage = homePage.navigateToDistributionWhenOnline(); distributionPage.syncDistribution(1); assertTrue(distributionPage.getSyncMessage().contains("F10-Village Dispensary")); distributionPage.syncDistributionMessageDone(); verifyRefrigeratorReadingDataInDatabase(refrigeratorTestData.get(FIRST_FACILITY_CODE), "GNR7878", 999.9F, "Y", 1, 0, "D", "miscellaneous"); verifyRefrigeratorProblemDataNullInDatabase("GNR7878", refrigeratorTestData.get(FIRST_FACILITY_CODE)); verifyRefrigeratorReadingDataInDatabase(refrigeratorTestData.get(FIRST_FACILITY_CODE), "TGNR7878", 5F, "N", 10, 5, "N", null); verifyRefrigeratorProblemDataNullInDatabase("TGNR7878", refrigeratorTestData.get(FIRST_FACILITY_CODE)); } @Test(groups = {"distribution"}) public void testRefrigeratorSyncWhenRefrigeratorHasProblem() throws Exception { HomePage homePage = loginPage.loginAs(refrigeratorTestData.get(USER), refrigeratorTestData.get(PASSWORD)); initiateDistribution(refrigeratorTestData.get(FIRST_DELIVERY_ZONE_NAME), refrigeratorTestData.get(VACCINES_PROGRAM)); GeneralObservationPage generalObservationPage = facilityListPage.selectFacility(refrigeratorTestData.get(FIRST_FACILITY_CODE)); generalObservationPage.enterDataWhenFacilityVisited("some observations", "samuel", "Doe", "Verifier", "XYZ"); RefrigeratorPage refrigeratorPage = generalObservationPage.navigateToRefrigerators(); refrigeratorPage.clickShowForRefrigerator1(); refrigeratorPage.verifyRefrigeratorColor("individual", "RED"); refrigeratorPage.enterValueInRefrigeratorTemperature("-999.9"); refrigeratorPage.clickFunctioningCorrectlyYesRadio(); refrigeratorPage.clickFunctioningCorrectlyNoRadio(); refrigeratorPage.enterValueInLowAlarmEvents("1"); refrigeratorPage.enterValueInHighAlarmEvents("0"); refrigeratorPage.clickProblemSinceLastVisitYesRadio(); refrigeratorPage.verifyRefrigeratorColor("overall", "AMBER"); refrigeratorPage.selectOtherProblem(); refrigeratorPage.verifyRefrigeratorColor("overall", "GREEN"); refrigeratorPage.verifyRefrigeratorColor("individual", "GREEN"); refrigeratorPage.enterTextInOtherProblemTextBox("others"); refrigeratorPage.selectGasLeakProblem(); refrigeratorPage.clickDone(); EPIUsePage epiUsePage = refrigeratorPage.navigateToEpiUse(); epiUsePage.enterData(10, 20, 30, 40, 50, "10/2011", 1); FullCoveragePage fullCoveragePage = refrigeratorPage.navigateToFullCoverage(); fullCoveragePage.enterData(67, 44, 22, "11"); fullCoveragePage.navigateToEpiInventory(); fillEpiInventoryWithOnlyDeliveredQuantity("2", "4", "6"); DistributionPage distributionPage = homePage.navigateToDistributionWhenOnline(); distributionPage.syncDistribution(1); assertTrue(distributionPage.getSyncMessage().contains("F10-Village Dispensary")); distributionPage.syncDistributionMessageDone(); verifyRefrigeratorReadingDataInDatabase(refrigeratorTestData.get(FIRST_FACILITY_CODE), "GNR7878", -999.9F, "N", 1, 0, "Y", null); verifyRefrigeratorProblemDataInDatabase(refrigeratorTestData.get(FIRST_FACILITY_CODE), "GNR7878", false, false, true, false, false, true, "others"); } @Test(groups = {"distribution"}) public void testRefrigeratorSyncWhenProblemIsSelectedAndAppliedNRBeforeSync() throws Exception { HomePage homePage = loginPage.loginAs(refrigeratorTestData.get(USER), refrigeratorTestData.get(PASSWORD)); initiateDistribution(refrigeratorTestData.get(FIRST_DELIVERY_ZONE_NAME), refrigeratorTestData.get(VACCINES_PROGRAM)); GeneralObservationPage generalObservationPage = facilityListPage.selectFacility(refrigeratorTestData.get(FIRST_FACILITY_CODE)); generalObservationPage.enterDataWhenFacilityVisited("some observations", "samuel", "Doe", "Verifier", "XYZ"); RefrigeratorPage refrigeratorPage = generalObservationPage.navigateToRefrigerators(); refrigeratorPage.clickShowForRefrigerator1(); refrigeratorPage.verifyRefrigeratorColor("individual", "RED"); refrigeratorPage.applyNRToRefrigeratorTemperature(); refrigeratorPage.clickFunctioningCorrectlyYesRadio(); refrigeratorPage.clickFunctioningCorrectlyNR(); refrigeratorPage.enterValueInLowAlarmEvents("1"); refrigeratorPage.applyNRToLowAlarmEvent(); refrigeratorPage.applyNRToHighAlarmEvent(); refrigeratorPage.verifyRefrigeratorColor("overall", "AMBER"); refrigeratorPage.clickProblemSinceLastVisitYesRadio(); refrigeratorPage.selectGasLeakProblem(); refrigeratorPage.clickProblemSinceLastVisitNR(); refrigeratorPage.verifyFieldsDisabledWhenAllNRSelected(); refrigeratorPage.verifyRefrigeratorColor("overall", "GREEN"); refrigeratorPage.verifyRefrigeratorColor("individual", "GREEN"); refrigeratorPage.clickDone(); EPIUsePage epiUsePage = refrigeratorPage.navigateToEpiUse(); epiUsePage.enterData(10, 20, 30, 40, 50, "10/2011", 1); FullCoveragePage fullCoveragePage = epiUsePage.navigateToFullCoverage(); fullCoveragePage.enterData(77, 56, 78, "34"); fullCoveragePage.navigateToEpiInventory(); fillEpiInventoryWithOnlyDeliveredQuantity("2", "4", "6"); DistributionPage distributionPage = homePage.navigateToDistributionWhenOnline(); distributionPage.syncDistribution(1); assertTrue(distributionPage.getSyncMessage().contains("F10-Village Dispensary")); distributionPage.syncDistributionMessageDone(); verifyRefrigeratorReadingDataInDatabase(refrigeratorTestData.get(FIRST_FACILITY_CODE), "GNR7878", null, null, null, null, null, null); verifyRefrigeratorProblemDataNullInDatabase("GNR7878", refrigeratorTestData.get(FIRST_FACILITY_CODE)); } @Test(groups = {"distribution"}) public void testRefrigeratorSyncWhenRefrigeratorIsDeletedBeforeSync() throws Exception { HomePage homePage = loginPage.loginAs(refrigeratorTestData.get(USER), refrigeratorTestData.get(PASSWORD)); initiateDistribution(refrigeratorTestData.get(FIRST_DELIVERY_ZONE_NAME), refrigeratorTestData.get(VACCINES_PROGRAM)); GeneralObservationPage generalObservationPage = facilityListPage.selectFacility(refrigeratorTestData.get(FIRST_FACILITY_CODE)); generalObservationPage.enterDataWhenFacilityVisited("some observations", "samuel", "Doe", "Verifier", "XYZ"); RefrigeratorPage refrigeratorPage = generalObservationPage.navigateToRefrigerators(); refrigeratorPage.clickShowForRefrigerator1(); refrigeratorPage.verifyRefrigeratorColor("individual", "RED"); refrigeratorPage.enterValueInRefrigeratorTemperature("3"); refrigeratorPage.clickFunctioningCorrectlyYesRadio(); refrigeratorPage.clickFunctioningCorrectlyNoRadio(); refrigeratorPage.enterValueInLowAlarmEvents("1"); refrigeratorPage.enterValueInHighAlarmEvents("0"); refrigeratorPage.clickProblemSinceLastVisitNoRadio(); refrigeratorPage.verifyRefrigeratorColor("overall", "GREEN"); refrigeratorPage.verifyRefrigeratorColor("individual", "GREEN"); refrigeratorPage.clickDone(); EPIUsePage epiUsePage = refrigeratorPage.navigateToEpiUse(); epiUsePage.enterData(10, 20, 30, 40, 50, "10/2011", 1); FullCoveragePage fullCoveragePage = epiUsePage.navigateToFullCoverage(); fullCoveragePage.enterData(78, 67, 34, "12"); fullCoveragePage.navigateToEpiInventory(); fillEpiInventoryWithOnlyDeliveredQuantity("2", "4", "6"); DistributionPage distributionPage = homePage.navigateToDistributionWhenOnline(); distributionPage.syncDistribution(1); assertTrue(distributionPage.getSyncMessage().contains("F10-Village Dispensary")); distributionPage.syncDistributionMessageDone(); initiateDistributionForPeriod("Period13"); distributionPage.clickRecordData(2); facilityListPage.selectFacility(refrigeratorTestData.get(FIRST_FACILITY_CODE)); facilityListPage.verifyFacilityIndicatorColor("Overall", "RED"); refrigeratorPage.navigateToRefrigeratorTab(); refrigeratorPage.verifyRefrigeratorColor("overall", "RED"); refrigeratorPage.clickShowForRefrigerator1(); refrigeratorPage.verifyRefrigeratorColor("individual", "RED"); refrigeratorPage.enterValueInRefrigeratorTemperature("3"); refrigeratorPage.clickFunctioningCorrectlyYesRadio(); refrigeratorPage.enterValueInLowAlarmEvents("2"); refrigeratorPage.enterValueInHighAlarmEvents("2"); refrigeratorPage.clickProblemSinceLastVisitYesRadio(); refrigeratorPage.verifyRefrigeratorColor("overall", "AMBER"); refrigeratorPage.selectOtherProblem(); refrigeratorPage.verifyRefrigeratorColor("overall", "GREEN"); refrigeratorPage.verifyRefrigeratorColor("individual", "GREEN"); refrigeratorPage.clickDone(); refrigeratorPage.clickDelete(); refrigeratorPage.clickOKButton(); refrigeratorPage.navigateToEpiUse(); epiUsePage.enterData(10, 20, 30, 40, 50, "10/2011", 1); epiUsePage.navigateToGeneralObservations(); generalObservationPage.enterDataWhenFacilityVisited("some observations", "samuel", "Doe", "Verifier", "XYZ"); generalObservationPage.navigateToFullCoverage(); fullCoveragePage.enterData(78, 67, 34, "12"); fullCoveragePage.navigateToEpiInventory(); fillEpiInventoryWithOnlyDeliveredQuantity("2", "4", "6"); homePage.navigateToDistributionWhenOnline(); distributionPage.syncDistribution(2); assertTrue(distributionPage.getSyncMessage().contains("F10-Village Dispensary")); distributionPage.syncDistributionMessageDone(); verifyRefrigeratorsDataInDatabase("F10", "GNR7878", "LG", "800L", "f"); } @Test(groups = {"distribution"}) public void testAddingDuplicateRefrigeratorForSameFacility() throws Exception { loginPage.loginAs(refrigeratorTestData.get(USER), refrigeratorTestData.get(PASSWORD)); initiateDistribution(refrigeratorTestData.get(FIRST_DELIVERY_ZONE_NAME), refrigeratorTestData.get(VACCINES_PROGRAM)); RefrigeratorPage refrigeratorPage = facilityListPage.selectFacility(refrigeratorTestData.get(FIRST_FACILITY_CODE)).navigateToRefrigerators(); refrigeratorPage.clickAddNew(); refrigeratorPage.addNewRefrigerator("LG", "800L1", "GNR7878"); refrigeratorPage.verifyDuplicateErrorMessage("Duplicate Manufacturer Serial Number"); } @Test(groups = {"distribution"}) public void testAddingDuplicateRefrigeratorForDifferentFacility() throws Exception { HomePage homePage = loginPage.loginAs(refrigeratorTestData.get(USER), refrigeratorTestData.get(PASSWORD)); initiateDistribution(refrigeratorTestData.get(FIRST_DELIVERY_ZONE_NAME), refrigeratorTestData.get(VACCINES_PROGRAM)); GeneralObservationPage generalObservationPage = facilityListPage.selectFacility(refrigeratorTestData.get(SECOND_FACILITY_CODE)); generalObservationPage.enterDataWhenFacilityVisited("some observations", "samuel", "Doe", "Verifier", "XYZ"); RefrigeratorPage refrigeratorPage = generalObservationPage.navigateToRefrigerators(); refrigeratorPage.clickAddNew(); refrigeratorPage.addNewRefrigerator("LG22", "800L22", "GNR7878"); refrigeratorPage.clickShowForRefrigerator1(); refrigeratorPage.enterValueInRefrigeratorTemperature("3"); refrigeratorPage.clickFunctioningCorrectlyYesRadio(); refrigeratorPage.enterValueInLowAlarmEvents("2"); refrigeratorPage.enterValueInHighAlarmEvents("2"); refrigeratorPage.clickProblemSinceLastVisitNR(); refrigeratorPage.verifyRefrigeratorColor("overall", "GREEN"); refrigeratorPage.verifyRefrigeratorColor("individual", "GREEN"); refrigeratorPage.clickDone(); EPIUsePage epiUsePage = refrigeratorPage.navigateToEpiUse(); epiUsePage.enterData(10, 20, 30, 40, 50, "10/2011", 1); FullCoveragePage fullCoveragePage = epiUsePage.navigateToFullCoverage(); fullCoveragePage.enterData(12, 34, 45, "56"); fullCoveragePage.navigateToEpiInventory(); fillEpiInventoryWithOnlyDeliveredQuantity("2", "4", "6"); DistributionPage distributionPage = homePage.navigateToDistributionWhenOnline(); distributionPage.syncDistribution(1); assertTrue(distributionPage.getSyncMessage().contains("F11-Central Hospital")); distributionPage.syncDistributionMessageDone(); verifyRefrigeratorReadingDataInDatabase(refrigeratorTestData.get(SECOND_FACILITY_CODE), "GNR7878", 3.0f, "Y", 2, 2, null, null); verifyRefrigeratorProblemDataNullInDatabase("GNR7878", refrigeratorTestData.get(SECOND_FACILITY_CODE)); verifyRefrigeratorsDataInDatabase("F11", "GNR7878", "LG22", "800L22", "t"); } @Test(groups = {"distribution"}) public void testUpdatingRefrigeratorAndSync() throws Exception { HomePage homePage = loginPage.loginAs(refrigeratorTestData.get(USER), refrigeratorTestData.get(PASSWORD)); initiateDistribution(refrigeratorTestData.get(FIRST_DELIVERY_ZONE_NAME), refrigeratorTestData.get(VACCINES_PROGRAM)); GeneralObservationPage generalObservationPage = facilityListPage.selectFacility(refrigeratorTestData.get(FIRST_FACILITY_CODE)); generalObservationPage.enterDataWhenFacilityVisited("some observations", "samuel", "Doe", "Verifier", "XYZ"); RefrigeratorPage refrigeratorPage = generalObservationPage.navigateToRefrigerators(); refrigeratorPage.clickDelete(); refrigeratorPage.clickOKButton(); facilityListPage = new FacilityListPage(testWebDriver); facilityListPage.verifyFacilityIndicatorColor("overall", "AMBER"); refrigeratorPage.clickAddNew(); refrigeratorPage.addNewRefrigerator("LG", "800L1", "GNR7878"); refrigeratorPage.verifyRefrigeratorColor("overall", "RED"); refrigeratorPage.clickShowForRefrigerator1(); refrigeratorPage.verifyRefrigeratorColor("individual", "RED"); refrigeratorPage.enterValueInRefrigeratorTemperature("3"); refrigeratorPage.clickFunctioningCorrectlyYesRadio(); refrigeratorPage.enterValueInLowAlarmEvents("2"); refrigeratorPage.enterValueInHighAlarmEvents("2"); refrigeratorPage.clickProblemSinceLastVisitNR(); refrigeratorPage.verifyRefrigeratorColor("overall", "GREEN"); refrigeratorPage.verifyRefrigeratorColor("individual", "GREEN"); refrigeratorPage.clickDone(); EPIUsePage epiUse = refrigeratorPage.navigateToEpiUse(); epiUse.enterData(10, 20, 30, 40, 50, "10/2011", 1); FullCoveragePage fullCoveragePage = epiUse.navigateToFullCoverage(); fullCoveragePage.enterData(67, 8, 33, "54"); fullCoveragePage.navigateToEpiInventory(); fillEpiInventoryWithOnlyDeliveredQuantity("2", "4", "6"); DistributionPage distributionPage = homePage.navigateToDistributionWhenOnline(); distributionPage.syncDistribution(1); assertTrue(distributionPage.getSyncMessage().contains("F10-Village Dispensary")); distributionPage.syncDistributionMessageDone(); verifyRefrigeratorReadingDataInDatabase(refrigeratorTestData.get(FIRST_FACILITY_CODE), "GNR7878", 3.0f, "Y", 2, 2, null, null); verifyRefrigeratorProblemDataNullInDatabase("GNR7878", refrigeratorTestData.get(FIRST_FACILITY_CODE)); verifyRefrigeratorsDataInDatabase("F10", "GNR7878", "LG", "800L1", "t"); } private void initiateDistributionForPeriod(String periodName) { DistributionPage distributionPage = PageFactory.getInstanceOfDistributionPage(testWebDriver); distributionPage.selectValueFromDeliveryZone(refrigeratorTestData.get(FIRST_DELIVERY_ZONE_NAME)); distributionPage.selectValueFromProgram(refrigeratorTestData.get(VACCINES_PROGRAM)); distributionPage.selectValueFromPeriod(periodName); distributionPage.clickInitiateDistribution(); } public void setupDataForDistributionTest(String userSIC, String deliveryZoneCodeFirst, String deliveryZoneCodeSecond, String deliveryZoneNameFirst, String deliveryZoneNameSecond, String facilityCodeFirst, String facilityCodeSecond, String programFirst, String programSecond, String schedule, String productGroupCode) throws Exception { List<String> rightsList = asList("MANAGE_DISTRIBUTION"); setupTestDataToInitiateRnRAndDistribution(facilityCodeFirst, facilityCodeSecond, true, programFirst, userSIC, "200", rightsList, programSecond, "District1", "Ngorongoro", "Ngorongoro"); setupDataForDeliveryZone(true, deliveryZoneCodeFirst, deliveryZoneCodeSecond, deliveryZoneNameFirst, deliveryZoneNameSecond, facilityCodeFirst, facilityCodeSecond, programFirst, programSecond, schedule); dbWrapper.insertRoleAssignmentForDistribution(userSIC, "store in-charge", deliveryZoneCodeFirst); dbWrapper.insertRoleAssignmentForDistribution(userSIC, "store in-charge", deliveryZoneCodeSecond); dbWrapper.insertProductGroup(productGroupCode); dbWrapper.insertProductWithGroup("Product5", "ProductName5", productGroupCode, true); dbWrapper.insertProductWithGroup("Product6", "ProductName6", productGroupCode, true); dbWrapper.insertProgramProduct("Product5", programFirst, "10", "false"); dbWrapper.insertProgramProduct("Product6", programFirst, "10", "true"); dbWrapper.addRefrigeratorToFacility("LG", "800L", "GNR7878", "F10"); } public void initiateDistribution(String deliveryZoneNameFirst, String programFirst) { HomePage homePage = PageFactory.getInstanceOfHomePage(testWebDriver); DistributionPage distributionPage = homePage.navigateToDistributionWhenOnline(); distributionPage.selectValueFromDeliveryZone(deliveryZoneNameFirst); distributionPage.selectValueFromProgram(programFirst); distributionPage.clickInitiateDistribution(); distributionPage.clickRecordData(1); } public void fillEpiInventoryWithOnlyDeliveredQuantity(String deliveredQuantity1, String deliveredQuantity2, String deliveredQuantity3) { EpiInventoryPage epiInventoryPage = PageFactory.getInstanceOfEpiInventoryPage(testWebDriver); epiInventoryPage.applyNRToAll(); epiInventoryPage.fillDeliveredQuantity(1, deliveredQuantity1); epiInventoryPage.fillDeliveredQuantity(2, deliveredQuantity2); epiInventoryPage.fillDeliveredQuantity(3, deliveredQuantity3); } @AfterMethod(groups = "distribution") public void tearDown() throws Exception { testWebDriver.sleep(500); if (!testWebDriver.getElementById("username").isDisplayed()) { HomePage homePage = PageFactory.getInstanceOfHomePage(testWebDriver); homePage.logout(baseUrlGlobal); dbWrapper.deleteData(); dbWrapper.closeConnection(); } ((JavascriptExecutor) TestWebDriver.getDriver()).executeScript("indexedDB.deleteDatabase('open_lmis');"); } }
test-modules/functional-tests/src/test/java/org/openlmis/functional/DistributionRefrigeratorSyncTest.java
/* * * * This program is part of the OpenLMIS logistics management information system platform software. * * Copyright © 2013 VillageReach * * * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * *   * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program.  If not, see http://www.gnu.org/licenses.  For additional information contact [email protected].  * */ package org.openlmis.functional; import org.openlmis.UiUtils.TestCaseHelper; import org.openlmis.UiUtils.TestWebDriver; import org.openlmis.pageobjects.*; import org.openqa.selenium.JavascriptExecutor; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.thoughtworks.selenium.SeleneseTestBase.assertTrue; import static java.util.Arrays.asList; public class DistributionRefrigeratorSyncTest extends TestCaseHelper { public static final String USER = "user"; public static final String PASSWORD = "password"; public static final String FIRST_DELIVERY_ZONE_CODE = "firstDeliveryZoneCode"; public static final String SECOND_DELIVERY_ZONE_CODE = "secondDeliveryZoneCode"; public static final String FIRST_DELIVERY_ZONE_NAME = "firstDeliveryZoneName"; public static final String SECOND_DELIVERY_ZONE_NAME = "secondDeliveryZoneName"; public static final String FIRST_FACILITY_CODE = "firstFacilityCode"; public static final String SECOND_FACILITY_CODE = "secondFacilityCode"; public static final String VACCINES_PROGRAM = "vaccinesProgram"; public static final String TB_PROGRAM = "secondProgram"; public static final String SCHEDULE = "schedule"; public static final String PRODUCT_GROUP_CODE = "productGroupName"; LoginPage loginPage; FacilityListPage facilityListPage; public Map<String, String> refrigeratorTestData = new HashMap<String, String>() {{ put(USER, "fieldCoordinator"); put(PASSWORD, "Admin123"); put(FIRST_DELIVERY_ZONE_CODE, "DZ1"); put(SECOND_DELIVERY_ZONE_CODE, "DZ2"); put(FIRST_DELIVERY_ZONE_NAME, "Delivery Zone First"); put(SECOND_DELIVERY_ZONE_NAME, "Delivery Zone Second"); put(FIRST_FACILITY_CODE, "F10"); put(SECOND_FACILITY_CODE, "F11"); put(VACCINES_PROGRAM, "VACCINES"); put(TB_PROGRAM, "TB"); put(SCHEDULE, "M"); put(PRODUCT_GROUP_CODE, "PG1"); }}; @BeforeMethod(groups = {"distribution"}) public void setUp() throws Exception { super.setup(); loginPage = new LoginPage(testWebDriver, baseUrlGlobal); facilityListPage = new FacilityListPage(testWebDriver); Map<String, String> dataMap = refrigeratorTestData; setupDataForDistributionTest(dataMap.get(USER), dataMap.get(FIRST_DELIVERY_ZONE_CODE), dataMap.get(SECOND_DELIVERY_ZONE_CODE), dataMap.get(FIRST_DELIVERY_ZONE_NAME), dataMap.get(SECOND_DELIVERY_ZONE_NAME), dataMap.get(FIRST_FACILITY_CODE), dataMap.get(SECOND_FACILITY_CODE), dataMap.get(VACCINES_PROGRAM), dataMap.get(TB_PROGRAM), dataMap.get(SCHEDULE), dataMap.get(PRODUCT_GROUP_CODE)); } @Test(groups = {"distribution"}) public void testRefrigeratorPageSyncWith2Refrigerators() throws Exception { dbWrapper.addRefrigeratorToFacility("LG", "800L1", "TGNR7878", "F10"); HomePage homePage = loginPage.loginAs(refrigeratorTestData.get(USER), refrigeratorTestData.get(PASSWORD)); initiateDistribution(refrigeratorTestData.get(FIRST_DELIVERY_ZONE_NAME), refrigeratorTestData.get(VACCINES_PROGRAM)); GeneralObservationPage generalObservationPage = facilityListPage.selectFacility(refrigeratorTestData.get(FIRST_FACILITY_CODE)); generalObservationPage.enterDataWhenFacilityVisited("some observations", "samuel", "Doe", "Verifier", "XYZ"); RefrigeratorPage refrigeratorPage = generalObservationPage.navigateToRefrigerators(); refrigeratorPage.clickShowForRefrigerator1(); refrigeratorPage.verifyRefrigeratorColor("individual", "RED"); refrigeratorPage.enterValueInRefrigeratorTemperature("999.9"); refrigeratorPage.verifyRefrigeratorColor("overall", "AMBER"); refrigeratorPage.verifyRefrigeratorColor("individual", "AMBER"); refrigeratorPage.clickFunctioningCorrectlyYesRadio(); refrigeratorPage.enterValueInLowAlarmEvents("1"); refrigeratorPage.enterValueInHighAlarmEvents("0"); refrigeratorPage.clickProblemSinceLastVisitDontKnowRadio(); refrigeratorPage.enterValueInNotesTextArea("miscellaneous"); refrigeratorPage.clickDone(); refrigeratorPage.verifyRefrigeratorColor("individual", "GREEN"); refrigeratorPage.verifyRefrigeratorColor("overall", "AMBER"); refrigeratorPage.clickShowForRefrigerator2(); refrigeratorPage.enterValueInRefrigeratorTemperatureForSecondRefrigerator("5"); refrigeratorPage.clickFunctioningCorrectlyNoRadioForSecondRefrigerator(); refrigeratorPage.enterValueInLowAlarmEventsForSecondRefrigerator("10"); refrigeratorPage.enterValueInHighAlarmEventsForSecondRefrigerator("05"); refrigeratorPage.clickProblemSinceLastVisitNoRadioForSecondRefrigerator(); refrigeratorPage.verifyRefrigeratorColor("individual", "GREEN"); refrigeratorPage.verifyRefrigeratorColor("overall", "GREEN"); EPIUsePage epiUsePage = refrigeratorPage.navigateToEpiUse(); epiUsePage.enterData(10, 20, 30, 40, 50, "10/2011", 1); FullCoveragePage fullCoveragePage = epiUsePage.navigateToFullCoverage(); fullCoveragePage.enterData(45, 67, 89, "90"); fullCoveragePage.navigateToEpiInventory(); fillEpiInventoryWithOnlyDeliveredQuantity("2", "4", "6"); DistributionPage distributionPage = homePage.navigateToDistributionWhenOnline(); distributionPage.syncDistribution(1); assertTrue(distributionPage.getSyncMessage().contains("F10-Village Dispensary")); distributionPage.syncDistributionMessageDone(); verifyRefrigeratorReadingDataInDatabase(refrigeratorTestData.get(FIRST_FACILITY_CODE), "GNR7878", 999.9F, "Y", 1, 0, "D", "miscellaneous"); verifyRefrigeratorProblemDataNullInDatabase("GNR7878", refrigeratorTestData.get(FIRST_FACILITY_CODE)); verifyRefrigeratorReadingDataInDatabase(refrigeratorTestData.get(FIRST_FACILITY_CODE), "TGNR7878", 5F, "N", 10, 5, "N", null); verifyRefrigeratorProblemDataNullInDatabase("TGNR7878", refrigeratorTestData.get(FIRST_FACILITY_CODE)); } @Test(groups = {"distribution"}) public void testRefrigeratorSyncWhenRefrigeratorHasProblem() throws Exception { HomePage homePage = loginPage.loginAs(refrigeratorTestData.get(USER), refrigeratorTestData.get(PASSWORD)); initiateDistribution(refrigeratorTestData.get(FIRST_DELIVERY_ZONE_NAME), refrigeratorTestData.get(VACCINES_PROGRAM)); GeneralObservationPage generalObservationPage = facilityListPage.selectFacility(refrigeratorTestData.get(FIRST_FACILITY_CODE)); generalObservationPage.enterDataWhenFacilityVisited("some observations", "samuel", "Doe", "Verifier", "XYZ"); RefrigeratorPage refrigeratorPage = generalObservationPage.navigateToRefrigerators(); refrigeratorPage.clickShowForRefrigerator1(); refrigeratorPage.verifyRefrigeratorColor("individual", "RED"); refrigeratorPage.enterValueInRefrigeratorTemperature("-999.9"); refrigeratorPage.clickFunctioningCorrectlyYesRadio(); refrigeratorPage.clickFunctioningCorrectlyNoRadio(); refrigeratorPage.enterValueInLowAlarmEvents("1"); refrigeratorPage.enterValueInHighAlarmEvents("0"); refrigeratorPage.clickProblemSinceLastVisitYesRadio(); refrigeratorPage.verifyRefrigeratorColor("overall", "AMBER"); refrigeratorPage.selectOtherProblem(); refrigeratorPage.verifyRefrigeratorColor("overall", "GREEN"); refrigeratorPage.verifyRefrigeratorColor("individual", "GREEN"); refrigeratorPage.enterTextInOtherProblemTextBox("others"); refrigeratorPage.selectGasLeakProblem(); refrigeratorPage.clickDone(); EPIUsePage epiUsePage = refrigeratorPage.navigateToEpiUse(); epiUsePage.enterData(10, 20, 30, 40, 50, "10/2011", 1); FullCoveragePage fullCoveragePage = refrigeratorPage.navigateToFullCoverage(); fullCoveragePage.enterData(67, 44, 22, "11"); fullCoveragePage.navigateToEpiInventory(); fillEpiInventoryWithOnlyDeliveredQuantity("2", "4", "6"); DistributionPage distributionPage = homePage.navigateToDistributionWhenOnline(); distributionPage.syncDistribution(1); assertTrue(distributionPage.getSyncMessage().contains("F10-Village Dispensary")); distributionPage.syncDistributionMessageDone(); verifyRefrigeratorReadingDataInDatabase(refrigeratorTestData.get(FIRST_FACILITY_CODE), "GNR7878", -999.9F, "N", 1, 0, "Y", null); verifyRefrigeratorProblemDataInDatabase(refrigeratorTestData.get(FIRST_FACILITY_CODE), "GNR7878", false, false, true, false, false, true, "others"); } @Test(groups = {"distribution"}) public void testRefrigeratorSyncWhenProblemIsSelectedAndAppliedNRBeforeSync() throws Exception { HomePage homePage = loginPage.loginAs(refrigeratorTestData.get(USER), refrigeratorTestData.get(PASSWORD)); initiateDistribution(refrigeratorTestData.get(FIRST_DELIVERY_ZONE_NAME), refrigeratorTestData.get(VACCINES_PROGRAM)); GeneralObservationPage generalObservationPage = facilityListPage.selectFacility(refrigeratorTestData.get(FIRST_FACILITY_CODE)); generalObservationPage.enterDataWhenFacilityVisited("some observations", "samuel", "Doe", "Verifier", "XYZ"); RefrigeratorPage refrigeratorPage = generalObservationPage.navigateToRefrigerators(); refrigeratorPage.clickShowForRefrigerator1(); refrigeratorPage.verifyRefrigeratorColor("individual", "RED"); refrigeratorPage.applyNRToRefrigeratorTemperature(); refrigeratorPage.clickFunctioningCorrectlyYesRadio(); refrigeratorPage.clickFunctioningCorrectlyNR(); refrigeratorPage.enterValueInLowAlarmEvents("1"); refrigeratorPage.applyNRToLowAlarmEvent(); refrigeratorPage.applyNRToHighAlarmEvent(); refrigeratorPage.verifyRefrigeratorColor("overall", "AMBER"); refrigeratorPage.clickProblemSinceLastVisitYesRadio(); refrigeratorPage.selectGasLeakProblem(); refrigeratorPage.clickProblemSinceLastVisitNR(); refrigeratorPage.verifyFieldsDisabledWhenAllNRSelected(); refrigeratorPage.verifyRefrigeratorColor("overall", "GREEN"); refrigeratorPage.verifyRefrigeratorColor("individual", "GREEN"); refrigeratorPage.clickDone(); EPIUsePage epiUsePage = refrigeratorPage.navigateToEpiUse(); epiUsePage.enterData(10, 20, 30, 40, 50, "10/2011", 1); FullCoveragePage fullCoveragePage = epiUsePage.navigateToFullCoverage(); fullCoveragePage.enterData(77, 56, 78, "34"); fullCoveragePage.navigateToEpiInventory(); fillEpiInventoryWithOnlyDeliveredQuantity("2", "4", "6"); DistributionPage distributionPage = homePage.navigateToDistributionWhenOnline(); distributionPage.syncDistribution(1); assertTrue(distributionPage.getSyncMessage().contains("F10-Village Dispensary")); distributionPage.syncDistributionMessageDone(); verifyRefrigeratorReadingDataInDatabase(refrigeratorTestData.get(FIRST_FACILITY_CODE), "GNR7878", null, null, null, null, null, null); verifyRefrigeratorProblemDataNullInDatabase("GNR7878", refrigeratorTestData.get(FIRST_FACILITY_CODE)); } @Test(groups = {"distribution"}) public void testRefrigeratorSyncWhenRefrigeratorIsDeletedBeforeSync() throws Exception { HomePage homePage = loginPage.loginAs(refrigeratorTestData.get(USER), refrigeratorTestData.get(PASSWORD)); initiateDistribution(refrigeratorTestData.get(FIRST_DELIVERY_ZONE_NAME), refrigeratorTestData.get(VACCINES_PROGRAM)); GeneralObservationPage generalObservationPage = facilityListPage.selectFacility(refrigeratorTestData.get(FIRST_FACILITY_CODE)); generalObservationPage.enterDataWhenFacilityVisited("some observations", "samuel", "Doe", "Verifier", "XYZ"); RefrigeratorPage refrigeratorPage = generalObservationPage.navigateToRefrigerators(); refrigeratorPage.clickShowForRefrigerator1(); refrigeratorPage.verifyRefrigeratorColor("individual", "RED"); refrigeratorPage.enterValueInRefrigeratorTemperature("3"); refrigeratorPage.clickFunctioningCorrectlyYesRadio(); refrigeratorPage.clickFunctioningCorrectlyNoRadio(); refrigeratorPage.enterValueInLowAlarmEvents("1"); refrigeratorPage.enterValueInHighAlarmEvents("0"); refrigeratorPage.clickProblemSinceLastVisitNoRadio(); refrigeratorPage.verifyRefrigeratorColor("overall", "GREEN"); refrigeratorPage.verifyRefrigeratorColor("individual", "GREEN"); refrigeratorPage.clickDone(); EPIUsePage epiUsePage = refrigeratorPage.navigateToEpiUse(); epiUsePage.enterData(10, 20, 30, 40, 50, "10/2011", 1); FullCoveragePage fullCoveragePage = epiUsePage.navigateToFullCoverage(); fullCoveragePage.enterData(78, 67, 34, "12"); fullCoveragePage.navigateToEpiInventory(); fillEpiInventoryWithOnlyDeliveredQuantity("2", "4", "6"); DistributionPage distributionPage = homePage.navigateToDistributionWhenOnline(); distributionPage.syncDistribution(1); assertTrue(distributionPage.getSyncMessage().contains("F10-Village Dispensary")); distributionPage.syncDistributionMessageDone(); initiateDistributionForPeriod("Period13"); distributionPage.clickRecordData(2); facilityListPage.selectFacility(refrigeratorTestData.get(FIRST_FACILITY_CODE)); facilityListPage.verifyFacilityIndicatorColor("Overall", "RED"); refrigeratorPage.verifyRefrigeratorColor("overall", "RED"); refrigeratorPage.clickShowForRefrigerator1(); refrigeratorPage.verifyRefrigeratorColor("individual", "RED"); refrigeratorPage.enterValueInRefrigeratorTemperature("3"); refrigeratorPage.clickFunctioningCorrectlyYesRadio(); refrigeratorPage.enterValueInLowAlarmEvents("2"); refrigeratorPage.enterValueInHighAlarmEvents("2"); refrigeratorPage.clickProblemSinceLastVisitYesRadio(); refrigeratorPage.verifyRefrigeratorColor("overall", "AMBER"); refrigeratorPage.selectOtherProblem(); refrigeratorPage.verifyRefrigeratorColor("overall", "GREEN"); refrigeratorPage.verifyRefrigeratorColor("individual", "GREEN"); refrigeratorPage.clickDone(); refrigeratorPage.clickDelete(); refrigeratorPage.clickOKButton(); refrigeratorPage.navigateToEpiUse(); epiUsePage.enterData(10, 20, 30, 40, 50, "10/2011", 1); epiUsePage.navigateToGeneralObservations(); generalObservationPage.enterDataWhenFacilityVisited("some observations", "samuel", "Doe", "Verifier", "XYZ"); generalObservationPage.navigateToFullCoverage(); fullCoveragePage.enterData(78, 67, 34, "12"); fullCoveragePage.navigateToEpiInventory(); fillEpiInventoryWithOnlyDeliveredQuantity("2", "4", "6"); homePage.navigateToDistributionWhenOnline(); distributionPage.syncDistribution(2); assertTrue(distributionPage.getSyncMessage().contains("F10-Village Dispensary")); distributionPage.syncDistributionMessageDone(); verifyRefrigeratorsDataInDatabase("F10", "GNR7878", "LG", "800L", "f"); } @Test(groups = {"distribution"}) public void testAddingDuplicateRefrigeratorForSameFacility() throws Exception { loginPage.loginAs(refrigeratorTestData.get(USER), refrigeratorTestData.get(PASSWORD)); initiateDistribution(refrigeratorTestData.get(FIRST_DELIVERY_ZONE_NAME), refrigeratorTestData.get(VACCINES_PROGRAM)); RefrigeratorPage refrigeratorPage = facilityListPage.selectFacility(refrigeratorTestData.get(FIRST_FACILITY_CODE)).navigateToRefrigerators(); refrigeratorPage.clickAddNew(); refrigeratorPage.addNewRefrigerator("LG", "800L1", "GNR7878"); refrigeratorPage.verifyDuplicateErrorMessage("Duplicate Manufacturer Serial Number"); } @Test(groups = {"distribution"}) public void testAddingDuplicateRefrigeratorForDifferentFacility() throws Exception { HomePage homePage = loginPage.loginAs(refrigeratorTestData.get(USER), refrigeratorTestData.get(PASSWORD)); initiateDistribution(refrigeratorTestData.get(FIRST_DELIVERY_ZONE_NAME), refrigeratorTestData.get(VACCINES_PROGRAM)); GeneralObservationPage generalObservationPage = facilityListPage.selectFacility(refrigeratorTestData.get(SECOND_FACILITY_CODE)); generalObservationPage.enterDataWhenFacilityVisited("some observations", "samuel", "Doe", "Verifier", "XYZ"); RefrigeratorPage refrigeratorPage = generalObservationPage.navigateToRefrigerators(); refrigeratorPage.clickAddNew(); refrigeratorPage.addNewRefrigerator("LG22", "800L22", "GNR7878"); refrigeratorPage.clickShowForRefrigerator1(); refrigeratorPage.enterValueInRefrigeratorTemperature("3"); refrigeratorPage.clickFunctioningCorrectlyYesRadio(); refrigeratorPage.enterValueInLowAlarmEvents("2"); refrigeratorPage.enterValueInHighAlarmEvents("2"); refrigeratorPage.clickProblemSinceLastVisitNR(); refrigeratorPage.verifyRefrigeratorColor("overall", "GREEN"); refrigeratorPage.verifyRefrigeratorColor("individual", "GREEN"); refrigeratorPage.clickDone(); EPIUsePage epiUsePage = refrigeratorPage.navigateToEpiUse(); epiUsePage.enterData(10, 20, 30, 40, 50, "10/2011", 1); FullCoveragePage fullCoveragePage = epiUsePage.navigateToFullCoverage(); fullCoveragePage.enterData(12, 34, 45, "56"); fullCoveragePage.navigateToEpiInventory(); fillEpiInventoryWithOnlyDeliveredQuantity("2", "4", "6"); DistributionPage distributionPage = homePage.navigateToDistributionWhenOnline(); distributionPage.syncDistribution(1); assertTrue(distributionPage.getSyncMessage().contains("F11-Central Hospital")); distributionPage.syncDistributionMessageDone(); verifyRefrigeratorReadingDataInDatabase(refrigeratorTestData.get(SECOND_FACILITY_CODE), "GNR7878", 3.0f, "Y", 2, 2, null, null); verifyRefrigeratorProblemDataNullInDatabase("GNR7878", refrigeratorTestData.get(SECOND_FACILITY_CODE)); verifyRefrigeratorsDataInDatabase("F11", "GNR7878", "LG22", "800L22", "t"); } @Test(groups = {"distribution"}) public void testUpdatingRefrigeratorAndSync() throws Exception { HomePage homePage = loginPage.loginAs(refrigeratorTestData.get(USER), refrigeratorTestData.get(PASSWORD)); initiateDistribution(refrigeratorTestData.get(FIRST_DELIVERY_ZONE_NAME), refrigeratorTestData.get(VACCINES_PROGRAM)); GeneralObservationPage generalObservationPage = facilityListPage.selectFacility(refrigeratorTestData.get(FIRST_FACILITY_CODE)); generalObservationPage.enterDataWhenFacilityVisited("some observations", "samuel", "Doe", "Verifier", "XYZ"); RefrigeratorPage refrigeratorPage = generalObservationPage.navigateToRefrigerators(); refrigeratorPage.clickDelete(); refrigeratorPage.clickOKButton(); facilityListPage = new FacilityListPage(testWebDriver); facilityListPage.verifyFacilityIndicatorColor("overall", "AMBER"); refrigeratorPage.clickAddNew(); refrigeratorPage.addNewRefrigerator("LG", "800L1", "GNR7878"); refrigeratorPage.verifyRefrigeratorColor("overall", "RED"); refrigeratorPage.clickShowForRefrigerator1(); refrigeratorPage.verifyRefrigeratorColor("individual", "RED"); refrigeratorPage.enterValueInRefrigeratorTemperature("3"); refrigeratorPage.clickFunctioningCorrectlyYesRadio(); refrigeratorPage.enterValueInLowAlarmEvents("2"); refrigeratorPage.enterValueInHighAlarmEvents("2"); refrigeratorPage.clickProblemSinceLastVisitNR(); refrigeratorPage.verifyRefrigeratorColor("overall", "GREEN"); refrigeratorPage.verifyRefrigeratorColor("individual", "GREEN"); refrigeratorPage.clickDone(); EPIUsePage epiUse = refrigeratorPage.navigateToEpiUse(); epiUse.enterData(10, 20, 30, 40, 50, "10/2011", 1); FullCoveragePage fullCoveragePage = epiUse.navigateToFullCoverage(); fullCoveragePage.enterData(67, 8, 33, "54"); fullCoveragePage.navigateToEpiInventory(); fillEpiInventoryWithOnlyDeliveredQuantity("2", "4", "6"); DistributionPage distributionPage = homePage.navigateToDistributionWhenOnline(); distributionPage.syncDistribution(1); assertTrue(distributionPage.getSyncMessage().contains("F10-Village Dispensary")); distributionPage.syncDistributionMessageDone(); verifyRefrigeratorReadingDataInDatabase(refrigeratorTestData.get(FIRST_FACILITY_CODE), "GNR7878", 3.0f, "Y", 2, 2, null, null); verifyRefrigeratorProblemDataNullInDatabase("GNR7878", refrigeratorTestData.get(FIRST_FACILITY_CODE)); verifyRefrigeratorsDataInDatabase("F10", "GNR7878", "LG", "800L1", "t"); } private void initiateDistributionForPeriod(String periodName) { DistributionPage distributionPage = PageFactory.getInstanceOfDistributionPage(testWebDriver); distributionPage.selectValueFromDeliveryZone(refrigeratorTestData.get(FIRST_DELIVERY_ZONE_NAME)); distributionPage.selectValueFromProgram(refrigeratorTestData.get(VACCINES_PROGRAM)); distributionPage.selectValueFromPeriod(periodName); distributionPage.clickInitiateDistribution(); } public void setupDataForDistributionTest(String userSIC, String deliveryZoneCodeFirst, String deliveryZoneCodeSecond, String deliveryZoneNameFirst, String deliveryZoneNameSecond, String facilityCodeFirst, String facilityCodeSecond, String programFirst, String programSecond, String schedule, String productGroupCode) throws Exception { List<String> rightsList = asList("MANAGE_DISTRIBUTION"); setupTestDataToInitiateRnRAndDistribution(facilityCodeFirst, facilityCodeSecond, true, programFirst, userSIC, "200", rightsList, programSecond, "District1", "Ngorongoro", "Ngorongoro"); setupDataForDeliveryZone(true, deliveryZoneCodeFirst, deliveryZoneCodeSecond, deliveryZoneNameFirst, deliveryZoneNameSecond, facilityCodeFirst, facilityCodeSecond, programFirst, programSecond, schedule); dbWrapper.insertRoleAssignmentForDistribution(userSIC, "store in-charge", deliveryZoneCodeFirst); dbWrapper.insertRoleAssignmentForDistribution(userSIC, "store in-charge", deliveryZoneCodeSecond); dbWrapper.insertProductGroup(productGroupCode); dbWrapper.insertProductWithGroup("Product5", "ProductName5", productGroupCode, true); dbWrapper.insertProductWithGroup("Product6", "ProductName6", productGroupCode, true); dbWrapper.insertProgramProduct("Product5", programFirst, "10", "false"); dbWrapper.insertProgramProduct("Product6", programFirst, "10", "true"); dbWrapper.addRefrigeratorToFacility("LG", "800L", "GNR7878", "F10"); } public void initiateDistribution(String deliveryZoneNameFirst, String programFirst) { HomePage homePage = PageFactory.getInstanceOfHomePage(testWebDriver); DistributionPage distributionPage = homePage.navigateToDistributionWhenOnline(); distributionPage.selectValueFromDeliveryZone(deliveryZoneNameFirst); distributionPage.selectValueFromProgram(programFirst); distributionPage.clickInitiateDistribution(); distributionPage.clickRecordData(1); } public void fillEpiInventoryWithOnlyDeliveredQuantity(String deliveredQuantity1, String deliveredQuantity2, String deliveredQuantity3) { EpiInventoryPage epiInventoryPage = PageFactory.getInstanceOfEpiInventoryPage(testWebDriver); epiInventoryPage.applyNRToAll(); epiInventoryPage.fillDeliveredQuantity(1, deliveredQuantity1); epiInventoryPage.fillDeliveredQuantity(2, deliveredQuantity2); epiInventoryPage.fillDeliveredQuantity(3, deliveredQuantity3); } @AfterMethod(groups = "distribution") public void tearDown() throws Exception { testWebDriver.sleep(500); if (!testWebDriver.getElementById("username").isDisplayed()) { HomePage homePage = PageFactory.getInstanceOfHomePage(testWebDriver); homePage.logout(baseUrlGlobal); dbWrapper.deleteData(); dbWrapper.closeConnection(); } ((JavascriptExecutor) TestWebDriver.getDriver()).executeScript("indexedDB.deleteDatabase('open_lmis');"); } }
Fixed FT Distribution tests - Added steps to navigate to refrigeratorpage
test-modules/functional-tests/src/test/java/org/openlmis/functional/DistributionRefrigeratorSyncTest.java
Fixed FT Distribution tests - Added steps to navigate to refrigeratorpage
Java
agpl-3.0
c2b64f8fa61fa1e463528f4af0ac83b2d58f94a2
0
o2oa/o2oa,o2oa/o2oa,o2oa/o2oa,o2oa/o2oa,o2oa/o2oa
package com.x.processplatform.core.entity.element; import java.util.ArrayList; import java.util.List; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Lob; import javax.persistence.OrderColumn; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import org.apache.openjpa.persistence.PersistentCollection; import org.apache.openjpa.persistence.jdbc.ContainerTable; import org.apache.openjpa.persistence.jdbc.ElementColumn; import org.apache.openjpa.persistence.jdbc.ElementIndex; import org.apache.openjpa.persistence.jdbc.Index; import com.x.base.core.entity.JpaObject; import com.x.base.core.entity.annotation.CheckPersist; import com.x.base.core.entity.annotation.ContainerEntity; import com.x.base.core.entity.annotation.Flag; import com.x.base.core.entity.annotation.IdReference; import com.x.base.core.project.annotation.FieldDescribe; import com.x.processplatform.core.entity.PersistenceProperties; @Entity @ContainerEntity(dumpSize = 5, type = ContainerEntity.Type.element, reference = ContainerEntity.Reference.strong) @Table(name = PersistenceProperties.Element.End.table, uniqueConstraints = { @UniqueConstraint(name = PersistenceProperties.Element.End.table + JpaObject.IndexNameMiddle + JpaObject.DefaultUniqueConstraintSuffix, columnNames = { JpaObject.IDCOLUMN, JpaObject.CREATETIMECOLUMN, JpaObject.UPDATETIMECOLUMN, JpaObject.SEQUENCECOLUMN }) }) @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public class End extends Activity { private static final long serialVersionUID = 4743363087103193389L; private static final String TABLE = PersistenceProperties.Element.End.table; public String getId() { return id; } public void setId(String id) { this.id = id; } @FieldDescribe("数据库主键,自动生成.") @Id @Column(length = length_id, name = ColumnNamePrefix + id_FIELDNAME) private String id = createId(); /* 以上为 JpaObject 默认字段 */ public void onPersist() throws Exception { // nothing } @Override public List<String> getRouteList() { return new ArrayList<>(); } @FieldDescribe("分组") @CheckPersist(allowEmpty = true) @Column(length = JpaObject.length_255B, name = ColumnNamePrefix + group_FIELDNAME) private String group; @FieldDescribe("意见分组") @CheckPersist(allowEmpty = true) @Column(length = JpaObject.length_255B, name = ColumnNamePrefix + opinionGroup_FIELDNAME) private String opinionGroup; @FieldDescribe("节点名称.") @Column(length = length_255B, name = ColumnNamePrefix + name_FIELDNAME) @CheckPersist(allowEmpty = true, simplyString = false) private String name; @Flag @FieldDescribe("节点别名.") @Column(length = length_255B, name = ColumnNamePrefix + alias_FIELDNAME) @CheckPersist(allowEmpty = true, simplyString = false) private String alias; @FieldDescribe("描述.") @Column(length = length_255B, name = ColumnNamePrefix + description_FIELDNAME) @CheckPersist(allowEmpty = true) private String description; @IdReference(Process.class) @FieldDescribe("流程标识,不为空.") @Column(length = JpaObject.length_id, name = ColumnNamePrefix + process_FIELDNAME) @Index(name = TABLE + IndexNameMiddle + process_FIELDNAME) @CheckPersist(allowEmpty = false) private String process; @FieldDescribe("节点位置.") @Column(length = JpaObject.length_32B, name = ColumnNamePrefix + position_FIELDNAME) @CheckPersist(allowEmpty = true) private String position; @FieldDescribe("前端自定内容.") @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + extension_FIELDNAME) @Basic(fetch = FetchType.EAGER) @Lob @CheckPersist(allowEmpty = true) private String extension; @IdReference(Form.class) @FieldDescribe("节点使用的表单.") @Column(length = JpaObject.length_id, name = ColumnNamePrefix + form_FIELDNAME) @Index(name = TABLE + IndexNameMiddle + form_FIELDNAME) @CheckPersist(allowEmpty = true) private String form; @FieldDescribe("待阅人名称,存储 Identity,多值.") @PersistentCollection(fetch = FetchType.EAGER) @ContainerTable(name = TABLE + ContainerTableNameMiddle + readIdentityList_FIELDNAME, joinIndex = @Index(name = TABLE + IndexNameMiddle + readIdentityList_FIELDNAME + JoinIndexNameSuffix)) @OrderColumn(name = ORDERCOLUMNCOLUMN) @ElementColumn(length = length_255B, name = ColumnNamePrefix + readIdentityList_FIELDNAME) @ElementIndex(name = TABLE + IndexNameMiddle + readIdentityList_FIELDNAME + ElementIndexNameSuffix) @CheckPersist(allowEmpty = true) private List<String> readIdentityList; @FieldDescribe("待阅组织名称,存储unit,多值.") @PersistentCollection(fetch = FetchType.EAGER) @ContainerTable(name = TABLE + ContainerTableNameMiddle + readUnitList_FIELDNAME, joinIndex = @Index(name = TABLE + IndexNameMiddle + readUnitList_FIELDNAME + JoinIndexNameSuffix)) @OrderColumn(name = ORDERCOLUMNCOLUMN) @ElementColumn(length = length_255B, name = ColumnNamePrefix + readUnitList_FIELDNAME) @ElementIndex(name = TABLE + IndexNameMiddle + readUnitList_FIELDNAME + ElementIndexNameSuffix) @CheckPersist(allowEmpty = true) private List<String> readUnitList; @FieldDescribe("待阅群组名称,存储group,多值.") @PersistentCollection(fetch = FetchType.EAGER) @ContainerTable(name = TABLE + ContainerTableNameMiddle + readGroupList_FIELDNAME, joinIndex = @Index(name = TABLE + IndexNameMiddle + readGroupList_FIELDNAME + JoinIndexNameSuffix)) @OrderColumn(name = ORDERCOLUMNCOLUMN) @ElementColumn(length = length_255B, name = ColumnNamePrefix + readGroupList_FIELDNAME) @ElementIndex(name = TABLE + IndexNameMiddle + readGroupList_FIELDNAME + ElementIndexNameSuffix) @CheckPersist(allowEmpty = true) private List<String> readGroupList; @IdReference(Script.class) @FieldDescribe("待阅人脚本.") @Column(length = length_255B, name = ColumnNamePrefix + readScript_FIELDNAME) @CheckPersist(allowEmpty = true) private String readScript; @FieldDescribe("待阅人脚本文本.") @Lob @Basic(fetch = FetchType.EAGER) @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + readScriptText_FIELDNAME) @CheckPersist(allowEmpty = true) private String readScriptText; @FieldDescribe("待阅角色定义内容.") @Lob @Basic(fetch = FetchType.EAGER) @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + readDuty_FIELDNAME) @CheckPersist(allowEmpty = true) private String readDuty; @FieldDescribe("活动待阅人员data数据路径.") @PersistentCollection(fetch = FetchType.EAGER) @ContainerTable(name = TABLE + ContainerTableNameMiddle + readDataPathList_FIELDNAME, joinIndex = @Index(name = TABLE + IndexNameMiddle + readDataPathList_FIELDNAME + JoinIndexNameSuffix)) @OrderColumn(name = ORDERCOLUMNCOLUMN) @ElementColumn(length = JpaObject.length_255B, name = ColumnNamePrefix + readDataPathList_FIELDNAME) @ElementIndex(name = TABLE + IndexNameMiddle + readDataPathList_FIELDNAME + ElementIndexNameSuffix) @CheckPersist(allowEmpty = true) private List<String> readDataPathList; @FieldDescribe("参与人名称,多值.") @PersistentCollection(fetch = FetchType.EAGER) @ContainerTable(name = TABLE + ContainerTableNameMiddle + reviewIdentityList_FIELDNAME, joinIndex = @Index(name = TABLE + IndexNameMiddle + reviewIdentityList_FIELDNAME + JoinIndexNameSuffix)) @OrderColumn(name = ORDERCOLUMNCOLUMN) @ElementColumn(length = length_255B, name = ColumnNamePrefix + reviewIdentityList_FIELDNAME) @ElementIndex(name = TABLE + IndexNameMiddle + reviewIdentityList_FIELDNAME + ElementIndexNameSuffix) @CheckPersist(allowEmpty = true) private List<String> reviewIdentityList; @FieldDescribe("参与人组织名称,多值.") @PersistentCollection(fetch = FetchType.EAGER) @ContainerTable(name = TABLE + ContainerTableNameMiddle + reviewUnitList_FIELDNAME, joinIndex = @Index(name = TABLE + IndexNameMiddle + reviewUnitList_FIELDNAME + JoinIndexNameSuffix)) @OrderColumn(name = ORDERCOLUMNCOLUMN) @ElementColumn(length = length_255B, name = ColumnNamePrefix + reviewUnitList_FIELDNAME) @ElementIndex(name = TABLE + IndexNameMiddle + reviewUnitList_FIELDNAME + ElementIndexNameSuffix) @CheckPersist(allowEmpty = true) private List<String> reviewUnitList; @FieldDescribe("参与人群组名称,存储group,多值.") @PersistentCollection(fetch = FetchType.EAGER) @ContainerTable(name = TABLE + ContainerTableNameMiddle + reviewGroupList_FIELDNAME, joinIndex = @Index(name = TABLE + IndexNameMiddle + reviewGroupList_FIELDNAME + JoinIndexNameSuffix)) @OrderColumn(name = ORDERCOLUMNCOLUMN) @ElementColumn(length = length_255B, name = ColumnNamePrefix + reviewGroupList_FIELDNAME) @ElementIndex(name = TABLE + IndexNameMiddle + reviewGroupList_FIELDNAME + ElementIndexNameSuffix) @CheckPersist(allowEmpty = true) private List<String> reviewGroupList; @IdReference(Script.class) @FieldDescribe("参与人脚本.") @Column(length = length_255B, name = ColumnNamePrefix + reviewScript_FIELDNAME) @CheckPersist(allowEmpty = true) private String reviewScript; @FieldDescribe("参与人脚本文本.") @Lob @Basic(fetch = FetchType.EAGER) @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + reviewScriptText_FIELDNAME) @CheckPersist(allowEmpty = true) private String reviewScriptText; @FieldDescribe("参阅角色定义内容.") @Lob @Basic(fetch = FetchType.EAGER) @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + reviewDuty_FIELDNAME) @CheckPersist(allowEmpty = true) private String reviewDuty; @FieldDescribe("参阅人员data数据路径.") @PersistentCollection(fetch = FetchType.EAGER) @ContainerTable(name = TABLE + ContainerTableNameMiddle + reviewDataPathList_FIELDNAME, joinIndex = @Index(name = TABLE + IndexNameMiddle + reviewDataPathList_FIELDNAME + JoinIndexNameSuffix)) @OrderColumn(name = ORDERCOLUMNCOLUMN) @ElementColumn(length = JpaObject.length_255B, name = ColumnNamePrefix + reviewDataPathList_FIELDNAME) @ElementIndex(name = TABLE + IndexNameMiddle + reviewDataPathList_FIELDNAME + ElementIndexNameSuffix) @CheckPersist(allowEmpty = true) private List<String> reviewDataPathList; @IdReference(Script.class) @FieldDescribe("活动到达前事件脚本.") @Column(length = length_255B, name = ColumnNamePrefix + beforeArriveScript_FIELDNAME) @CheckPersist(allowEmpty = true) private String beforeArriveScript; @FieldDescribe("活动到达前事件脚本文本.") @Lob @Basic(fetch = FetchType.EAGER) @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + beforeArriveScriptText_FIELDNAME) @CheckPersist(allowEmpty = true) private String beforeArriveScriptText; @IdReference(Script.class) @FieldDescribe("活动到达后事件脚本.") @Column(length = length_255B, name = ColumnNamePrefix + afterArriveScript_FIELDNAME) @CheckPersist(allowEmpty = true) private String afterArriveScript; @FieldDescribe("活动到达后事件脚本文本.") @Lob @Basic(fetch = FetchType.EAGER) @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + afterArriveScriptText_FIELDNAME) @CheckPersist(allowEmpty = true) private String afterArriveScriptText; @IdReference(Script.class) @FieldDescribe("活动执行前事件脚本.") @Column(length = length_255B, name = ColumnNamePrefix + beforeExecuteScript_FIELDNAME) @CheckPersist(allowEmpty = true) private String beforeExecuteScript; @FieldDescribe("活动执行前事件脚本文本.") @Lob @Basic(fetch = FetchType.EAGER) @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + beforeExecuteScriptText_FIELDNAME) @CheckPersist(allowEmpty = true) private String beforeExecuteScriptText; @IdReference(Script.class) @FieldDescribe("活动执行后事件脚本.") @Column(length = length_255B, name = ColumnNamePrefix + afterExecuteScript_FIELDNAME) @CheckPersist(allowEmpty = true) private String afterExecuteScript; @FieldDescribe("活动执行后事件脚本文本.") @Lob @Basic(fetch = FetchType.EAGER) @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + afterExecuteScriptText_FIELDNAME) @CheckPersist(allowEmpty = true) private String afterExecuteScriptText; @IdReference(Script.class) @FieldDescribe("路由查询前事件脚本.") @Column(length = length_255B, name = ColumnNamePrefix + beforeInquireScript_FIELDNAME) @CheckPersist(allowEmpty = true) private String beforeInquireScript; @FieldDescribe("路由查询前事件脚本文本.") @Lob @Basic(fetch = FetchType.EAGER) @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + beforeInquireScriptText_FIELDNAME) @CheckPersist(allowEmpty = true) private String beforeInquireScriptText; @IdReference(Script.class) @FieldDescribe("路由查询后事件脚本.") @Column(length = length_255B, name = ColumnNamePrefix + afterInquireScript_FIELDNAME) @CheckPersist(allowEmpty = true) private String afterInquireScript; @FieldDescribe("路由查询后事件脚本文本.") @Lob @Basic(fetch = FetchType.EAGER) @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + afterInquireScriptText_FIELDNAME) @CheckPersist(allowEmpty = true) private String afterInquireScriptText; @FieldDescribe("允许调度") @CheckPersist(allowEmpty = true) @Column(name = ColumnNamePrefix + allowReroute_FIELDNAME) @Index(name = TABLE + IndexNameMiddle + allowReroute_FIELDNAME) private Boolean allowReroute; @FieldDescribe("允许调度到此节点") @CheckPersist(allowEmpty = true) @Column(name = ColumnNamePrefix + allowRerouteTo_FIELDNAME) @Index(name = TABLE + IndexNameMiddle + allowRerouteTo_FIELDNAME) private Boolean allowRerouteTo; @FieldDescribe("允许挂起") @CheckPersist(allowEmpty = true) @Column(name = ColumnNamePrefix + allowSuspend_FIELDNAME) private Boolean allowSuspend; public static final String allowRollback_FIELDNAME = "allowRollback"; @FieldDescribe("允许回滚") @CheckPersist(allowEmpty = true) @Column(name = ColumnNamePrefix + allowRollback_FIELDNAME) private Boolean allowRollback; @IdReference(Script.class) @FieldDescribe("生成displayLog脚本.") @Column(length = length_255B, name = ColumnNamePrefix + displayLogScript_FIELDNAME) @CheckPersist(allowEmpty = true) private String displayLogScript; @FieldDescribe("生成displayLog脚本文本.") @Lob @Basic(fetch = FetchType.EAGER) @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + displayLogScriptText_FIELDNAME) @CheckPersist(allowEmpty = true) private String displayLogScriptText; public static final String edition_FIELDNAME = "edition"; @FieldDescribe("版本编码.") @Column(length = JpaObject.length_255B, name = ColumnNamePrefix + edition_FIELDNAME) private String edition; public String getDisplayLogScript() { return displayLogScript; } public void setDisplayLogScript(String displayLogScript) { this.displayLogScript = displayLogScript; } public String getDisplayLogScriptText() { return displayLogScriptText; } public void setDisplayLogScriptText(String displayLogScriptText) { this.displayLogScriptText = displayLogScriptText; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getProcess() { return process; } public void setProcess(String process) { this.process = process; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public String getExtension() { return extension; } public Boolean getAllowSuspend() { return allowSuspend; } public void setAllowSuspend(Boolean allowSuspend) { this.allowSuspend = allowSuspend; } public void setExtension(String extension) { this.extension = extension; } public String getBeforeArriveScript() { return beforeArriveScript; } public void setBeforeArriveScript(String beforeArriveScript) { this.beforeArriveScript = beforeArriveScript; } public String getAfterArriveScript() { return afterArriveScript; } public void setAfterArriveScript(String afterArriveScript) { this.afterArriveScript = afterArriveScript; } public String getBeforeExecuteScript() { return beforeExecuteScript; } public void setBeforeExecuteScript(String beforeExecuteScript) { this.beforeExecuteScript = beforeExecuteScript; } public String getAfterExecuteScript() { return afterExecuteScript; } public void setAfterExecuteScript(String afterExecuteScript) { this.afterExecuteScript = afterExecuteScript; } public String getForm() { return form; } public void setForm(String form) { this.form = form; } public List<String> getReviewIdentityList() { return reviewIdentityList; } public void setReviewIdentityList(List<String> reviewIdentityList) { this.reviewIdentityList = reviewIdentityList; } public List<String> getReviewUnitList() { return reviewUnitList; } public void setReviewUnitList(List<String> reviewUnitList) { this.reviewUnitList = reviewUnitList; } public String getReviewScript() { return reviewScript; } public void setReviewScript(String reviewScript) { this.reviewScript = reviewScript; } public String getReviewScriptText() { return reviewScriptText; } public void setReviewScriptText(String reviewScriptText) { this.reviewScriptText = reviewScriptText; } public String getBeforeArriveScriptText() { return beforeArriveScriptText; } public void setBeforeArriveScriptText(String beforeArriveScriptText) { this.beforeArriveScriptText = beforeArriveScriptText; } public String getAfterArriveScriptText() { return afterArriveScriptText; } public void setAfterArriveScriptText(String afterArriveScriptText) { this.afterArriveScriptText = afterArriveScriptText; } public String getBeforeExecuteScriptText() { return beforeExecuteScriptText; } public void setBeforeExecuteScriptText(String beforeExecuteScriptText) { this.beforeExecuteScriptText = beforeExecuteScriptText; } public String getAfterExecuteScriptText() { return afterExecuteScriptText; } public void setAfterExecuteScriptText(String afterExecuteScriptText) { this.afterExecuteScriptText = afterExecuteScriptText; } public List<String> getReadIdentityList() { return readIdentityList; } public void setReadIdentityList(List<String> readIdentityList) { this.readIdentityList = readIdentityList; } public List<String> getReadUnitList() { return readUnitList; } public void setReadUnitList(List<String> readUnitList) { this.readUnitList = readUnitList; } public String getReadScript() { return readScript; } public void setReadScript(String readScript) { this.readScript = readScript; } public String getReadScriptText() { return readScriptText; } public void setReadScriptText(String readScriptText) { this.readScriptText = readScriptText; } public Boolean getAllowReroute() { return allowReroute; } public void setAllowReroute(Boolean allowReroute) { this.allowReroute = allowReroute; } public Boolean getAllowRerouteTo() { return allowRerouteTo; } public void setAllowRerouteTo(Boolean allowRerouteTo) { this.allowRerouteTo = allowRerouteTo; } public String getReadDuty() { return readDuty; } public void setReadDuty(String readDuty) { this.readDuty = readDuty; } public List<String> getReadDataPathList() { return readDataPathList; } public void setReadDataPathList(List<String> readDataPathList) { this.readDataPathList = readDataPathList; } public String getReviewDuty() { return reviewDuty; } public void setReviewDuty(String reviewDuty) { this.reviewDuty = reviewDuty; } public List<String> getReviewDataPathList() { return reviewDataPathList; } public void setReviewDataPathList(List<String> reviewDataPathList) { this.reviewDataPathList = reviewDataPathList; } public List<String> getReadGroupList() { return readGroupList; } public void setReadGroupList(List<String> readGroupList) { this.readGroupList = readGroupList; } public List<String> getReviewGroupList() { return reviewGroupList; } public void setReviewGroupList(List<String> reviewGroupList) { this.reviewGroupList = reviewGroupList; } public String getBeforeInquireScript() { return beforeInquireScript; } public void setBeforeInquireScript(String beforeInquireScript) { this.beforeInquireScript = beforeInquireScript; } public String getBeforeInquireScriptText() { return beforeInquireScriptText; } public void setBeforeInquireScriptText(String beforeInquireScriptText) { this.beforeInquireScriptText = beforeInquireScriptText; } public String getAfterInquireScript() { return afterInquireScript; } public void setAfterInquireScript(String afterInquireScript) { this.afterInquireScript = afterInquireScript; } public String getAfterInquireScriptText() { return afterInquireScriptText; } public void setAfterInquireScriptText(String afterInquireScriptText) { this.afterInquireScriptText = afterInquireScriptText; } public Boolean getAllowRollback() { return allowRollback; } public void setAllowRollback(Boolean allowRollback) { this.allowRollback = allowRollback; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public String getOpinionGroup() { return opinionGroup; } public void setOpinionGroup(String opinionGroup) { this.opinionGroup = opinionGroup; } public String getEdition() { return edition; } public void setEdition(String edition) { this.edition = edition; } }
o2server/x_processplatform_core_entity/src/main/java/com/x/processplatform/core/entity/element/End.java
package com.x.processplatform.core.entity.element; import java.util.ArrayList; import java.util.List; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Lob; import javax.persistence.OrderColumn; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import com.x.base.core.entity.JpaObject; import com.x.base.core.entity.annotation.CheckPersist; import com.x.base.core.entity.annotation.ContainerEntity; import com.x.base.core.entity.annotation.Flag; import com.x.base.core.entity.annotation.IdReference; import com.x.base.core.project.annotation.FieldDescribe; import com.x.base.core.project.tools.ListTools; import com.x.processplatform.core.entity.PersistenceProperties; import org.apache.commons.lang3.StringUtils; import org.apache.openjpa.persistence.PersistentCollection; import org.apache.openjpa.persistence.jdbc.ContainerTable; import org.apache.openjpa.persistence.jdbc.ElementColumn; import org.apache.openjpa.persistence.jdbc.ElementIndex; import org.apache.openjpa.persistence.jdbc.Index; @Entity @ContainerEntity(dumpSize = 5, type = ContainerEntity.Type.element, reference = ContainerEntity.Reference.strong) @Table(name = PersistenceProperties.Element.End.table, uniqueConstraints = { @UniqueConstraint(name = PersistenceProperties.Element.End.table + JpaObject.IndexNameMiddle + JpaObject.DefaultUniqueConstraintSuffix, columnNames = { JpaObject.IDCOLUMN, JpaObject.CREATETIMECOLUMN, JpaObject.UPDATETIMECOLUMN, JpaObject.SEQUENCECOLUMN }) }) @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public class End extends Activity { private static final long serialVersionUID = 4743363087103193389L; private static final String TABLE = PersistenceProperties.Element.End.table; public String getId() { return id; } public void setId(String id) { this.id = id; } @FieldDescribe("数据库主键,自动生成.") @Id @Column(length = length_id, name = ColumnNamePrefix + id_FIELDNAME) private String id = createId(); /* 以上为 JpaObject 默认字段 */ public void onPersist() throws Exception { // nothing } @Override public List<String> getRouteList() { return new ArrayList<>(); } @FieldDescribe("分组") @CheckPersist(allowEmpty = true) @Column(length = JpaObject.length_255B, name = ColumnNamePrefix + group_FIELDNAME) private String group; @FieldDescribe("意见分组") @CheckPersist(allowEmpty = true) @Column(length = JpaObject.length_255B, name = ColumnNamePrefix + opinionGroup_FIELDNAME) private String opinionGroup; @FieldDescribe("节点名称.") @Column(length = length_255B, name = ColumnNamePrefix + name_FIELDNAME) @CheckPersist(allowEmpty = true, simplyString = false) private String name; @Flag @FieldDescribe("节点别名.") @Column(length = length_255B, name = ColumnNamePrefix + alias_FIELDNAME) @CheckPersist(allowEmpty = true, simplyString = false) private String alias; @FieldDescribe("描述.") @Column(length = length_255B, name = ColumnNamePrefix + description_FIELDNAME) @CheckPersist(allowEmpty = true) private String description; @IdReference(Process.class) @FieldDescribe("流程标识,不为空.") @Column(length = JpaObject.length_id, name = ColumnNamePrefix + process_FIELDNAME) @Index(name = TABLE + IndexNameMiddle + process_FIELDNAME) @CheckPersist(allowEmpty = false) private String process; @FieldDescribe("节点位置.") @Column(length = JpaObject.length_32B, name = ColumnNamePrefix + position_FIELDNAME) @CheckPersist(allowEmpty = true) private String position; @FieldDescribe("前端自定内容.") @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + extension_FIELDNAME) @Basic(fetch = FetchType.EAGER) @Lob @CheckPersist(allowEmpty = true) private String extension; @IdReference(Form.class) @FieldDescribe("节点使用的表单.") @Column(length = JpaObject.length_id, name = ColumnNamePrefix + form_FIELDNAME) @Index(name = TABLE + IndexNameMiddle + form_FIELDNAME) @CheckPersist(allowEmpty = true) private String form; @FieldDescribe("待阅人名称,存储 Identity,多值.") @PersistentCollection(fetch = FetchType.EAGER) @ContainerTable(name = TABLE + ContainerTableNameMiddle + readIdentityList_FIELDNAME, joinIndex = @Index(name = TABLE + IndexNameMiddle + readIdentityList_FIELDNAME + JoinIndexNameSuffix)) @OrderColumn(name = ORDERCOLUMNCOLUMN) @ElementColumn(length = length_255B, name = ColumnNamePrefix + readIdentityList_FIELDNAME) @ElementIndex(name = TABLE + IndexNameMiddle + readIdentityList_FIELDNAME + ElementIndexNameSuffix) @CheckPersist(allowEmpty = true) private List<String> readIdentityList; @FieldDescribe("待阅组织名称,存储unit,多值.") @PersistentCollection(fetch = FetchType.EAGER) @ContainerTable(name = TABLE + ContainerTableNameMiddle + readUnitList_FIELDNAME, joinIndex = @Index(name = TABLE + IndexNameMiddle + readUnitList_FIELDNAME + JoinIndexNameSuffix)) @OrderColumn(name = ORDERCOLUMNCOLUMN) @ElementColumn(length = length_255B, name = ColumnNamePrefix + readUnitList_FIELDNAME) @ElementIndex(name = TABLE + IndexNameMiddle + readUnitList_FIELDNAME + ElementIndexNameSuffix) @CheckPersist(allowEmpty = true) private List<String> readUnitList; @FieldDescribe("待阅群组名称,存储group,多值.") @PersistentCollection(fetch = FetchType.EAGER) @ContainerTable(name = TABLE + ContainerTableNameMiddle + readGroupList_FIELDNAME, joinIndex = @Index(name = TABLE + IndexNameMiddle + readGroupList_FIELDNAME + JoinIndexNameSuffix)) @OrderColumn(name = ORDERCOLUMNCOLUMN) @ElementColumn(length = length_255B, name = ColumnNamePrefix + readGroupList_FIELDNAME) @ElementIndex(name = TABLE + IndexNameMiddle + readGroupList_FIELDNAME + ElementIndexNameSuffix) @CheckPersist(allowEmpty = true) private List<String> readGroupList; @IdReference(Script.class) @FieldDescribe("待阅人脚本.") @Column(length = length_255B, name = ColumnNamePrefix + readScript_FIELDNAME) @CheckPersist(allowEmpty = true) private String readScript; @FieldDescribe("待阅人脚本文本.") @Lob @Basic(fetch = FetchType.EAGER) @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + readScriptText_FIELDNAME) @CheckPersist(allowEmpty = true) private String readScriptText; @FieldDescribe("待阅角色定义内容.") @Lob @Basic(fetch = FetchType.EAGER) @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + readDuty_FIELDNAME) @CheckPersist(allowEmpty = true) private String readDuty; @FieldDescribe("活动待阅人员data数据路径.") @PersistentCollection(fetch = FetchType.EAGER) @ContainerTable(name = TABLE + ContainerTableNameMiddle + readDataPathList_FIELDNAME, joinIndex = @Index(name = TABLE + IndexNameMiddle + readDataPathList_FIELDNAME + JoinIndexNameSuffix)) @OrderColumn(name = ORDERCOLUMNCOLUMN) @ElementColumn(length = JpaObject.length_255B, name = ColumnNamePrefix + readDataPathList_FIELDNAME) @ElementIndex(name = TABLE + IndexNameMiddle + readDataPathList_FIELDNAME + ElementIndexNameSuffix) @CheckPersist(allowEmpty = true) private List<String> readDataPathList; @FieldDescribe("参与人名称,多值.") @PersistentCollection(fetch = FetchType.EAGER) @ContainerTable(name = TABLE + ContainerTableNameMiddle + reviewIdentityList_FIELDNAME, joinIndex = @Index(name = TABLE + IndexNameMiddle + reviewIdentityList_FIELDNAME + JoinIndexNameSuffix)) @OrderColumn(name = ORDERCOLUMNCOLUMN) @ElementColumn(length = length_255B, name = ColumnNamePrefix + reviewIdentityList_FIELDNAME) @ElementIndex(name = TABLE + IndexNameMiddle + reviewIdentityList_FIELDNAME + ElementIndexNameSuffix) @CheckPersist(allowEmpty = true) private List<String> reviewIdentityList; @FieldDescribe("参与人组织名称,多值.") @PersistentCollection(fetch = FetchType.EAGER) @ContainerTable(name = TABLE + ContainerTableNameMiddle + reviewUnitList_FIELDNAME, joinIndex = @Index(name = TABLE + IndexNameMiddle + reviewUnitList_FIELDNAME + JoinIndexNameSuffix)) @OrderColumn(name = ORDERCOLUMNCOLUMN) @ElementColumn(length = length_255B, name = ColumnNamePrefix + reviewUnitList_FIELDNAME) @ElementIndex(name = TABLE + IndexNameMiddle + reviewUnitList_FIELDNAME + ElementIndexNameSuffix) @CheckPersist(allowEmpty = true) private List<String> reviewUnitList; @FieldDescribe("参与人群组名称,存储group,多值.") @PersistentCollection(fetch = FetchType.EAGER) @ContainerTable(name = TABLE + ContainerTableNameMiddle + reviewGroupList_FIELDNAME, joinIndex = @Index(name = TABLE + IndexNameMiddle + reviewGroupList_FIELDNAME + JoinIndexNameSuffix)) @OrderColumn(name = ORDERCOLUMNCOLUMN) @ElementColumn(length = length_255B, name = ColumnNamePrefix + reviewGroupList_FIELDNAME) @ElementIndex(name = TABLE + IndexNameMiddle + reviewGroupList_FIELDNAME + ElementIndexNameSuffix) @CheckPersist(allowEmpty = true) private List<String> reviewGroupList; @IdReference(Script.class) @FieldDescribe("参与人脚本.") @Column(length = length_255B, name = ColumnNamePrefix + reviewScript_FIELDNAME) @CheckPersist(allowEmpty = true) private String reviewScript; @FieldDescribe("参与人脚本文本.") @Lob @Basic(fetch = FetchType.EAGER) @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + reviewScriptText_FIELDNAME) @CheckPersist(allowEmpty = true) private String reviewScriptText; @FieldDescribe("参阅角色定义内容.") @Lob @Basic(fetch = FetchType.EAGER) @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + reviewDuty_FIELDNAME) @CheckPersist(allowEmpty = true) private String reviewDuty; @FieldDescribe("参阅人员data数据路径.") @PersistentCollection(fetch = FetchType.EAGER) @ContainerTable(name = TABLE + ContainerTableNameMiddle + reviewDataPathList_FIELDNAME, joinIndex = @Index(name = TABLE + IndexNameMiddle + reviewDataPathList_FIELDNAME + JoinIndexNameSuffix)) @OrderColumn(name = ORDERCOLUMNCOLUMN) @ElementColumn(length = JpaObject.length_255B, name = ColumnNamePrefix + reviewDataPathList_FIELDNAME) @ElementIndex(name = TABLE + IndexNameMiddle + reviewDataPathList_FIELDNAME + ElementIndexNameSuffix) @CheckPersist(allowEmpty = true) private List<String> reviewDataPathList; @IdReference(Script.class) @FieldDescribe("活动到达前事件脚本.") @Column(length = length_255B, name = ColumnNamePrefix + beforeArriveScript_FIELDNAME) @CheckPersist(allowEmpty = true) private String beforeArriveScript; @FieldDescribe("活动到达前事件脚本文本.") @Lob @Basic(fetch = FetchType.EAGER) @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + beforeArriveScriptText_FIELDNAME) @CheckPersist(allowEmpty = true) private String beforeArriveScriptText; @IdReference(Script.class) @FieldDescribe("活动到达后事件脚本.") @Column(length = length_255B, name = ColumnNamePrefix + afterArriveScript_FIELDNAME) @CheckPersist(allowEmpty = true) private String afterArriveScript; @FieldDescribe("活动到达后事件脚本文本.") @Lob @Basic(fetch = FetchType.EAGER) @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + afterArriveScriptText_FIELDNAME) @CheckPersist(allowEmpty = true) private String afterArriveScriptText; @IdReference(Script.class) @FieldDescribe("活动执行前事件脚本.") @Column(length = length_255B, name = ColumnNamePrefix + beforeExecuteScript_FIELDNAME) @CheckPersist(allowEmpty = true) private String beforeExecuteScript; @FieldDescribe("活动执行前事件脚本文本.") @Lob @Basic(fetch = FetchType.EAGER) @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + beforeExecuteScriptText_FIELDNAME) @CheckPersist(allowEmpty = true) private String beforeExecuteScriptText; @IdReference(Script.class) @FieldDescribe("活动执行后事件脚本.") @Column(length = length_255B, name = ColumnNamePrefix + afterExecuteScript_FIELDNAME) @CheckPersist(allowEmpty = true) private String afterExecuteScript; @FieldDescribe("活动执行后事件脚本文本.") @Lob @Basic(fetch = FetchType.EAGER) @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + afterExecuteScriptText_FIELDNAME) @CheckPersist(allowEmpty = true) private String afterExecuteScriptText; @IdReference(Script.class) @FieldDescribe("路由查询前事件脚本.") @Column(length = length_255B, name = ColumnNamePrefix + beforeInquireScript_FIELDNAME) @CheckPersist(allowEmpty = true) private String beforeInquireScript; @FieldDescribe("路由查询前事件脚本文本.") @Lob @Basic(fetch = FetchType.EAGER) @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + beforeInquireScriptText_FIELDNAME) @CheckPersist(allowEmpty = true) private String beforeInquireScriptText; @IdReference(Script.class) @FieldDescribe("路由查询后事件脚本.") @Column(length = length_255B, name = ColumnNamePrefix + afterInquireScript_FIELDNAME) @CheckPersist(allowEmpty = true) private String afterInquireScript; @FieldDescribe("路由查询后事件脚本文本.") @Lob @Basic(fetch = FetchType.EAGER) @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + afterInquireScriptText_FIELDNAME) @CheckPersist(allowEmpty = true) private String afterInquireScriptText; @FieldDescribe("允许调度") @CheckPersist(allowEmpty = true) @Column(name = ColumnNamePrefix + allowReroute_FIELDNAME) @Index(name = TABLE + IndexNameMiddle + allowReroute_FIELDNAME) private Boolean allowReroute; @FieldDescribe("允许调度到此节点") @CheckPersist(allowEmpty = true) @Column(name = ColumnNamePrefix + allowRerouteTo_FIELDNAME) @Index(name = TABLE + IndexNameMiddle + allowRerouteTo_FIELDNAME) private Boolean allowRerouteTo; @FieldDescribe("允许挂起") @CheckPersist(allowEmpty = true) @Column(name = ColumnNamePrefix + allowSuspend_FIELDNAME) private Boolean allowSuspend; public static final String allowRollback_FIELDNAME = "allowRollback"; @FieldDescribe("允许回滚") @CheckPersist(allowEmpty = true) @Column(name = ColumnNamePrefix + allowRollback_FIELDNAME) private Boolean allowRollback; @IdReference(Script.class) @FieldDescribe("生成displayLog脚本.") @Column(length = length_255B, name = ColumnNamePrefix + displayLogScript_FIELDNAME) @CheckPersist(allowEmpty = true) private String displayLogScript; @FieldDescribe("生成displayLog脚本文本.") @Lob @Basic(fetch = FetchType.EAGER) @Column(length = JpaObject.length_1M, name = ColumnNamePrefix + displayLogScriptText_FIELDNAME) @CheckPersist(allowEmpty = true) private String displayLogScriptText; public static final String edition_FIELDNAME = "edition"; @FieldDescribe("版本编码.") @Column(length = JpaObject.length_255B, name = ColumnNamePrefix + edition_FIELDNAME) private String edition; public String getDisplayLogScript() { return displayLogScript; } public void setDisplayLogScript(String displayLogScript) { this.displayLogScript = displayLogScript; } public String getDisplayLogScriptText() { return displayLogScriptText; } public void setDisplayLogScriptText(String displayLogScriptText) { this.displayLogScriptText = displayLogScriptText; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getProcess() { return process; } public void setProcess(String process) { this.process = process; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public String getExtension() { return extension; } public Boolean getAllowSuspend() { return allowSuspend; } public void setAllowSuspend(Boolean allowSuspend) { this.allowSuspend = allowSuspend; } public void setExtension(String extension) { this.extension = extension; } public String getBeforeArriveScript() { return beforeArriveScript; } public void setBeforeArriveScript(String beforeArriveScript) { this.beforeArriveScript = beforeArriveScript; } public String getAfterArriveScript() { return afterArriveScript; } public void setAfterArriveScript(String afterArriveScript) { this.afterArriveScript = afterArriveScript; } public String getBeforeExecuteScript() { return beforeExecuteScript; } public void setBeforeExecuteScript(String beforeExecuteScript) { this.beforeExecuteScript = beforeExecuteScript; } public String getAfterExecuteScript() { return afterExecuteScript; } public void setAfterExecuteScript(String afterExecuteScript) { this.afterExecuteScript = afterExecuteScript; } public String getForm() { return form; } public void setForm(String form) { this.form = form; } public List<String> getReviewIdentityList() { return reviewIdentityList; } public void setReviewIdentityList(List<String> reviewIdentityList) { this.reviewIdentityList = reviewIdentityList; } public List<String> getReviewUnitList() { return reviewUnitList; } public void setReviewUnitList(List<String> reviewUnitList) { this.reviewUnitList = reviewUnitList; } public String getReviewScript() { return reviewScript; } public void setReviewScript(String reviewScript) { this.reviewScript = reviewScript; } public String getReviewScriptText() { return reviewScriptText; } public void setReviewScriptText(String reviewScriptText) { this.reviewScriptText = reviewScriptText; } public String getBeforeArriveScriptText() { return beforeArriveScriptText; } public void setBeforeArriveScriptText(String beforeArriveScriptText) { this.beforeArriveScriptText = beforeArriveScriptText; } public String getAfterArriveScriptText() { return afterArriveScriptText; } public void setAfterArriveScriptText(String afterArriveScriptText) { this.afterArriveScriptText = afterArriveScriptText; } public String getBeforeExecuteScriptText() { return beforeExecuteScriptText; } public void setBeforeExecuteScriptText(String beforeExecuteScriptText) { this.beforeExecuteScriptText = beforeExecuteScriptText; } public String getAfterExecuteScriptText() { return afterExecuteScriptText; } public void setAfterExecuteScriptText(String afterExecuteScriptText) { this.afterExecuteScriptText = afterExecuteScriptText; } public List<String> getReadIdentityList() { return readIdentityList; } public void setReadIdentityList(List<String> readIdentityList) { this.readIdentityList = readIdentityList; } public List<String> getReadUnitList() { return readUnitList; } public void setReadUnitList(List<String> readUnitList) { this.readUnitList = readUnitList; } public String getReadScript() { return readScript; } public void setReadScript(String readScript) { this.readScript = readScript; } public String getReadScriptText() { return readScriptText; } public void setReadScriptText(String readScriptText) { this.readScriptText = readScriptText; } public Boolean getAllowReroute() { return allowReroute; } public void setAllowReroute(Boolean allowReroute) { this.allowReroute = allowReroute; } public Boolean getAllowRerouteTo() { return allowRerouteTo; } public void setAllowRerouteTo(Boolean allowRerouteTo) { this.allowRerouteTo = allowRerouteTo; } public String getReadDuty() { return readDuty; } public void setReadDuty(String readDuty) { this.readDuty = readDuty; } public List<String> getReadDataPathList() { return readDataPathList; } public void setReadDataPathList(List<String> readDataPathList) { this.readDataPathList = readDataPathList; } public String getReviewDuty() { return reviewDuty; } public void setReviewDuty(String reviewDuty) { this.reviewDuty = reviewDuty; } public List<String> getReviewDataPathList() { return reviewDataPathList; } public void setReviewDataPathList(List<String> reviewDataPathList) { this.reviewDataPathList = reviewDataPathList; } public List<String> getReadGroupList() { return readGroupList; } public void setReadGroupList(List<String> readGroupList) { this.readGroupList = readGroupList; } public List<String> getReviewGroupList() { return reviewGroupList; } public void setReviewGroupList(List<String> reviewGroupList) { this.reviewGroupList = reviewGroupList; } public String getBeforeInquireScript() { return beforeInquireScript; } public void setBeforeInquireScript(String beforeInquireScript) { this.beforeInquireScript = beforeInquireScript; } public String getBeforeInquireScriptText() { return beforeInquireScriptText; } public void setBeforeInquireScriptText(String beforeInquireScriptText) { this.beforeInquireScriptText = beforeInquireScriptText; } public String getAfterInquireScript() { return afterInquireScript; } public void setAfterInquireScript(String afterInquireScript) { this.afterInquireScript = afterInquireScript; } public String getAfterInquireScriptText() { return afterInquireScriptText; } public void setAfterInquireScriptText(String afterInquireScriptText) { this.afterInquireScriptText = afterInquireScriptText; } public Boolean getAllowRollback() { return allowRollback; } public void setAllowRollback(Boolean allowRollback) { this.allowRollback = allowRollback; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public String getOpinionGroup() { return opinionGroup; } public void setOpinionGroup(String opinionGroup) { this.opinionGroup = opinionGroup; } public String getEdition() { return edition; } public void setEdition(String edition) { this.edition = edition; } }
modify end
o2server/x_processplatform_core_entity/src/main/java/com/x/processplatform/core/entity/element/End.java
modify end
Java
lgpl-2.1
0944bf991059a7c9260aba2f9bdfe72865e4d193
0
pferraro/wildfly,xasx/wildfly,iweiss/wildfly,golovnin/wildfly,iweiss/wildfly,wildfly/wildfly,99sono/wildfly,99sono/wildfly,99sono/wildfly,jstourac/wildfly,jstourac/wildfly,wildfly/wildfly,tomazzupan/wildfly,xasx/wildfly,iweiss/wildfly,tadamski/wildfly,tadamski/wildfly,wildfly/wildfly,golovnin/wildfly,rhusar/wildfly,xasx/wildfly,jstourac/wildfly,pferraro/wildfly,pferraro/wildfly,rhusar/wildfly,rhusar/wildfly,pferraro/wildfly,tomazzupan/wildfly,wildfly/wildfly,tadamski/wildfly,jstourac/wildfly,iweiss/wildfly,tomazzupan/wildfly,golovnin/wildfly,rhusar/wildfly
/* * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.jboss.as.controller.operations.common; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import java.util.Locale; import org.jboss.as.controller.Cancellable; import org.jboss.as.controller.ModelAddOperationHandler; import org.jboss.as.controller.NewOperationContext; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.ResultHandler; import org.jboss.as.controller.descriptions.DescriptionProvider; import org.jboss.as.controller.descriptions.common.ExtensionDescription; import org.jboss.dmr.ModelNode; /** * Base handler for the extension resource add operation. * * @author Brian Stansberry (c) 2011 Red Hat Inc. */ // TODO consider making this concrete and folding in subclass logic public abstract class AbstractExtensionAddHandler implements ModelAddOperationHandler, DescriptionProvider { public static final String OPERATION_NAME = ADD; public static ModelNode getAddExtensionOperation(ModelNode address) { ModelNode op = new ModelNode(); op.get(OP).set(OPERATION_NAME); op.get(OP_ADDR).set(address); return op; } /** * Create the AbstractAddExtensionHandler */ protected AbstractExtensionAddHandler() { } /** * {@inheritDoc} */ @Override public Cancellable execute(NewOperationContext context, ModelNode operation, ResultHandler resultHandler) { try { ModelNode opAddr = operation.get(OP_ADDR); PathAddress address = PathAddress.pathAddress(opAddr); String module = address.getLastElement().getValue(); context.getSubModel().get(ExtensionDescription.MODULE).set(module); String failure = installExtension(module, context); if (failure == null) { ModelNode compensating = AbstractExtensionRemoveHandler.getRemoveExtensionOperation(opAddr); resultHandler.handleResultComplete(compensating); } else { resultHandler.handleFailed(new ModelNode().set(failure)); } } catch (Exception e) { resultHandler.handleFailed(new ModelNode().set(e.getLocalizedMessage())); } return Cancellable.NULL; } @Override public ModelNode getModelDescription(Locale locale) { return ExtensionDescription.getExtensionAddOperation(locale); } protected abstract String installExtension(String module, NewOperationContext context); }
controller/src/main/java/org/jboss/as/controller/operations/common/AbstractExtensionAddHandler.java
/* * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.jboss.as.controller.operations.common; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import java.util.Locale; import org.jboss.as.controller.Cancellable; import org.jboss.as.controller.ModelAddOperationHandler; import org.jboss.as.controller.NewOperationContext; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.ResultHandler; import org.jboss.as.controller.descriptions.DescriptionProvider; import org.jboss.as.controller.descriptions.common.ExtensionDescription; import org.jboss.dmr.ModelNode; /** * Base handler for the extension resource add operation. * * @author Brian Stansberry (c) 2011 Red Hat Inc. */ // TODO consider making this concrete and folding in subclass logic public abstract class AbstractExtensionAddHandler implements ModelAddOperationHandler, DescriptionProvider { public static final String OPERATION_NAME = ADD; public static ModelNode getAddExtensionOperation(ModelNode address) { ModelNode op = new ModelNode(); op.get(OP).set(OPERATION_NAME); op.get(OP_ADDR).set(address); return op; } /** * Create the AbstractAddExtensionHandler */ protected AbstractExtensionAddHandler() { } /** * {@inheritDoc} */ @Override public Cancellable execute(NewOperationContext context, ModelNode operation, ResultHandler resultHandler) { try { PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR)); String module = address.getLastElement().getValue(); context.getSubModel().get(ExtensionDescription.MODULE).set(module); String failure = installExtension(module, context); if (failure == null) { ModelNode compensating = AbstractExtensionRemoveHandler.getRemoveExtensionOperation(operation.get(OP_ADDR)); resultHandler.handleResultComplete(compensating); } else { resultHandler.handleFailed(new ModelNode().set(failure)); } } catch (Exception e) { resultHandler.handleFailed(new ModelNode().set(e.getLocalizedMessage())); } return Cancellable.NULL; } @Override public ModelNode getModelDescription(Locale locale) { return ExtensionDescription.getExtensionAddOperation(locale); } protected abstract String installExtension(String module, NewOperationContext context); }
Reuse address
controller/src/main/java/org/jboss/as/controller/operations/common/AbstractExtensionAddHandler.java
Reuse address
Java
lgpl-2.1
88a418315aa7d26c870c674c6cbffc3da2301b85
0
99sono/wildfly,jstourac/wildfly,wildfly/wildfly,jstourac/wildfly,iweiss/wildfly,99sono/wildfly,rhusar/wildfly,iweiss/wildfly,wildfly/wildfly,tomazzupan/wildfly,tadamski/wildfly,rhusar/wildfly,tomazzupan/wildfly,wildfly/wildfly,jstourac/wildfly,tadamski/wildfly,99sono/wildfly,pferraro/wildfly,tomazzupan/wildfly,pferraro/wildfly,wildfly/wildfly,pferraro/wildfly,rhusar/wildfly,iweiss/wildfly,xasx/wildfly,pferraro/wildfly,xasx/wildfly,xasx/wildfly,jstourac/wildfly,iweiss/wildfly,golovnin/wildfly,rhusar/wildfly,tadamski/wildfly,golovnin/wildfly,golovnin/wildfly
/** * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.clustering.jgroups.subsystem; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE; import static org.junit.Assert.assertEquals; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.model.test.FailedOperationTransformationConfig; import org.jboss.as.model.test.ModelTestControllerVersion; import org.jboss.as.model.test.ModelTestUtils; import org.jboss.as.subsystem.test.AdditionalInitialization; import org.jboss.as.subsystem.test.KernelServices; import org.jboss.as.subsystem.test.KernelServicesBuilder; import org.jboss.byteman.contrib.bmunit.BMRule; import org.jboss.byteman.contrib.bmunit.BMUnitRunner; import org.jboss.dmr.ModelNode; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; /** * Test cases for transformers used in the JGroups subsystem. * * AS version / model version / schema version overview * 7.1.1 / 1.1.0 / 1_1 * 7.1.2 / 1.1.0 / 1_1 * 7.1.3 / 1.1.0 / 1_1 * 7.2.0 / 1.2.0 / 1_1 * 8.0.0 / 2.0.0 / 2_0 * * @author <a href="[email protected]">Tomaz Cerar</a> * @author Richard Achmatowicz (c) 2011 Red Hat Inc. * @author Radoslav Husar */ @RunWith(BMUnitRunner.class) public class TransformersTestCase extends OperationTestCaseBase { @Test public void testTransformerAS712() throws Exception { testTransformer_1_1_0( ModelTestControllerVersion.V7_1_2_FINAL, "org.jboss.as:jboss-as-clustering-jgroups:" + ModelTestControllerVersion.V7_1_2_FINAL.getMavenGavVersion() ); } @Test public void testTransformerAS713() throws Exception { testTransformer_1_1_0( ModelTestControllerVersion.V7_1_3_FINAL, "org.jboss.as:jboss-as-clustering-jgroups:" + ModelTestControllerVersion.V7_1_3_FINAL.getMavenGavVersion() ); } @Test public void testTransformerAS720() throws Exception { testTransformer_1_2_0( ModelTestControllerVersion.V7_2_0_FINAL, "org.jboss.as:jboss-as-clustering-jgroups:" + ModelTestControllerVersion.V7_2_0_FINAL.getMavenGavVersion() ); } @Test public void testTransformerEAP600() throws Exception { testTransformer_1_1_0( ModelTestControllerVersion.EAP_6_0_0, "org.jboss.as:jboss-as-clustering-jgroups:" + ModelTestControllerVersion.EAP_6_0_0.getMavenGavVersion() ); } @Test public void testTransformerEAP601() throws Exception { testTransformer_1_1_0( ModelTestControllerVersion.EAP_6_0_1, "org.jboss.as:jboss-as-clustering-jgroups:" + ModelTestControllerVersion.EAP_6_0_1.getMavenGavVersion() ); } @Test public void testTransformerEAP610() throws Exception { testTransformer_1_2_0( ModelTestControllerVersion.EAP_6_1_0, "org.jboss.as:jboss-as-clustering-jgroups:" + ModelTestControllerVersion.EAP_6_1_0.getMavenGavVersion() ); } @Test public void testTransformerEAP611() throws Exception { testTransformer_1_2_0( ModelTestControllerVersion.EAP_6_1_1, "org.jboss.as:jboss-as-clustering-jgroups:" + ModelTestControllerVersion.EAP_6_1_1.getMavenGavVersion() ); } /** * Tests transformation of model from 2.0.0 version into 1.1.0 version. * * @throws Exception */ private void testTransformer_1_1_0(ModelTestControllerVersion controllerVersion, String ... mavenResourceURLs) throws Exception { ModelVersion version110 = ModelVersion.create(1,1,0); String subsystemXml = readResource("subsystem-jgroups-transform-2_0.xml"); // create builder for current subsystem version KernelServicesBuilder builder = createKernelServicesBuilder(AdditionalInitialization.MANAGEMENT) .setSubsystemXml(subsystemXml); // initialize the legacy services and add required jars builder.createLegacyKernelServicesBuilder(null, controllerVersion, version110) .addMavenResourceURL(mavenResourceURLs); KernelServices mainServices = builder.build(); Assert.assertTrue(mainServices.isSuccessfulBoot()); Assert.assertTrue(mainServices.getLegacyServices(version110).isSuccessfulBoot()); // check that both versions of the legacy model are the same and valid checkSubsystemModelTransformation(mainServices, version110); // 1.1.0 API specific checks: // - check description here } /** * Tests transformation of model from 2.0.0 version into 1.2.0 version. * * @throws Exception */ private void testTransformer_1_2_0(ModelTestControllerVersion controllerVersion, String ... mavenResourceURLs) throws Exception { ModelVersion version120 = ModelVersion.create(1,2,0); String subsystemXml = readResource("subsystem-jgroups-transform-2_0.xml"); // create builder for current subsystem version KernelServicesBuilder builder = createKernelServicesBuilder(AdditionalInitialization.MANAGEMENT) .setSubsystemXml(subsystemXml); // initialize the legacy services and add required jars builder.createLegacyKernelServicesBuilder(null, controllerVersion, version120) .addMavenResourceURL(mavenResourceURLs); KernelServices mainServices = builder.build(); Assert.assertTrue(mainServices.isSuccessfulBoot()); Assert.assertTrue(mainServices.getLegacyServices(version120).isSuccessfulBoot()); // check that both versions of the legacy model are the same and valid checkSubsystemModelTransformation(mainServices, version120); // 1.2.0 API specific checks: // - check description here } /** * Tests resolution of property expressions during performRuntime() * * This test uses Byteman to inject code into AbstractAddStepHandler.performRuntime() to * resolve the value of an expression and check that expression resolution is working as expected. * * The test is currently broken due to an outstanding class loading problem with Byteman, but it is included * here for re-enabling when the issue is resolved. * * @throws Exception */ @Ignore @Test @BMRule(name="Test support for expression resolution", targetClass="^org.jboss.as.controller.AbstractAddStepHandler", targetMethod="performRuntime", targetLocation="AT ENTRY", binding="context:OperationContext = $1; operation:ModelNode = $2; model:ModelNode = $3", condition="operation.hasDefined(\"name\") AND operation.hasDefined(\"value\")", action="traceln(\"resolved value = \" + org.jboss.as.clustering.jgroups.subsystem.PropertyResourceDefinition.VALUE.resolveModelAttribute(context,model))") public void testProtocolStackPropertyResolve() throws Exception { // Parse and install the XML into the controller String subsystemXml = getSubsystemXml() ; KernelServices services = createKernelServicesBuilder(null).setSubsystemXmlResource(subsystemXml).build(); // set a property to have an expression and let Byteman intercept the performRuntime call // build an ADD command to add a transport property using expression value ModelNode operation = getTransportPropertyAddOperation("maximal", "bundler_type", "${the_bundler_type:new}"); // perform operation on the 1.1.1 model ModelNode mainResult = services.executeOperation(operation); assertEquals(mainResult.toJSONString(true), SUCCESS, mainResult.get(OUTCOME).asString()); } @Test public void testRejectionsAS712() throws Exception { testRejections_1_1_0( ModelTestControllerVersion.V7_1_2_FINAL, "org.jboss.as:jboss-as-clustering-jgroups:" + ModelTestControllerVersion.V7_1_2_FINAL.getMavenGavVersion() ); } @Test public void testRejectionsAS713() throws Exception { testRejections_1_1_0( ModelTestControllerVersion.V7_1_3_FINAL, "org.jboss.as:jboss-as-clustering-jgroups:" + ModelTestControllerVersion.V7_1_3_FINAL.getMavenGavVersion() ); } @Test public void testRejectionsAS720() throws Exception { testRejections_1_2_0( ModelTestControllerVersion.V7_2_0_FINAL, "org.jboss.as:jboss-as-clustering-jgroups:" + ModelTestControllerVersion.V7_2_0_FINAL.getMavenGavVersion() ); } @Test public void testRejectionsEAP600() throws Exception { testRejections_1_1_0( ModelTestControllerVersion.EAP_6_0_0, "org.jboss.as:jboss-as-clustering-jgroups:" + ModelTestControllerVersion.EAP_6_0_0.getMavenGavVersion() ); } @Test public void testRejectionsEAP601() throws Exception { testRejections_1_1_0( ModelTestControllerVersion.EAP_6_0_1, "org.jboss.as:jboss-as-clustering-jgroups:" + ModelTestControllerVersion.EAP_6_0_1.getMavenGavVersion() ); } @Test public void testRejectionsEAP610() throws Exception { testRejections_1_2_0( ModelTestControllerVersion.EAP_6_1_0, "org.jboss.as:jboss-as-clustering-jgroups:" + ModelTestControllerVersion.EAP_6_1_0.getMavenGavVersion() ); } @Test public void testRejectionsEAP611() throws Exception { testRejections_1_2_0( ModelTestControllerVersion.EAP_6_1_1, "org.jboss.as:jboss-as-clustering-jgroups:" + ModelTestControllerVersion.EAP_6_1_1.getMavenGavVersion() ); } /** * Tests rejection of resources / attributes / operations in 1.1.0 model. * * @throws Exception */ private void testRejections_1_1_0(ModelTestControllerVersion controllerVersion, String ... mavenResourceURLs) throws Exception { ModelVersion version_1_1_0 = ModelVersion.create(1, 1, 0); // create builder for current subsystem version KernelServicesBuilder builder = createKernelServicesBuilder(AdditionalInitialization.MANAGEMENT); // initialize the legacy services and add required jars builder.createLegacyKernelServicesBuilder(null, controllerVersion, version_1_1_0) .addMavenResourceURL(mavenResourceURLs) //TODO storing the model triggers the weirdness mentioned in SubsystemTestDelegate.LegacyKernelServiceInitializerImpl.install() //which is strange since it should be loading it all from the current jboss modules //Also this works in several other tests .dontPersistXml(); KernelServices mainServices = builder.build(); Assert.assertTrue(mainServices.isSuccessfulBoot()); KernelServices legacyServices = mainServices.getLegacyServices(version_1_1_0); Assert.assertNotNull(legacyServices); Assert.assertTrue(legacyServices.isSuccessfulBoot()); //Use the real xml with expressions for testing all the attributes PathAddress subsystemAddress = PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM, JGroupsExtension.SUBSYSTEM_NAME)); ModelTestUtils.checkFailedTransformedBootOperations( mainServices, version_1_1_0, builder.parseXmlResource("subsystem-jgroups-2_0.xml"), new FailedOperationTransformationConfig() // expect certain rejected expressions .addFailedAttribute( subsystemAddress.append(PathElement.pathElement("stack")) .append(PathElement.pathElement("transport", "TRANSPORT")), new FailedOperationTransformationConfig.RejectExpressionsConfig(ModelKeys.SHARED)) .addFailedAttribute( subsystemAddress.append(PathElement.pathElement("stack")) .append(PathElement.pathElement("transport", "TRANSPORT")) .append("property"), new FailedOperationTransformationConfig.RejectExpressionsConfig(VALUE)) .addFailedAttribute( subsystemAddress.append(PathElement.pathElement("stack")) .append(PathElement.pathElement("protocol")) .append("property"), new FailedOperationTransformationConfig.RejectExpressionsConfig(VALUE)) // expect rejection of relay and child .addFailedAttribute( subsystemAddress.append("stack").append("relay", "RELAY"), FailedOperationTransformationConfig.REJECTED_RESOURCE) .addFailedAttribute( subsystemAddress.append("stack").append("relay", "RELAY").append("remote-site"), FailedOperationTransformationConfig.REJECTED_RESOURCE) ); } /** * Tests rejection of resources / attributes / operations in 1.2.0 model. * * @throws Exception */ private void testRejections_1_2_0(ModelTestControllerVersion controllerVersion, String ... mavenResourceURLs) throws Exception { ModelVersion version_1_2_0 = ModelVersion.create(1, 2, 0); // create builder for current subsystem version KernelServicesBuilder builder = createKernelServicesBuilder(AdditionalInitialization.MANAGEMENT); // initialize the legacy services and add required jars builder.createLegacyKernelServicesBuilder(null, controllerVersion, version_1_2_0) .addMavenResourceURL(mavenResourceURLs) .dontPersistXml(); KernelServices mainServices = builder.build(); Assert.assertTrue(mainServices.isSuccessfulBoot()); KernelServices legacyServices = mainServices.getLegacyServices(version_1_2_0); Assert.assertNotNull(legacyServices); Assert.assertTrue(legacyServices.isSuccessfulBoot()); // Use the real xml with expressions for testing all the attributes PathAddress subsystemAddress = PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM, JGroupsExtension.SUBSYSTEM_NAME)); ModelTestUtils.checkFailedTransformedBootOperations( mainServices, version_1_2_0, builder.parseXmlResource("subsystem-jgroups-transform-2_0-reject.xml"), new FailedOperationTransformationConfig() // expect rejection of relay and child .addFailedAttribute( subsystemAddress.append("stack").append("relay", "RELAY"), FailedOperationTransformationConfig.REJECTED_RESOURCE) .addFailedAttribute( subsystemAddress.append("stack").append("relay", "RELAY").append("remote-site"), FailedOperationTransformationConfig.REJECTED_RESOURCE) ); } }
clustering/jgroups/src/test/java/org/jboss/as/clustering/jgroups/subsystem/TransformersTestCase.java
/** * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.clustering.jgroups.subsystem; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE; import static org.junit.Assert.assertEquals; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.model.test.FailedOperationTransformationConfig; import org.jboss.as.model.test.ModelTestControllerVersion; import org.jboss.as.model.test.ModelTestUtils; import org.jboss.as.subsystem.test.AdditionalInitialization; import org.jboss.as.subsystem.test.KernelServices; import org.jboss.as.subsystem.test.KernelServicesBuilder; import org.jboss.byteman.contrib.bmunit.BMRule; import org.jboss.byteman.contrib.bmunit.BMUnitRunner; import org.jboss.dmr.ModelNode; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; /** * Test cases for transformers used in the JGroups subsystem. * * AS version / model version / schema version overview * 7.1.1 / 1.1.0 / 1_1 * 7.1.2 / 1.1.0 / 1_1 * 7.1.3 / 1.1.0 / 1_1 * 7.2.0 / 1.2.0 / 1_1 * 8.0.0 / 2.0.0 / 2_0 * * @author <a href="[email protected]">Tomaz Cerar</a> * @author Richard Achmatowicz (c) 2011 Red Hat Inc. * @author Radoslav Husar */ @RunWith(BMUnitRunner.class) public class TransformersTestCase extends OperationTestCaseBase { @Test public void testTransformerAS712() throws Exception { testTransformer(ModelTestControllerVersion.V7_1_2_FINAL, ModelVersion.create(1, 1, 0)); } @Test public void testTransformerAS713() throws Exception { testTransformer(ModelTestControllerVersion.V7_1_3_FINAL, ModelVersion.create(1, 1, 0)); } @Test public void testTransformerAS720() throws Exception { testTransformer(ModelTestControllerVersion.V7_2_0_FINAL, ModelVersion.create(1, 2, 0)); } /** * Tests transformation of model from 2.0.0 version into 1.1.0 or 1.2.0 version. * * @throws Exception */ private void testTransformer(ModelTestControllerVersion controllerVersion, ModelVersion version) throws Exception { String subsystemXml = readResource("subsystem-jgroups-transform-2_0.xml"); KernelServicesBuilder builder = createKernelServicesBuilder(AdditionalInitialization.MANAGEMENT) .setSubsystemXml(subsystemXml); builder.createLegacyKernelServicesBuilder(null, controllerVersion, version) .addMavenResourceURL("org.jboss.as:jboss-as-clustering-jgroups:" + controllerVersion.getMavenGavVersion()); KernelServices mainServices = builder.build(); Assert.assertTrue(mainServices.isSuccessfulBoot()); Assert.assertTrue(mainServices.getLegacyServices(version).isSuccessfulBoot()); checkSubsystemModelTransformation(mainServices, version); } /** * Tests resolution of property expressions during performRuntime() * * This test uses Byteman to inject code into AbstractAddStepHandler.performRuntime() to * resolve the value of an expression and check that expression resolution is working as expected. * * The test is currently broken due to an outstanding class loading problem with Byteman, but it is included * here for re-enabling when the issue is resolved. * * @throws Exception */ @Ignore @Test @BMRule(name="Test support for expression resolution", targetClass="^org.jboss.as.controller.AbstractAddStepHandler", targetMethod="performRuntime", targetLocation="AT ENTRY", binding="context:OperationContext = $1; operation:ModelNode = $2; model:ModelNode = $3", condition="operation.hasDefined(\"name\") AND operation.hasDefined(\"value\")", action="traceln(\"resolved value = \" + org.jboss.as.clustering.jgroups.subsystem.PropertyResourceDefinition.VALUE.resolveModelAttribute(context,model))") public void testProtocolStackPropertyResolve() throws Exception { // Parse and install the XML into the controller String subsystemXml = getSubsystemXml() ; KernelServices services = createKernelServicesBuilder(null).setSubsystemXmlResource(subsystemXml).build(); // set a property to have an expression and let Byteman intercept the performRuntime call // build an ADD command to add a transport property using expression value ModelNode operation = getTransportPropertyAddOperation("maximal", "bundler_type", "${the_bundler_type:new}"); // perform operation on the 1.1.1 model ModelNode mainResult = services.executeOperation(operation); assertEquals(mainResult.toJSONString(true), SUCCESS, mainResult.get(OUTCOME).asString()); } @Test public void testRejectionsAS712() throws Exception { testRejections_1_1_0(ModelTestControllerVersion.V7_1_2_FINAL); } @Test public void testRejectionsAS713() throws Exception { testRejections_1_1_0(ModelTestControllerVersion.V7_1_3_FINAL); } @Test public void testRejectionsAS720() throws Exception { testRejections_1_2_0(ModelTestControllerVersion.V7_2_0_FINAL); } /** * Tests rejection of resources / attributes / operations in 1.1.0 model. * * @throws Exception */ private void testRejections_1_1_0(ModelTestControllerVersion controllerVersion) throws Exception { // create builder for current subsystem version KernelServicesBuilder builder = createKernelServicesBuilder(AdditionalInitialization.MANAGEMENT); // create builder for legacy subsystem version ModelVersion version_1_1_0 = ModelVersion.create(1, 1, 0); builder.createLegacyKernelServicesBuilder(null, controllerVersion, version_1_1_0) .addMavenResourceURL("org.jboss.as:jboss-as-clustering-jgroups:" + controllerVersion.getMavenGavVersion()) //TODO storing the model triggers the weirdness mentioned in SubsystemTestDelegate.LegacyKernelServiceInitializerImpl.install() //which is strange since it should be loading it all from the current jboss modules //Also this works in several other tests .dontPersistXml(); KernelServices mainServices = builder.build(); Assert.assertTrue(mainServices.isSuccessfulBoot()); KernelServices legacyServices = mainServices.getLegacyServices(version_1_1_0); Assert.assertNotNull(legacyServices); Assert.assertTrue(legacyServices.isSuccessfulBoot()); //Use the real xml with expressions for testing all the attributes PathAddress subsystemAddress = PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM, JGroupsExtension.SUBSYSTEM_NAME)); ModelTestUtils.checkFailedTransformedBootOperations( mainServices, version_1_1_0, builder.parseXmlResource("subsystem-jgroups-2_0.xml"), new FailedOperationTransformationConfig() // expect certain rejected expressions .addFailedAttribute( subsystemAddress.append(PathElement.pathElement("stack")) .append(PathElement.pathElement("transport", "TRANSPORT")), new FailedOperationTransformationConfig.RejectExpressionsConfig(ModelKeys.SHARED)) .addFailedAttribute( subsystemAddress.append(PathElement.pathElement("stack")) .append(PathElement.pathElement("transport", "TRANSPORT")) .append("property"), new FailedOperationTransformationConfig.RejectExpressionsConfig(VALUE)) .addFailedAttribute( subsystemAddress.append(PathElement.pathElement("stack")) .append(PathElement.pathElement("protocol")) .append("property"), new FailedOperationTransformationConfig.RejectExpressionsConfig(VALUE)) // expect rejection of relay and child .addFailedAttribute( subsystemAddress.append("stack").append("relay", "RELAY"), FailedOperationTransformationConfig.REJECTED_RESOURCE) .addFailedAttribute( subsystemAddress.append("stack").append("relay", "RELAY").append("remote-site"), FailedOperationTransformationConfig.REJECTED_RESOURCE) ); } /** * Tests rejection of resources / attributes / operations in 1.2.0 model. * * @throws Exception */ private void testRejections_1_2_0(ModelTestControllerVersion controllerVersion) throws Exception { KernelServicesBuilder builder = createKernelServicesBuilder(AdditionalInitialization.MANAGEMENT); ModelVersion version_1_2_0 = ModelVersion.create(1, 2, 0); builder.createLegacyKernelServicesBuilder(null, controllerVersion, version_1_2_0) .addMavenResourceURL("org.jboss.as:jboss-as-clustering-jgroups:" + controllerVersion.getMavenGavVersion()) .dontPersistXml(); KernelServices mainServices = builder.build(); Assert.assertTrue(mainServices.isSuccessfulBoot()); KernelServices legacyServices = mainServices.getLegacyServices(version_1_2_0); Assert.assertNotNull(legacyServices); Assert.assertTrue(legacyServices.isSuccessfulBoot()); // Use the real xml with expressions for testing all the attributes PathAddress subsystemAddress = PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM, JGroupsExtension.SUBSYSTEM_NAME)); ModelTestUtils.checkFailedTransformedBootOperations( mainServices, version_1_2_0, builder.parseXmlResource("subsystem-jgroups-transform-2_0-reject.xml"), new FailedOperationTransformationConfig() // expect rejection of relay and child .addFailedAttribute( subsystemAddress.append("stack").append("relay", "RELAY"), FailedOperationTransformationConfig.REJECTED_RESOURCE) .addFailedAttribute( subsystemAddress.append("stack").append("relay", "RELAY").append("remote-site"), FailedOperationTransformationConfig.REJECTED_RESOURCE) ); } }
[WFLY-2505] Update EAP transformer tests for JGroups.
clustering/jgroups/src/test/java/org/jboss/as/clustering/jgroups/subsystem/TransformersTestCase.java
[WFLY-2505] Update EAP transformer tests for JGroups.
Java
lgpl-2.1
203e7fac95010cbc0acd82f9fbf0d73d9d381b31
0
kenweezy/teiid,kenweezy/teiid,kenweezy/teiid
/* * JBoss, Home of Professional Open Source. * See the COPYRIGHT.txt file distributed with this work for information * regarding copyright ownership. Some portions may be licensed * to Red Hat, Inc. under one or more contributor license agreements. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. */ package org.teiid.translator.jdbc.teradata; import static org.teiid.translator.TypeFacility.RUNTIME_NAMES.*; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.teiid.language.*; import org.teiid.translator.ExecutionContext; import org.teiid.translator.SourceSystemFunctions; import org.teiid.translator.Translator; import org.teiid.translator.TranslatorException; import org.teiid.translator.TypeFacility; import org.teiid.translator.jdbc.AliasModifier; import org.teiid.translator.jdbc.ConvertModifier; import org.teiid.translator.jdbc.FunctionModifier; import org.teiid.translator.jdbc.JDBCExecutionFactory; import org.teiid.translator.jdbc.SQLConversionVisitor; /** * Teradata database Release 12 */ @Translator(name="teradata", description="A translator for Teradata Database") public class TeradataExecutionFactory extends JDBCExecutionFactory { public static String TERADATA = "teradata"; //$NON-NLS-1$ protected ConvertModifier convert = new ConvertModifier(); public TeradataExecutionFactory() { } @Override public void start() throws TranslatorException { super.start(); convert.addTypeMapping("byteint", FunctionModifier.BYTE, FunctionModifier.SHORT, FunctionModifier.BOOLEAN); //$NON-NLS-1$ convert.addTypeMapping("double precision", FunctionModifier.DOUBLE); //$NON-NLS-1$ convert.addTypeMapping("numeric(18,0)", FunctionModifier.BIGINTEGER); //$NON-NLS-1$ convert.addTypeMapping("char(1)", FunctionModifier.CHAR); //$NON-NLS-1$ convert.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.TIME, new CastModifier("TIME")); //$NON-NLS-1$ convert.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.DATE, new CastModifier("DATE")); //$NON-NLS-1$ convert.addConvert(FunctionModifier.TIME, FunctionModifier.TIMESTAMP, new CastModifier("TIMESTAMP")); //$NON-NLS-1$ convert.addConvert(FunctionModifier.DATE, FunctionModifier.TIMESTAMP, new CastModifier("TIMESTAMP")); //$NON-NLS-1$ convert.addConvert(FunctionModifier.STRING, FunctionModifier.INTEGER, new CastModifier("integer")); //$NON-NLS-1$ convert.addConvert(FunctionModifier.STRING, FunctionModifier.BIGDECIMAL, new CastModifier("decimal(37,5)"));//$NON-NLS-1$ convert.addConvert(FunctionModifier.STRING, FunctionModifier.BIGINTEGER, new CastModifier("numeric(18,0)"));//$NON-NLS-1$ convert.addConvert(FunctionModifier.STRING, FunctionModifier.FLOAT, new CastModifier("float"));//$NON-NLS-1$ convert.addConvert(FunctionModifier.STRING, FunctionModifier.BOOLEAN, new CastModifier("byteint"));//$NON-NLS-1$ convert.addConvert(FunctionModifier.STRING, FunctionModifier.LONG, new CastModifier("numeric(18,0)"));//$NON-NLS-1$ convert.addConvert(FunctionModifier.STRING, FunctionModifier.SHORT, new CastModifier("smallint"));//$NON-NLS-1$ convert.addConvert(FunctionModifier.STRING, FunctionModifier.DOUBLE, new CastModifier("double precision"));//$NON-NLS-1$ convert.addConvert(FunctionModifier.STRING, FunctionModifier.BYTE, new CastModifier("byteint")); //$NON-NLS-1$ convert.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.STRING, new FunctionModifier() { @Override public List<?> translate(Function function) { return Arrays.asList("cast(cast(", function.getParameters().get(0), " AS FORMAT 'Y4-MM-DDBHH:MI:SSDS(6)') AS VARCHAR(26))"); //$NON-NLS-1$ //$NON-NLS-2$ } }); convert.addConvert(FunctionModifier.TIME, FunctionModifier.STRING, new FunctionModifier() { @Override public List<?> translate(Function function) { return Arrays.asList("cast(cast(", function.getParameters().get(0), " AS FORMAT 'HH:MI:SS') AS VARCHAR(9))"); //$NON-NLS-1$ //$NON-NLS-2$ } }); convert.addConvert(FunctionModifier.DATE, FunctionModifier.STRING, new FunctionModifier() { @Override public List<?> translate(Function function) { return Arrays.asList("cast(cast(", function.getParameters().get(0), " AS FORMAT 'YYYY-MM-DD') AS VARCHAR(11))"); //$NON-NLS-1$ //$NON-NLS-2$ } }); convert.addTypeMapping("varchar(4000)", FunctionModifier.STRING); //$NON-NLS-1$ convert.addNumericBooleanConversions(); registerFunctionModifier(SourceSystemFunctions.CONVERT, convert); registerFunctionModifier(SourceSystemFunctions.SUBSTRING, new AliasModifier("substr")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.LOG, new AliasModifier("LN")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.LCASE, new AliasModifier("LOWER")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.UCASE, new AliasModifier("UPPER")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.LENGTH, new AliasModifier("character_length")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.CURDATE, new AliasModifier("CURRENT_DATE")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.CURTIME, new AliasModifier("CURRENT_TIME")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.YEAR, new ExtractModifier("YEAR")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.MONTH, new ExtractModifier("MONTH")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.DAYOFMONTH, new ExtractModifier("DAY")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.HOUR, new ExtractModifier("HOUR")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.MINUTE, new ExtractModifier("MINUTE")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.SECOND, new ExtractModifier("SECOND")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.LOCATE, new LocateModifier(this.convert)); registerFunctionModifier(SourceSystemFunctions.LEFT, new LeftOrRightFunctionModifier(getLanguageFactory(), this.convert)); registerFunctionModifier(SourceSystemFunctions.RIGHT, new LeftOrRightFunctionModifier(getLanguageFactory(), this.convert)); registerFunctionModifier(SourceSystemFunctions.COT, new FunctionModifier() { @Override public List<?> translate(Function function) { function.setName(SourceSystemFunctions.TAN); return Arrays.asList(getLanguageFactory().createFunction(SourceSystemFunctions.DIVIDE_OP, new Expression[] {new Literal(1, TypeFacility.RUNTIME_TYPES.INTEGER), function}, TypeFacility.RUNTIME_TYPES.DOUBLE)); } }); registerFunctionModifier(SourceSystemFunctions.LTRIM, new FunctionModifier() { @Override public List<?> translate(Function function) { ArrayList<Object> target = new ArrayList<Object>(); target.add("TRIM(LEADING FROM ");//$NON-NLS-1$ target.add(function.getParameters().get(0)); target.add(")"); //$NON-NLS-1$ return target; } }); registerFunctionModifier(SourceSystemFunctions.RTRIM, new FunctionModifier() { @Override public List<?> translate(Function function) { ArrayList<Object> target = new ArrayList<Object>(); target.add("TRIM(TRAILING FROM ");//$NON-NLS-1$ target.add(function.getParameters().get(0)); target.add(")"); //$NON-NLS-1$ return target; } }); registerFunctionModifier(SourceSystemFunctions.MOD, new FunctionModifier() { @Override public List<?> translate(Function function) { return Arrays.asList(function.getParameters().get(0), " MOD ", function.getParameters().get(1)); //$NON-NLS-1$ } }); addPushDownFunction(TERADATA, "COSH", FLOAT, FLOAT); //$NON-NLS-1$ addPushDownFunction(TERADATA, "TANH", FLOAT, FLOAT); //$NON-NLS-1$ addPushDownFunction(TERADATA, "ACOSH", FLOAT, FLOAT); //$NON-NLS-1$ addPushDownFunction(TERADATA, "ASINH", FLOAT, FLOAT); //$NON-NLS-1$ addPushDownFunction(TERADATA, "ATANH", FLOAT, FLOAT); //$NON-NLS-1$ addPushDownFunction(TERADATA, "CHAR2HEXINT", STRING, STRING); //$NON-NLS-1$ addPushDownFunction(TERADATA, "INDEX", INTEGER, STRING, STRING); //$NON-NLS-1$ addPushDownFunction(TERADATA, "BYTES", INTEGER, STRING); //$NON-NLS-1$ addPushDownFunction(TERADATA, "OCTET_LENGTH", INTEGER, STRING); //$NON-NLS-1$ addPushDownFunction(TERADATA, "HASHAMP", INTEGER, STRING); //$NON-NLS-1$ addPushDownFunction(TERADATA, "HASHBAKAMP", INTEGER, STRING); //$NON-NLS-1$ addPushDownFunction(TERADATA, "HASHBUCKET", INTEGER, STRING); //$NON-NLS-1$ addPushDownFunction(TERADATA, "HASHROW", INTEGER, STRING); //$NON-NLS-1$ addPushDownFunction(TERADATA, "NULLIFZERO", BIG_DECIMAL, BIG_DECIMAL); //$NON-NLS-1$ addPushDownFunction(TERADATA, "ZEROIFNULL", BIG_DECIMAL, BIG_DECIMAL); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.COT, new FunctionModifier() { @Override public List<?> translate(Function function) { function.setName(SourceSystemFunctions.TAN); return Arrays.asList(getLanguageFactory().createFunction(SourceSystemFunctions.DIVIDE_OP, new Expression[] {new Literal(1, TypeFacility.RUNTIME_TYPES.INTEGER), function}, TypeFacility.RUNTIME_TYPES.DOUBLE)); } }); registerFunctionModifier(SourceSystemFunctions.LTRIM, new FunctionModifier() { @Override public List<?> translate(Function function) { return Arrays.asList("TRIM(LEADING FROM ", function.getParameters().get(0), ")"); //$NON-NLS-1$ //$NON-NLS-2$ } }); registerFunctionModifier(SourceSystemFunctions.RTRIM, new FunctionModifier() { @Override public List<?> translate(Function function) { return Arrays.asList("TRIM(TRAILING FROM ", function.getParameters().get(0), ")"); //$NON-NLS-1$ //$NON-NLS-2$ } }); registerFunctionModifier(SourceSystemFunctions.MOD, new FunctionModifier() { @Override public List<?> translate(Function function) { return Arrays.asList(function.getParameters().get(0), " MOD ", function.getParameters().get(1)); //$NON-NLS-1$ } }); } @Override public SQLConversionVisitor getSQLConversionVisitor() { return new TeradataSQLConversionVisitor(this); } @Override public List<String> getSupportedFunctions() { List<String> supportedFunctions = new ArrayList<String>(); supportedFunctions.addAll(super.getSupportedFunctions()); supportedFunctions.add(SourceSystemFunctions.ABS); supportedFunctions.add(SourceSystemFunctions.ACOS); supportedFunctions.add(SourceSystemFunctions.ASIN); supportedFunctions.add(SourceSystemFunctions.ATAN); supportedFunctions.add(SourceSystemFunctions.ATAN2); supportedFunctions.add(SourceSystemFunctions.COALESCE); supportedFunctions.add(SourceSystemFunctions.COS); supportedFunctions.add(SourceSystemFunctions.COT); supportedFunctions.add(SourceSystemFunctions.CONVERT); supportedFunctions.add(SourceSystemFunctions.CURDATE); supportedFunctions.add(SourceSystemFunctions.CURTIME); supportedFunctions.add(SourceSystemFunctions.DAYOFMONTH); supportedFunctions.add(SourceSystemFunctions.EXP); supportedFunctions.add(SourceSystemFunctions.HOUR); supportedFunctions.add(SourceSystemFunctions.LEFT); supportedFunctions.add(SourceSystemFunctions.LOCATE); supportedFunctions.add(SourceSystemFunctions.LOG); supportedFunctions.add(SourceSystemFunctions.LCASE); supportedFunctions.add(SourceSystemFunctions.LTRIM); supportedFunctions.add(SourceSystemFunctions.LENGTH); supportedFunctions.add(SourceSystemFunctions.MINUTE); supportedFunctions.add(SourceSystemFunctions.MOD); supportedFunctions.add(SourceSystemFunctions.MONTH); supportedFunctions.add(SourceSystemFunctions.NULLIF); supportedFunctions.add(SourceSystemFunctions.RIGHT); supportedFunctions.add(SourceSystemFunctions.RTRIM); supportedFunctions.add(SourceSystemFunctions.SECOND); supportedFunctions.add(SourceSystemFunctions.SIN); supportedFunctions.add(SourceSystemFunctions.SQRT); supportedFunctions.add(SourceSystemFunctions.SUBSTRING); supportedFunctions.add(SourceSystemFunctions.TAN); supportedFunctions.add(SourceSystemFunctions.TRIM); supportedFunctions.add(SourceSystemFunctions.UCASE); supportedFunctions.add(SourceSystemFunctions.YEAR); return supportedFunctions; } @Override public String translateLiteralDate(Date dateValue) { return "cast('" + formatDateValue(dateValue) + "' AS DATE FORMAT 'yyyy-mm-dd')"; //$NON-NLS-1$//$NON-NLS-2$ } @Override public String translateLiteralTime(Time timeValue) { return "cast('" + formatDateValue(timeValue) + "' AS TIME(0) FORMAT 'hh:mi:ss')"; //$NON-NLS-1$//$NON-NLS-2$ } @Override public String translateLiteralTimestamp(Timestamp timestampValue) { return "cast('" + formatDateValue(timestampValue) + "' AS TIMESTAMP(6))"; //$NON-NLS-1$//$NON-NLS-2$ } // Teradata also supports MINUS & ALL set operators // more aggregates available @Override public boolean supportsScalarSubqueries() { return false; } @Override public boolean supportsUnions() { return true; } @Override public boolean supportsIntersect() { return true; } @Override public boolean supportsExcept() { return true; } @Override public boolean supportsInlineViews() { return true; } @Override public boolean supportsAggregatesEnhancedNumeric() { return true; } @Override public boolean supportsCommonTableExpressions() { return false; } @Override public NullOrder getDefaultNullOrder() { return NullOrder.FIRST; } @Override public List<?> translateCommand(Command command, ExecutionContext context) { if (command instanceof QueryExpression) { QueryExpression qe = (QueryExpression)command; //teradata prefers positional ordering if (qe.getOrderBy() != null) { Select select = qe.getProjectedQuery(); List<DerivedColumn> derivedColumns = select.getDerivedColumns(); Map<String, Integer> positions = new HashMap<String, Integer>(); int i = 1; for (DerivedColumn derivedColumn : derivedColumns) { String name = derivedColumn.getAlias(); if (name == null && derivedColumn.getExpression() instanceof ColumnReference) { ColumnReference cr = (ColumnReference)derivedColumn.getExpression(); name = cr.toString(); } positions.put(name, i++); } for (SortSpecification ss : qe.getOrderBy().getSortSpecifications()) { Expression ex = ss.getExpression(); if (!(ex instanceof ColumnReference)) { continue; } ColumnReference cr = (ColumnReference)ex; Integer position = positions.get(cr.toString()); if (position != null) { ss.setExpression(new Literal(position, TypeFacility.RUNTIME_TYPES.INTEGER)); } } } } return super.translateCommand(command, context); } public static class LocateModifier extends FunctionModifier { ConvertModifier convertModifier; public LocateModifier(ConvertModifier convertModifier) { this.convertModifier = convertModifier; } @Override public List<?> translate(Function function) { ArrayList<Object> target = new ArrayList<Object>(); Expression expr1 = function.getParameters().get(0); Expression expr2 = function.getParameters().get(1); if (function.getParameters().size() > 2) { Expression expr3 = function.getParameters().get(2); target.add("position("); //$NON-NLS-1$ target.add(expr1); target.add( " in "); //$NON-NLS-1$ target.add("substr("); //$NON-NLS-1$ target.add(expr2); target.add(","); //$NON-NLS-1$ target.add(expr3); target.add("))"); //$NON-NLS-1$ } else { target.add("position("); //$NON-NLS-1$ target.add(expr1); target.add( " in "); //$NON-NLS-1$ target.add(expr2); target.add(")"); //$NON-NLS-1$ } return target; } } public static class ExtractModifier extends FunctionModifier { private String type; public ExtractModifier(String type) { this.type = type; } @Override public List<?> translate(Function function) { return Arrays.asList("extract(",this.type," from ",function.getParameters().get(0) ,")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } public static class CastModifier extends FunctionModifier { private String target; public CastModifier(String target) { this.target = target; } @Override public List<?> translate(Function function) { return Arrays.asList("cast(", function.getParameters().get(0), " AS "+this.target+")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } public static class LeftOrRightFunctionModifier extends FunctionModifier { private LanguageFactory langFactory; ConvertModifier convertModifier; public LeftOrRightFunctionModifier(LanguageFactory langFactory, ConvertModifier converModifier) { this.langFactory = langFactory; this.convertModifier = converModifier; } @Override public List<?> translate(Function function) { List<Expression> args = function.getParameters(); ArrayList<Object> target = new ArrayList<Object>(); if (function.getName().equalsIgnoreCase("left")) { //$NON-NLS-1$ //substr(string, 1, length) target.add("substr("); //$NON-NLS-1$ target.add(args.get(0)); target.add(","); //$NON-NLS-1$ target.add(langFactory.createLiteral(Integer.valueOf(1), TypeFacility.RUNTIME_TYPES.INTEGER)); target.add(","); //$NON-NLS-1$ target.add(args.get(1)); target.add(")"); //$NON-NLS-1$ } else if (function.getName().equalsIgnoreCase("right")) { //$NON-NLS-1$ //substr(case_size, character_length(case_size) -4) target.add("substr("); //$NON-NLS-1$ target.add(args.get(0)); target.add(",(character_length("); //$NON-NLS-1$ target.add(args.get(0)); target.add(")-"); //$NON-NLS-1$ target.add(args.get(1)); target.add("+1))"); //$NON-NLS-1$ // offset for 1 based index } return target; } } }
connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teradata/TeradataExecutionFactory.java
/* * JBoss, Home of Professional Open Source. * See the COPYRIGHT.txt file distributed with this work for information * regarding copyright ownership. Some portions may be licensed * to Red Hat, Inc. under one or more contributor license agreements. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. */ package org.teiid.translator.jdbc.teradata; import static org.teiid.translator.TypeFacility.RUNTIME_NAMES.*; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.teiid.language.*; import org.teiid.translator.ExecutionContext; import org.teiid.translator.SourceSystemFunctions; import org.teiid.translator.Translator; import org.teiid.translator.TranslatorException; import org.teiid.translator.TypeFacility; import org.teiid.translator.jdbc.AliasModifier; import org.teiid.translator.jdbc.ConvertModifier; import org.teiid.translator.jdbc.FunctionModifier; import org.teiid.translator.jdbc.JDBCExecutionFactory; import org.teiid.translator.jdbc.SQLConversionVisitor; /** * Teradata database Release 12 */ @Translator(name="teradata", description="A translator for Teradata Database") public class TeradataExecutionFactory extends JDBCExecutionFactory { public static String TERADATA = "teradata"; //$NON-NLS-1$ protected ConvertModifier convert = new ConvertModifier(); public TeradataExecutionFactory() { setSupportsOuterJoins(false); } @Override public void start() throws TranslatorException { super.start(); convert.addTypeMapping("byteint", FunctionModifier.BYTE, FunctionModifier.SHORT, FunctionModifier.BOOLEAN); //$NON-NLS-1$ convert.addTypeMapping("double precision", FunctionModifier.DOUBLE); //$NON-NLS-1$ convert.addTypeMapping("numeric(18,0)", FunctionModifier.BIGINTEGER); //$NON-NLS-1$ convert.addTypeMapping("char(1)", FunctionModifier.CHAR); //$NON-NLS-1$ convert.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.TIME, new CastModifier("TIME")); //$NON-NLS-1$ convert.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.DATE, new CastModifier("DATE")); //$NON-NLS-1$ convert.addConvert(FunctionModifier.TIME, FunctionModifier.TIMESTAMP, new CastModifier("TIMESTAMP")); //$NON-NLS-1$ convert.addConvert(FunctionModifier.DATE, FunctionModifier.TIMESTAMP, new CastModifier("TIMESTAMP")); //$NON-NLS-1$ convert.addConvert(FunctionModifier.STRING, FunctionModifier.INTEGER, new CastModifier("integer")); //$NON-NLS-1$ convert.addConvert(FunctionModifier.STRING, FunctionModifier.BIGDECIMAL, new CastModifier("decimal(37,5)"));//$NON-NLS-1$ convert.addConvert(FunctionModifier.STRING, FunctionModifier.BIGINTEGER, new CastModifier("numeric(18,0)"));//$NON-NLS-1$ convert.addConvert(FunctionModifier.STRING, FunctionModifier.FLOAT, new CastModifier("float"));//$NON-NLS-1$ convert.addConvert(FunctionModifier.STRING, FunctionModifier.BOOLEAN, new CastModifier("byteint"));//$NON-NLS-1$ convert.addConvert(FunctionModifier.STRING, FunctionModifier.LONG, new CastModifier("numeric(18,0)"));//$NON-NLS-1$ convert.addConvert(FunctionModifier.STRING, FunctionModifier.SHORT, new CastModifier("smallint"));//$NON-NLS-1$ convert.addConvert(FunctionModifier.STRING, FunctionModifier.DOUBLE, new CastModifier("double precision"));//$NON-NLS-1$ convert.addConvert(FunctionModifier.STRING, FunctionModifier.BYTE, new CastModifier("byteint")); //$NON-NLS-1$ convert.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.STRING, new FunctionModifier() { @Override public List<?> translate(Function function) { return Arrays.asList("cast(cast(", function.getParameters().get(0), " AS FORMAT 'Y4-MM-DDBHH:MI:SSDS(6)') AS VARCHAR(26))"); //$NON-NLS-1$ //$NON-NLS-2$ } }); convert.addConvert(FunctionModifier.TIME, FunctionModifier.STRING, new FunctionModifier() { @Override public List<?> translate(Function function) { return Arrays.asList("cast(cast(", function.getParameters().get(0), " AS FORMAT 'HH:MI:SS') AS VARCHAR(9))"); //$NON-NLS-1$ //$NON-NLS-2$ } }); convert.addConvert(FunctionModifier.DATE, FunctionModifier.STRING, new FunctionModifier() { @Override public List<?> translate(Function function) { return Arrays.asList("cast(cast(", function.getParameters().get(0), " AS FORMAT 'YYYY-MM-DD') AS VARCHAR(11))"); //$NON-NLS-1$ //$NON-NLS-2$ } }); convert.addTypeMapping("varchar(4000)", FunctionModifier.STRING); //$NON-NLS-1$ convert.addNumericBooleanConversions(); registerFunctionModifier(SourceSystemFunctions.CONVERT, convert); registerFunctionModifier(SourceSystemFunctions.SUBSTRING, new AliasModifier("substr")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.LOG, new AliasModifier("LN")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.LCASE, new AliasModifier("LOWER")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.UCASE, new AliasModifier("UPPER")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.LENGTH, new AliasModifier("character_length")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.CURDATE, new AliasModifier("CURRENT_DATE")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.CURTIME, new AliasModifier("CURRENT_TIME")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.YEAR, new ExtractModifier("YEAR")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.MONTH, new ExtractModifier("MONTH")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.DAYOFMONTH, new ExtractModifier("DAY")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.HOUR, new ExtractModifier("HOUR")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.MINUTE, new ExtractModifier("MINUTE")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.SECOND, new ExtractModifier("SECOND")); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.LOCATE, new LocateModifier(this.convert)); registerFunctionModifier(SourceSystemFunctions.LEFT, new LeftOrRightFunctionModifier(getLanguageFactory(), this.convert)); registerFunctionModifier(SourceSystemFunctions.RIGHT, new LeftOrRightFunctionModifier(getLanguageFactory(), this.convert)); registerFunctionModifier(SourceSystemFunctions.COT, new FunctionModifier() { @Override public List<?> translate(Function function) { function.setName(SourceSystemFunctions.TAN); return Arrays.asList(getLanguageFactory().createFunction(SourceSystemFunctions.DIVIDE_OP, new Expression[] {new Literal(1, TypeFacility.RUNTIME_TYPES.INTEGER), function}, TypeFacility.RUNTIME_TYPES.DOUBLE)); } }); registerFunctionModifier(SourceSystemFunctions.LTRIM, new FunctionModifier() { @Override public List<?> translate(Function function) { ArrayList<Object> target = new ArrayList<Object>(); target.add("TRIM(LEADING FROM ");//$NON-NLS-1$ target.add(function.getParameters().get(0)); target.add(")"); //$NON-NLS-1$ return target; } }); registerFunctionModifier(SourceSystemFunctions.RTRIM, new FunctionModifier() { @Override public List<?> translate(Function function) { ArrayList<Object> target = new ArrayList<Object>(); target.add("TRIM(TRAILING FROM ");//$NON-NLS-1$ target.add(function.getParameters().get(0)); target.add(")"); //$NON-NLS-1$ return target; } }); registerFunctionModifier(SourceSystemFunctions.MOD, new FunctionModifier() { @Override public List<?> translate(Function function) { return Arrays.asList(function.getParameters().get(0), " MOD ", function.getParameters().get(1)); //$NON-NLS-1$ } }); addPushDownFunction(TERADATA, "COSH", FLOAT, FLOAT); //$NON-NLS-1$ addPushDownFunction(TERADATA, "TANH", FLOAT, FLOAT); //$NON-NLS-1$ addPushDownFunction(TERADATA, "ACOSH", FLOAT, FLOAT); //$NON-NLS-1$ addPushDownFunction(TERADATA, "ASINH", FLOAT, FLOAT); //$NON-NLS-1$ addPushDownFunction(TERADATA, "ATANH", FLOAT, FLOAT); //$NON-NLS-1$ addPushDownFunction(TERADATA, "CHAR2HEXINT", STRING, STRING); //$NON-NLS-1$ addPushDownFunction(TERADATA, "INDEX", INTEGER, STRING, STRING); //$NON-NLS-1$ addPushDownFunction(TERADATA, "BYTES", INTEGER, STRING); //$NON-NLS-1$ addPushDownFunction(TERADATA, "OCTET_LENGTH", INTEGER, STRING); //$NON-NLS-1$ addPushDownFunction(TERADATA, "HASHAMP", INTEGER, STRING); //$NON-NLS-1$ addPushDownFunction(TERADATA, "HASHBAKAMP", INTEGER, STRING); //$NON-NLS-1$ addPushDownFunction(TERADATA, "HASHBUCKET", INTEGER, STRING); //$NON-NLS-1$ addPushDownFunction(TERADATA, "HASHROW", INTEGER, STRING); //$NON-NLS-1$ addPushDownFunction(TERADATA, "NULLIFZERO", BIG_DECIMAL, BIG_DECIMAL); //$NON-NLS-1$ addPushDownFunction(TERADATA, "ZEROIFNULL", BIG_DECIMAL, BIG_DECIMAL); //$NON-NLS-1$ registerFunctionModifier(SourceSystemFunctions.COT, new FunctionModifier() { @Override public List<?> translate(Function function) { function.setName(SourceSystemFunctions.TAN); return Arrays.asList(getLanguageFactory().createFunction(SourceSystemFunctions.DIVIDE_OP, new Expression[] {new Literal(1, TypeFacility.RUNTIME_TYPES.INTEGER), function}, TypeFacility.RUNTIME_TYPES.DOUBLE)); } }); registerFunctionModifier(SourceSystemFunctions.LTRIM, new FunctionModifier() { @Override public List<?> translate(Function function) { return Arrays.asList("TRIM(LEADING FROM ", function.getParameters().get(0), ")"); //$NON-NLS-1$ //$NON-NLS-2$ } }); registerFunctionModifier(SourceSystemFunctions.RTRIM, new FunctionModifier() { @Override public List<?> translate(Function function) { return Arrays.asList("TRIM(TRAILING FROM ", function.getParameters().get(0), ")"); //$NON-NLS-1$ //$NON-NLS-2$ } }); registerFunctionModifier(SourceSystemFunctions.MOD, new FunctionModifier() { @Override public List<?> translate(Function function) { return Arrays.asList(function.getParameters().get(0), " MOD ", function.getParameters().get(1)); //$NON-NLS-1$ } }); } @Override public SQLConversionVisitor getSQLConversionVisitor() { return new TeradataSQLConversionVisitor(this); } @Override public List<String> getSupportedFunctions() { List<String> supportedFunctions = new ArrayList<String>(); supportedFunctions.addAll(super.getSupportedFunctions()); supportedFunctions.add(SourceSystemFunctions.ABS); supportedFunctions.add(SourceSystemFunctions.ACOS); supportedFunctions.add(SourceSystemFunctions.ASIN); supportedFunctions.add(SourceSystemFunctions.ATAN); supportedFunctions.add(SourceSystemFunctions.ATAN2); supportedFunctions.add(SourceSystemFunctions.COALESCE); supportedFunctions.add(SourceSystemFunctions.COS); supportedFunctions.add(SourceSystemFunctions.COT); supportedFunctions.add(SourceSystemFunctions.CONVERT); supportedFunctions.add(SourceSystemFunctions.CURDATE); supportedFunctions.add(SourceSystemFunctions.CURTIME); supportedFunctions.add(SourceSystemFunctions.DAYOFMONTH); supportedFunctions.add(SourceSystemFunctions.EXP); supportedFunctions.add(SourceSystemFunctions.HOUR); supportedFunctions.add(SourceSystemFunctions.LEFT); supportedFunctions.add(SourceSystemFunctions.LOCATE); supportedFunctions.add(SourceSystemFunctions.LOG); supportedFunctions.add(SourceSystemFunctions.LCASE); supportedFunctions.add(SourceSystemFunctions.LTRIM); supportedFunctions.add(SourceSystemFunctions.LENGTH); supportedFunctions.add(SourceSystemFunctions.MINUTE); supportedFunctions.add(SourceSystemFunctions.MOD); supportedFunctions.add(SourceSystemFunctions.MONTH); supportedFunctions.add(SourceSystemFunctions.NULLIF); supportedFunctions.add(SourceSystemFunctions.RIGHT); supportedFunctions.add(SourceSystemFunctions.RTRIM); supportedFunctions.add(SourceSystemFunctions.SECOND); supportedFunctions.add(SourceSystemFunctions.SIN); supportedFunctions.add(SourceSystemFunctions.SQRT); supportedFunctions.add(SourceSystemFunctions.SUBSTRING); supportedFunctions.add(SourceSystemFunctions.TAN); supportedFunctions.add(SourceSystemFunctions.TRIM); supportedFunctions.add(SourceSystemFunctions.UCASE); supportedFunctions.add(SourceSystemFunctions.YEAR); return supportedFunctions; } @Override public String translateLiteralDate(Date dateValue) { return "cast('" + formatDateValue(dateValue) + "' AS DATE FORMAT 'yyyy-mm-dd')"; //$NON-NLS-1$//$NON-NLS-2$ } @Override public String translateLiteralTime(Time timeValue) { return "cast('" + formatDateValue(timeValue) + "' AS TIME(0) FORMAT 'hh:mi:ss')"; //$NON-NLS-1$//$NON-NLS-2$ } @Override public String translateLiteralTimestamp(Timestamp timestampValue) { return "cast('" + formatDateValue(timestampValue) + "' AS TIMESTAMP(6))"; //$NON-NLS-1$//$NON-NLS-2$ } // Teradata also supports MINUS & ALL set operators // more aggregates available @Override public boolean supportsScalarSubqueries() { return false; } @Override public boolean supportsUnions() { return true; } @Override public boolean supportsIntersect() { return true; } @Override public boolean supportsExcept() { return true; } @Override public boolean supportsInlineViews() { return true; } @Override public boolean supportsAggregatesEnhancedNumeric() { return true; } @Override public boolean supportsCommonTableExpressions() { return false; } @Override public NullOrder getDefaultNullOrder() { return NullOrder.FIRST; } @Override public List<?> translateCommand(Command command, ExecutionContext context) { if (command instanceof QueryExpression) { QueryExpression qe = (QueryExpression)command; //teradata prefers positional ordering if (qe.getOrderBy() != null) { Select select = qe.getProjectedQuery(); List<DerivedColumn> derivedColumns = select.getDerivedColumns(); Map<String, Integer> positions = new HashMap<String, Integer>(); int i = 1; for (DerivedColumn derivedColumn : derivedColumns) { String name = derivedColumn.getAlias(); if (name == null && derivedColumn.getExpression() instanceof ColumnReference) { ColumnReference cr = (ColumnReference)derivedColumn.getExpression(); name = cr.toString(); } positions.put(name, i++); } for (SortSpecification ss : qe.getOrderBy().getSortSpecifications()) { Expression ex = ss.getExpression(); if (!(ex instanceof ColumnReference)) { continue; } ColumnReference cr = (ColumnReference)ex; Integer position = positions.get(cr.toString()); if (position != null) { ss.setExpression(new Literal(position, TypeFacility.RUNTIME_TYPES.INTEGER)); } } } } return super.translateCommand(command, context); } public static class LocateModifier extends FunctionModifier { ConvertModifier convertModifier; public LocateModifier(ConvertModifier convertModifier) { this.convertModifier = convertModifier; } @Override public List<?> translate(Function function) { ArrayList<Object> target = new ArrayList<Object>(); Expression expr1 = function.getParameters().get(0); Expression expr2 = function.getParameters().get(1); if (function.getParameters().size() > 2) { Expression expr3 = function.getParameters().get(2); target.add("position("); //$NON-NLS-1$ target.add(expr1); target.add( " in "); //$NON-NLS-1$ target.add("substr("); //$NON-NLS-1$ target.add(expr2); target.add(","); //$NON-NLS-1$ target.add(expr3); target.add("))"); //$NON-NLS-1$ } else { target.add("position("); //$NON-NLS-1$ target.add(expr1); target.add( " in "); //$NON-NLS-1$ target.add(expr2); target.add(")"); //$NON-NLS-1$ } return target; } } public static class ExtractModifier extends FunctionModifier { private String type; public ExtractModifier(String type) { this.type = type; } @Override public List<?> translate(Function function) { return Arrays.asList("extract(",this.type," from ",function.getParameters().get(0) ,")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } public static class CastModifier extends FunctionModifier { private String target; public CastModifier(String target) { this.target = target; } @Override public List<?> translate(Function function) { return Arrays.asList("cast(", function.getParameters().get(0), " AS "+this.target+")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } public static class LeftOrRightFunctionModifier extends FunctionModifier { private LanguageFactory langFactory; ConvertModifier convertModifier; public LeftOrRightFunctionModifier(LanguageFactory langFactory, ConvertModifier converModifier) { this.langFactory = langFactory; this.convertModifier = converModifier; } @Override public List<?> translate(Function function) { List<Expression> args = function.getParameters(); ArrayList<Object> target = new ArrayList<Object>(); if (function.getName().equalsIgnoreCase("left")) { //$NON-NLS-1$ //substr(string, 1, length) target.add("substr("); //$NON-NLS-1$ target.add(args.get(0)); target.add(","); //$NON-NLS-1$ target.add(langFactory.createLiteral(Integer.valueOf(1), TypeFacility.RUNTIME_TYPES.INTEGER)); target.add(","); //$NON-NLS-1$ target.add(args.get(1)); target.add(")"); //$NON-NLS-1$ } else if (function.getName().equalsIgnoreCase("right")) { //$NON-NLS-1$ //substr(case_size, character_length(case_size) -4) target.add("substr("); //$NON-NLS-1$ target.add(args.get(0)); target.add(",(character_length("); //$NON-NLS-1$ target.add(args.get(0)); target.add(")-"); //$NON-NLS-1$ target.add(args.get(1)); target.add("+1))"); //$NON-NLS-1$ // offset for 1 based index } return target; } } }
TEIID-3196 removing teradata join restriction
connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teradata/TeradataExecutionFactory.java
TEIID-3196 removing teradata join restriction
Java
apache-2.0
cdaaea784305f5d46293e733cd4930476c36cd08
0
rouazana/james,rouazana/james,chibenwa/james,chibenwa/james,rouazana/james,aduprat/james,aduprat/james,rouazana/james,chibenwa/james,aduprat/james,aduprat/james,chibenwa/james
/**************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * ****************************************************************/ package org.apache.james.imapserver.netty; import java.net.InetSocketAddress; import java.util.concurrent.TimeUnit; import org.apache.james.imap.api.process.ImapSession; import org.apache.james.protocols.impl.ChannelAttributeSupport; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.handler.timeout.IdleState; import org.jboss.netty.handler.timeout.IdleStateHandler; import org.jboss.netty.util.Timer; /** * {@link IdleStateHandler} which will call {@link ImapSession#logout()} if the * connected client did not receive or send any traffic in a given timeframe * * */ public class ImapIdleStateHandler extends IdleStateHandler implements ChannelAttributeSupport { public ImapIdleStateHandler(Timer timer, long allIdleTime, TimeUnit unit) { super(timer, 0, 0, allIdleTime, unit); } @Override protected void channelIdle(ChannelHandlerContext ctx, IdleState state, long lastActivityTimeMillis) throws Exception { // check if the client did nothing for too long if (state.equals(IdleState.ALL_IDLE)) { ImapSession session = (ImapSession) attributes.get(ctx.getChannel()); InetSocketAddress address = (InetSocketAddress) ctx.getChannel().getRemoteAddress(); session.getLog().info("Logout client " + address.getHostName() + " (" + address.getAddress().getHostAddress() + ") because it idled for too long..."); // logout the client session.logout(); } } }
imapserver/src/main/java/org/apache/james/imapserver/netty/ImapIdleStateHandler.java
/**************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * ****************************************************************/ package org.apache.james.imapserver.netty; import java.net.InetSocketAddress; import java.util.concurrent.TimeUnit; import org.apache.james.imap.api.process.ImapSession; import org.apache.james.protocols.impl.ChannelAttributeSupport; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.handler.timeout.IdleState; import org.jboss.netty.handler.timeout.IdleStateHandler; import org.jboss.netty.util.Timer; /** * {@link IdleStateHandler} which will call {@link ImapSession#logout()} if the connected client did not receive or send any traffic in a given timeframe * * */ public class ImapIdleStateHandler extends IdleStateHandler implements ChannelAttributeSupport{ public ImapIdleStateHandler(Timer timer, long allIdleTime, TimeUnit unit) { super(timer, 0, 0, allIdleTime, unit); } @Override protected void channelIdle(ChannelHandlerContext ctx, IdleState state, long lastActivityTimeMillis) throws Exception { // check if the client did nothing for too long if (state.equals(IdleState.ALL_IDLE)) { ImapSession session = (ImapSession) attributes.get(ctx.getChannel()); InetSocketAddress address = (InetSocketAddress) ctx.getChannel().getRemoteAddress(); session.getLog().info("Logout client "+ address.getHostName() + " (" + address.getAddress().getHostAddress()+ ") because it idled for too long..."); // logout the client session.logout(); } } }
Replace tabs with spaces git-svn-id: de9d04cf23151003780adc3e4ddb7078e3680318@1088028 13f79535-47bb-0310-9956-ffa450edef68
imapserver/src/main/java/org/apache/james/imapserver/netty/ImapIdleStateHandler.java
Replace tabs with spaces
Java
apache-2.0
7922b427a9942ed40845ae4ef899781286444672
0
Erudika/para,Erudika/para
/* * Copyright 2013-2020 Erudika. https://erudika.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For issues and patches go to: https://github.com/erudika */ package com.erudika.para.security.filters; import com.erudika.para.Para; import com.erudika.para.core.App; import com.erudika.para.core.utils.ParaObjectUtils; import com.erudika.para.core.User; import com.erudika.para.security.AuthenticatedUserDetails; import com.erudika.para.security.SecurityUtils; import com.erudika.para.security.UserAuthentication; import com.erudika.para.utils.Config; import com.erudika.para.utils.Utils; import com.fasterxml.jackson.databind.ObjectReader; import java.io.IOException; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.NoConnectionReuseStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; /** * A filter that handles authentication requests to Microsoft. * @author Alex Bogdanovski [[email protected]] */ public class MicrosoftAuthFilter extends AbstractAuthenticationProcessingFilter { private final CloseableHttpClient httpclient; private final ObjectReader jreader; private static final String PROFILE_URL = "https://graph.microsoft.com/v1.0/me"; private static final String PHOTO_URL = "https://graph.microsoft.com/v1.0/me/photo/$value"; private static final String TOKEN_URL = "https://login.microsoftonline.com/{0}/oauth2/v2.0/token"; private static final String PAYLOAD = "code={0}&redirect_uri={1}" + "&scope=https%3A%2F%2Fgraph.microsoft.com%2Fuser.read&client_id={2}" + "&client_secret={3}&grant_type=authorization_code"; /** * The default filter mapping. */ public static final String MICROSOFT_ACTION = "microsoft_auth"; /** * Default constructor. * @param defaultFilterProcessesUrl the url of the filter */ public MicrosoftAuthFilter(final String defaultFilterProcessesUrl) { super(defaultFilterProcessesUrl); this.jreader = ParaObjectUtils.getJsonReader(Map.class); int timeout = 30 * 1000; this.httpclient = HttpClientBuilder.create(). setConnectionReuseStrategy(new NoConnectionReuseStrategy()). setDefaultRequestConfig(RequestConfig.custom(). setConnectTimeout(timeout). setConnectionRequestTimeout(timeout). setCookieSpec(CookieSpecs.STANDARD). setSocketTimeout(timeout). build()). build(); } /** * Handles an authentication request. * @param request HTTP request * @param response HTTP response * @return an authentication object that contains the principal object if successful. * @throws IOException ex */ @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException { final String requestURI = request.getRequestURI(); UserAuthentication userAuth = null; if (requestURI.endsWith(MICROSOFT_ACTION)) { String authCode = request.getParameter("code"); if (!StringUtils.isBlank(authCode)) { String appid = SecurityUtils.getAppidFromAuthRequest(request); String redirectURI = SecurityUtils.getRedirectUrl(request); App app = Para.getDAO().read(App.id(appid == null ? Config.getRootAppIdentifier() : appid)); String[] keys = SecurityUtils.getOAuthKeysForApp(app, Config.MICROSOFT_PREFIX); String entity = Utils.formatMessage(PAYLOAD, authCode, Utils.urlEncode(redirectURI), keys[0], keys[1]); HttpPost tokenPost = new HttpPost(Utils.formatMessage(TOKEN_URL, SecurityUtils.getSettingForApp(app, "ms_tenant_id", "common"))); tokenPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); tokenPost.setEntity(new StringEntity(entity, "UTF-8")); try (CloseableHttpResponse resp1 = httpclient.execute(tokenPost)) { if (resp1 != null && resp1.getEntity() != null) { Map<String, Object> token = jreader.readValue(resp1.getEntity().getContent()); if (token != null && token.containsKey("access_token")) { userAuth = getOrCreateUser(app, (String) token.get("access_token")); } else { logger.info("Authentication request failed with status '" + resp1.getStatusLine().getReasonPhrase() + "' - " + token); } EntityUtils.consumeQuietly(resp1.getEntity()); } else { logger.info("Authentication request failed with status '" + (resp1 != null ? resp1.getStatusLine().getReasonPhrase() : "null") + "' and empty response body."); } } } } return SecurityUtils.checkIfActive(userAuth, SecurityUtils.getAuthenticatedUser(userAuth), true); } /** * Calls the Microsoft Graph API to get the user profile using a given access token. * @param app the app where the user will be created, use null for root app * @param accessToken access token * @return {@link UserAuthentication} object or null if something went wrong * @throws IOException ex */ public UserAuthentication getOrCreateUser(App app, String accessToken) throws IOException { UserAuthentication userAuth = null; User user = new User(); if (accessToken != null) { HttpGet profileGet = new HttpGet(PROFILE_URL); profileGet.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken); profileGet.setHeader(HttpHeaders.ACCEPT, "application/json"); Map<String, Object> profile = null; try (CloseableHttpResponse resp2 = httpclient.execute(profileGet)) { HttpEntity respEntity = resp2.getEntity(); if (respEntity != null) { profile = jreader.readValue(respEntity.getContent()); EntityUtils.consumeQuietly(respEntity); } } if (profile != null && profile.containsKey("id")) { String microsoftId = (String) profile.get("id"); String email = getEmail(profile); String name = (String) profile.get("displayName"); user.setAppid(getAppid(app)); user.setIdentifier(Config.MICROSOFT_PREFIX + microsoftId); user.setEmail(email); user = User.readUserForIdentifier(user); if (user == null) { //user is new user = new User(); user.setActive(true); user.setAppid(getAppid(app)); user.setEmail(StringUtils.isBlank(email) ? Utils.getNewId() + "@windowslive.com" : email); user.setName(StringUtils.isBlank(name) ? "No Name" : name); user.setPassword(Utils.generateSecurityToken()); user.setPicture(getPicture(accessToken)); user.setIdentifier(Config.MICROSOFT_PREFIX + microsoftId); String id = user.create(); if (id == null) { throw new AuthenticationServiceException("Authentication failed: cannot create new user."); } } else { if (updateUserInfo(user, email, name, accessToken)) { user.update(); } } userAuth = new UserAuthentication(new AuthenticatedUserDetails(user)); } } return SecurityUtils.checkIfActive(userAuth, user, false); } private boolean updateUserInfo(User user, String email, String name, String accessToken) throws IOException { String picture = getPicture(accessToken); boolean update = false; if (!StringUtils.equals(user.getPicture(), picture)) { user.setPicture(picture); update = true; } if (!StringUtils.isBlank(email) && !StringUtils.equals(user.getEmail(), email)) { user.setEmail(email); update = true; } if (!StringUtils.isBlank(name) && !StringUtils.equals(user.getName(), name)) { user.setName(name); update = true; } return update; } private String getPicture(String accessToken) throws IOException { if (accessToken != null) { HttpGet profileGet = new HttpGet(PHOTO_URL); profileGet.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken); profileGet.setHeader(HttpHeaders.ACCEPT, "application/json"); try (CloseableHttpResponse resp = httpclient.execute(profileGet)) { HttpEntity respEntity = resp.getEntity(); if (respEntity != null && respEntity.getContentType().getValue().startsWith("image")) { byte[] bytes = IOUtils.toByteArray(respEntity.getContent()); if (bytes != null && bytes.length > 0) { byte[] bytes64 = Base64.encodeBase64(bytes); return "data:" + respEntity.getContentType().getValue() + ";base64," + new String(bytes64); } } EntityUtils.consumeQuietly(respEntity); } } return null; } private String getEmail(Map<String, Object> profile) { String email = (String) profile.get("userPrincipalName"); if (StringUtils.isBlank(email) || !StringUtils.contains(email, "@")) { email = (String) profile.get("mail"); } return email; } private String getAppid(App app) { return (app == null) ? null : app.getAppIdentifier(); } }
para-server/src/main/java/com/erudika/para/security/filters/MicrosoftAuthFilter.java
/* * Copyright 2013-2020 Erudika. https://erudika.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For issues and patches go to: https://github.com/erudika */ package com.erudika.para.security.filters; import com.erudika.para.Para; import com.erudika.para.core.App; import com.erudika.para.core.utils.ParaObjectUtils; import com.erudika.para.core.User; import com.erudika.para.security.AuthenticatedUserDetails; import com.erudika.para.security.SecurityUtils; import com.erudika.para.security.UserAuthentication; import com.erudika.para.utils.Config; import com.erudika.para.utils.Utils; import com.fasterxml.jackson.databind.ObjectReader; import java.io.IOException; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.NoConnectionReuseStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; /** * A filter that handles authentication requests to Microsoft. * @author Alex Bogdanovski [[email protected]] */ public class MicrosoftAuthFilter extends AbstractAuthenticationProcessingFilter { private final CloseableHttpClient httpclient; private final ObjectReader jreader; private static final String PROFILE_URL = "https://graph.microsoft.com/v1.0/me"; private static final String PHOTO_URL = "https://graph.microsoft.com/v1.0/me/photo/$value"; private static final String TOKEN_URL = "https://login.microsoftonline.com/{0}/oauth2/v2.0/token"; private static final String PAYLOAD = "code={0}&redirect_uri={1}" + "&scope=https%3A%2F%2Fgraph.microsoft.com%2Fuser.read&client_id={2}" + "&client_secret={3}&grant_type=authorization_code"; /** * The default filter mapping. */ public static final String MICROSOFT_ACTION = "microsoft_auth"; /** * Default constructor. * @param defaultFilterProcessesUrl the url of the filter */ public MicrosoftAuthFilter(final String defaultFilterProcessesUrl) { super(defaultFilterProcessesUrl); this.jreader = ParaObjectUtils.getJsonReader(Map.class); int timeout = 30 * 1000; this.httpclient = HttpClientBuilder.create(). setConnectionReuseStrategy(new NoConnectionReuseStrategy()). setDefaultRequestConfig(RequestConfig.custom(). setConnectTimeout(timeout). setConnectionRequestTimeout(timeout). setCookieSpec(CookieSpecs.STANDARD). setSocketTimeout(timeout). build()). build(); } /** * Handles an authentication request. * @param request HTTP request * @param response HTTP response * @return an authentication object that contains the principal object if successful. * @throws IOException ex */ @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException { final String requestURI = request.getRequestURI(); UserAuthentication userAuth = null; if (requestURI.endsWith(MICROSOFT_ACTION)) { String authCode = request.getParameter("code"); if (!StringUtils.isBlank(authCode)) { String appid = SecurityUtils.getAppidFromAuthRequest(request); String redirectURI = SecurityUtils.getRedirectUrl(request); App app = Para.getDAO().read(App.id(appid == null ? Config.getRootAppIdentifier() : appid)); String[] keys = SecurityUtils.getOAuthKeysForApp(app, Config.MICROSOFT_PREFIX); String entity = Utils.formatMessage(PAYLOAD, authCode, Utils.urlEncode(redirectURI), keys[0], keys[1]); HttpPost tokenPost = new HttpPost(Utils.formatMessage(TOKEN_URL, SecurityUtils.getSettingForApp(app, "ms_tenant_id", "common"))); tokenPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); tokenPost.setEntity(new StringEntity(entity, "UTF-8")); try (CloseableHttpResponse resp1 = httpclient.execute(tokenPost)) { if (resp1 != null && resp1.getEntity() != null) { Map<String, Object> token = jreader.readValue(resp1.getEntity().getContent()); if (token != null && token.containsKey("access_token")) { userAuth = getOrCreateUser(app, (String) token.get("access_token")); } else { logger.warn("Authentication request failed - " + token); } EntityUtils.consumeQuietly(resp1.getEntity()); } } } } return SecurityUtils.checkIfActive(userAuth, SecurityUtils.getAuthenticatedUser(userAuth), true); } /** * Calls the Microsoft Graph API to get the user profile using a given access token. * @param app the app where the user will be created, use null for root app * @param accessToken access token * @return {@link UserAuthentication} object or null if something went wrong * @throws IOException ex */ public UserAuthentication getOrCreateUser(App app, String accessToken) throws IOException { UserAuthentication userAuth = null; User user = new User(); if (accessToken != null) { HttpGet profileGet = new HttpGet(PROFILE_URL); profileGet.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken); profileGet.setHeader(HttpHeaders.ACCEPT, "application/json"); Map<String, Object> profile = null; try (CloseableHttpResponse resp2 = httpclient.execute(profileGet)) { HttpEntity respEntity = resp2.getEntity(); if (respEntity != null) { profile = jreader.readValue(respEntity.getContent()); EntityUtils.consumeQuietly(respEntity); } } if (profile != null && profile.containsKey("id")) { String microsoftId = (String) profile.get("id"); String email = getEmail(profile); String name = (String) profile.get("displayName"); user.setAppid(getAppid(app)); user.setIdentifier(Config.MICROSOFT_PREFIX + microsoftId); user.setEmail(email); user = User.readUserForIdentifier(user); if (user == null) { //user is new user = new User(); user.setActive(true); user.setAppid(getAppid(app)); user.setEmail(StringUtils.isBlank(email) ? Utils.getNewId() + "@windowslive.com" : email); user.setName(StringUtils.isBlank(name) ? "No Name" : name); user.setPassword(Utils.generateSecurityToken()); user.setPicture(getPicture(accessToken)); user.setIdentifier(Config.MICROSOFT_PREFIX + microsoftId); String id = user.create(); if (id == null) { throw new AuthenticationServiceException("Authentication failed: cannot create new user."); } } else { if (updateUserInfo(user, email, name, accessToken)) { user.update(); } } userAuth = new UserAuthentication(new AuthenticatedUserDetails(user)); } } return SecurityUtils.checkIfActive(userAuth, user, false); } private boolean updateUserInfo(User user, String email, String name, String accessToken) throws IOException { String picture = getPicture(accessToken); boolean update = false; if (!StringUtils.equals(user.getPicture(), picture)) { user.setPicture(picture); update = true; } if (!StringUtils.isBlank(email) && !StringUtils.equals(user.getEmail(), email)) { user.setEmail(email); update = true; } if (!StringUtils.isBlank(name) && !StringUtils.equals(user.getName(), name)) { user.setName(name); update = true; } return update; } private String getPicture(String accessToken) throws IOException { if (accessToken != null) { HttpGet profileGet = new HttpGet(PHOTO_URL); profileGet.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken); profileGet.setHeader(HttpHeaders.ACCEPT, "application/json"); try (CloseableHttpResponse resp = httpclient.execute(profileGet)) { HttpEntity respEntity = resp.getEntity(); if (respEntity != null && respEntity.getContentType().getValue().startsWith("image")) { byte[] bytes = IOUtils.toByteArray(respEntity.getContent()); if (bytes != null && bytes.length > 0) { byte[] bytes64 = Base64.encodeBase64(bytes); return "data:" + respEntity.getContentType().getValue() + ";base64," + new String(bytes64); } } EntityUtils.consumeQuietly(respEntity); } } return null; } private String getEmail(Map<String, Object> profile) { String email = (String) profile.get("userPrincipalName"); if (StringUtils.isBlank(email) || !StringUtils.contains(email, "@")) { email = (String) profile.get("mail"); } return email; } private String getAppid(App app) { return (app == null) ? null : app.getAppIdentifier(); } }
added some more log messages in MicrosoftAuthFilter
para-server/src/main/java/com/erudika/para/security/filters/MicrosoftAuthFilter.java
added some more log messages in MicrosoftAuthFilter
Java
apache-2.0
f37981efe13bcfdf350599fe9698da44900943ef
0
dsanchor/bushy-evergreen,dsanchor/bushy-evergreen
package com.redhat.virtualsummit.hackathon.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Logger; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.inject.Inject; import com.redhat.virtualsummit.hackathon.model.Service; import com.redhat.virtualsummit.hackathon.model.Team; import com.redhat.virtualsummit.hackathon.util.Constants; @LocalBean @Stateless public class BushyEvergreenService { @Inject Logger log; @Inject ProxyNotificationService proxy; @Inject SorterService sorterService; public Service manageReindeers(Service service) throws Exception { Service sortedOutput = null; Team[] sortedPayload = sorterService.sort(createPayload(service.getPayload())); if (sortedPayload != null) { // create sortedOuput sortedOutput = new Service(); sortedOutput.setServiceName(Constants.SERVICE_NAME); sortedOutput.setPayload(sortedPayload); if (proxy.notify(sortedOutput)) { log.info("Proxy has been notified"); } else { String msg = "Could not notify proxy: Unexpected error"; log.severe(msg); } } return sortedOutput; } // FIXME do it differently private Team[] createPayload(Team[] inputPayload) { List<Team> payload = new ArrayList<Team>(); // create ours Map<String, String> teamMembers = new HashMap<String, String>(); teamMembers.put(Constants.MEMBER_1_NAME, Constants.MEMBER_1_EMAIL); teamMembers.put(Constants.MEMBER_2_NAME, Constants.MEMBER_2_EMAIL); Map<String, String> envs = System.getenv(); for (Entry<String, String> envEntry : envs.entrySet()) { if (envEntry.getKey().startsWith(Constants.TEAM_A_REINDEER_PREFIX_ENV)) { Team team = new Team(); team.setReindeerName(envEntry.getValue()); team.setTeamName(Constants.TEAM_NAME); team.setNameEmailap(teamMembers); payload.add(team); } } if (inputPayload!=null) { for (Team team : inputPayload) { payload.add(team); } } return payload.toArray(new Team[payload.size()]); } }
reindeer-manager/src/main/java/com/redhat/virtualsummit/hackathon/service/BushyEvergreenService.java
package com.redhat.virtualsummit.hackathon.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Logger; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.inject.Inject; import com.redhat.virtualsummit.hackathon.model.Service; import com.redhat.virtualsummit.hackathon.model.Team; import com.redhat.virtualsummit.hackathon.util.Constants; @LocalBean @Stateless public class BushyEvergreenService { @Inject Logger log; @Inject ProxyNotificationService proxy; @Inject SorterService sorterService; public Service manageReindeers(Service service) throws Exception { Service sortedOutput = null; Team[] sortedPayload = sorterService.sort(createPayload(service.getPayload())); if (sortedPayload != null) { // create sortedOuput sortedOutput = new Service(); sortedOutput.setServiceName(Constants.SERVICE_NAME); sortedOutput.setPayload(sortedPayload); if (proxy.notify(sortedOutput)) { log.info("Proxy has been notified"); } else { String msg = "Could not notify proxy: Unexpected error"; log.severe(msg); } } return sortedOutput; } // FIXME do it differently private Team[] createPayload(Team[] inputPayload) { List<Team> payload = new ArrayList<Team>(); // create ours Map<String, String> teamMembers = new HashMap<String, String>(); teamMembers.put(Constants.MEMBER_1_NAME, Constants.MEMBER_1_EMAIL); teamMembers.put(Constants.MEMBER_2_NAME, Constants.MEMBER_2_EMAIL); Map<String, String> envs = System.getenv(); for (Entry<String, String> envEntry : envs.entrySet()) { if (envEntry.getKey().startsWith(Constants.TEAM_A_REINDEER_PREFIX_ENV)) { Team team = new Team(); team.setReindeerName(envEntry.getValue()); team.setTeamName(Constants.TEAM_NAME); team.setNameEmailap(teamMembers); payload.add(team); } } for (Team team : inputPayload) { payload.add(team); } return payload.toArray(new Team[payload.size()]); } }
Fixed possible null pointer
reindeer-manager/src/main/java/com/redhat/virtualsummit/hackathon/service/BushyEvergreenService.java
Fixed possible null pointer
Java
apache-2.0
94b1a334ec6b7a880464c28fe4240d4cea99d822
0
RBMHTechnology/vind,RBMHTechnology/vind
package com.rbmhtechnology.vind.elasticsearch.backend.util; import com.rbmhtechnology.vind.elasticsearch.backend.ElasticSearchServer; import com.rbmhtechnology.vind.model.ComplexFieldDescriptor; import com.rbmhtechnology.vind.model.FieldDescriptor; import com.rbmhtechnology.vind.model.value.LatLng; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; import java.time.ZonedDateTime; import java.util.Date; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.rbmhtechnology.vind.elasticsearch.backend.util.FieldUtil.Fieldname.UseCase; public class FieldUtil { private static final Logger log = LoggerFactory.getLogger(ElasticSearchServer.class); public static final String ID = "_id_"; public static final String TYPE = "_type_"; public static final String SCORE = "score"; public static final String DISTANCE = "_distance_"; public static final String FACETS = "facets"; public static final String TEXT = "text_"; public static final String FACET = "facet_"; private static final String _DYNAMIC = "dynamic_"; private static final String _COMPLEX = "complex_"; private static final String _STORED = ".stored"; private static final String _MULTI = "multi_"; private static final String _SINGLE = "single_"; private static final String _FACET = ".facet"; private static final String _SUGGEST = ".suggestion"; private static final String _FILTER = ".filter"; private static final String _SORT = ".sort"; public static final String INTERNAL_FIELD_PREFIX = String.format("%s(%s|%s|%s|%s|%s|%s|%s|%s)", _DYNAMIC, Fieldname.Type.BOOLEAN.getName(), Fieldname.Type.DATE.getName(), Fieldname.Type.INTEGER.getName(), Fieldname.Type.LONG.getName(), Fieldname.Type.NUMBER.getName(), Fieldname.Type.STRING.getName(), Fieldname.Type.BINARY.getName(), Fieldname.Type.LOCATION.getName()); public static final String INTERNAL_COMPLEX_FIELD_PREFIX = String.format("%s(%s|%s|%s|%s|%s|%s|%s|%s)?(%s|%s|%s|%s|%s)", _COMPLEX, Fieldname.Type.BOOLEAN.getName(), Fieldname.Type.DATE.getName(), Fieldname.Type.INTEGER.getName(), Fieldname.Type.LONG.getName(), Fieldname.Type.NUMBER.getName(), Fieldname.Type.STRING.getName(), Fieldname.Type.BINARY.getName(), Fieldname.Type.LOCATION.getName(), TEXT, FACET, "suggestion_", "sort_", "stored_" ); public static final String INTERNAL_FACET_FIELD_PREFIX = String.format("%s(%s)?%s(%s|%s|%s|%s|%s|%s|%s)", _DYNAMIC, _STORED, _FACET, Fieldname.Type.BOOLEAN.getName(), Fieldname.Type.DATE.getName(), Fieldname.Type.INTEGER.getName(), Fieldname.Type.LONG.getName(), Fieldname.Type.NUMBER.getName(), Fieldname.Type.STRING.getName(), Fieldname.Type.LOCATION.getName()); public static final String INTERNAL_SCOPE_FACET_FIELD_PREFIX = String.format("%s(%s|%s)(%s)?(%s|%s|%s)(%s|%s|%s|%s|%s|%s|%s)", _DYNAMIC, _MULTI,_SINGLE, _STORED, _FACET,_SUGGEST,_FILTER, Fieldname.Type.BOOLEAN.getName(), Fieldname.Type.DATE.getName(), Fieldname.Type.INTEGER.getName(), Fieldname.Type.LONG.getName(), Fieldname.Type.NUMBER.getName(), Fieldname.Type.STRING.getName(), Fieldname.Type.LOCATION.getName()); public static final String INTERNAL_SUGGEST_FIELD_PREFIX = String.format("%s(%s|%s)(%s)?%s(%s|%s|%s|%s|%s|%s|%s|%s)", _DYNAMIC, _MULTI,_SINGLE, _STORED, _SUGGEST, Fieldname.Type.BOOLEAN.getName(), Fieldname.Type.DATE.getName(), Fieldname.Type.INTEGER.getName(), Fieldname.Type.LONG.getName(), Fieldname.Type.NUMBER.getName(), Fieldname.Type.STRING.getName(), Fieldname.Type.LOCATION.getName(), Fieldname.Type.ANALYZED.getName()); public static final String INTERNAL_CONTEXT_PREFIX = "(%s_)?"; public static String getFieldName(FieldDescriptor<?> descriptor, String context) { return getFieldName(descriptor, null, context); } public static String getFieldName(FieldDescriptor descriptor, UseCase useCase, String context) { if (Objects.isNull(descriptor)) { log.warn("Trying to get name of null field descriptor."); return null; } final String contextPrefix; if (Objects.isNull(context) || !descriptor.isContextualized()) { contextPrefix = ""; } else { contextPrefix = context + "_"; } String fieldName = _DYNAMIC; Fieldname.Type type = Fieldname.Type.getFromClass(descriptor.getType()); final boolean isComplexField = ComplexFieldDescriptor.class.isAssignableFrom(descriptor.getClass()); if (Objects.isNull(useCase)) { return fieldName + type.getName() + contextPrefix + descriptor.getName(); } switch (useCase) { case Fulltext: { if (descriptor.isFullText()) { fieldName = fieldName + type.getName(); final String lang = "." + StringUtils.defaultIfBlank(descriptor.getLanguage().getLangCode(),"text"); if (isComplexField) { fieldName = _COMPLEX + TEXT; } return fieldName + contextPrefix + descriptor.getName() + lang; } else { log.debug("Descriptor {} is not configured for full text search.", descriptor.getName()); return null; } } case Facet: { if(descriptor.isFacet()) { if (isComplexField) { type = Fieldname.Type.getFromClass(((ComplexFieldDescriptor)descriptor).getFacetType()); return _COMPLEX + type.getName() + FACET + contextPrefix + descriptor.getName() + _FACET; } return fieldName + type.getName() + contextPrefix + descriptor.getName() + _FACET; } else { log.debug("Descriptor {} is not configured for facet search.", descriptor.getName()); return null; } } case Suggest: { if(descriptor.isSuggest()) { if (isComplexField) { return _COMPLEX + "suggestion_" + contextPrefix + descriptor.getName() + _SUGGEST; } else { type = Fieldname.Type.getFromClass(descriptor.getType()); return fieldName + type.getName() + contextPrefix + descriptor.getName() + _SUGGEST; } } else { log.debug("Descriptor {} is not configured for suggestion search.", descriptor.getName()); return null; } } case Stored: { //TODO if (descriptor.isStored()) { fieldName = fieldName + type.getName(); if (isComplexField) { type = Fieldname.Type.getFromClass(((ComplexFieldDescriptor) descriptor).getStoreType()); fieldName = _COMPLEX + type.getName() + "stored_" ; } } return fieldName + contextPrefix + descriptor.getName(); } case Sort: { fieldName = fieldName + type.getName(); if (isComplexField) { type = Fieldname.Type.getFromClass(((ComplexFieldDescriptor) descriptor).getStoreType()); fieldName = _COMPLEX + type.getName() + "sort_"; } if (descriptor.isSort() && Objects.nonNull(type)){ return fieldName + contextPrefix + descriptor.getName() + _SORT; } else if(isComplexField && descriptor.isStored() && !descriptor.isMultiValue() && Objects.nonNull(type)){ return fieldName + contextPrefix + descriptor.getName() + _SORT ; } else { log.debug("Descriptor {} is not configured for sorting.", descriptor.getName()); return null; //TODO: throw runtime exception? } } case Filter: { if(isComplexField && ((ComplexFieldDescriptor)descriptor).isAdvanceFilter() && Objects.nonNull(((ComplexFieldDescriptor)descriptor).getFacetType())) { type = Fieldname.Type.getFromClass(((ComplexFieldDescriptor)descriptor).getFacetType()); fieldName = _COMPLEX; return fieldName + type.getName() + "filter_" + contextPrefix + descriptor.getName() + _FILTER; } else { log.debug("Descriptor {} is not configured for advance filter search.", descriptor.getName()); return null; } } default: { log.warn("Unsupported use case {}.", useCase); return fieldName + type.getName() + contextPrefix + descriptor.getName(); } } } public static String getSourceFieldName(String elasticFieldName, String context) { final String contextPrefix = context != null ? context + "_" : ""; final String pattern = "(" + FieldUtil.INTERNAL_FIELD_PREFIX + ")|(" + FieldUtil.INTERNAL_COMPLEX_FIELD_PREFIX + ")"; final Matcher internalPrefixMatcher = Pattern.compile(pattern).matcher(elasticFieldName); final String contextualizedName = internalPrefixMatcher.replaceFirst(""); return contextualizedName.replace(contextPrefix, ""); } public static final class Fieldname { public enum UseCase { Facet, Fulltext, Stored, Suggest, Sort, Filter } private enum Type { DATE("date_"), STRING("string_"), INTEGER("int_"), LONG("long_"), NUMBER("float_"), LOCATION("location_"), BOOLEAN("boolean_"), BINARY("binary_"), ANALYZED("analyzed_"); private String name; Type(String name) { this.name = name; } public String getName() { return this.name; } public static Type getFromClass(Class clazz) { if (Objects.nonNull(clazz)) { if (Integer.class.isAssignableFrom(clazz)) { return INTEGER; } else if (Long.class.isAssignableFrom(clazz)) { return LONG; } else if (Number.class.isAssignableFrom(clazz)) { return NUMBER; } else if (Boolean.class.isAssignableFrom(clazz)) { return BOOLEAN; } else if (ZonedDateTime.class.isAssignableFrom(clazz)) { return DATE; } else if (Date.class.isAssignableFrom(clazz)) { return DATE; } else if (LatLng.class.isAssignableFrom(clazz)) { return LOCATION; } else if (ByteBuffer.class.isAssignableFrom(clazz)) { return BINARY; } else if (CharSequence.class.isAssignableFrom(clazz)) { return STRING; } else { return BINARY; } } else return null; } } } }
backend/elasticsearch/src/main/java/com/rbmhtechnology/vind/elasticsearch/backend/util/FieldUtil.java
package com.rbmhtechnology.vind.elasticsearch.backend.util; import com.rbmhtechnology.vind.elasticsearch.backend.ElasticSearchServer; import com.rbmhtechnology.vind.model.ComplexFieldDescriptor; import com.rbmhtechnology.vind.model.FieldDescriptor; import com.rbmhtechnology.vind.model.value.LatLng; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; import java.time.ZonedDateTime; import java.util.Date; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.rbmhtechnology.vind.elasticsearch.backend.util.FieldUtil.Fieldname.UseCase; public class FieldUtil { private static final Logger log = LoggerFactory.getLogger(ElasticSearchServer.class); public static final String ID = "_id_"; public static final String TYPE = "_type_"; public static final String SCORE = "score"; public static final String DISTANCE = "_distance_"; public static final String FACETS = "facets"; public static final String TEXT = "text_"; public static final String FACET = "facet_"; private static final String _DYNAMIC = "dynamic_"; private static final String _COMPLEX = "complex_"; private static final String _STORED = ".stored"; private static final String _MULTI = "multi_"; private static final String _SINGLE = "single_"; private static final String _FACET = ".facet"; private static final String _SUGGEST = ".suggestion"; private static final String _FILTER = ".filter"; private static final String _SORT = ".sort"; public static final String INTERNAL_FIELD_PREFIX = String.format("%s(%s|%s|%s|%s|%s|%s|%s|%s)", _DYNAMIC, Fieldname.Type.BOOLEAN.getName(), Fieldname.Type.DATE.getName(), Fieldname.Type.INTEGER.getName(), Fieldname.Type.LONG.getName(), Fieldname.Type.NUMBER.getName(), Fieldname.Type.STRING.getName(), Fieldname.Type.BINARY.getName(), Fieldname.Type.LOCATION.getName()); public static final String INTERNAL_COMPLEX_FIELD_PREFIX = String.format("%s(%s|%s|%s|%s|%s|%s|%s|%s)?(%s|%s|%s|%s|%s)", _COMPLEX, Fieldname.Type.BOOLEAN.getName(), Fieldname.Type.DATE.getName(), Fieldname.Type.INTEGER.getName(), Fieldname.Type.LONG.getName(), Fieldname.Type.NUMBER.getName(), Fieldname.Type.STRING.getName(), Fieldname.Type.BINARY.getName(), Fieldname.Type.LOCATION.getName(), TEXT, FACET, "suggestion_", "sort_", "stored_" ); public static final String INTERNAL_FACET_FIELD_PREFIX = String.format("%s(%s)?%s(%s|%s|%s|%s|%s|%s|%s)", _DYNAMIC, _STORED, _FACET, Fieldname.Type.BOOLEAN.getName(), Fieldname.Type.DATE.getName(), Fieldname.Type.INTEGER.getName(), Fieldname.Type.LONG.getName(), Fieldname.Type.NUMBER.getName(), Fieldname.Type.STRING.getName(), Fieldname.Type.LOCATION.getName()); public static final String INTERNAL_SCOPE_FACET_FIELD_PREFIX = String.format("%s(%s|%s)(%s)?(%s|%s|%s)(%s|%s|%s|%s|%s|%s|%s)", _DYNAMIC, _MULTI,_SINGLE, _STORED, _FACET,_SUGGEST,_FILTER, Fieldname.Type.BOOLEAN.getName(), Fieldname.Type.DATE.getName(), Fieldname.Type.INTEGER.getName(), Fieldname.Type.LONG.getName(), Fieldname.Type.NUMBER.getName(), Fieldname.Type.STRING.getName(), Fieldname.Type.LOCATION.getName()); public static final String INTERNAL_SUGGEST_FIELD_PREFIX = String.format("%s(%s|%s)(%s)?%s(%s|%s|%s|%s|%s|%s|%s|%s)", _DYNAMIC, _MULTI,_SINGLE, _STORED, _SUGGEST, Fieldname.Type.BOOLEAN.getName(), Fieldname.Type.DATE.getName(), Fieldname.Type.INTEGER.getName(), Fieldname.Type.LONG.getName(), Fieldname.Type.NUMBER.getName(), Fieldname.Type.STRING.getName(), Fieldname.Type.LOCATION.getName(), Fieldname.Type.ANALYZED.getName()); public static final String INTERNAL_CONTEXT_PREFIX = "(%s_)?"; public static String getFieldName(FieldDescriptor<?> descriptor, String context) { return getFieldName(descriptor, null, context); } public static String getFieldName(FieldDescriptor descriptor, UseCase useCase, String context) { if (Objects.isNull(descriptor)) { log.warn("Trying to get name of null field descriptor."); return null; } final String contextPrefix; if (Objects.isNull(context) || !descriptor.isContextualized()) { contextPrefix = ""; } else { contextPrefix = context + "_"; } String fieldName = _DYNAMIC; Fieldname.Type type = Fieldname.Type.getFromClass(descriptor.getType()); final boolean isComplexField = ComplexFieldDescriptor.class.isAssignableFrom(descriptor.getClass()); if (Objects.isNull(useCase)) { return fieldName + type.getName() + contextPrefix + descriptor.getName(); } switch (useCase) { case Fulltext: { if (descriptor.isFullText()) { fieldName = fieldName + type.getName(); final String lang = "." + StringUtils.defaultIfBlank(descriptor.getLanguage().getLangCode(),"text"); if (isComplexField) { fieldName = _COMPLEX + TEXT; } return fieldName + contextPrefix + descriptor.getName() + lang; } else { log.debug("Descriptor {} is not configured for full text search.", descriptor.getName()); return null; } } case Facet: { if(descriptor.isFacet()) { if (isComplexField) { type = Fieldname.Type.getFromClass(((ComplexFieldDescriptor)descriptor).getFacetType()); return _COMPLEX + type.getName() + FACET + contextPrefix + descriptor.getName() + _FACET; } return fieldName + type.getName() + contextPrefix + descriptor.getName() + _FACET; } else { log.debug("Descriptor {} is not configured for facet search.", descriptor.getName()); return null; } } case Suggest: { if(descriptor.isSuggest()) { if (isComplexField) { return _COMPLEX + "suggestion_" + contextPrefix + descriptor.getName() + _SUGGEST; } else { type = Fieldname.Type.getFromClass(descriptor.getType()); return fieldName + type.getName() + contextPrefix + descriptor.getName() + _SUGGEST; } } else { log.debug("Descriptor {} is not configured for suggestion search.", descriptor.getName()); return null; } } case Stored: { //TODO if (descriptor.isStored()) { fieldName = fieldName + type.getName(); if (isComplexField) { type = Fieldname.Type.getFromClass(((ComplexFieldDescriptor) descriptor).getStoreType()); fieldName = _COMPLEX + type.getName() + "stored_" ; } } return fieldName + contextPrefix + descriptor.getName(); } case Sort: { fieldName = fieldName + type.getName(); if (isComplexField) { type = Fieldname.Type.getFromClass(((ComplexFieldDescriptor) descriptor).getStoreType()); fieldName = _COMPLEX + type.getName() + "sort_"; } if (descriptor.isSort() && Objects.nonNull(type)){ return fieldName + contextPrefix + descriptor.getName() + _SORT; } else if(isComplexField && descriptor.isStored() && !descriptor.isMultiValue() && Objects.nonNull(type)){ return fieldName + contextPrefix + descriptor.getName() + _SORT ; } else { log.debug("Descriptor {} is not configured for sorting.", descriptor.getName()); return null; //TODO: throw runtime exception? } } case Filter: { if(isComplexField && ((ComplexFieldDescriptor)descriptor).isAdvanceFilter() && Objects.nonNull(((ComplexFieldDescriptor)descriptor).getFacetType())) { type = Fieldname.Type.getFromClass(((ComplexFieldDescriptor)descriptor).getFacetType()); return fieldName + type.getName() + "filter_" + contextPrefix + descriptor.getName() + _FILTER; } else { log.debug("Descriptor {} is not configured for advance filter search.", descriptor.getName()); return null; } } default: { log.warn("Unsupported use case {}.", useCase); return fieldName + type.getName() + contextPrefix + descriptor.getName(); } } } public static String getSourceFieldName(String elasticFieldName, String context) { final String contextPrefix = context != null ? context + "_" : ""; final String pattern = "(" + FieldUtil.INTERNAL_FIELD_PREFIX + ")|(" + FieldUtil.INTERNAL_COMPLEX_FIELD_PREFIX + ")"; final Matcher internalPrefixMatcher = Pattern.compile(pattern).matcher(elasticFieldName); final String contextualizedName = internalPrefixMatcher.replaceFirst(""); return contextualizedName.replace(contextPrefix, ""); } public static final class Fieldname { public enum UseCase { Facet, Fulltext, Stored, Suggest, Sort, Filter } private enum Type { DATE("date_"), STRING("string_"), INTEGER("int_"), LONG("long_"), NUMBER("float_"), LOCATION("location_"), BOOLEAN("boolean_"), BINARY("binary_"), ANALYZED("analyzed_"); private String name; Type(String name) { this.name = name; } public String getName() { return this.name; } public static Type getFromClass(Class clazz) { if (Objects.nonNull(clazz)) { if (Integer.class.isAssignableFrom(clazz)) { return INTEGER; } else if (Long.class.isAssignableFrom(clazz)) { return LONG; } else if (Number.class.isAssignableFrom(clazz)) { return NUMBER; } else if (Boolean.class.isAssignableFrom(clazz)) { return BOOLEAN; } else if (ZonedDateTime.class.isAssignableFrom(clazz)) { return DATE; } else if (Date.class.isAssignableFrom(clazz)) { return DATE; } else if (LatLng.class.isAssignableFrom(clazz)) { return LOCATION; } else if (ByteBuffer.class.isAssignableFrom(clazz)) { return BINARY; } else if (CharSequence.class.isAssignableFrom(clazz)) { return STRING; } else { return BINARY; } } else return null; } } } }
#142: Fixed issue on filter scoped field name generation
backend/elasticsearch/src/main/java/com/rbmhtechnology/vind/elasticsearch/backend/util/FieldUtil.java
#142: Fixed issue on filter scoped field name generation
Java
apache-2.0
023e4a28073910ef8355630f4859b34f005a709c
0
nakul02/systemml,asurve/incubator-systemml,asurve/arvind-sysml2,gweidner/systemml,asurve/systemml,asurve/systemml,apache/incubator-systemml,deroneriksson/systemml,dhutchis/systemml,akchinSTC/systemml,nakul02/incubator-systemml,asurve/arvind-sysml2,deroneriksson/incubator-systemml,akchinSTC/systemml,gweidner/systemml,asurve/incubator-systemml,apache/incubator-systemml,gweidner/incubator-systemml,gweidner/systemml,sandeep-n/incubator-systemml,deroneriksson/systemml,asurve/arvind-sysml2,deroneriksson/systemml,dusenberrymw/incubator-systemml,Myasuka/systemml,apache/incubator-systemml,iyounus/incubator-systemml,dusenberrymw/systemml,nakul02/incubator-systemml,Myasuka/systemml,niketanpansare/systemml,dhutchis/systemml,nakul02/incubator-systemml,dusenberrymw/incubator-systemml,dhutchis/systemml,asurve/systemml,iyounus/incubator-systemml,asurve/arvind-sysml2,niketanpansare/systemml,asurve/incubator-systemml,deroneriksson/incubator-systemml,dusenberrymw/incubator-systemml,dusenberrymw/systemml,niketanpansare/systemml,asurve/systemml,gweidner/systemml,deroneriksson/systemml,deroneriksson/systemml,akchinSTC/systemml,nakul02/incubator-systemml,asurve/systemml,asurve/incubator-systemml,deroneriksson/incubator-systemml,akchinSTC/systemml,niketanpansare/systemml,nakul02/systemml,dusenberrymw/incubator-systemml,niketanpansare/incubator-systemml,Myasuka/systemml,niketanpansare/incubator-systemml,Wenpei/incubator-systemml,apache/incubator-systemml,iyounus/incubator-systemml,dhutchis/systemml,akchinSTC/systemml,fschueler/incubator-systemml,Wenpei/incubator-systemml,Wenpei/incubator-systemml,nakul02/systemml,niketanpansare/systemml,iyounus/incubator-systemml,dusenberrymw/incubator-systemml,sandeep-n/incubator-systemml,iyounus/incubator-systemml,gweidner/systemml,gweidner/incubator-systemml,nakul02/systemml,niketanpansare/systemml,akchinSTC/systemml,nakul02/systemml,dusenberrymw/systemml,apache/incubator-systemml,asurve/arvind-sysml2,fschueler/incubator-systemml,gweidner/incubator-systemml,gweidner/incubator-systemml,nakul02/incubator-systemml,nakul02/systemml,fschueler/incubator-systemml,dhutchis/systemml,asurve/incubator-systemml,sandeep-n/incubator-systemml,Myasuka/systemml,dhutchis/systemml,dusenberrymw/systemml,fschueler/incubator-systemml,dusenberrymw/systemml,Wenpei/incubator-systemml,Myasuka/systemml,apache/incubator-systemml,deroneriksson/incubator-systemml,asurve/arvind-sysml2,gweidner/incubator-systemml,niketanpansare/incubator-systemml,dusenberrymw/incubator-systemml,niketanpansare/incubator-systemml,asurve/systemml,deroneriksson/systemml,asurve/incubator-systemml,deroneriksson/incubator-systemml,Myasuka/systemml,sandeep-n/incubator-systemml,gweidner/incubator-systemml,iyounus/incubator-systemml,deroneriksson/incubator-systemml,dusenberrymw/systemml,gweidner/systemml,nakul02/incubator-systemml
/**  * IBM Confidential  * OCO Source Materials  * (C) Copyright IBM Corp. 2010, 2015  * The source code for this program is not published or otherwise divested of its trade secrets, irrespective of what has been deposited with the U.S. Copyright Office.  */ package com.ibm.bi.dml.runtime.matrix.data; import java.util.ArrayList; import java.util.Arrays; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.ibm.bi.dml.lops.MapMultChain.ChainType; import com.ibm.bi.dml.runtime.DMLRuntimeException; import com.ibm.bi.dml.runtime.DMLUnsupportedOperationException; import com.ibm.bi.dml.runtime.functionobjects.SwapIndex; import com.ibm.bi.dml.runtime.matrix.operators.ReorgOperator; import com.ibm.bi.dml.runtime.util.UtilFunctions; /** * MB: * Library for matrix multiplications including MM, MV, VV for all * combinations of dense and sparse representations and special * operations such as transpose-self matrix multiplication. * * In general all implementations use internally dense outputs * for direct access, but change the final result to sparse if necessary. * * NOTES on BLAS: * * Experiments in 04/2013 showed that even on dense-dense this implementation * is 3x faster than f2j-BLAS-DGEMM, 2x faster than f2c-BLAS-DGEMM, and * level (+10% after JIT) with a native C implementation. * * Calling native BLAS would loose platform independence and would require * JNI calls incl data transfer. Furthermore, BLAS does not support sparse * matrices (except Sparse BLAS, with dedicated function calls and matrix formats) * and would be an external dependency. * * Experiments in 02/2014 showed that on dense-dense this implementation now achieves * almost 30% peak FP performance. Compared to Intel MKL 11.1 (dgemm, N=1000) it is * just 3.2x (sparsity=1.0) and 1.9x (sparsity=0.5) slower, respectively. * * */ public class LibMatrixMult { @SuppressWarnings("unused") private static final String _COPYRIGHT = "Licensed Materials - Property of IBM\n(C) Copyright IBM Corp. 2010, 2015\n" + "US Government Users Restricted Rights - Use, duplication disclosure restricted by GSA ADP Schedule Contract with IBM Corp."; public static final boolean LOW_LEVEL_OPTIMIZATION = true; private LibMatrixMult() { //prevent instantiation via private constructor } //////////////////////////////// // public matrix mult interface //////////////////////////////// /** * Performs a matrix multiplication and stores the result in the output matrix. * * All variants use a IKJ access pattern, and internally use dense output. After the * actual computation, we recompute nnz and check for sparse/dense representation. * * * @param m1 first matrix * @param m2 second matrix * @param ret result matrix * @throws DMLRuntimeException */ public static void matrixMult(MatrixBlock m1, MatrixBlock m2, MatrixBlock ret) throws DMLRuntimeException { //check inputs / outputs if( m1.isEmptyBlock(false) || m2.isEmptyBlock(false) ) return; //Timing time = new Timing(true); //pre-processing ret.sparse = (m1.isUltraSparse() || m2.isUltraSparse()); if( !ret.sparse ) ret.allocateDenseBlock(); //core matrix mult computation if( m1.isUltraSparse() || m2.isUltraSparse() ) matrixMultUltraSparse(m1, m2, ret, 0, m1.rlen); else if(!m1.sparse && !m2.sparse) matrixMultDenseDense(m1, m2, ret, 0, m1.rlen); else if(m1.sparse && m2.sparse) matrixMultSparseSparse(m1, m2, ret, 0, m1.rlen); else if(m1.sparse) matrixMultSparseDense(m1, m2, ret, 0, m1.rlen); else matrixMultDenseSparse(m1, m2, ret, 0, m1.rlen); //post-processing if( !ret.sparse ) ret.recomputeNonZeros(); ret.examSparsity(); //System.out.println("MM ("+m1.isInSparseFormat()+","+m1.getNumRows()+","+m1.getNumColumns()+","+m1.getNonZeros()+")x" + // "("+m2.isInSparseFormat()+","+m2.getNumRows()+","+m2.getNumColumns()+","+m2.getNonZeros()+") in "+time.stop()); } /** * Performs a multi-threaded matrix multiplication and stores the result in the output matrix. * The parameter k (k>=1) determines the max parallelism k' with k'=min(k, vcores, m1.rlen). * * @param m1 * @param m2 * @param ret * @param k * @throws DMLRuntimeException */ public static void matrixMult(MatrixBlock m1, MatrixBlock m2, MatrixBlock ret, int k) throws DMLRuntimeException { //check inputs / outputs if( m1.isEmptyBlock(false) || m2.isEmptyBlock(false) ) return; //check no parallelization benefit (fallback to sequential) if( m1.rlen == 1 ) { matrixMult(m1, m2, ret); return; } //Timing time = new Timing(true); //pre-processing ret.sparse = (m1.isUltraSparse() || m2.isUltraSparse()); if( !ret.sparse ) ret.allocateDenseBlock(); //core multi-threaded matrix mult computation //(currently: always parallelization over number of rows) try { ExecutorService pool = Executors.newFixedThreadPool( k ); ArrayList<MatrixMultTask> tasks = new ArrayList<MatrixMultTask>(); int blklen = (int)((double)m1.rlen/k); for( int i=0; i<k & i*blklen<m1.rlen; i++ ) tasks.add(new MatrixMultTask(m1, m2, ret, i*blklen, Math.min((i+1)*blklen, m1.rlen))); pool.invokeAll(tasks); pool.shutdown(); } catch(Exception ex) { throw new DMLRuntimeException(ex); } //post-processing if( !ret.sparse ) ret.recomputeNonZeros(); ret.examSparsity(); //System.out.println("MM ("+m1.isInSparseFormat()+","+m1.getNumRows()+","+m1.getNumColumns()+","+m1.getNonZeros()+")x" + // "("+m2.isInSparseFormat()+","+m2.getNumRows()+","+m2.getNumColumns()+","+m2.getNonZeros()+") in "+time.stop()); } /** * Performs a matrix multiplication chain operation of type t(X)%*%(X%*%v) or t(X)%*%(w*(X%*%v)). * * All variants use a IKJ access pattern, and internally use dense output. After the * actual computation, we recompute nnz and check for sparse/dense representation. * * @param m1 * @param m2 * @param w * @param ret * @param ct * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static void matrixMultChain(MatrixBlock mX, MatrixBlock mV, MatrixBlock mW, MatrixBlock ret, ChainType ct) throws DMLRuntimeException, DMLUnsupportedOperationException { //Timing time = new Timing(true); if( mX.sparse ) matrixMultChainSparse(mX, mV, mW, ret, ct); else matrixMultChainDense(mX, mV, mW, ret, ct); //System.out.println("MMChain "+ct.toString()+" ("+mX.isInSparseFormat()+","+mX.getNumRows()+","+mX.getNumColumns()+","+mX.getNonZeros()+")x" + // "("+mV.isInSparseFormat()+","+mV.getNumRows()+","+mV.getNumColumns()+","+mV.getNonZeros()+") in "+time.stop()); } /** * * @param m1 * @param ret * @param leftTranspose * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static void matrixMultTransposeSelf( MatrixBlock m1, MatrixBlock ret, boolean leftTranspose ) throws DMLUnsupportedOperationException, DMLRuntimeException { //Timing time = new Timing(true); if( m1.sparse ) matrixMultTransposeSelfSparse(m1, ret, leftTranspose); else matrixMultTransposeSelfDense(m1, ret, leftTranspose); //System.out.println("TSMM ("+m1.isInSparseFormat()+","+m1.getNumRows()+","+m1.getNumColumns()+","+m1.getNonZeros()+","+leftTranspose+") in "+time.stop()); } /** * * @param m1 * @param m2 * @param ret1 * @param ret2 * @throws DMLUnsupportedOperationException * @throws DMLRuntimeException */ public static void matrixMultPermute( MatrixBlock pm1, MatrixBlock m2, MatrixBlock ret1, MatrixBlock ret2 ) throws DMLUnsupportedOperationException, DMLRuntimeException { //Timing time = new Timing(true); if( m2.sparse ) matrixMultPermuteSparse(pm1, m2, ret1, ret2); else if( ret1.sparse ) matrixMultPermuteDenseSparse(pm1, m2, ret1, ret2); else matrixMultPermuteDense(pm1, m2, ret1, ret2); //System.out.println("PMM ("+m1.isInSparseFormat()+","+m1.getNumRows()+","+m1.getNumColumns()+","+m1.getNonZeros()+")x" + // "("+m2.isInSparseFormat()+","+m2.getNumRows()+","+m2.getNumColumns()+","+m2.getNonZeros()+") in "+time.stop()); } ////////////////////////////////////////// // optimized matrix mult implementation // ////////////////////////////////////////// /** * * @param m1 * @param m2 * @param ret * @throws DMLRuntimeException */ private static void matrixMultDenseDense(MatrixBlock m1, MatrixBlock m2, MatrixBlock ret, int rl, int ru) throws DMLRuntimeException { double[] a = m1.denseBlock; double[] b = m2.denseBlock; double[] c = ret.denseBlock; final int m = m1.rlen; final int n = m2.clen; final int cd = m1.clen; if( LOW_LEVEL_OPTIMIZATION ) { if( m==1 && n==1 ) //DOT PRODUCT { c[0] = dotProduct(a, b, cd); } else if( n>1 && cd == 1 ) //OUTER PRODUCT { for( int i=rl, cix=rl*n; i < ru; i++, cix+=n) { if( a[i] == 1 ) System.arraycopy(b, 0, c, cix, n); else if( a[i] != 0 ) vectMultiplyWrite(a[i], b, c, 0, cix, n); else Arrays.fill(c, cix, cix+n, 0); } } else if( n==1 && cd == 1 ) //VECTOR-SCALAR { vectMultiplyWrite(b[0], a, c, rl, rl, ru-rl); } else if( n==1 ) //MATRIX-VECTOR { for( int i=rl, aix=rl*cd; i < ru; i++, aix+=cd) c[ i ] = dotProduct(a, b, aix, 0, cd); } else //MATRIX-MATRIX { //1) Unrolled inner loop (for better instruction-level parallelism) //2) Blocked execution (for less cache trashing in parallel exec) //3) Asymmetric block sizes (for less misses in inner loop, yet blocks in L1/L2) final int blocksizeI = 32; //64//256KB c block (typical L2 size per core), 32KB a block final int blocksizeK = 24; //64//256KB b block (typical L2 size per core), used while read 512B of a / read/write 4KB of c final int blocksizeJ = 1024; //512//4KB (typical main-memory page size), for scan //temporary arrays (nnz a, b index) double[] ta = new double[ blocksizeK ]; int[] tbi = new int[ blocksizeK ]; //blocked execution for( int bi = rl; bi < ru; bi+=blocksizeI ) for( int bk = 0, bimin = Math.min(ru, bi+blocksizeI); bk < cd; bk+=blocksizeK ) for( int bj = 0, bkmin = Math.min(cd, bk+blocksizeK); bj < n; bj+=blocksizeJ ) { int bklen = bkmin-bk; int bjlen = Math.min(n, bj+blocksizeJ)-bj; //core sub block matrix multiplication for( int i = bi; i < bimin; i++) { int aixi = i * cd + bk; //start index on a int cixj = i * n + bj; //scan index on c //determine nnz of a (for sparsity-aware skipping of rows) int knnz = copyNonZeroElements(a, aixi, bk, bj, n, ta, tbi, bklen); //if( knnz > 0 ) //for skipping empty rows //rest not aligned to blocks of 4 rows final int bn = knnz % 4; switch( bn ){ case 1: vectMultiplyAdd(ta[0], b, c, tbi[0], cixj, bjlen); break; case 2: vectMultiplyAdd2(ta[0],ta[1], b, c, tbi[0], tbi[1], cixj, bjlen); break; case 3: vectMultiplyAdd3(ta[0],ta[1],ta[2], b, c, tbi[0], tbi[1],tbi[2], cixj, bjlen); break; } //compute blocks of 4 rows (core inner loop) for( int k = bn; k<knnz; k+=4 ){ vectMultiplyAdd4( ta[k], ta[k+1], ta[k+2], ta[k+3], b, c, tbi[k], tbi[k+1], tbi[k+2], tbi[k+3], cixj, bjlen ); } } } } } else { //init empty result Arrays.fill(c, 0, c.length, 0); double val; for( int i = rl, aix=rl*cd, cix=rl*n; i < ru; i++, cix+=n) for( int k = 0, bix=0; k < cd; k++, aix++, bix+=n) { val = a[ aix ]; if( val != 0 ) for( int j = 0; j < n; j++) c[ cix+j ] += val * b[ bix+j ]; } } } /** * * @param m1 * @param m2 * @param ret * @throws DMLRuntimeException */ private static void matrixMultDenseSparse(MatrixBlock m1, MatrixBlock m2, MatrixBlock ret, int rl, int ru) throws DMLRuntimeException { double[] a = m1.denseBlock; double[] c = ret.denseBlock; //int m = m1.rlen; int n = m2.clen; int cd = m1.clen; // MATRIX-MATRIX (VV, MV not applicable here because V always dense) if( LOW_LEVEL_OPTIMIZATION ) { final int blocksizeI = 32; //256KB c block (typical L2 size per core), 32KB a block final int blocksizeK = 32; //note: in contrast to dense-dense, no blocking over j (would require maintaining blocksizeK indexes, counter-productive on skew) SparseRow[] b = m2.sparseRows; //blocked execution for( int bi = rl; bi < ru; bi+=blocksizeI ) for( int bk = 0, bimin = Math.min(ru, bi+blocksizeI); bk < cd; bk+=blocksizeK ) { int bklen = Math.min(cd, bk+blocksizeK)-bk; //core sub block matrix multiplication for( int i = bi; i < bimin; i++) { int aixi = i * cd + bk; //start index on a int cixj = i * n + 0; //scan index on c for( int k = 0; k < bklen; k++ ) { double val = a[aixi+k]; SparseRow brow = b[ bk+k ]; if( val != 0 && brow != null && !brow.isEmpty() ) { int blen = brow.size(); int[] bix = brow.getIndexContainer(); double[] bvals = brow.getValueContainer(); vectMultiplyAdd(val, bvals, c, bix, cixj, blen); } } } } } else { for( int i=rl, aix=rl*cd, cix=rl*n; i < ru; i++, cix+=n ) for(int k = 0; k < cd; k++, aix++ ) { double val = a[aix]; if( val!=0 ) { SparseRow brow = m2.sparseRows[ k ]; if( brow != null && !brow.isEmpty() ) { int blen = brow.size(); int[] bix = brow.getIndexContainer(); double[] bvals = brow.getValueContainer(); for(int j = 0; j < blen; j++) c[cix+bix[j]] += val * bvals[j]; } } } } } /** * * @param m1 * @param m2 * @param ret * @throws DMLRuntimeException */ private static void matrixMultSparseDense(MatrixBlock m1, MatrixBlock m2, MatrixBlock ret, int rl, int ru) throws DMLRuntimeException { double[] b = m2.denseBlock; double[] c = ret.denseBlock; final int m = m1.rlen; final int n = m2.clen; if( LOW_LEVEL_OPTIMIZATION ) { if( m==1 && n==1 ) //DOT PRODUCT { SparseRow arow = m1.sparseRows[0]; if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); c[0] = dotProduct(avals, b, aix, 0, alen); } } else if( n==1 ) //MATRIX-VECTOR { for( int i=rl; i<Math.min(ru, m1.sparseRows.length); i++ ) { SparseRow arow = m1.sparseRows[i]; if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); c[i] = dotProduct(avals, b, aix, 0, alen); } } } else //MATRIX-MATRIX { for( int i=rl, cix=rl*n; i<Math.min(ru, m1.sparseRows.length); i++, cix+=n ) { SparseRow arow = m1.sparseRows[i]; if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); if( alen==1 && avals[0]==1 ) //ROW SELECTION { //plain memcopy for permutation matrices System.arraycopy(b, aix[0]*n, c, cix, n); } else //GENERAL CASE { //rest not aligned to blocks of 4 rows final int bn = alen % 4; switch( bn ){ case 1: vectMultiplyAdd(avals[0], b, c, aix[0]*n, cix, n); break; case 2: vectMultiplyAdd2(avals[0],avals[1], b, c, aix[0]*n, aix[1]*n, cix, n); break; case 3: vectMultiplyAdd3(avals[0],avals[1],avals[2], b, c, aix[0]*n, aix[1]*n, aix[2]*n, cix, n); break; } //compute blocks of 4 rows (core inner loop) for( int k = bn; k<alen; k+=4 ) { vectMultiplyAdd4( avals[k], avals[k+1], avals[k+2], avals[k+3], b, c, aix[k]*n, aix[k+1]*n, aix[k+2]*n, aix[k+3]*n, cix, n ); } } } } } } else { //init empty result Arrays.fill(c, 0, c.length, 0); for( int i=rl, cix=rl*n; i<Math.min(ru, m1.sparseRows.length); i++, cix+=n ) { SparseRow arow = m1.sparseRows[i]; if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); for(int k = 0; k < alen; k++) { double val = avals[k]; for(int j = 0, bix=aix[k]*n; j < n; j++) c[cix+j] += val * b[bix+j]; } } } } } /** * * @param m1 * @param m2 * @param ret * @throws DMLRuntimeException */ private static void matrixMultSparseSparse(MatrixBlock m1, MatrixBlock m2, MatrixBlock ret, int rl, int ru) throws DMLRuntimeException { double[] c = ret.denseBlock; //int m = m1.rlen; int n = m2.clen; // MATRIX-MATRIX (VV, MV not applicable here because V always dense) if(LOW_LEVEL_OPTIMIZATION) { for( int i=rl, cix=rl*n; i<Math.min(ru, m1.sparseRows.length); i++, cix+=n ) { SparseRow arow = m1.sparseRows[i]; if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); for(int k = 0; k < alen; k++) { double val = avals[k]; SparseRow brow = m2.sparseRows[ aix[k] ]; if( brow != null && !brow.isEmpty() ) { int blen = brow.size(); int[] bix = brow.getIndexContainer(); double[] bvals = brow.getValueContainer(); vectMultiplyAdd(val, bvals, c, bix, cix, blen); } } } } } else { for( int i=rl, cix=rl*n; i<Math.min(ru, m1.sparseRows.length); i++, cix+=n ) { SparseRow arow = m1.sparseRows[i]; if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); for(int k = 0; k < alen; k++) { double val = avals[k]; SparseRow brow = m2.sparseRows[ aix[k] ]; if( brow != null && !brow.isEmpty() ) { int blen = brow.size(); int[] bix = brow.getIndexContainer(); double[] bvals = brow.getValueContainer(); for(int j = 0; j < blen; j++) c[cix+bix[j]] += val * bvals[j]; } } } } } } /** * This implementation applies to any combination of dense/sparse if at least one * input is ultrasparse (sparse and very few nnz). In that case, most importantly, * we want to create a sparse output and only iterate over the few nnz as the major * dimension. Low-level optimization have less importance in that case and having * this generic implementation helps to reduce the implementations from (2+1)^2 * to 2^2+1. * * @param m1 * @param m2 * @param ret * @throws DMLRuntimeException */ private static void matrixMultUltraSparse(MatrixBlock m1, MatrixBlock m2, MatrixBlock ret, int rl, int ru) throws DMLRuntimeException { boolean leftUS = m1.isUltraSparse(); final int m = m1.rlen; final int cd = m1.clen; final int n = m2.clen; if( leftUS ) //left is ultra-sparse (IKJ) { boolean rightSparse = m2.sparse; for( int i=rl; i<ru; i++ ) { SparseRow arow = m1.sparseRows[ i ]; if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aixs = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); if( alen==1 && avals[0]==1 ) //ROW SELECTION (no aggregation) { int aix = aixs[0]; if( rightSparse ) { //sparse right matrix (full row copy) if( m2.sparseRows!=null && m2.sparseRows[aix]!=null ) { ret.rlen=m; ret.allocateSparseRowsBlock(false); //allocation on demand ret.sparseRows[i] = new SparseRow(m2.sparseRows[aix]); ret.nonZeros += ret.sparseRows[i].size(); } } else { //dense right matrix (append all values) for( int j=0; j<n; j++ ) ret.appendValue(i, j, m2.quickGetValue(aix, j)); } } else //GENERAL CASE { for( int k=0; k<alen; k++ ) { double aval = avals[k]; int aix = aixs[k]; for( int j=0; j<n; j++ ) { double cval = ret.quickGetValue(i, j); double cvald = aval*m2.quickGetValue(aix, j); if( cvald != 0 ) ret.quickSetValue(i, j, cval+cvald); } } } } } } else //right is ultra-sparse (KJI) { for(int k = 0; k < cd; k++ ) { SparseRow brow = m2.sparseRows[ k ]; if( brow != null && !brow.isEmpty() ) { int blen = brow.size(); int[] bixs = brow.getIndexContainer(); double[] bvals = brow.getValueContainer(); for( int j=0; j<blen; j++ ) { double bval = bvals[j]; int bix = bixs[j]; for( int i=rl; i<ru; i++ ) { double cvald = bval*m1.quickGetValue(i, k); if( cvald != 0 ){ double cval = ret.quickGetValue(i, bix); ret.quickSetValue(i, bix, cval+cvald); } } } } } } //no need to recompute nonzeros because maintained internally } /** * * @param mX * @param mV * @param mW * @param ret * @param ct * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ private static void matrixMultChainDense(MatrixBlock mX, MatrixBlock mV, MatrixBlock mW, MatrixBlock ret, ChainType ct) throws DMLRuntimeException, DMLUnsupportedOperationException { //check inputs / outputs (after that mV and mW guaranteed to be dense) if( mX.isEmptyBlock(false) || mV.isEmptyBlock(false) || (mW !=null && mW.isEmptyBlock(false)) ) return; ret.sparse = false; ret.allocateDenseBlock(); double[] a = mX.denseBlock; double[] b = mV.denseBlock; double[] w = (mW!=null) ? mW.denseBlock : null; double[] c = ret.denseBlock; final int m = mX.rlen; //rows in X final int cd = mX.clen; //features in X boolean weights = (ct == ChainType.XtwXv); Arrays.fill(c, 0, c.length, 0); //temporary array for cache blocking //(blocksize chosen to fit b+v in L2 (256KB) for default 1k blocks) final int blocksize = 24; //constraint: factor of 4 double[] tmp = new double[blocksize]; //blockwise mmchain computation final int bn = m - m % blocksize; for( int bi=0; bi < bn; bi+=blocksize ) { //compute 1st matrix-vector for row block for( int j=0, aix=bi*cd; j < blocksize; j++, aix+=cd) tmp[j] = dotProduct(a, b, aix, 0, cd); //multiply weights (in-place), if required if( weights ) vectMultiply(w, tmp, bi, 0, blocksize); //compute 2nd matrix vector for row block and aggregate for (int j=0, aix=bi*cd; j < blocksize; j+=4, aix+=4*cd) vectMultiplyAdd4(tmp[j], tmp[j+1], tmp[j+2], tmp[j+3], a, c, aix, aix+cd, aix+2*cd, aix+3*cd, 0, cd); } //compute rest (not aligned to blocksize) for( int i=bn, aix=i*cd; i < m; i++, aix+=cd ) { double val = dotProduct(a, b, aix, 0, cd); val *= (weights) ? w[i] : 1; vectMultiplyAdd(val, a, c, aix, 0, cd); } ret.recomputeNonZeros(); ret.examSparsity(); } /** * * @param mX * @param mV * @param mW * @param ret * @param ct * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ private static void matrixMultChainSparse(MatrixBlock mX, MatrixBlock mV, MatrixBlock mW, MatrixBlock ret, ChainType ct) throws DMLRuntimeException, DMLUnsupportedOperationException { //check inputs / outputs (after that mV and mW guaranteed to be dense) if( mX.isEmptyBlock(false) || mV.isEmptyBlock(false) || (mW !=null && mW.isEmptyBlock(false)) ) return; ret.sparse = false; ret.allocateDenseBlock(); SparseRow[] a = mX.sparseRows; double[] b = mV.denseBlock; double[] w = (mW!=null) ? mW.denseBlock : null; double[] c = ret.denseBlock; final int m = mX.rlen; boolean weights = (ct == ChainType.XtwXv); Arrays.fill(c, 0, c.length, 0); //temporary array for cache blocking //(blocksize chosen to fit b+v in L2 (256KB) for default 1k blocks) final int blocksize = 24; double[] tmp = new double[blocksize]; //blockwise mmchain computation for( int bi=0; bi < m; bi+=blocksize ) { //reset row block intermediate int tmplen = Math.min(blocksize, m-bi); //compute 1st matrix-vector for row block for( int j=0; j < tmplen; j++) { SparseRow arow = a[bi+j]; if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); tmp[j] = dotProduct(avals, b, aix, 0, alen); } } //multiply weights (in-place), if required if( weights ) vectMultiply(w, tmp, bi, 0, tmplen); //compute 2nd matrix vector for row block and aggregate for( int j=0; j < tmplen; j++) { SparseRow arow = a[bi+j]; if( arow != null && !arow.isEmpty() && tmp[j] != 0 ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); vectMultiplyAdd(tmp[j], avals, c, aix, 0, alen); } } } ret.recomputeNonZeros(); ret.examSparsity(); } /** * * @param m1 * @param ret * @param leftTranspose * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ private static void matrixMultTransposeSelfDense( MatrixBlock m1, MatrixBlock ret, boolean leftTranspose ) throws DMLRuntimeException, DMLUnsupportedOperationException { //1) allocate output block ret.rlen = leftTranspose ? m1.clen : m1.rlen; ret.clen = leftTranspose ? m1.clen : m1.rlen; ret.sparse = false; ret.allocateDenseBlock(); if( m1.denseBlock == null ) return; //2) transpose self matrix multiply dense // (compute only upper-triangular matrix due to symmetry) double[] a = m1.denseBlock; double[] c = ret.denseBlock; int m = m1.rlen; int n = m1.clen; if( leftTranspose ) // t(X)%*%X { if( LOW_LEVEL_OPTIMIZATION ) { if( n==1 ) //VECTOR (col) { c[0] = dotProduct(a, a, m); } else //MATRIX { //init empty result Arrays.fill(c, 0, c.length, 0); //1) Unrolled inner loop (for better instruction-level parallelism) //2) Blocked execution (for less cache trashing in parallel exec) //3) Asymmetric block sizes (for less misses in inner loop, yet blocks in L1/L2) final int blocksizeI = 32; //64//256KB c block (typical L2 size per core), 32KB a block final int blocksizeK = 24; //64//256KB b block (typical L2 size per core), used while read 512B of a / read/write 4KB of c final int blocksizeJ = 1024; //512//4KB (typical main-memory page size), for scan //temporary arrays (nnz a, b index) double[] ta = new double[ blocksizeK ]; int[] tbi = new int[ blocksizeK ]; final int mx = n; final int cdx = m; final int nx = n; //blocked execution for( int bi = 0; bi < mx; bi+=blocksizeI ) //from bi due to symmetry for( int bk = 0, bimin = Math.min(mx, bi+blocksizeI); bk < cdx; bk+=blocksizeK ) for( int bj = bi, bkmin = Math.min(cdx, bk+blocksizeK); bj < nx; bj+=blocksizeJ ) { int bklen = bkmin-bk; int bjlen = Math.min(nx, bj+blocksizeJ)-bj; //core sub block matrix multiplication for( int i = bi; i < bimin; i++) { int aixi = bk*n +i; //start index on a (logical t(X)) int cixj = i * nx + bj; //scan index on c //determine nnz of a (for sparsity-aware skipping of rows) int knnz = copyNonZeroElements(a, aixi, bk, bj, n, nx, ta, tbi, bklen); //rest not aligned to blocks of 4 rows final int bn = knnz % 4; switch( bn ){ case 1: vectMultiplyAdd(ta[0], a, c, tbi[0], cixj, bjlen); break; case 2: vectMultiplyAdd2(ta[0],ta[1], a, c, tbi[0], tbi[1], cixj, bjlen); break; case 3: vectMultiplyAdd3(ta[0],ta[1],ta[2], a, c, tbi[0], tbi[1],tbi[2], cixj, bjlen); break; } //compute blocks of 4 rows (core inner loop) for( int k = bn; k<knnz; k+=4 ){ vectMultiplyAdd4( ta[k], ta[k+1], ta[k+2], ta[k+3], a, c, tbi[k], tbi[k+1], tbi[k+2], tbi[k+3], cixj, bjlen ); } } } } } else { //init empty result Arrays.fill(c, 0, c.length, 0); for(int k = 0, ix1 = 0; k < m; k++, ix1+=n) for(int i = 0, ix3 = 0; i < n; i++, ix3+=n) { double val = a[ ix1+i ]; if( val != 0 ) { for(int j = i; j < n; j++) //from i due to symmetry c[ ix3+j ] += val * a[ ix1+j ]; } } } } else // X%*%t(X) { if(LOW_LEVEL_OPTIMIZATION) { if( m==1 ) //VECTOR { c[0] = dotProduct(a, a, n); } else //MATRIX { //init empty result Arrays.fill(c, 0, c.length, 0); //algorithm: scan c, foreach ci,j: scan row of a and t(a) (IJK) //1) Unrolled inner loop, for better ILP //2) Blocked execution, for less cache trashing in parallel exec // (smaller block sizes would be slightly better, but consistent as is) //3) Single write in inner loop (transient intermediates) int blocksize = 64; for( int bi = 0; bi<m; bi+=blocksize ) for( int bj = bi; bj<m; bj+=blocksize ) { final int bimin = Math.min(m, bi+blocksize); final int bjmin = Math.min(m, bj+blocksize); for(int i = bi, ix1 = bi*n, ix3 = bi*m; i < bimin; i++, ix1+=n, ix3+=m) { final int bjmax = Math.max(i,bj); for(int j = bjmax, ix2 = bjmax*n; j <bjmin; j++, ix2+=n) //from i due to symmetry { c[ ix3+j ] = dotProduct(a, a, ix1, ix2, n); } } } } } else { for(int i = 0, ix1 = 0, ix3 = 0; i < m; i++, ix1+=n, ix3+=m) for(int j = i, ix2 = i*n; j < m; j++, ix2+=n) //from i due to symmetry { double val = 0; for(int k = 0; k < n; k++) val += a[ ix1+k ] * a[ix2+k]; c[ ix3+j ] = val; } } } //3) copy symmetric values copyUpperToLowerTriangle( ret ); ret.recomputeNonZeros(); ret.examSparsity(); } /** * * @param out * @param leftTranspose * @throws DMLUnsupportedOperationException * @throws DMLRuntimeException */ private static void matrixMultTransposeSelfSparse( MatrixBlock m1, MatrixBlock ret, boolean leftTranspose ) throws DMLUnsupportedOperationException, DMLRuntimeException { //1) allocate output block ret.rlen = leftTranspose ? m1.clen : m1.rlen; ret.clen = leftTranspose ? m1.clen : m1.rlen; ret.sparse = false; //assumption dense output if( m1.sparseRows == null ) return; ret.allocateDenseBlock(); //2) transpose self matrix multiply sparse // (compute only upper-triangular matrix due to symmetry) double[] c = ret.denseBlock; int m = m1.rlen; int n = m1.clen; if( leftTranspose ) // t(X)%*%X { //init empty result Arrays.fill(c, 0, c.length, 0); //only general case (because vectors always dense) //algorithm: scan rows, foreach row self join (KIJ) if( LOW_LEVEL_OPTIMIZATION ) { for( SparseRow arow : m1.sparseRows ) if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); for(int i = 0; i < alen; i++) { double val = avals[i]; if( val != 0 ) { int ix2 = aix[i]*n; vectMultiplyAdd(val, avals, c, aix, i, ix2, alen); } } } } else { for( SparseRow arow : m1.sparseRows ) if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); for(int i = 0; i < alen; i++) { double val = avals[i]; if( val != 0 ) for(int j = i, ix2 = aix[i]*n; j < alen; j++) c[ix2+aix[j]] += val * avals[j]; } } } } else // X%*%t(X) { if( m==1 ) //VECTOR { SparseRow arow = m1.sparseRows[0]; if( arow !=null && !arow.isEmpty() ) { int alen = arow.size(); double[] avals = arow.getValueContainer(); c[0] = dotProduct(avals, avals, alen); } } else //MATRIX { //init empty result Arrays.fill(c, 0, c.length, 0); //note: reorg to similar layout as t(X)%*%X because faster than //direct computation with IJK (no dependencies/branches in inner loop) MatrixBlock tmpBlock = new MatrixBlock(n,m,m1.sparse); m1.reorgOperations(new ReorgOperator(SwapIndex.getSwapIndexFnObject()), tmpBlock, 0, 0, -1); if( tmpBlock.sparseRows == null ) return; //algorithm: scan rows, foreach row self join (KIJ) if( LOW_LEVEL_OPTIMIZATION ) { for( SparseRow arow : tmpBlock.sparseRows ) if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); for(int i = 0; i < alen; i++) { double val = avals[i]; if( val != 0 ) { int ix2 = aix[i]*m; vectMultiplyAdd(val, avals, c, aix, i, ix2, alen); } } } } else { for( SparseRow arow : tmpBlock.sparseRows ) if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); for(int i = 0; i < alen; i++) { double val = avals[i]; if( val != 0 ) for(int j = i, ix2 = aix[i]*m; j < alen; j++) c[ix2+aix[j]] += val * avals[j]; } } } } } //3) copy symmetric values copyUpperToLowerTriangle( ret ); ret.recomputeNonZeros(); ret.examSparsity(); } /** * * @param pm1 * @param m2 * @param ret1 * @param ret2 * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ private static void matrixMultPermuteDense( MatrixBlock pm1, MatrixBlock m2, MatrixBlock ret1, MatrixBlock ret2 ) throws DMLRuntimeException, DMLUnsupportedOperationException { //check inputs / outputs if( pm1.isEmptyBlock(false) || m2.isEmptyBlock(false) ) return; //allocate first output block (second allocated if needed) ret1.sparse = false; ret1.allocateDenseBlock(); double[] a = pm1.denseBlock; double[] b = m2.denseBlock; double[] c = ret1.denseBlock; final int m = pm1.rlen; final int n = m2.clen; final int brlen = ret1.getNumRows(); int lastblk = -1; for( int i=0, bix=0; i<m; i++, bix+=n ) { //compute block index and in-block indexes int pos = UtilFunctions.toInt( a[ i ]); //safe cast if( pos > 0 ) //selected row { int bpos = (pos-1) % brlen; int blk = (pos-1) / brlen; //allocate and switch to second output block if( lastblk!=-1 && lastblk<blk ){ ret2.sparse = false; ret2.allocateDenseBlock(); c = ret2.denseBlock; } //memcopy entire dense row into target position System.arraycopy(b, bix, c, bpos*n, n); lastblk = blk; } } ret1.recomputeNonZeros(); ret1.examSparsity(); if( ret2 != null ) { //optional second output ret2.recomputeNonZeros(); ret2.examSparsity(); } } /** * * @param pm1 * @param m2 * @param ret1 * @param ret2 * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ private static void matrixMultPermuteDenseSparse( MatrixBlock pm1, MatrixBlock m2, MatrixBlock ret1, MatrixBlock ret2 ) throws DMLRuntimeException, DMLUnsupportedOperationException { //check inputs / outputs if( pm1.isEmptyBlock(false) || m2.isEmptyBlock(false) ) return; //allocate first output block (second allocated if needed) ret1.sparse = true; ret1.allocateSparseRowsBlock(); double[] a = pm1.denseBlock; double[] b = m2.denseBlock; SparseRow[] c = ret1.sparseRows; final int m = pm1.rlen; final int n = m2.clen; final int brlen = ret1.getNumRows(); int lastblk = -1; for( int i=0, bix=0; i<m; i++, bix+=n ) { //compute block index and in-block indexes int pos = UtilFunctions.toInt( a[ i ]); //safe cast if( pos > 0 ) //selected row { int bpos = (pos-1) % brlen; int blk = (pos-1) / brlen; //allocate and switch to second output block if( lastblk!=-1 && lastblk<blk ){ ret2.sparse = true; ret2.rlen=ret1.rlen; ret2.allocateSparseRowsBlock(); c = ret2.sparseRows; } //append entire dense row into sparse target position c[bpos] = new SparseRow( n ); for( int j=0; j<n; j++ ) c[bpos].append(j, b[bix+j]); lastblk = blk; } } ret1.recomputeNonZeros(); ret1.examSparsity(); if( ret2 != null ) { //optional second output ret2.recomputeNonZeros(); ret2.examSparsity(); } } /** * * @param pm1 * @param m2 * @param ret1 * @param ret2 * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ private static void matrixMultPermuteSparse( MatrixBlock pm1, MatrixBlock m2, MatrixBlock ret1, MatrixBlock ret2 ) throws DMLRuntimeException, DMLUnsupportedOperationException { //check inputs / outputs if( pm1.isEmptyBlock(false) || m2.isEmptyBlock(false) ) return; //allocate first output block (second allocated if needed) ret1.sparse = true; ret1.allocateSparseRowsBlock(); double[] a = pm1.denseBlock; SparseRow[] b = m2.sparseRows; SparseRow[] c = ret1.sparseRows; final int m = pm1.rlen; final int brlen = ret1.getNumRows(); int lastblk = -1; for( int i=0; i<m; i++ ) { //compute block index and in-block indexes int pos = UtilFunctions.toInt( a[ i ]); //safe cast if( pos > 0 ) //selected row { int bpos = (pos-1) % brlen; int blk = (pos-1) / brlen; //allocate and switch to second output block if( lastblk!=-1 && lastblk<blk ){ ret2.sparse = true; ret2.allocateSparseRowsBlock(); c = ret2.sparseRows; } //memcopy entire sparse row into target position if( b[i] != null ) c[bpos] = new SparseRow( b[i] ); lastblk = blk; } } ret1.recomputeNonZeros(); ret1.examSparsity(); if( ret2 != null ) { //optional second output ret2.recomputeNonZeros(); ret2.examSparsity(); } } //////////////////////////////////////////// // performance-relevant utility functions // //////////////////////////////////////////// /** * Computes the dot-product of two vectors. Experiments (on long vectors of * 10^7 values) showed that this generic function provides equivalent performance * even for the specific case of dotProduct(a,a,len) as used for TSMM. * * @param a * @param b * @param len * @return */ private static double dotProduct( double[] a, double[] b, final int len ) { double val = 0; final int bn = len%8; //compute rest for( int i = 0; i < bn; i++ ) val += a[ i ] * b[ i ]; //unrolled 8-block (for better instruction-level parallelism) for( int i = bn; i < len; i+=8 ) { //read 64B cachelines of a and b //compute cval' = sum(a * b) + cval val += a[ i+0 ] * b[ i+0 ] + a[ i+1 ] * b[ i+1 ] + a[ i+2 ] * b[ i+2 ] + a[ i+3 ] * b[ i+3 ] + a[ i+4 ] * b[ i+4 ] + a[ i+5 ] * b[ i+5 ] + a[ i+6 ] * b[ i+6 ] + a[ i+7 ] * b[ i+7 ]; } //scalar result return val; } /** * * @param a * @param b * @param ai * @param bi * @param len * @return */ private static double dotProduct( double[] a, double[] b, int ai, int bi, final int len ) { double val = 0; final int bn = len%8; //compute rest for( int i = 0; i < bn; i++, ai++, bi++ ) val += a[ ai ] * b[ bi ]; //unrolled 8-block (for better instruction-level parallelism) for( int i = bn; i < len; i+=8, ai+=8, bi+=8 ) { //read 64B cachelines of a and b //compute cval' = sum(a * b) + cval val += a[ ai+0 ] * b[ bi+0 ] + a[ ai+1 ] * b[ bi+1 ] + a[ ai+2 ] * b[ bi+2 ] + a[ ai+3 ] * b[ bi+3 ] + a[ ai+4 ] * b[ bi+4 ] + a[ ai+5 ] * b[ bi+5 ] + a[ ai+6 ] * b[ bi+6 ] + a[ ai+7 ] * b[ bi+7 ]; } //scalar result return val; } private static double dotProduct( double[] a, double[] b, int[] aix, final int bi, final int len ) { double val = 0; final int bn = len%8; //compute rest for( int i = 0; i < bn; i++ ) val += a[ i ] * b[ bi+aix[i] ]; //unrolled 8-block (for better instruction-level parallelism) for( int i = bn; i < len; i+=8 ) { //read 64B cacheline of a //read 64B of b via 'gather' //compute cval' = sum(a * b) + cval val += a[ i+0 ] * b[ bi+aix[i+0] ] + a[ i+1 ] * b[ bi+aix[i+1] ] + a[ i+2 ] * b[ bi+aix[i+2] ] + a[ i+3 ] * b[ bi+aix[i+3] ] + a[ i+4 ] * b[ bi+aix[i+4] ] + a[ i+5 ] * b[ bi+aix[i+5] ] + a[ i+6 ] * b[ bi+aix[i+6] ] + a[ i+7 ] * b[ bi+aix[i+7] ]; } //scalar result return val; } /** * * @param aval * @param b * @param c * @param bi * @param ci * @param len */ private static void vectMultiplyAdd( final double aval, double[] b, double[] c, int bi, int ci, final int len ) { final int bn = len%8; //rest, not aligned to 8-blocks for( int j = 0; j < bn; j++, bi++, ci++) c[ ci ] += aval * b[ bi ]; //unrolled 8-block (for better instruction-level parallelism) for( int j = bn; j < len; j+=8, bi+=8, ci+=8) { //read 64B cachelines of b and c //compute c' = aval * b + c //write back 64B cacheline of c = c' c[ ci+0 ] += aval * b[ bi+0 ]; c[ ci+1 ] += aval * b[ bi+1 ]; c[ ci+2 ] += aval * b[ bi+2 ]; c[ ci+3 ] += aval * b[ bi+3 ]; c[ ci+4 ] += aval * b[ bi+4 ]; c[ ci+5 ] += aval * b[ bi+5 ]; c[ ci+6 ] += aval * b[ bi+6 ]; c[ ci+7 ] += aval * b[ bi+7 ]; } } /** * * @param aval1 * @param aval2 * @param b * @param c * @param bi * @param bi2 * @param ci * @param len */ private static void vectMultiplyAdd2( final double aval1, final double aval2, double[] b, double[] c, int bi1, int bi2, int ci, final int len ) { final int bn = len%8; //rest, not aligned to 8-blocks for( int j = 0; j < bn; j++, bi1++, bi2++, ci++ ) c[ ci ] += aval1 * b[ bi1 ] + aval2 * b[ bi2 ]; //unrolled 8-block (for better instruction-level parallelism) for( int j = bn; j < len; j+=8, bi1+=8, bi2+=8, ci+=8 ) { //read 64B cachelines of b (2x) and c //compute c' = aval_1 * b_1 + aval_2 * b_2 + c //write back 64B cacheline of c = c' c[ ci+0 ] += aval1 * b[ bi1+0 ] + aval2 * b[ bi2+0 ]; c[ ci+1 ] += aval1 * b[ bi1+1 ] + aval2 * b[ bi2+1 ]; c[ ci+2 ] += aval1 * b[ bi1+2 ] + aval2 * b[ bi2+2 ]; c[ ci+3 ] += aval1 * b[ bi1+3 ] + aval2 * b[ bi2+3 ]; c[ ci+4 ] += aval1 * b[ bi1+4 ] + aval2 * b[ bi2+4 ]; c[ ci+5 ] += aval1 * b[ bi1+5 ] + aval2 * b[ bi2+5 ]; c[ ci+6 ] += aval1 * b[ bi1+6 ] + aval2 * b[ bi2+6 ]; c[ ci+7 ] += aval1 * b[ bi1+7 ] + aval2 * b[ bi2+7 ]; } } /** * * @param aval1 * @param aval2 * @param aval3 * @param b * @param c * @param bi1 * @param bi2 * @param bi3 * @param ci * @param len */ private static void vectMultiplyAdd3( final double aval1, final double aval2, final double aval3, double[] b, double[] c, int bi1, int bi2, int bi3, int ci, final int len ) { final int bn = len%8; //rest, not aligned to 8-blocks for( int j = 0; j < bn; j++, bi1++, bi2++, bi3++, ci++ ) c[ ci ] += aval1 * b[ bi1 ] + aval2 * b[ bi2 ] + aval3 * b[ bi3 ]; //unrolled 8-block (for better instruction-level parallelism) for( int j = bn; j < len; j+=8, bi1+=8, bi2+=8, bi3+=8, ci+=8 ) { //read 64B cachelines of b (3x) and c //compute c' = aval_1 * b_1 + aval_2 * b_2 + c //write back 64B cacheline of c = c' c[ ci+0 ] += aval1 * b[ bi1+0 ] + aval2 * b[ bi2+0 ] + aval3 * b[ bi3+0 ]; c[ ci+1 ] += aval1 * b[ bi1+1 ] + aval2 * b[ bi2+1 ] + aval3 * b[ bi3+1 ]; c[ ci+2 ] += aval1 * b[ bi1+2 ] + aval2 * b[ bi2+2 ] + aval3 * b[ bi3+2 ]; c[ ci+3 ] += aval1 * b[ bi1+3 ] + aval2 * b[ bi2+3 ] + aval3 * b[ bi3+3 ]; c[ ci+4 ] += aval1 * b[ bi1+4 ] + aval2 * b[ bi2+4 ] + aval3 * b[ bi3+4 ]; c[ ci+5 ] += aval1 * b[ bi1+5 ] + aval2 * b[ bi2+5 ] + aval3 * b[ bi3+5 ]; c[ ci+6 ] += aval1 * b[ bi1+6 ] + aval2 * b[ bi2+6 ] + aval3 * b[ bi3+6 ]; c[ ci+7 ] += aval1 * b[ bi1+7 ] + aval2 * b[ bi2+7 ] + aval3 * b[ bi3+7 ]; } } /** * * @param aval1 * @param aval2 * @param aval3 * @param aval4 * @param b * @param c * @param bi1 * @param bi2 * @param bi3 * @param bi4 * @param ci * @param len */ private static void vectMultiplyAdd4( final double aval1, final double aval2, final double aval3, final double aval4, double[] b, double[] c, int bi1, int bi2, int bi3, int bi4, int ci, final int len ) { final int bn = len%8; //rest, not aligned to 8-blocks for( int j = 0; j < bn; j++, bi1++, bi2++, bi3++, bi4++, ci++ ) c[ ci ] += aval1 * b[ bi1 ] + aval2 * b[ bi2 ] + aval3 * b[ bi3 ] + aval4 * b[ bi4 ]; //unrolled 8-block (for better instruction-level parallelism) for( int j = bn; j < len; j+=8, bi1+=8, bi2+=8, bi3+=8, bi4+=8, ci+=8) { //read 64B cachelines of b (4x) and c //compute c' = aval_1 * b_1 + aval_2 * b_2 + c //write back 64B cacheline of c = c' c[ ci+0 ] += aval1 * b[ bi1+0 ] + aval2 * b[ bi2+0 ] + aval3 * b[ bi3+0 ] + aval4 * b[ bi4+0 ]; c[ ci+1 ] += aval1 * b[ bi1+1 ] + aval2 * b[ bi2+1 ] + aval3 * b[ bi3+1 ] + aval4 * b[ bi4+1 ]; c[ ci+2 ] += aval1 * b[ bi1+2 ] + aval2 * b[ bi2+2 ] + aval3 * b[ bi3+2 ] + aval4 * b[ bi4+2 ]; c[ ci+3 ] += aval1 * b[ bi1+3 ] + aval2 * b[ bi2+3 ] + aval3 * b[ bi3+3 ] + aval4 * b[ bi4+3 ]; c[ ci+4 ] += aval1 * b[ bi1+4 ] + aval2 * b[ bi2+4 ] + aval3 * b[ bi3+4 ] + aval4 * b[ bi4+4 ]; c[ ci+5 ] += aval1 * b[ bi1+5 ] + aval2 * b[ bi2+5 ] + aval3 * b[ bi3+5 ] + aval4 * b[ bi4+5 ]; c[ ci+6 ] += aval1 * b[ bi1+6 ] + aval2 * b[ bi2+6 ] + aval3 * b[ bi3+6 ] + aval4 * b[ bi4+6 ]; c[ ci+7 ] += aval1 * b[ bi1+7 ] + aval2 * b[ bi2+7 ] + aval3 * b[ bi3+7 ] + aval4 * b[ bi4+7 ]; } } /** * * @param aval * @param b * @param c * @param bix * @param ci * @param len */ private static void vectMultiplyAdd( final double aval, double[] b, double[] c, int[] bix, final int ci, final int len ) { final int bn = len%8; //rest, not aligned to 8-blocks for( int j = 0; j < bn; j++ ) c[ ci + bix[j] ] += aval * b[ j ]; //unrolled 8-block (for better instruction-level parallelism) for( int j = bn; j < len; j+=8 ) { //read 64B cacheline of b //read 64B of c via 'gather' //compute c' = aval * b + c //write back 64B of c = c' via 'scatter' c[ ci+bix[j+0] ] += aval * b[ j+0 ]; c[ ci+bix[j+1] ] += aval * b[ j+1 ]; c[ ci+bix[j+2] ] += aval * b[ j+2 ]; c[ ci+bix[j+3] ] += aval * b[ j+3 ]; c[ ci+bix[j+4] ] += aval * b[ j+4 ]; c[ ci+bix[j+5] ] += aval * b[ j+5 ]; c[ ci+bix[j+6] ] += aval * b[ j+6 ]; c[ ci+bix[j+7] ] += aval * b[ j+7 ]; } } private static void vectMultiplyAdd( final double aval, double[] b, double[] c, int[] bix, final int bi, final int ci, final int len ) { final int bn = (len-bi)%8; //rest, not aligned to 8-blocks for( int j = bi; j < bi+bn; j++ ) c[ ci + bix[j] ] += aval * b[ j ]; //unrolled 8-block (for better instruction-level parallelism) for( int j = bi+bn; j < len; j+=8 ) { //read 64B cacheline of b //read 64B of c via 'gather' //compute c' = aval * b + c //write back 64B of c = c' via 'scatter' c[ ci+bix[j+0] ] += aval * b[ j+0 ]; c[ ci+bix[j+1] ] += aval * b[ j+1 ]; c[ ci+bix[j+2] ] += aval * b[ j+2 ]; c[ ci+bix[j+3] ] += aval * b[ j+3 ]; c[ ci+bix[j+4] ] += aval * b[ j+4 ]; c[ ci+bix[j+5] ] += aval * b[ j+5 ]; c[ ci+bix[j+6] ] += aval * b[ j+6 ]; c[ ci+bix[j+7] ] += aval * b[ j+7 ]; } } /** * * @param aval * @param b * @param c * @param bi * @param ci * @param len */ private static void vectMultiplyWrite( final double aval, double[] b, double[] c, int bi, int ci, final int len ) { final int bn = len%8; //rest, not aligned to 8-blocks for( int j = 0; j < bn; j++, bi++, ci++) c[ ci ] = aval * b[ bi ]; //unrolled 8-block (for better instruction-level parallelism) for( int j = bn; j < len; j+=8, bi+=8, ci+=8) { //read 64B cachelines of b and c //compute c' = aval * b + c //write back 64B cacheline of c = c' c[ ci+0 ] = aval * b[ bi+0 ]; c[ ci+1 ] = aval * b[ bi+1 ]; c[ ci+2 ] = aval * b[ bi+2 ]; c[ ci+3 ] = aval * b[ bi+3 ]; c[ ci+4 ] = aval * b[ bi+4 ]; c[ ci+5 ] = aval * b[ bi+5 ]; c[ ci+6 ] = aval * b[ bi+6 ]; c[ ci+7 ] = aval * b[ bi+7 ]; } } /** * * @param a * @param b * @param c * @param ai * @param bi * @param ci * @param len */ @SuppressWarnings("unused") private static void vectMultiplyWrite( double[] a, double[] b, double[] c, int ai, int bi, int ci, final int len ) { final int bn = len%8; //rest, not aligned to 8-blocks for( int j = 0; j < bn; j++, ai++, bi++, ci++) c[ ci ] = a[ ai ] * b[ bi ]; //unrolled 8-block (for better instruction-level parallelism) for( int j = bn; j < len; j+=8, ai+=8, bi+=8, ci+=8) { //read 64B cachelines of a and b //compute c' = a * b //write back 64B cacheline of c = c' c[ ci+0 ] = a[ ai+0 ] * b[ bi+0 ]; c[ ci+1 ] = a[ ai+1 ] * b[ bi+1 ]; c[ ci+2 ] = a[ ai+2 ] * b[ bi+2 ]; c[ ci+3 ] = a[ ai+3 ] * b[ bi+3 ]; c[ ci+4 ] = a[ ai+4 ] * b[ bi+4 ]; c[ ci+5 ] = a[ ai+5 ] * b[ bi+5 ]; c[ ci+6 ] = a[ ai+6 ] * b[ bi+6 ]; c[ ci+7 ] = a[ ai+7 ] * b[ bi+7 ]; } } private static void vectMultiply( double[] a, double[] c, int ai, int ci, final int len ) { final int bn = len%8; //rest, not aligned to 8-blocks for( int j = 0; j < bn; j++, ai++, ci++) c[ ci ] *= a[ ai ]; //unrolled 8-block (for better instruction-level parallelism) for( int j = bn; j < len; j+=8, ai+=8, ci+=8) { //read 64B cachelines of a and c //compute c' = c * a //write back 64B cacheline of c = c' c[ ci+0 ] *= a[ ai+0 ]; c[ ci+1 ] *= a[ ai+1 ]; c[ ci+2 ] *= a[ ai+2 ]; c[ ci+3 ] *= a[ ai+3 ]; c[ ci+4 ] *= a[ ai+4 ]; c[ ci+5 ] *= a[ ai+5 ]; c[ ci+6 ] *= a[ ai+6 ]; c[ ci+7 ] *= a[ ai+7 ]; } } /** * Used for all version of TSMM where the result is known to be symmetric. * Hence, we compute only the upper triangular matrix and copy this partial * result down to lower triangular matrix once. * * @param ret */ private static void copyUpperToLowerTriangle( MatrixBlock ret ) { double[] c = ret.denseBlock; final int m = ret.rlen; final int n = ret.clen; //copy symmetric values for( int i=0, uix=0; i<m; i++, uix+=n ) for( int j=i+1, lix=j*n+i; j<n; j++, lix+=n ) c[ lix ] = c[ uix+j ]; } /** * * @param a * @param aixi * @param bk * @param bj * @param n * @param tmpa * @param tmpbi * @param bklen * @return */ private static int copyNonZeroElements( double[] a, final int aixi, final int bk, final int bj, final int n, double[] tmpa, int[] tmpbi, final int bklen ) { int knnz = 0; for( int k = 0; k < bklen; k++ ) if( a[ aixi+k ] != 0 ) { tmpa[ knnz ] = a[ aixi+k ]; tmpbi[ knnz ] = (bk+k) * n + bj; //scan index on b knnz ++; } return knnz; } /** * * @param a * @param aixi * @param bk * @param bj * @param n * @param nx * @param tmpa * @param tmpbi * @param bklen * @return */ private static int copyNonZeroElements( double[] a, int aixi, final int bk, final int bj, final int n, final int nx, double[] tmpa, int[] tmpbi, final int bklen ) { int knnz = 0; for( int k = 0; k < bklen; k++, aixi+=n ) if( a[ aixi ] != 0 ) { tmpa[ knnz ] = a[ aixi ]; tmpbi[ knnz ] = (bk+k) * nx + bj; //scan index on b knnz ++; } return knnz; } private static class MatrixMultTask implements Callable<Object> { private MatrixBlock _m1 = null; private MatrixBlock _m2 = null; private MatrixBlock _ret = null; private int _rl = -1; private int _ru = -1; protected MatrixMultTask( MatrixBlock m1, MatrixBlock m2, MatrixBlock ret, int rl, int ru ) { _m1 = m1; _m2 = m2; _ret = ret; _rl = rl; _ru = ru; } @Override public Object call() throws DMLRuntimeException { if( _m1.isUltraSparse() || _m2.isUltraSparse() ) matrixMultUltraSparse(_m1, _m2, _ret, _rl, _ru); else if(!_m1.sparse && !_m2.sparse) matrixMultDenseDense(_m1, _m2, _ret, _rl, _ru); else if(_m1.sparse && _m2.sparse) matrixMultSparseSparse(_m1, _m2, _ret, _rl, _ru); else if(_m1.sparse) matrixMultSparseDense(_m1, _m2, _ret, _rl, _ru); else matrixMultDenseSparse(_m1, _m2, _ret, _rl, _ru); return null; } } }
SystemML/SystemML/src/main/java/com/ibm/bi/dml/runtime/matrix/data/LibMatrixMult.java
/**  * IBM Confidential  * OCO Source Materials  * (C) Copyright IBM Corp. 2010, 2015  * The source code for this program is not published or otherwise divested of its trade secrets, irrespective of what has been deposited with the U.S. Copyright Office.  */ package com.ibm.bi.dml.runtime.matrix.data; import java.util.Arrays; import com.ibm.bi.dml.lops.MapMultChain.ChainType; import com.ibm.bi.dml.runtime.DMLRuntimeException; import com.ibm.bi.dml.runtime.DMLUnsupportedOperationException; import com.ibm.bi.dml.runtime.functionobjects.SwapIndex; import com.ibm.bi.dml.runtime.matrix.operators.ReorgOperator; import com.ibm.bi.dml.runtime.util.UtilFunctions; /** * MB: * Library for matrix multiplications including MM, MV, VV for all * combinations of dense and sparse representations and special * operations such as transpose-self matrix multiplication. * * In general all implementations use internally dense outputs * for direct access, but change the final result to sparse if necessary. * * NOTES on BLAS: * * Experiments in 04/2013 showed that even on dense-dense this implementation * is 3x faster than f2j-BLAS-DGEMM, 2x faster than f2c-BLAS-DGEMM, and * level (+10% after JIT) with a native C implementation. * * Calling native BLAS would loose platform independence and would require * JNI calls incl data transfer. Furthermore, BLAS does not support sparse * matrices (except Sparse BLAS, with dedicated function calls and matrix formats) * and would be an external dependency. * * Experiments in 02/2014 showed that on dense-dense this implementation now achieves * almost 30% peak FP performance. Compared to Intel MKL 11.1 (dgemm, N=1000) it is * just 3.2x (sparsity=1.0) and 1.9x (sparsity=0.5) slower, respectively. * * */ public class LibMatrixMult { @SuppressWarnings("unused") private static final String _COPYRIGHT = "Licensed Materials - Property of IBM\n(C) Copyright IBM Corp. 2010, 2015\n" + "US Government Users Restricted Rights - Use, duplication disclosure restricted by GSA ADP Schedule Contract with IBM Corp."; public static final boolean LOW_LEVEL_OPTIMIZATION = true; private LibMatrixMult() { //prevent instantiation via private constructor } //////////////////////////////// // public matrix mult interface //////////////////////////////// /** * Performs a matrix multiplication and stores the result in the resulting matrix. * * All variants use a IKJ access pattern, and internally use dense output. After the * actual computation, we recompute nnz and check for sparse/dense representation. * * * @param m1 first matrix * @param m2 second matrix * @param ret result matrix * @throws DMLRuntimeException */ public static void matrixMult(MatrixBlock m1, MatrixBlock m2, MatrixBlock ret) throws DMLRuntimeException { //Timing time = new Timing(true); if( m1.isUltraSparse() || m2.isUltraSparse() ) matrixMultUltraSparse(m1, m2, ret); else if(!m1.sparse && !m2.sparse) matrixMultDenseDense(m1, m2, ret); else if(m1.sparse && m2.sparse) matrixMultSparseSparse(m1, m2, ret); else if(m1.sparse) matrixMultSparseDense(m1, m2, ret); else matrixMultDenseSparse(m1, m2, ret); //System.out.println("MM ("+m1.isInSparseFormat()+","+m1.getNumRows()+","+m1.getNumColumns()+","+m1.getNonZeros()+")x" + // "("+m2.isInSparseFormat()+","+m2.getNumRows()+","+m2.getNumColumns()+","+m2.getNonZeros()+") in "+time.stop()); } /** * Performs a matrix multiplication chain operation of type t(X)%*%(X%*%v) or t(X)%*%(w*(X%*%v)). * * All variants use a IKJ access pattern, and internally use dense output. After the * actual computation, we recompute nnz and check for sparse/dense representation. * * @param m1 * @param m2 * @param w * @param ret * @param ct * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static void matrixMultChain(MatrixBlock mX, MatrixBlock mV, MatrixBlock mW, MatrixBlock ret, ChainType ct) throws DMLRuntimeException, DMLUnsupportedOperationException { //Timing time = new Timing(true); if( mX.sparse ) matrixMultChainSparse(mX, mV, mW, ret, ct); else matrixMultChainDense(mX, mV, mW, ret, ct); //System.out.println("MMChain "+ct.toString()+" ("+mX.isInSparseFormat()+","+mX.getNumRows()+","+mX.getNumColumns()+","+mX.getNonZeros()+")x" + // "("+mV.isInSparseFormat()+","+mV.getNumRows()+","+mV.getNumColumns()+","+mV.getNonZeros()+") in "+time.stop()); } /** * * @param m1 * @param ret * @param leftTranspose * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static void matrixMultTransposeSelf( MatrixBlock m1, MatrixBlock ret, boolean leftTranspose ) throws DMLUnsupportedOperationException, DMLRuntimeException { //Timing time = new Timing(true); if( m1.sparse ) matrixMultTransposeSelfSparse(m1, ret, leftTranspose); else matrixMultTransposeSelfDense(m1, ret, leftTranspose); //System.out.println("TSMM ("+m1.isInSparseFormat()+","+m1.getNumRows()+","+m1.getNumColumns()+","+m1.getNonZeros()+","+leftTranspose+") in "+time.stop()); } /** * * @param m1 * @param m2 * @param ret1 * @param ret2 * @throws DMLUnsupportedOperationException * @throws DMLRuntimeException */ public static void matrixMultPermute( MatrixBlock pm1, MatrixBlock m2, MatrixBlock ret1, MatrixBlock ret2 ) throws DMLUnsupportedOperationException, DMLRuntimeException { //Timing time = new Timing(true); if( m2.sparse ) matrixMultPermuteSparse(pm1, m2, ret1, ret2); else if( ret1.sparse ) matrixMultPermuteDenseSparse(pm1, m2, ret1, ret2); else matrixMultPermuteDense(pm1, m2, ret1, ret2); //System.out.println("PMM ("+m1.isInSparseFormat()+","+m1.getNumRows()+","+m1.getNumColumns()+","+m1.getNonZeros()+")x" + // "("+m2.isInSparseFormat()+","+m2.getNumRows()+","+m2.getNumColumns()+","+m2.getNonZeros()+") in "+time.stop()); } ////////////////////////////////////////// // optimized matrix mult implementation // ////////////////////////////////////////// /** * * @param m1 * @param m2 * @param ret * @throws DMLRuntimeException */ private static void matrixMultDenseDense(MatrixBlock m1, MatrixBlock m2, MatrixBlock ret) throws DMLRuntimeException { //check inputs / outputs if( m1.isEmptyBlock(false) || m2.isEmptyBlock(false) ) return; ret.sparse = false; ret.allocateDenseBlock(); double[] a = m1.denseBlock; double[] b = m2.denseBlock; double[] c = ret.denseBlock; final int m = m1.rlen; final int n = m2.clen; final int cd = m1.clen; if( LOW_LEVEL_OPTIMIZATION ) { if( m==1 && n==1 ) //DOT PRODUCT { c[0] = dotProduct(a, b, cd); } else if( n>1 && cd == 1 ) //OUTER PRODUCT { for( int i=0, cix=0; i < m; i++, cix+=n) { if( a[i] == 1 ) System.arraycopy(b, 0, c, cix, n); else if( a[i] != 0 ) vectMultiplyWrite(a[i], b, c, 0, cix, n); else Arrays.fill(c, cix, cix+n, 0); } } else if( n==1 && cd == 1 ) //VECTOR-SCALAR { vectMultiplyWrite(b[0], a, c, 0, 0, m); } else if( n==1 ) //MATRIX-VECTOR { for( int i=0, aix=0; i < m; i++, aix+=cd) c[ i ] = dotProduct(a, b, aix, 0, cd); } else //MATRIX-MATRIX { //init empty result Arrays.fill(c, 0, c.length, 0); //1) Unrolled inner loop (for better instruction-level parallelism) //2) Blocked execution (for less cache trashing in parallel exec) //3) Asymmetric block sizes (for less misses in inner loop, yet blocks in L1/L2) final int blocksizeI = 32; //64//256KB c block (typical L2 size per core), 32KB a block final int blocksizeK = 24; //64//256KB b block (typical L2 size per core), used while read 512B of a / read/write 4KB of c final int blocksizeJ = 1024; //512//4KB (typical main-memory page size), for scan //temporary arrays (nnz a, b index) double[] ta = new double[ blocksizeK ]; int[] tbi = new int[ blocksizeK ]; //blocked execution for( int bi = 0; bi < m; bi+=blocksizeI ) for( int bk = 0, bimin = Math.min(m, bi+blocksizeI); bk < cd; bk+=blocksizeK ) for( int bj = 0, bkmin = Math.min(cd, bk+blocksizeK); bj < n; bj+=blocksizeJ ) { int bklen = bkmin-bk; int bjlen = Math.min(n, bj+blocksizeJ)-bj; //core sub block matrix multiplication for( int i = bi; i < bimin; i++) { int aixi = i * cd + bk; //start index on a int cixj = i * n + bj; //scan index on c //determine nnz of a (for sparsity-aware skipping of rows) int knnz = copyNonZeroElements(a, aixi, bk, bj, n, ta, tbi, bklen); //if( knnz > 0 ) //for skipping empty rows //rest not aligned to blocks of 4 rows final int bn = knnz % 4; switch( bn ){ case 1: vectMultiplyAdd(ta[0], b, c, tbi[0], cixj, bjlen); break; case 2: vectMultiplyAdd2(ta[0],ta[1], b, c, tbi[0], tbi[1], cixj, bjlen); break; case 3: vectMultiplyAdd3(ta[0],ta[1],ta[2], b, c, tbi[0], tbi[1],tbi[2], cixj, bjlen); break; } //compute blocks of 4 rows (core inner loop) for( int k = bn; k<knnz; k+=4 ){ vectMultiplyAdd4( ta[k], ta[k+1], ta[k+2], ta[k+3], b, c, tbi[k], tbi[k+1], tbi[k+2], tbi[k+3], cixj, bjlen ); } } } } } else { //init empty result Arrays.fill(c, 0, c.length, 0); double val; for( int i = 0, aix=0, cix=0; i < m; i++, cix+=n) for( int k = 0, bix=0; k < cd; k++, aix++, bix+=n) { val = a[ aix ]; if( val != 0 ) for( int j = 0; j < n; j++) c[ cix+j ] += val * b[ bix+j ]; } } ret.recomputeNonZeros(); ret.examSparsity(); } /** * * @param m1 * @param m2 * @param ret * @throws DMLRuntimeException */ private static void matrixMultDenseSparse(MatrixBlock m1, MatrixBlock m2, MatrixBlock ret) throws DMLRuntimeException { //check inputs / outputs if( m1.isEmptyBlock(false) || m2.isEmptyBlock(false) ) return; ret.sparse = false; ret.allocateDenseBlock(); Arrays.fill(ret.denseBlock, 0, ret.denseBlock.length, 0); double[] a = m1.denseBlock; double[] c = ret.denseBlock; int m = m1.rlen; int n = m2.clen; int cd = m1.clen; // MATRIX-MATRIX (VV, MV not applicable here because V always dense) if( LOW_LEVEL_OPTIMIZATION ) { final int blocksizeI = 32; //256KB c block (typical L2 size per core), 32KB a block final int blocksizeK = 32; //note: in contrast to dense-dense, no blocking over j (would require maintaining blocksizeK indexes, counter-productive on skew) SparseRow[] b = m2.sparseRows; //blocked execution for( int bi = 0; bi < m; bi+=blocksizeI ) for( int bk = 0, bimin = Math.min(m, bi+blocksizeI); bk < cd; bk+=blocksizeK ) { int bklen = Math.min(cd, bk+blocksizeK)-bk; //core sub block matrix multiplication for( int i = bi; i < bimin; i++) { int aixi = i * cd + bk; //start index on a int cixj = i * n + 0; //scan index on c for( int k = 0; k < bklen; k++ ) { double val = a[aixi+k]; SparseRow brow = b[ bk+k ]; if( val != 0 && brow != null && !brow.isEmpty() ) { int blen = brow.size(); int[] bix = brow.getIndexContainer(); double[] bvals = brow.getValueContainer(); vectMultiplyAdd(val, bvals, c, bix, cixj, blen); } } } } } else { for( int i=0, aix=0, cix=0; i < m; i++, cix+=n ) for(int k = 0; k < cd; k++, aix++ ) { double val = a[aix]; if( val!=0 ) { SparseRow brow = m2.sparseRows[ k ]; if( brow != null && !brow.isEmpty() ) { int blen = brow.size(); int[] bix = brow.getIndexContainer(); double[] bvals = brow.getValueContainer(); for(int j = 0; j < blen; j++) c[cix+bix[j]] += val * bvals[j]; } } } } ret.recomputeNonZeros(); ret.examSparsity(); } /** * * @param m1 * @param m2 * @param ret * @throws DMLRuntimeException */ private static void matrixMultSparseDense(MatrixBlock m1, MatrixBlock m2, MatrixBlock ret) throws DMLRuntimeException { //check inputs / outputs if( m1.isEmptyBlock(false) || m2.isEmptyBlock(false) ) return; ret.sparse = false; ret.allocateDenseBlock(); double[] b = m2.denseBlock; double[] c = ret.denseBlock; final int m = m1.rlen; final int n = m2.clen; if( LOW_LEVEL_OPTIMIZATION ) { if( m==1 && n==1 ) //DOT PRODUCT { SparseRow arow = m1.sparseRows[0]; if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); c[0] = dotProduct(avals, b, aix, 0, alen); } } else if( n==1 ) //MATRIX-VECTOR { for( int i=0; i<Math.min(m, m1.sparseRows.length); i++ ) { SparseRow arow = m1.sparseRows[i]; if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); c[i] = dotProduct(avals, b, aix, 0, alen); } } } else //MATRIX-MATRIX { //init empty result Arrays.fill(c, 0, c.length, 0); for( int i=0, cix=0; i<Math.min(m, m1.sparseRows.length); i++, cix+=n ) { SparseRow arow = m1.sparseRows[i]; if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); if( alen==1 && avals[0]==1 ) //ROW SELECTION { //plain memcopy for permutation matrices System.arraycopy(b, aix[0]*n, c, cix, n); } else //GENERAL CASE { //rest not aligned to blocks of 4 rows final int bn = alen % 4; switch( bn ){ case 1: vectMultiplyAdd(avals[0], b, c, aix[0]*n, cix, n); break; case 2: vectMultiplyAdd2(avals[0],avals[1], b, c, aix[0]*n, aix[1]*n, cix, n); break; case 3: vectMultiplyAdd3(avals[0],avals[1],avals[2], b, c, aix[0]*n, aix[1]*n, aix[2]*n, cix, n); break; } //compute blocks of 4 rows (core inner loop) for( int k = bn; k<alen; k+=4 ) { vectMultiplyAdd4( avals[k], avals[k+1], avals[k+2], avals[k+3], b, c, aix[k]*n, aix[k+1]*n, aix[k+2]*n, aix[k+3]*n, cix, n ); } } } } } } else { //init empty result Arrays.fill(c, 0, c.length, 0); for( int i=0, cix=0; i<Math.min(m, m1.sparseRows.length); i++, cix+=n ) { SparseRow arow = m1.sparseRows[i]; if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); for(int k = 0; k < alen; k++) { double val = avals[k]; for(int j = 0, bix=aix[k]*n; j < n; j++) c[cix+j] += val * b[bix+j]; } } } } ret.recomputeNonZeros(); ret.examSparsity(); } /** * * @param m1 * @param m2 * @param ret * @throws DMLRuntimeException */ private static void matrixMultSparseSparse(MatrixBlock m1, MatrixBlock m2, MatrixBlock ret) throws DMLRuntimeException { //check inputs / outputs if( m1.isEmptyBlock(false) || m2.isEmptyBlock(false) ) return; ret.sparse=false; ret.allocateDenseBlock(); Arrays.fill(ret.denseBlock, 0, ret.denseBlock.length, 0); double[] c = ret.denseBlock; int m = m1.rlen; int n = m2.clen; // MATRIX-MATRIX (VV, MV not applicable here because V always dense) if(LOW_LEVEL_OPTIMIZATION) { for( int i=0, cix=0; i<Math.min(m, m1.sparseRows.length); i++, cix+=n ) { SparseRow arow = m1.sparseRows[i]; if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); for(int k = 0; k < alen; k++) { double val = avals[k]; SparseRow brow = m2.sparseRows[ aix[k] ]; if( brow != null && !brow.isEmpty() ) { int blen = brow.size(); int[] bix = brow.getIndexContainer(); double[] bvals = brow.getValueContainer(); vectMultiplyAdd(val, bvals, c, bix, cix, blen); } } } } } else { for( int i=0, cix=0; i<Math.min(m, m1.sparseRows.length); i++, cix+=n ) { SparseRow arow = m1.sparseRows[i]; if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); for(int k = 0; k < alen; k++) { double val = avals[k]; SparseRow brow = m2.sparseRows[ aix[k] ]; if( brow != null && !brow.isEmpty() ) { int blen = brow.size(); int[] bix = brow.getIndexContainer(); double[] bvals = brow.getValueContainer(); for(int j = 0; j < blen; j++) c[cix+bix[j]] += val * bvals[j]; } } } } } ret.recomputeNonZeros(); ret.examSparsity(); } /** * This implementation applies to any combination of dense/sparse if at least one * input is ultrasparse (sparse and very few nnz). In that case, most importantly, * we want to create a sparse output and only iterate over the few nnz as the major * dimension. Low-level optimization have less importance in that case and having * this generic implementation helps to reduce the implementations from (2+1)^2 * to 2^2+1. * * @param m1 * @param m2 * @param ret * @throws DMLRuntimeException */ private static void matrixMultUltraSparse(MatrixBlock m1, MatrixBlock m2, MatrixBlock ret) throws DMLRuntimeException { //check inputs / outputs if( m1.isEmptyBlock(false) || m2.isEmptyBlock(false) ) return; ret.sparse = true; ret.reset(); boolean leftUS = m1.isUltraSparse(); int m = m1.rlen; int cd = m1.clen; int n = m2.clen; if( leftUS ) //left is ultra-sparse (IKJ) { boolean rightSparse = m2.sparse; for( int i=0; i<m; i++ ) { SparseRow arow = m1.sparseRows[ i ]; if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aixs = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); if( alen==1 && avals[0]==1 ) //ROW SELECTION (no aggregation) { int aix = aixs[0]; if( rightSparse ) { //sparse right matrix (full row copy) if( m2.sparseRows!=null && m2.sparseRows[aix]!=null ) { ret.rlen=m; ret.allocateSparseRowsBlock(false); //allocation on demand ret.sparseRows[i] = new SparseRow(m2.sparseRows[aix]); ret.nonZeros += ret.sparseRows[i].size(); } } else { //dense right matrix (append all values) for( int j=0; j<n; j++ ) ret.appendValue(i, j, m2.quickGetValue(aix, j)); } } else //GENERAL CASE { for( int k=0; k<alen; k++ ) { double aval = avals[k]; int aix = aixs[k]; for( int j=0; j<n; j++ ) { double cval = ret.quickGetValue(i, j); double cvald = aval*m2.quickGetValue(aix, j); if( cvald != 0 ) ret.quickSetValue(i, j, cval+cvald); } } } } } } else //right is ultra-sparse (KJI) { for(int k = 0; k < cd; k++ ) { SparseRow brow = m2.sparseRows[ k ]; if( brow != null && !brow.isEmpty() ) { int blen = brow.size(); int[] bixs = brow.getIndexContainer(); double[] bvals = brow.getValueContainer(); for( int j=0; j<blen; j++ ) { double bval = bvals[j]; int bix = bixs[j]; for( int i=0; i<m; i++ ) { double cvald = bval*m1.quickGetValue(i, k); if( cvald != 0 ){ double cval = ret.quickGetValue(i, bix); ret.quickSetValue(i, bix, cval+cvald); } } } } } } //check if sparse output if correct //no need to recompute nonzeros because maintained internally ret.examSparsity(); } /** * * @param mX * @param mV * @param mW * @param ret * @param ct * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ private static void matrixMultChainDense(MatrixBlock mX, MatrixBlock mV, MatrixBlock mW, MatrixBlock ret, ChainType ct) throws DMLRuntimeException, DMLUnsupportedOperationException { //check inputs / outputs (after that mV and mW guaranteed to be dense) if( mX.isEmptyBlock(false) || mV.isEmptyBlock(false) || (mW !=null && mW.isEmptyBlock(false)) ) return; ret.sparse = false; ret.allocateDenseBlock(); double[] a = mX.denseBlock; double[] b = mV.denseBlock; double[] w = (mW!=null) ? mW.denseBlock : null; double[] c = ret.denseBlock; final int m = mX.rlen; //rows in X final int cd = mX.clen; //features in X boolean weights = (ct == ChainType.XtwXv); Arrays.fill(c, 0, c.length, 0); //temporary array for cache blocking //(blocksize chosen to fit b+v in L2 (256KB) for default 1k blocks) final int blocksize = 24; //constraint: factor of 4 double[] tmp = new double[blocksize]; //blockwise mmchain computation final int bn = m - m % blocksize; for( int bi=0; bi < bn; bi+=blocksize ) { //compute 1st matrix-vector for row block for( int j=0, aix=bi*cd; j < blocksize; j++, aix+=cd) tmp[j] = dotProduct(a, b, aix, 0, cd); //multiply weights (in-place), if required if( weights ) vectMultiply(w, tmp, bi, 0, blocksize); //compute 2nd matrix vector for row block and aggregate for (int j=0, aix=bi*cd; j < blocksize; j+=4, aix+=4*cd) vectMultiplyAdd4(tmp[j], tmp[j+1], tmp[j+2], tmp[j+3], a, c, aix, aix+cd, aix+2*cd, aix+3*cd, 0, cd); } //compute rest (not aligned to blocksize) for( int i=bn, aix=i*cd; i < m; i++, aix+=cd ) { double val = dotProduct(a, b, aix, 0, cd); val *= (weights) ? w[i] : 1; vectMultiplyAdd(val, a, c, aix, 0, cd); } ret.recomputeNonZeros(); ret.examSparsity(); } /** * * @param mX * @param mV * @param mW * @param ret * @param ct * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ private static void matrixMultChainSparse(MatrixBlock mX, MatrixBlock mV, MatrixBlock mW, MatrixBlock ret, ChainType ct) throws DMLRuntimeException, DMLUnsupportedOperationException { //check inputs / outputs (after that mV and mW guaranteed to be dense) if( mX.isEmptyBlock(false) || mV.isEmptyBlock(false) || (mW !=null && mW.isEmptyBlock(false)) ) return; ret.sparse = false; ret.allocateDenseBlock(); SparseRow[] a = mX.sparseRows; double[] b = mV.denseBlock; double[] w = (mW!=null) ? mW.denseBlock : null; double[] c = ret.denseBlock; final int m = mX.rlen; boolean weights = (ct == ChainType.XtwXv); Arrays.fill(c, 0, c.length, 0); //temporary array for cache blocking //(blocksize chosen to fit b+v in L2 (256KB) for default 1k blocks) final int blocksize = 24; double[] tmp = new double[blocksize]; //blockwise mmchain computation for( int bi=0; bi < m; bi+=blocksize ) { //reset row block intermediate int tmplen = Math.min(blocksize, m-bi); //compute 1st matrix-vector for row block for( int j=0; j < tmplen; j++) { SparseRow arow = a[bi+j]; if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); tmp[j] = dotProduct(avals, b, aix, 0, alen); } } //multiply weights (in-place), if required if( weights ) vectMultiply(w, tmp, bi, 0, tmplen); //compute 2nd matrix vector for row block and aggregate for( int j=0; j < tmplen; j++) { SparseRow arow = a[bi+j]; if( arow != null && !arow.isEmpty() && tmp[j] != 0 ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); vectMultiplyAdd(tmp[j], avals, c, aix, 0, alen); } } } ret.recomputeNonZeros(); ret.examSparsity(); } /** * * @param m1 * @param ret * @param leftTranspose * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ private static void matrixMultTransposeSelfDense( MatrixBlock m1, MatrixBlock ret, boolean leftTranspose ) throws DMLRuntimeException, DMLUnsupportedOperationException { //1) allocate output block ret.rlen = leftTranspose ? m1.clen : m1.rlen; ret.clen = leftTranspose ? m1.clen : m1.rlen; ret.sparse = false; ret.allocateDenseBlock(); if( m1.denseBlock == null ) return; //2) transpose self matrix multiply dense // (compute only upper-triangular matrix due to symmetry) double[] a = m1.denseBlock; double[] c = ret.denseBlock; int m = m1.rlen; int n = m1.clen; if( leftTranspose ) // t(X)%*%X { if( LOW_LEVEL_OPTIMIZATION ) { if( n==1 ) //VECTOR (col) { c[0] = dotProduct(a, a, m); } else //MATRIX { //init empty result Arrays.fill(c, 0, c.length, 0); //1) Unrolled inner loop (for better instruction-level parallelism) //2) Blocked execution (for less cache trashing in parallel exec) //3) Asymmetric block sizes (for less misses in inner loop, yet blocks in L1/L2) final int blocksizeI = 32; //64//256KB c block (typical L2 size per core), 32KB a block final int blocksizeK = 24; //64//256KB b block (typical L2 size per core), used while read 512B of a / read/write 4KB of c final int blocksizeJ = 1024; //512//4KB (typical main-memory page size), for scan //temporary arrays (nnz a, b index) double[] ta = new double[ blocksizeK ]; int[] tbi = new int[ blocksizeK ]; final int mx = n; final int cdx = m; final int nx = n; //blocked execution for( int bi = 0; bi < mx; bi+=blocksizeI ) //from bi due to symmetry for( int bk = 0, bimin = Math.min(mx, bi+blocksizeI); bk < cdx; bk+=blocksizeK ) for( int bj = bi, bkmin = Math.min(cdx, bk+blocksizeK); bj < nx; bj+=blocksizeJ ) { int bklen = bkmin-bk; int bjlen = Math.min(nx, bj+blocksizeJ)-bj; //core sub block matrix multiplication for( int i = bi; i < bimin; i++) { int aixi = bk*n +i; //start index on a (logical t(X)) int cixj = i * nx + bj; //scan index on c //determine nnz of a (for sparsity-aware skipping of rows) int knnz = copyNonZeroElements(a, aixi, bk, bj, n, nx, ta, tbi, bklen); //rest not aligned to blocks of 4 rows final int bn = knnz % 4; switch( bn ){ case 1: vectMultiplyAdd(ta[0], a, c, tbi[0], cixj, bjlen); break; case 2: vectMultiplyAdd2(ta[0],ta[1], a, c, tbi[0], tbi[1], cixj, bjlen); break; case 3: vectMultiplyAdd3(ta[0],ta[1],ta[2], a, c, tbi[0], tbi[1],tbi[2], cixj, bjlen); break; } //compute blocks of 4 rows (core inner loop) for( int k = bn; k<knnz; k+=4 ){ vectMultiplyAdd4( ta[k], ta[k+1], ta[k+2], ta[k+3], a, c, tbi[k], tbi[k+1], tbi[k+2], tbi[k+3], cixj, bjlen ); } } } } } else { //init empty result Arrays.fill(c, 0, c.length, 0); for(int k = 0, ix1 = 0; k < m; k++, ix1+=n) for(int i = 0, ix3 = 0; i < n; i++, ix3+=n) { double val = a[ ix1+i ]; if( val != 0 ) { for(int j = i; j < n; j++) //from i due to symmetry c[ ix3+j ] += val * a[ ix1+j ]; } } } } else // X%*%t(X) { if(LOW_LEVEL_OPTIMIZATION) { if( m==1 ) //VECTOR { c[0] = dotProduct(a, a, n); } else //MATRIX { //init empty result Arrays.fill(c, 0, c.length, 0); //algorithm: scan c, foreach ci,j: scan row of a and t(a) (IJK) //1) Unrolled inner loop, for better ILP //2) Blocked execution, for less cache trashing in parallel exec // (smaller block sizes would be slightly better, but consistent as is) //3) Single write in inner loop (transient intermediates) int blocksize = 64; for( int bi = 0; bi<m; bi+=blocksize ) for( int bj = bi; bj<m; bj+=blocksize ) { final int bimin = Math.min(m, bi+blocksize); final int bjmin = Math.min(m, bj+blocksize); for(int i = bi, ix1 = bi*n, ix3 = bi*m; i < bimin; i++, ix1+=n, ix3+=m) { final int bjmax = Math.max(i,bj); for(int j = bjmax, ix2 = bjmax*n; j <bjmin; j++, ix2+=n) //from i due to symmetry { c[ ix3+j ] = dotProduct(a, a, ix1, ix2, n); } } } } } else { for(int i = 0, ix1 = 0, ix3 = 0; i < m; i++, ix1+=n, ix3+=m) for(int j = i, ix2 = i*n; j < m; j++, ix2+=n) //from i due to symmetry { double val = 0; for(int k = 0; k < n; k++) val += a[ ix1+k ] * a[ix2+k]; c[ ix3+j ] = val; } } } //3) copy symmetric values copyUpperToLowerTriangle( ret ); ret.recomputeNonZeros(); ret.examSparsity(); } /** * * @param out * @param leftTranspose * @throws DMLUnsupportedOperationException * @throws DMLRuntimeException */ private static void matrixMultTransposeSelfSparse( MatrixBlock m1, MatrixBlock ret, boolean leftTranspose ) throws DMLUnsupportedOperationException, DMLRuntimeException { //1) allocate output block ret.rlen = leftTranspose ? m1.clen : m1.rlen; ret.clen = leftTranspose ? m1.clen : m1.rlen; ret.sparse = false; //assumption dense output if( m1.sparseRows == null ) return; ret.allocateDenseBlock(); //2) transpose self matrix multiply sparse // (compute only upper-triangular matrix due to symmetry) double[] c = ret.denseBlock; int m = m1.rlen; int n = m1.clen; if( leftTranspose ) // t(X)%*%X { //init empty result Arrays.fill(c, 0, c.length, 0); //only general case (because vectors always dense) //algorithm: scan rows, foreach row self join (KIJ) if( LOW_LEVEL_OPTIMIZATION ) { for( SparseRow arow : m1.sparseRows ) if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); for(int i = 0; i < alen; i++) { double val = avals[i]; if( val != 0 ) { int ix2 = aix[i]*n; vectMultiplyAdd(val, avals, c, aix, i, ix2, alen); } } } } else { for( SparseRow arow : m1.sparseRows ) if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); for(int i = 0; i < alen; i++) { double val = avals[i]; if( val != 0 ) for(int j = i, ix2 = aix[i]*n; j < alen; j++) c[ix2+aix[j]] += val * avals[j]; } } } } else // X%*%t(X) { if( m==1 ) //VECTOR { SparseRow arow = m1.sparseRows[0]; if( arow !=null && !arow.isEmpty() ) { int alen = arow.size(); double[] avals = arow.getValueContainer(); c[0] = dotProduct(avals, avals, alen); } } else //MATRIX { //init empty result Arrays.fill(c, 0, c.length, 0); //note: reorg to similar layout as t(X)%*%X because faster than //direct computation with IJK (no dependencies/branches in inner loop) MatrixBlock tmpBlock = new MatrixBlock(n,m,m1.sparse); m1.reorgOperations(new ReorgOperator(SwapIndex.getSwapIndexFnObject()), tmpBlock, 0, 0, -1); if( tmpBlock.sparseRows == null ) return; //algorithm: scan rows, foreach row self join (KIJ) if( LOW_LEVEL_OPTIMIZATION ) { for( SparseRow arow : tmpBlock.sparseRows ) if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); for(int i = 0; i < alen; i++) { double val = avals[i]; if( val != 0 ) { int ix2 = aix[i]*m; vectMultiplyAdd(val, avals, c, aix, i, ix2, alen); } } } } else { for( SparseRow arow : tmpBlock.sparseRows ) if( arow != null && !arow.isEmpty() ) { int alen = arow.size(); int[] aix = arow.getIndexContainer(); double[] avals = arow.getValueContainer(); for(int i = 0; i < alen; i++) { double val = avals[i]; if( val != 0 ) for(int j = i, ix2 = aix[i]*m; j < alen; j++) c[ix2+aix[j]] += val * avals[j]; } } } } } //3) copy symmetric values copyUpperToLowerTriangle( ret ); ret.recomputeNonZeros(); ret.examSparsity(); } /** * * @param pm1 * @param m2 * @param ret1 * @param ret2 * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ private static void matrixMultPermuteDense( MatrixBlock pm1, MatrixBlock m2, MatrixBlock ret1, MatrixBlock ret2 ) throws DMLRuntimeException, DMLUnsupportedOperationException { //check inputs / outputs if( pm1.isEmptyBlock(false) || m2.isEmptyBlock(false) ) return; //allocate first output block (second allocated if needed) ret1.sparse = false; ret1.allocateDenseBlock(); double[] a = pm1.denseBlock; double[] b = m2.denseBlock; double[] c = ret1.denseBlock; final int m = pm1.rlen; final int n = m2.clen; final int brlen = ret1.getNumRows(); int lastblk = -1; for( int i=0, bix=0; i<m; i++, bix+=n ) { //compute block index and in-block indexes int pos = UtilFunctions.toInt( a[ i ]); //safe cast if( pos > 0 ) //selected row { int bpos = (pos-1) % brlen; int blk = (pos-1) / brlen; //allocate and switch to second output block if( lastblk!=-1 && lastblk<blk ){ ret2.sparse = false; ret2.allocateDenseBlock(); c = ret2.denseBlock; } //memcopy entire dense row into target position System.arraycopy(b, bix, c, bpos*n, n); lastblk = blk; } } ret1.recomputeNonZeros(); ret1.examSparsity(); if( ret2 != null ) { //optional second output ret2.recomputeNonZeros(); ret2.examSparsity(); } } /** * * @param pm1 * @param m2 * @param ret1 * @param ret2 * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ private static void matrixMultPermuteDenseSparse( MatrixBlock pm1, MatrixBlock m2, MatrixBlock ret1, MatrixBlock ret2 ) throws DMLRuntimeException, DMLUnsupportedOperationException { //check inputs / outputs if( pm1.isEmptyBlock(false) || m2.isEmptyBlock(false) ) return; //allocate first output block (second allocated if needed) ret1.sparse = true; ret1.allocateSparseRowsBlock(); double[] a = pm1.denseBlock; double[] b = m2.denseBlock; SparseRow[] c = ret1.sparseRows; final int m = pm1.rlen; final int n = m2.clen; final int brlen = ret1.getNumRows(); int lastblk = -1; for( int i=0, bix=0; i<m; i++, bix+=n ) { //compute block index and in-block indexes int pos = UtilFunctions.toInt( a[ i ]); //safe cast if( pos > 0 ) //selected row { int bpos = (pos-1) % brlen; int blk = (pos-1) / brlen; //allocate and switch to second output block if( lastblk!=-1 && lastblk<blk ){ ret2.sparse = true; ret2.rlen=ret1.rlen; ret2.allocateSparseRowsBlock(); c = ret2.sparseRows; } //append entire dense row into sparse target position c[bpos] = new SparseRow( n ); for( int j=0; j<n; j++ ) c[bpos].append(j, b[bix+j]); lastblk = blk; } } ret1.recomputeNonZeros(); ret1.examSparsity(); if( ret2 != null ) { //optional second output ret2.recomputeNonZeros(); ret2.examSparsity(); } } /** * * @param pm1 * @param m2 * @param ret1 * @param ret2 * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ private static void matrixMultPermuteSparse( MatrixBlock pm1, MatrixBlock m2, MatrixBlock ret1, MatrixBlock ret2 ) throws DMLRuntimeException, DMLUnsupportedOperationException { //check inputs / outputs if( pm1.isEmptyBlock(false) || m2.isEmptyBlock(false) ) return; //allocate first output block (second allocated if needed) ret1.sparse = true; ret1.allocateSparseRowsBlock(); double[] a = pm1.denseBlock; SparseRow[] b = m2.sparseRows; SparseRow[] c = ret1.sparseRows; final int m = pm1.rlen; final int brlen = ret1.getNumRows(); int lastblk = -1; for( int i=0; i<m; i++ ) { //compute block index and in-block indexes int pos = UtilFunctions.toInt( a[ i ]); //safe cast if( pos > 0 ) //selected row { int bpos = (pos-1) % brlen; int blk = (pos-1) / brlen; //allocate and switch to second output block if( lastblk!=-1 && lastblk<blk ){ ret2.sparse = true; ret2.allocateSparseRowsBlock(); c = ret2.sparseRows; } //memcopy entire sparse row into target position if( b[i] != null ) c[bpos] = new SparseRow( b[i] ); lastblk = blk; } } ret1.recomputeNonZeros(); ret1.examSparsity(); if( ret2 != null ) { //optional second output ret2.recomputeNonZeros(); ret2.examSparsity(); } } //////////////////////////////////////////// // performance-relevant utility functions // //////////////////////////////////////////// /** * Computes the dot-product of two vectors. Experiments (on long vectors of * 10^7 values) showed that this generic function provides equivalent performance * even for the specific case of dotProduct(a,a,len) as used for TSMM. * * @param a * @param b * @param len * @return */ private static double dotProduct( double[] a, double[] b, final int len ) { double val = 0; final int bn = len%8; //compute rest for( int i = 0; i < bn; i++ ) val += a[ i ] * b[ i ]; //unrolled 8-block (for better instruction-level parallelism) for( int i = bn; i < len; i+=8 ) { //read 64B cachelines of a and b //compute cval' = sum(a * b) + cval val += a[ i+0 ] * b[ i+0 ] + a[ i+1 ] * b[ i+1 ] + a[ i+2 ] * b[ i+2 ] + a[ i+3 ] * b[ i+3 ] + a[ i+4 ] * b[ i+4 ] + a[ i+5 ] * b[ i+5 ] + a[ i+6 ] * b[ i+6 ] + a[ i+7 ] * b[ i+7 ]; } //scalar result return val; } /** * * @param a * @param b * @param ai * @param bi * @param len * @return */ private static double dotProduct( double[] a, double[] b, int ai, int bi, final int len ) { double val = 0; final int bn = len%8; //compute rest for( int i = 0; i < bn; i++, ai++, bi++ ) val += a[ ai ] * b[ bi ]; //unrolled 8-block (for better instruction-level parallelism) for( int i = bn; i < len; i+=8, ai+=8, bi+=8 ) { //read 64B cachelines of a and b //compute cval' = sum(a * b) + cval val += a[ ai+0 ] * b[ bi+0 ] + a[ ai+1 ] * b[ bi+1 ] + a[ ai+2 ] * b[ bi+2 ] + a[ ai+3 ] * b[ bi+3 ] + a[ ai+4 ] * b[ bi+4 ] + a[ ai+5 ] * b[ bi+5 ] + a[ ai+6 ] * b[ bi+6 ] + a[ ai+7 ] * b[ bi+7 ]; } //scalar result return val; } private static double dotProduct( double[] a, double[] b, int[] aix, final int bi, final int len ) { double val = 0; final int bn = len%8; //compute rest for( int i = 0; i < bn; i++ ) val += a[ i ] * b[ bi+aix[i] ]; //unrolled 8-block (for better instruction-level parallelism) for( int i = bn; i < len; i+=8 ) { //read 64B cacheline of a //read 64B of b via 'gather' //compute cval' = sum(a * b) + cval val += a[ i+0 ] * b[ bi+aix[i+0] ] + a[ i+1 ] * b[ bi+aix[i+1] ] + a[ i+2 ] * b[ bi+aix[i+2] ] + a[ i+3 ] * b[ bi+aix[i+3] ] + a[ i+4 ] * b[ bi+aix[i+4] ] + a[ i+5 ] * b[ bi+aix[i+5] ] + a[ i+6 ] * b[ bi+aix[i+6] ] + a[ i+7 ] * b[ bi+aix[i+7] ]; } //scalar result return val; } /** * * @param aval * @param b * @param c * @param bi * @param ci * @param len */ private static void vectMultiplyAdd( final double aval, double[] b, double[] c, int bi, int ci, final int len ) { final int bn = len%8; //rest, not aligned to 8-blocks for( int j = 0; j < bn; j++, bi++, ci++) c[ ci ] += aval * b[ bi ]; //unrolled 8-block (for better instruction-level parallelism) for( int j = bn; j < len; j+=8, bi+=8, ci+=8) { //read 64B cachelines of b and c //compute c' = aval * b + c //write back 64B cacheline of c = c' c[ ci+0 ] += aval * b[ bi+0 ]; c[ ci+1 ] += aval * b[ bi+1 ]; c[ ci+2 ] += aval * b[ bi+2 ]; c[ ci+3 ] += aval * b[ bi+3 ]; c[ ci+4 ] += aval * b[ bi+4 ]; c[ ci+5 ] += aval * b[ bi+5 ]; c[ ci+6 ] += aval * b[ bi+6 ]; c[ ci+7 ] += aval * b[ bi+7 ]; } } /** * * @param aval1 * @param aval2 * @param b * @param c * @param bi * @param bi2 * @param ci * @param len */ private static void vectMultiplyAdd2( final double aval1, final double aval2, double[] b, double[] c, int bi1, int bi2, int ci, final int len ) { final int bn = len%8; //rest, not aligned to 8-blocks for( int j = 0; j < bn; j++, bi1++, bi2++, ci++ ) c[ ci ] += aval1 * b[ bi1 ] + aval2 * b[ bi2 ]; //unrolled 8-block (for better instruction-level parallelism) for( int j = bn; j < len; j+=8, bi1+=8, bi2+=8, ci+=8 ) { //read 64B cachelines of b (2x) and c //compute c' = aval_1 * b_1 + aval_2 * b_2 + c //write back 64B cacheline of c = c' c[ ci+0 ] += aval1 * b[ bi1+0 ] + aval2 * b[ bi2+0 ]; c[ ci+1 ] += aval1 * b[ bi1+1 ] + aval2 * b[ bi2+1 ]; c[ ci+2 ] += aval1 * b[ bi1+2 ] + aval2 * b[ bi2+2 ]; c[ ci+3 ] += aval1 * b[ bi1+3 ] + aval2 * b[ bi2+3 ]; c[ ci+4 ] += aval1 * b[ bi1+4 ] + aval2 * b[ bi2+4 ]; c[ ci+5 ] += aval1 * b[ bi1+5 ] + aval2 * b[ bi2+5 ]; c[ ci+6 ] += aval1 * b[ bi1+6 ] + aval2 * b[ bi2+6 ]; c[ ci+7 ] += aval1 * b[ bi1+7 ] + aval2 * b[ bi2+7 ]; } } /** * * @param aval1 * @param aval2 * @param aval3 * @param b * @param c * @param bi1 * @param bi2 * @param bi3 * @param ci * @param len */ private static void vectMultiplyAdd3( final double aval1, final double aval2, final double aval3, double[] b, double[] c, int bi1, int bi2, int bi3, int ci, final int len ) { final int bn = len%8; //rest, not aligned to 8-blocks for( int j = 0; j < bn; j++, bi1++, bi2++, bi3++, ci++ ) c[ ci ] += aval1 * b[ bi1 ] + aval2 * b[ bi2 ] + aval3 * b[ bi3 ]; //unrolled 8-block (for better instruction-level parallelism) for( int j = bn; j < len; j+=8, bi1+=8, bi2+=8, bi3+=8, ci+=8 ) { //read 64B cachelines of b (3x) and c //compute c' = aval_1 * b_1 + aval_2 * b_2 + c //write back 64B cacheline of c = c' c[ ci+0 ] += aval1 * b[ bi1+0 ] + aval2 * b[ bi2+0 ] + aval3 * b[ bi3+0 ]; c[ ci+1 ] += aval1 * b[ bi1+1 ] + aval2 * b[ bi2+1 ] + aval3 * b[ bi3+1 ]; c[ ci+2 ] += aval1 * b[ bi1+2 ] + aval2 * b[ bi2+2 ] + aval3 * b[ bi3+2 ]; c[ ci+3 ] += aval1 * b[ bi1+3 ] + aval2 * b[ bi2+3 ] + aval3 * b[ bi3+3 ]; c[ ci+4 ] += aval1 * b[ bi1+4 ] + aval2 * b[ bi2+4 ] + aval3 * b[ bi3+4 ]; c[ ci+5 ] += aval1 * b[ bi1+5 ] + aval2 * b[ bi2+5 ] + aval3 * b[ bi3+5 ]; c[ ci+6 ] += aval1 * b[ bi1+6 ] + aval2 * b[ bi2+6 ] + aval3 * b[ bi3+6 ]; c[ ci+7 ] += aval1 * b[ bi1+7 ] + aval2 * b[ bi2+7 ] + aval3 * b[ bi3+7 ]; } } /** * * @param aval1 * @param aval2 * @param aval3 * @param aval4 * @param b * @param c * @param bi1 * @param bi2 * @param bi3 * @param bi4 * @param ci * @param len */ private static void vectMultiplyAdd4( final double aval1, final double aval2, final double aval3, final double aval4, double[] b, double[] c, int bi1, int bi2, int bi3, int bi4, int ci, final int len ) { final int bn = len%8; //rest, not aligned to 8-blocks for( int j = 0; j < bn; j++, bi1++, bi2++, bi3++, bi4++, ci++ ) c[ ci ] += aval1 * b[ bi1 ] + aval2 * b[ bi2 ] + aval3 * b[ bi3 ] + aval4 * b[ bi4 ]; //unrolled 8-block (for better instruction-level parallelism) for( int j = bn; j < len; j+=8, bi1+=8, bi2+=8, bi3+=8, bi4+=8, ci+=8) { //read 64B cachelines of b (4x) and c //compute c' = aval_1 * b_1 + aval_2 * b_2 + c //write back 64B cacheline of c = c' c[ ci+0 ] += aval1 * b[ bi1+0 ] + aval2 * b[ bi2+0 ] + aval3 * b[ bi3+0 ] + aval4 * b[ bi4+0 ]; c[ ci+1 ] += aval1 * b[ bi1+1 ] + aval2 * b[ bi2+1 ] + aval3 * b[ bi3+1 ] + aval4 * b[ bi4+1 ]; c[ ci+2 ] += aval1 * b[ bi1+2 ] + aval2 * b[ bi2+2 ] + aval3 * b[ bi3+2 ] + aval4 * b[ bi4+2 ]; c[ ci+3 ] += aval1 * b[ bi1+3 ] + aval2 * b[ bi2+3 ] + aval3 * b[ bi3+3 ] + aval4 * b[ bi4+3 ]; c[ ci+4 ] += aval1 * b[ bi1+4 ] + aval2 * b[ bi2+4 ] + aval3 * b[ bi3+4 ] + aval4 * b[ bi4+4 ]; c[ ci+5 ] += aval1 * b[ bi1+5 ] + aval2 * b[ bi2+5 ] + aval3 * b[ bi3+5 ] + aval4 * b[ bi4+5 ]; c[ ci+6 ] += aval1 * b[ bi1+6 ] + aval2 * b[ bi2+6 ] + aval3 * b[ bi3+6 ] + aval4 * b[ bi4+6 ]; c[ ci+7 ] += aval1 * b[ bi1+7 ] + aval2 * b[ bi2+7 ] + aval3 * b[ bi3+7 ] + aval4 * b[ bi4+7 ]; } } /** * * @param aval * @param b * @param c * @param bix * @param ci * @param len */ private static void vectMultiplyAdd( final double aval, double[] b, double[] c, int[] bix, final int ci, final int len ) { final int bn = len%8; //rest, not aligned to 8-blocks for( int j = 0; j < bn; j++ ) c[ ci + bix[j] ] += aval * b[ j ]; //unrolled 8-block (for better instruction-level parallelism) for( int j = bn; j < len; j+=8 ) { //read 64B cacheline of b //read 64B of c via 'gather' //compute c' = aval * b + c //write back 64B of c = c' via 'scatter' c[ ci+bix[j+0] ] += aval * b[ j+0 ]; c[ ci+bix[j+1] ] += aval * b[ j+1 ]; c[ ci+bix[j+2] ] += aval * b[ j+2 ]; c[ ci+bix[j+3] ] += aval * b[ j+3 ]; c[ ci+bix[j+4] ] += aval * b[ j+4 ]; c[ ci+bix[j+5] ] += aval * b[ j+5 ]; c[ ci+bix[j+6] ] += aval * b[ j+6 ]; c[ ci+bix[j+7] ] += aval * b[ j+7 ]; } } private static void vectMultiplyAdd( final double aval, double[] b, double[] c, int[] bix, final int bi, final int ci, final int len ) { final int bn = (len-bi)%8; //rest, not aligned to 8-blocks for( int j = bi; j < bi+bn; j++ ) c[ ci + bix[j] ] += aval * b[ j ]; //unrolled 8-block (for better instruction-level parallelism) for( int j = bi+bn; j < len; j+=8 ) { //read 64B cacheline of b //read 64B of c via 'gather' //compute c' = aval * b + c //write back 64B of c = c' via 'scatter' c[ ci+bix[j+0] ] += aval * b[ j+0 ]; c[ ci+bix[j+1] ] += aval * b[ j+1 ]; c[ ci+bix[j+2] ] += aval * b[ j+2 ]; c[ ci+bix[j+3] ] += aval * b[ j+3 ]; c[ ci+bix[j+4] ] += aval * b[ j+4 ]; c[ ci+bix[j+5] ] += aval * b[ j+5 ]; c[ ci+bix[j+6] ] += aval * b[ j+6 ]; c[ ci+bix[j+7] ] += aval * b[ j+7 ]; } } /** * * @param aval * @param b * @param c * @param bi * @param ci * @param len */ private static void vectMultiplyWrite( final double aval, double[] b, double[] c, int bi, int ci, final int len ) { final int bn = len%8; //rest, not aligned to 8-blocks for( int j = 0; j < bn; j++, bi++, ci++) c[ ci ] = aval * b[ bi ]; //unrolled 8-block (for better instruction-level parallelism) for( int j = bn; j < len; j+=8, bi+=8, ci+=8) { //read 64B cachelines of b and c //compute c' = aval * b + c //write back 64B cacheline of c = c' c[ ci+0 ] = aval * b[ bi+0 ]; c[ ci+1 ] = aval * b[ bi+1 ]; c[ ci+2 ] = aval * b[ bi+2 ]; c[ ci+3 ] = aval * b[ bi+3 ]; c[ ci+4 ] = aval * b[ bi+4 ]; c[ ci+5 ] = aval * b[ bi+5 ]; c[ ci+6 ] = aval * b[ bi+6 ]; c[ ci+7 ] = aval * b[ bi+7 ]; } } /** * * @param a * @param b * @param c * @param ai * @param bi * @param ci * @param len */ @SuppressWarnings("unused") private static void vectMultiplyWrite( double[] a, double[] b, double[] c, int ai, int bi, int ci, final int len ) { final int bn = len%8; //rest, not aligned to 8-blocks for( int j = 0; j < bn; j++, ai++, bi++, ci++) c[ ci ] = a[ ai ] * b[ bi ]; //unrolled 8-block (for better instruction-level parallelism) for( int j = bn; j < len; j+=8, ai+=8, bi+=8, ci+=8) { //read 64B cachelines of a and b //compute c' = a * b //write back 64B cacheline of c = c' c[ ci+0 ] = a[ ai+0 ] * b[ bi+0 ]; c[ ci+1 ] = a[ ai+1 ] * b[ bi+1 ]; c[ ci+2 ] = a[ ai+2 ] * b[ bi+2 ]; c[ ci+3 ] = a[ ai+3 ] * b[ bi+3 ]; c[ ci+4 ] = a[ ai+4 ] * b[ bi+4 ]; c[ ci+5 ] = a[ ai+5 ] * b[ bi+5 ]; c[ ci+6 ] = a[ ai+6 ] * b[ bi+6 ]; c[ ci+7 ] = a[ ai+7 ] * b[ bi+7 ]; } } private static void vectMultiply( double[] a, double[] c, int ai, int ci, final int len ) { final int bn = len%8; //rest, not aligned to 8-blocks for( int j = 0; j < bn; j++, ai++, ci++) c[ ci ] *= a[ ai ]; //unrolled 8-block (for better instruction-level parallelism) for( int j = bn; j < len; j+=8, ai+=8, ci+=8) { //read 64B cachelines of a and c //compute c' = c * a //write back 64B cacheline of c = c' c[ ci+0 ] *= a[ ai+0 ]; c[ ci+1 ] *= a[ ai+1 ]; c[ ci+2 ] *= a[ ai+2 ]; c[ ci+3 ] *= a[ ai+3 ]; c[ ci+4 ] *= a[ ai+4 ]; c[ ci+5 ] *= a[ ai+5 ]; c[ ci+6 ] *= a[ ai+6 ]; c[ ci+7 ] *= a[ ai+7 ]; } } /** * Used for all version of TSMM where the result is known to be symmetric. * Hence, we compute only the upper triangular matrix and copy this partial * result down to lower triangular matrix once. * * @param ret */ private static void copyUpperToLowerTriangle( MatrixBlock ret ) { double[] c = ret.denseBlock; final int m = ret.rlen; final int n = ret.clen; //copy symmetric values for( int i=0, uix=0; i<m; i++, uix+=n ) for( int j=i+1, lix=j*n+i; j<n; j++, lix+=n ) c[ lix ] = c[ uix+j ]; } /** * * @param a * @param aixi * @param bk * @param bj * @param n * @param tmpa * @param tmpbi * @param bklen * @return */ private static int copyNonZeroElements( double[] a, final int aixi, final int bk, final int bj, final int n, double[] tmpa, int[] tmpbi, final int bklen ) { int knnz = 0; for( int k = 0; k < bklen; k++ ) if( a[ aixi+k ] != 0 ) { tmpa[ knnz ] = a[ aixi+k ]; tmpbi[ knnz ] = (bk+k) * n + bj; //scan index on b knnz ++; } return knnz; } /** * * @param a * @param aixi * @param bk * @param bj * @param n * @param nx * @param tmpa * @param tmpbi * @param bklen * @return */ private static int copyNonZeroElements( double[] a, int aixi, final int bk, final int bj, final int n, final int nx, double[] tmpa, int[] tmpbi, final int bklen ) { int knnz = 0; for( int k = 0; k < bklen; k++, aixi+=n ) if( a[ aixi ] != 0 ) { tmpa[ knnz ] = a[ aixi ]; tmpbi[ knnz ] = (bk+k) * nx + bj; //scan index on b knnz ++; } return knnz; } /* public static void matrixMult(MatrixBlockDSM m1, MatrixBlockDSM m2, MatrixBlockDSM ret, int k) throws DMLRuntimeException { //Timing time = new Timing(true); if(!m1.sparse && !m2.sparse) matrixMultDenseDense(m1, m2, ret, k); else throw new DMLRuntimeException("Not implemented yet."); //System.out.println("MM("+k+") ("+m1.isInSparseFormat()+","+m1.getNumRows()+","+m1.getNumColumns()+","+m1.getNonZeros()+")x" + // "("+m2.isInSparseFormat()+","+m2.getNumRows()+","+m2.getNumColumns()+","+m2.getNonZeros()+") in "+time.stop()); } */ /* private static void matrixMultDenseDense(MatrixBlockDSM m1, MatrixBlockDSM m2, MatrixBlockDSM ret, int k) throws DMLRuntimeException { //check inputs / outputs if( m1.denseBlock==null || m2.denseBlock==null ) return; ret.sparse = false; if( ret.denseBlock==null ) ret.denseBlock = new double[ret.rlen * ret.clen]; double[] a = m1.denseBlock; double[] b = m2.denseBlock; double[] c = ret.denseBlock; final int m = m1.rlen; final int n = m2.clen; final int cd = m1.clen; final int blocksizeI = 32; //64//256KB c block (typical L2 size per core), 32KB a block //init empty result Arrays.fill(c, 0, c.length, 0); try { int blk = (m/k)+((m/k)%blocksizeI); Thread[] t = new Thread[k]; for( int i=0; i<k; i++ ) t[i] = new Thread(new MatrixMultLib().new MMWorker( a,b,c,m,n,cd,i*blk,(i+1)*blk )); for( int i=0; i<k; i++ ) t[i].start(); for( int i=0; i<k; i++ ) t[i].join(); } catch(Exception ex) { throw new DMLRuntimeException(ex); } ret.recomputeNonZeros(); ret.examSparsity(); } private class MMWorker implements Runnable { private double[] a = null; private double[] b = null; private double[] c = null; private int m; private int n; private int cd; private int starti; private int endi; public MMWorker(double[] a, double[] b, double[] c, int m, int n, int cd, int starti, int endi) { this.a = a; this.b = b; this.c = c; //this.a = new double[a.length]; System.arraycopy(a, 0, this.a, 0, a.length); //this.b = new double[b.length]; System.arraycopy(b, 0, this.b, 0, a.length); //this.c = new double[c.length]; System.arraycopy(c, 0, this.c, 0, a.length); this.m = m; this.n = n; this.cd = cd; this.starti = starti; this.endi = Math.min(endi,m); System.out.println("MMWorker: "+(endi-starti)+" rows"); } @Override public void run() { //1) Unrolled inner loop (for better instruction-level parallelism) //2) Blocked execution (for less cache trashing in parallel exec) //3) Asymmetric block sizes (for less misses in inner loop, yet blocks in L1/L2) final int blocksizeI = 32; //64//256KB c block (typical L2 size per core), 32KB a block final int blocksizeK = 24; //64//256KB b block (typical L2 size per core), used while read 512B of a / read/write 4KB of c final int blocksizeJ = 1024; //512//4KB (typical main-memory page size), for scan //temporary arrays (nnz a, b index) double[] ta = new double[ blocksizeK ]; int[] tbi = new int[ blocksizeK ]; //blocked execution for( int bi = starti; bi < endi; bi+=blocksizeI ) for( int bk = 0, bimin = Math.min(endi, bi+blocksizeI); bk < cd; bk+=blocksizeK ) for( int bj = 0, bkmin = Math.min(cd, bk+blocksizeK); bj < n; bj+=blocksizeJ ) { int bklen = bkmin-bk; int bjlen = Math.min(n, bj+blocksizeJ)-bj; //core sub block matrix multiplication for( int i = bi; i < bimin; i++) { int aixi = i * cd + bk; //start index on a int cixj = i * n + bj; //scan index on c //determine nnz of a (for sparsity-aware skipping of rows) int knnz = 0; for( int k = 0; k < bklen; k++ ) if( a[aixi+k] != 0 ) { ta[ knnz ] = a[aixi+k]; tbi[ knnz ] = (bk+k) * n + bj; //scan index on b knnz ++; } //rest not aligned to blocks of 4 rows final int bn = knnz % 4; switch( bn ){ case 1: vectMultiplyAdd(ta[0], b, c, tbi[0], cixj, bjlen); break; case 2: vectMultiplyAdd2(ta[0],ta[1], b, c, tbi[0], tbi[1], cixj, bjlen); break; case 3: vectMultiplyAdd3(ta[0],ta[1],ta[2], b, c, tbi[0], tbi[1],tbi[2], cixj, bjlen); break; } //compute blocks of 4 rows (core inner loop) for( int k = bn; k<knnz; k+=4 ){ vectMultiplyAdd4( ta[k], ta[k+1], ta[k+2], ta[k+3], b, c, tbi[k], tbi[k+1], tbi[k+2], tbi[k+3], cixj, bjlen ); } } } } } */ }
94449: Scale-up CP Runtime - New multi-threaded core block matrix multiply (prototype still disabled), incl refactoring libmatrixmult
SystemML/SystemML/src/main/java/com/ibm/bi/dml/runtime/matrix/data/LibMatrixMult.java
94449: Scale-up CP Runtime - New multi-threaded core block matrix multiply (prototype still disabled), incl refactoring libmatrixmult
Java
apache-2.0
a55cad4c46bc8a1ba141c7374c0ce65dcc6e800f
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.documentation; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.hint.HintManagerImpl; import com.intellij.codeInsight.lookup.LookupEx; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.icons.AllIcons; import com.intellij.ide.DataManager; import com.intellij.ide.actions.BaseNavigateToSourceAction; import com.intellij.ide.actions.ExternalJavaDocAction; import com.intellij.ide.actions.WindowAction; import com.intellij.ide.util.PropertiesComponent; import com.intellij.lang.documentation.CompositeDocumentationProvider; import com.intellij.lang.documentation.DocumentationMarkup; import com.intellij.lang.documentation.DocumentationProvider; import com.intellij.lang.documentation.ExternalDocumentationHandler; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.AnActionListener; import com.intellij.openapi.actionSystem.impl.ActionButton; import com.intellij.openapi.actionSystem.impl.ActionManagerImpl; import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl; import com.intellij.openapi.actionSystem.impl.MenuItemPresentationFactory; import com.intellij.openapi.application.ApplicationBundle; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.colors.ColorKey; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.EditorColorsUtil; import com.intellij.openapi.editor.ex.EditorSettingsExternalizable; import com.intellij.openapi.editor.ex.util.EditorUtil; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.keymap.ex.KeymapManagerEx; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.module.ModuleTypeManager; import com.intellij.openapi.options.FontSize; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.*; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.util.PopupUtil; import com.intellij.openapi.util.DimensionService; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.ToolWindowId; import com.intellij.openapi.wm.ex.ToolWindowManagerEx; import com.intellij.openapi.wm.ex.WindowManagerEx; import com.intellij.pom.Navigatable; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.SmartPointerManager; import com.intellij.psi.SmartPsiElementPointer; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.reference.SoftReference; import com.intellij.ui.*; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.components.JBLayeredPane; import com.intellij.ui.components.JBScrollPane; import com.intellij.ui.popup.AbstractPopup; import com.intellij.ui.popup.PopupPositionManager; import com.intellij.ui.scale.JBUIScale; import com.intellij.ui.scale.ScaleContext; import com.intellij.util.ArrayUtilRt; import com.intellij.util.ImageLoader; import com.intellij.util.Url; import com.intellij.util.Urls; import com.intellij.util.ui.*; import com.intellij.util.ui.accessibility.ScreenReader; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.ide.BuiltInServerManager; import javax.swing.*; import javax.swing.border.Border; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.plaf.TextUI; import javax.swing.text.*; import javax.swing.text.html.HTML; import javax.swing.text.html.HTMLDocument; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.ImageView; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.awt.image.RenderedImage; import java.awt.image.renderable.RenderContext; import java.awt.image.renderable.RenderableImage; import java.awt.image.renderable.RenderableImageProducer; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.List; import java.util.*; public class DocumentationComponent extends JPanel implements Disposable, DataProvider { private static final Logger LOG = Logger.getInstance(DocumentationComponent.class); private static final String DOCUMENTATION_TOPIC_ID = "reference.toolWindows.Documentation"; private static final Color DOCUMENTATION_COLOR = new JBColor(new Color(0xf7f7f7), new Color(0x46484a)); private static final JBColor BORDER_COLOR = new JBColor(new Color(0xadadad), new Color(0x616366)); public static final ColorKey COLOR_KEY = ColorKey.createColorKey("DOCUMENTATION_COLOR", DOCUMENTATION_COLOR); public static final Color SECTION_COLOR = Gray.get(0x90); private static final Highlighter.HighlightPainter LINK_HIGHLIGHTER = new LinkHighlighter(); private static final int PREFERRED_HEIGHT_MAX_EM = 10; private static final JBDimension MAX_DEFAULT = new JBDimension(650, 500); private static final JBDimension MIN_DEFAULT = new JBDimension(300, 20); private final ExternalDocAction myExternalDocAction; private DocumentationManager myManager; private SmartPsiElementPointer myElement; private long myModificationCount; public static final String QUICK_DOC_FONT_SIZE_PROPERTY = "quick.doc.font.size"; private final Stack<Context> myBackStack = new Stack<>(); private final Stack<Context> myForwardStack = new Stack<>(); private final ActionToolbarImpl myToolBar; private volatile boolean myIsEmpty; private boolean mySizeTrackerRegistered; private JSlider myFontSizeSlider; private final JComponent mySettingsPanel; private boolean myIgnoreFontSizeSliderChange; private String myExternalUrl; private DocumentationProvider myProvider; private Reference<Component> myReferenceComponent; private final MyDictionary<String, Image> myImageProvider = new MyDictionary<String, Image>() { @Override public Image get(Object key) { return getImageByKeyImpl(key); } }; private Runnable myToolwindowCallback; private final ActionButton myCorner; private final MyScrollPane myScrollPane; private final JEditorPane myEditorPane; private String myText; // myEditorPane.getText() surprisingly crashes.., let's cache the text private String myDecoratedText; // myEditorPane.getText() surprisingly crashes.., let's cache the text private final JComponent myControlPanel; private boolean myControlPanelVisible; private int myHighlightedLink = -1; private Object myHighlightingTag; private final boolean myStoreSize; private boolean myManuallyResized; private AbstractPopup myHint; private final Map<KeyStroke, ActionListener> myKeyboardActions = new HashMap<>(); @NotNull public static DocumentationComponent createAndFetch(@NotNull Project project, @NotNull PsiElement element, @NotNull Disposable disposable) { DocumentationManager manager = DocumentationManager.getInstance(project); DocumentationComponent component = new DocumentationComponent(manager); Disposer.register(disposable, component); manager.fetchDocInfo(element, component); return component; } public DocumentationComponent(DocumentationManager manager) { this(manager, true); } public DocumentationComponent(DocumentationManager manager, boolean storeSize) { myManager = manager; myIsEmpty = true; myStoreSize = storeSize; myEditorPane = new JEditorPane(UIUtil.HTML_MIME, "") { { enableEvents(AWTEvent.KEY_EVENT_MASK); } @Override protected void processKeyEvent(KeyEvent e) { KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(e); ActionListener listener = myKeyboardActions.get(keyStroke); if (listener != null) { listener.actionPerformed(new ActionEvent(DocumentationComponent.this, 0, "")); e.consume(); return; } super.processKeyEvent(e); } Point initialClick; @Override protected void processMouseEvent(MouseEvent e) { if (e.getID() == MouseEvent.MOUSE_PRESSED && myHint != null) { //DocumentationComponent.this.requestFocus(); initialClick = null; StyledDocument document = (StyledDocument)getDocument(); int x = e.getX(); int y = e.getY(); if (!hasTextAt(document, x, y) && !hasTextAt(document, x + 3, y) && !hasTextAt(document, x - 3, y) && !hasTextAt(document, x, y + 3) && !hasTextAt(document, x, y - 3)) { initialClick = e.getPoint(); } } super.processMouseEvent(e); } private boolean hasTextAt(StyledDocument document, int x, int y) { Element element = document.getCharacterElement(viewToModel(new Point(x, y))); try { String text = document.getText(element.getStartOffset(), element.getEndOffset() - element.getStartOffset()); if (StringUtil.isEmpty(text.trim())) { return false; } } catch (BadLocationException ignored) { return false; } return true; } @Override protected void processMouseMotionEvent(MouseEvent e) { if (e.getID() == MouseEvent.MOUSE_DRAGGED && myHint != null && initialClick != null) { Point location = myHint.getLocationOnScreen(); myHint.setLocation(new Point(location.x + e.getX() - initialClick.x, location.y + e.getY() - initialClick.y)); e.consume(); return; } super.processMouseMotionEvent(e); } @Override protected void paintComponent(Graphics g) { GraphicsUtil.setupAntialiasing(g); super.paintComponent(g); } @Override public void setDocument(Document doc) { super.setDocument(doc); doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE); if (doc instanceof StyledDocument) { doc.putProperty("imageCache", myImageProvider); } } }; DataProvider helpDataProvider = dataId -> PlatformDataKeys.HELP_ID.is(dataId) ? DOCUMENTATION_TOPIC_ID : null; myEditorPane.putClientProperty(DataManager.CLIENT_PROPERTY_DATA_PROVIDER, helpDataProvider); myText = ""; myDecoratedText = ""; myEditorPane.setEditable(false); if (ScreenReader.isActive()) { // Note: Making the caret visible is merely for convenience myEditorPane.getCaret().setVisible(true); } else { myEditorPane.putClientProperty("caretWidth", 0); // do not reserve space for caret (making content one pixel narrower than component) } myEditorPane.setBackground(EditorColorsUtil.getGlobalOrDefaultColor(COLOR_KEY)); HTMLEditorKit editorKit = new JBHtmlEditorKit(true) { @Override public ViewFactory getViewFactory() { return new HTMLFactory() { @Override public View create(Element elem) { if ("icon".equals(elem.getName())) { Object src = elem.getAttributes().getAttribute(HTML.Attribute.SRC); Icon icon = src != null ? IconLoader.findIcon((String)src, false) : null; if (icon == null) { ModuleType id = ModuleTypeManager.getInstance().findByID((String)src); if (id != null) icon = id.getIcon(); } if (icon != null) { Icon viewIcon = icon; return new View(elem) { @Override public float getPreferredSpan(int axis) { switch (axis) { case View.X_AXIS: return viewIcon.getIconWidth(); case View.Y_AXIS: return viewIcon.getIconHeight(); default: throw new IllegalArgumentException("Invalid axis: " + axis); } } @Override public String getToolTipText(float x, float y, Shape allocation) { return (String)getElement().getAttributes().getAttribute(HTML.Attribute.ALT); } @Override public void paint(Graphics g, Shape allocation) { viewIcon.paintIcon(null, g, allocation.getBounds().x, allocation.getBounds().y - 4); } @Override public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException { int p0 = getStartOffset(); int p1 = getEndOffset(); if ((pos >= p0) && (pos <= p1)) { Rectangle r = a.getBounds(); if (pos == p1) { r.x += r.width; } r.width = 0; return r; } throw new BadLocationException(pos + " not in range " + p0 + "," + p1, pos); } @Override public int viewToModel(float x, float y, Shape a, Position.Bias[] bias) { Rectangle alloc = (Rectangle)a; if (x < alloc.x + (alloc.width / 2f)) { bias[0] = Position.Bias.Forward; return getStartOffset(); } bias[0] = Position.Bias.Backward; return getEndOffset(); } }; } } View view = super.create(elem); if (view instanceof ImageView) { // we have to work with raw image, apply scaling manually return new ImageView(elem) { @Override public float getMaximumSpan(int axis) { return super.getMaximumSpan(axis) / JBUIScale.sysScale(myEditorPane); } @Override public float getMinimumSpan(int axis) { return super.getMinimumSpan(axis) / JBUIScale.sysScale(myEditorPane); } @Override public float getPreferredSpan(int axis) { return super.getPreferredSpan(axis) / JBUIScale.sysScale(myEditorPane); } @Override public void paint(Graphics g, Shape a) { Rectangle bounds = a.getBounds(); int width = (int)super.getPreferredSpan(View.X_AXIS); int height = (int)super.getPreferredSpan(View.Y_AXIS); if (width <= 0 || height <= 0) return; @SuppressWarnings("UndesirableClassUsage") BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = image.createGraphics(); super.paint(graphics, new Rectangle(image.getWidth(), image.getHeight())); UIUtil.drawImage(g, ImageUtil.ensureHiDPI(image, ScaleContext.create(myEditorPane)), bounds.x, bounds.y, null); } }; } return view; } }; } }; prepareCSS(editorKit); myEditorPane.setEditorKit(editorKit); myEditorPane.setBorder(JBUI.Borders.empty()); myScrollPane = new MyScrollPane(); myScrollPane.putClientProperty(DataManager.CLIENT_PROPERTY_DATA_PROVIDER, helpDataProvider); FocusListener focusAdapter = new FocusAdapter() { @Override public void focusLost(FocusEvent e) { Component previouslyFocused = WindowManagerEx.getInstanceEx().getFocusedComponent(manager.getProject(getElement())); if (previouslyFocused != myEditorPane) { if (myHint != null && !myHint.isDisposed()) myHint.cancel(); } } }; myEditorPane.addFocusListener(focusAdapter); Disposer.register(this, new Disposable() { @Override public void dispose() { myEditorPane.removeFocusListener(focusAdapter); } }); setLayout(new BorderLayout()); mySettingsPanel = createSettingsPanel(); //add(myScrollPane, BorderLayout.CENTER); setOpaque(true); myScrollPane.setBorder(JBUI.Borders.empty()); DefaultActionGroup actions = new DefaultActionGroup(); BackAction back = new BackAction(); ForwardAction forward = new ForwardAction(); EditDocumentationSourceAction edit = new EditDocumentationSourceAction(); myExternalDocAction = new ExternalDocAction(); actions.add(back); actions.add(forward); actions.add(edit); try { String backKey = ScreenReader.isActive() ? "alt LEFT" : "LEFT"; CustomShortcutSet backShortcutSet = new CustomShortcutSet(KeyboardShortcut.fromString(backKey), KeymapUtil.parseMouseShortcut("button4")); String forwardKey = ScreenReader.isActive() ? "alt RIGHT" : "RIGHT"; CustomShortcutSet forwardShortcutSet = new CustomShortcutSet(KeyboardShortcut.fromString(forwardKey), KeymapUtil.parseMouseShortcut("button5")); back.registerCustomShortcutSet(backShortcutSet, this); forward.registerCustomShortcutSet(forwardShortcutSet, this); // mouse actions are checked only for exact component over which click was performed, // so we need to register shortcuts for myEditorPane as well back.registerCustomShortcutSet(backShortcutSet, myEditorPane); forward.registerCustomShortcutSet(forwardShortcutSet, myEditorPane); } catch (InvalidDataException e) { LOG.error(e); } myExternalDocAction.registerCustomShortcutSet(CustomShortcutSet.fromString("UP"), this); myExternalDocAction.registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_EXTERNAL_JAVADOC).getShortcutSet(), myEditorPane); edit.registerCustomShortcutSet(CommonShortcuts.getEditSource(), this); ActionPopupMenu contextMenu = ((ActionManagerImpl)ActionManager.getInstance()).createActionPopupMenu( ActionPlaces.JAVADOC_TOOLBAR, actions, new MenuItemPresentationFactory(true)); PopupHandler popupHandler = new PopupHandler() { @Override public void invokePopup(Component comp, int x, int y) { contextMenu.getComponent().show(comp, x, y); } }; myEditorPane.addMouseListener(popupHandler); Disposer.register(this, () -> myEditorPane.removeMouseListener(popupHandler)); new NextLinkAction().registerCustomShortcutSet(CustomShortcutSet.fromString("TAB"), this); new PreviousLinkAction().registerCustomShortcutSet(CustomShortcutSet.fromString("shift TAB"), this); new ActivateLinkAction().registerCustomShortcutSet(CustomShortcutSet.fromString("ENTER"), this); DefaultActionGroup toolbarActions = new DefaultActionGroup(); toolbarActions.add(actions); toolbarActions.addAction(new ShowAsToolwindowAction()).setAsSecondary(true); toolbarActions.addAction(new MyShowSettingsAction(true)).setAsSecondary(true); toolbarActions.addAction(new ShowToolbarAction()).setAsSecondary(true); toolbarActions.addAction(new RestoreDefaultSizeAction()).setAsSecondary(true); myToolBar = new ActionToolbarImpl(ActionPlaces.JAVADOC_TOOLBAR, toolbarActions, true, KeymapManagerEx.getInstanceEx()) { Point initialClick; @Override protected void processMouseEvent(MouseEvent e) { if (e.getID() == MouseEvent.MOUSE_PRESSED && myHint != null) { initialClick = e.getPoint(); } super.processMouseEvent(e); } @Override protected void processMouseMotionEvent(MouseEvent e) { if (e.getID() == MouseEvent.MOUSE_DRAGGED && myHint != null && initialClick != null) { Point location = myHint.getLocationOnScreen(); myHint.setLocation(new Point(location.x + e.getX() - initialClick.x, location.y + e.getY() - initialClick.y)); e.consume(); return; } super.processMouseMotionEvent(e); } }; myToolBar.setSecondaryActionsIcon(AllIcons.Actions.More, true); JLayeredPane layeredPane = new JBLayeredPane() { @Override public void doLayout() { Rectangle r = getBounds(); for (Component component : getComponents()) { if (component instanceof JScrollPane) { component.setBounds(0, 0, r.width, r.height); } else { Dimension d = component.getPreferredSize(); component.setBounds(r.width - d.width - 2, r.height - d.height - 3, d.width, d.height); } } } @Override public Dimension getPreferredSize() { Dimension size = myScrollPane.getPreferredSize(); if (myHint == null && myManager != null && myManager.myToolWindow == null) { int em = myEditorPane.getFont().getSize(); int prefHeightMax = PREFERRED_HEIGHT_MAX_EM * em; return new Dimension(size.width, Math.min(prefHeightMax, size.height + (needsToolbar() ? myControlPanel.getPreferredSize().height : 0))); } return size; } }; layeredPane.add(myScrollPane); layeredPane.setLayer(myScrollPane, 0); DefaultActionGroup gearActions = new MyGearActionGroup(); ShowAsToolwindowAction showAsToolwindowAction = new ShowAsToolwindowAction(); gearActions.add(showAsToolwindowAction); gearActions.add(new MyShowSettingsAction(false)); gearActions.add(new ShowToolbarAction()); gearActions.add(new RestoreDefaultSizeAction()); gearActions.addSeparator(); gearActions.addAll(actions); Presentation presentation = new Presentation(); presentation.setIcon(AllIcons.Actions.More); presentation.putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, Boolean.TRUE); myCorner = new ActionButton(gearActions, presentation, ActionPlaces.UNKNOWN, new Dimension(20, 20)) { @Override protected DataContext getDataContext() { return DataManager.getInstance().getDataContext(myCorner); } }; myCorner.setNoIconsInPopup(true); showAsToolwindowAction.registerCustomShortcutSet(KeymapUtil.getActiveKeymapShortcuts("QuickJavaDoc"), myCorner); layeredPane.add(myCorner); layeredPane.setLayer(myCorner, JLayeredPane.POPUP_LAYER); add(layeredPane, BorderLayout.CENTER); myControlPanel = myToolBar.getComponent(); myControlPanel.setBorder(IdeBorderFactory.createBorder(SideBorder.BOTTOM)); myControlPanelVisible = false; HyperlinkListener hyperlinkListener = new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent e) { HyperlinkEvent.EventType type = e.getEventType(); if (type == HyperlinkEvent.EventType.ACTIVATED) { manager.navigateByLink(DocumentationComponent.this, e.getDescription()); } } }; myEditorPane.addHyperlinkListener(hyperlinkListener); Disposer.register(this, new Disposable() { @Override public void dispose() { myEditorPane.removeHyperlinkListener(hyperlinkListener); } }); if (myHint != null) { Disposer.register(myHint, this); } else if (myManager.myToolWindow != null) { Disposer.register(myManager.myToolWindow.getContentManager(), this); } registerActions(); updateControlState(); } public AnAction[] getActions() { return myToolBar.getActions().stream().filter((action -> !(action instanceof Separator))).toArray(AnAction[]::new); } public AnAction getFontSizeAction() { return new MyShowSettingsAction(false); } public void removeCornerMenu() { myCorner.setVisible(false); } public void setToolwindowCallback(Runnable callback) { myToolwindowCallback = callback; } public void showExternalDoc() { DataContext dataContext = DataManager.getInstance().getDataContext(this); myExternalDocAction.actionPerformed(AnActionEvent.createFromDataContext(ActionPlaces.UNKNOWN, null, dataContext)); } @Override public boolean requestFocusInWindow() { // With a screen reader active, set the focus directly to the editor because // it makes it easier for users to read/navigate the documentation contents. if (ScreenReader.isActive()) { return myEditorPane.requestFocusInWindow(); } else { return myScrollPane.requestFocusInWindow(); } } @Override public void requestFocus() { // With a screen reader active, set the focus directly to the editor because // it makes it easier for users to read/navigate the documentation contents. IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> { if (ScreenReader.isActive()) { IdeFocusManager.getGlobalInstance().requestFocus(myEditorPane, true); } else { IdeFocusManager.getGlobalInstance().requestFocus(myScrollPane, true); } }); } private static void prepareCSS(HTMLEditorKit editorKit) { Color borderColor = ColorUtil.mix(DOCUMENTATION_COLOR, BORDER_COLOR, 0.5); String editorFontName = StringUtil.escapeQuotes(EditorColorsManager.getInstance().getGlobalScheme().getEditorFontName()); editorKit.getStyleSheet().addRule("code {font-family:\"" + editorFontName + "\"}"); editorKit.getStyleSheet().addRule("pre {font-family:\"" + editorFontName + "\"}"); editorKit.getStyleSheet().addRule(".pre {font-family:\"" + editorFontName + "\"}"); editorKit.getStyleSheet().addRule("html { padding-bottom: 5px; }"); editorKit.getStyleSheet().addRule("h1, h2, h3, h4, h5, h6 { margin-top: 0; padding-top: 1px; }"); editorKit.getStyleSheet().addRule("a { color: #" + ColorUtil.toHex(getLinkColor()) + "; text-decoration: none;}"); editorKit.getStyleSheet().addRule(".definition { padding: 3px 17px 1px 7px; border-bottom: thin solid #" + ColorUtil.toHex(borderColor) + "; }"); editorKit.getStyleSheet().addRule(".definition-only { padding: 3px 17px 0 7px; }"); editorKit.getStyleSheet().addRule(".content { padding: 5px 16px 0 7px; max-width: 100% }"); editorKit.getStyleSheet().addRule(".bottom { padding: 3px 16px 0 7px; }"); editorKit.getStyleSheet().addRule(".bottom-no-content { padding: 5px 16px 0 7px; }"); editorKit.getStyleSheet().addRule("p { padding: 1px 0 2px 0; }"); editorKit.getStyleSheet().addRule("ol { padding: 0 16px 0 0; }"); editorKit.getStyleSheet().addRule("ul { padding: 0 16px 0 0; }"); editorKit.getStyleSheet().addRule("li { padding: 1px 0 2px 0; }"); editorKit.getStyleSheet().addRule(".grayed { color: #909090; display: inline;}"); editorKit.getStyleSheet().addRule(".centered { text-align: center}"); // sections table editorKit.getStyleSheet().addRule(".sections { padding: 0 16px 0 7px; border-spacing: 0; }"); editorKit.getStyleSheet().addRule("tr { margin: 0 0 0 0; padding: 0 0 0 0; }"); editorKit.getStyleSheet().addRule("td { margin: 2px 0 3.5px 0; padding: 0 0 0 0; }"); editorKit.getStyleSheet().addRule("th { text-align: left; }"); editorKit.getStyleSheet().addRule(".section { color: " + ColorUtil.toHtmlColor(SECTION_COLOR) + "; padding-right: 4px}"); } private static Color getLinkColor() { return JBUI.CurrentTheme.Link.linkColor(); } @Override public Object getData(@NotNull @NonNls String dataId) { if (DocumentationManager.SELECTED_QUICK_DOC_TEXT.getName().equals(dataId)) { // Javadocs often contain &nbsp; symbols (non-breakable white space). We don't want to copy them as is and replace // with raw white spaces. See IDEA-86633 for more details. String selectedText = myEditorPane.getSelectedText(); return selectedText == null ? null : selectedText.replace((char)160, ' '); } return null; } private JComponent createSettingsPanel() { JPanel result = new JPanel(new FlowLayout(FlowLayout.RIGHT, 3, 0)); result.add(new JLabel(ApplicationBundle.message("label.font.size"))); myFontSizeSlider = new JSlider(SwingConstants.HORIZONTAL, 0, FontSize.values().length - 1, 3); myFontSizeSlider.setMinorTickSpacing(1); myFontSizeSlider.setPaintTicks(true); myFontSizeSlider.setPaintTrack(true); myFontSizeSlider.setSnapToTicks(true); UIUtil.setSliderIsFilled(myFontSizeSlider, true); result.add(myFontSizeSlider); result.setBorder(BorderFactory.createLineBorder(JBColor.border(), 1)); myFontSizeSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (myIgnoreFontSizeSliderChange) { return; } setQuickDocFontSize(FontSize.values()[myFontSizeSlider.getValue()]); applyFontProps(); // resize popup according to new font size, if user didn't set popup size manually if (!myManuallyResized && myHint != null && myHint.getDimensionServiceKey() == null) showHint(); } }); String tooltipText = ApplicationBundle.message("quickdoc.tooltip.font.size.by.wheel"); result.setToolTipText(tooltipText); myFontSizeSlider.setToolTipText(tooltipText); result.setVisible(false); result.setOpaque(true); myFontSizeSlider.setOpaque(true); return result; } @NotNull public static FontSize getQuickDocFontSize() { String strValue = PropertiesComponent.getInstance().getValue(QUICK_DOC_FONT_SIZE_PROPERTY); if (strValue != null) { try { return FontSize.valueOf(strValue); } catch (IllegalArgumentException iae) { // ignore, fall back to default font. } } return FontSize.SMALL; } public void setQuickDocFontSize(@NotNull FontSize fontSize) { PropertiesComponent.getInstance().setValue(QUICK_DOC_FONT_SIZE_PROPERTY, fontSize.toString()); } private void setFontSizeSliderSize(FontSize fontSize) { myIgnoreFontSizeSliderChange = true; try { FontSize[] sizes = FontSize.values(); for (int i = 0; i < sizes.length; i++) { if (fontSize == sizes[i]) { myFontSizeSlider.setValue(i); break; } } } finally { myIgnoreFontSizeSliderChange = false; } } public boolean isEmpty() { return myIsEmpty; } public void startWait() { myIsEmpty = true; } private void setControlPanelVisible() { if (myControlPanelVisible) return; add(myControlPanel, BorderLayout.NORTH); myControlPanelVisible = true; } public void setHint(JBPopup hint) { myHint = (AbstractPopup)hint; } public JBPopup getHint() { return myHint; } public JComponent getComponent() { return myEditorPane; } @Nullable public PsiElement getElement() { return myElement != null ? myElement.getElement() : null; } private void setElement(SmartPsiElementPointer element) { myElement = element; myModificationCount = getCurrentModificationCount(); } public boolean isUpToDate() { return getElement() != null && myModificationCount == getCurrentModificationCount(); } private long getCurrentModificationCount() { return myElement != null ? PsiModificationTracker.SERVICE.getInstance(myElement.getProject()).getModificationCount() : -1; } public void setText(@NotNull String text, @Nullable PsiElement element, @Nullable DocumentationProvider provider) { setData(element, text, null, null, provider); } public void replaceText(@NotNull String text, @Nullable PsiElement element) { PsiElement current = getElement(); if (current == null || !current.getManager().areElementsEquivalent(current, element)) return; restoreContext(saveContext().withText(text)); } public void clearHistory() { myForwardStack.clear(); myBackStack.clear(); } private void pushHistory() { if (myElement != null) { myBackStack.push(saveContext()); myForwardStack.clear(); } } public void setData(@Nullable PsiElement element, @NotNull String text, @Nullable String effectiveExternalUrl, @Nullable String ref, @Nullable DocumentationProvider provider) { pushHistory(); myExternalUrl = effectiveExternalUrl; myProvider = provider; SmartPsiElementPointer pointer = null; if (element != null && element.isValid()) { pointer = SmartPointerManager.getInstance(element.getProject()).createSmartPsiElementPointer(element); } setDataInternal(pointer, text, new Rectangle(0, 0), ref); } private void setDataInternal(@Nullable SmartPsiElementPointer element, @NotNull String text, @NotNull Rectangle viewRect, @Nullable String ref) { myIsEmpty = false; if (myManager == null) return; myText = text; myDecoratedText = decorate(text); setElement(element); showHint(viewRect, ref); } protected void showHint(@NotNull Rectangle viewRect, @Nullable String ref) { String refToUse; Rectangle viewRectToUse; if (DocumentationManagerProtocol.KEEP_SCROLLING_POSITION_REF.equals(ref)) { refToUse = null; viewRectToUse = myScrollPane.getViewport().getViewRect(); } else { refToUse = ref; viewRectToUse = viewRect; } updateControlState(); highlightLink(-1); myEditorPane.setText(myDecoratedText); applyFontProps(); showHint(); //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> { myEditorPane.scrollRectToVisible(viewRectToUse); // if ref is defined but is not found in document, this provides a default location if (refToUse != null) { myEditorPane.scrollToReference(refToUse); } else if (ScreenReader.isActive()) { myEditorPane.setCaretPosition(0); } }); } private void showHint() { if (myHint == null) return; setHintSize(); DataContext dataContext = getDataContext(); PopupPositionManager.positionPopupInBestPosition(myHint, myManager.getEditor(), dataContext, PopupPositionManager.Position.RIGHT, PopupPositionManager.Position.LEFT); Window window = myHint.getPopupWindow(); if (window != null) window.setFocusableWindowState(true); if (myHint.getDimensionServiceKey() == null) { registerSizeTracker(); } } private DataContext getDataContext() { Component referenceComponent; if (myReferenceComponent == null) { referenceComponent = IdeFocusManager.getInstance(myManager.myProject).getFocusOwner(); myReferenceComponent = new WeakReference<>(referenceComponent); } else { referenceComponent = SoftReference.dereference(myReferenceComponent); if (referenceComponent == null || ! referenceComponent.isShowing()) referenceComponent = myHint.getComponent(); } return DataManager.getInstance().getDataContext(referenceComponent); } private void setHintSize() { Dimension hintSize; if (!myManuallyResized && myHint.getDimensionServiceKey() == null) { int minWidth = JBUIScale.scale(300); int maxWidth = getPopupAnchor() != null ? JBUIScale.scale(435) : MAX_DEFAULT.width; int width = definitionPreferredWidth(); if (width < 0) { // no definition found width = myEditorPane.getPreferredSize().width; } else { width = Math.max(width, myEditorPane.getMinimumSize().width); } width = Math.min(maxWidth, Math.max(minWidth, width)); myEditorPane.setBounds(0, 0, width, MAX_DEFAULT.height); myEditorPane.setText(myDecoratedText); Dimension preferredSize = myEditorPane.getPreferredSize(); int height = preferredSize.height + (needsToolbar() ? myControlPanel.getPreferredSize().height : 0); height = Math.min(MAX_DEFAULT.height, Math.max(MIN_DEFAULT.height, height)); hintSize = new Dimension(width, height); } else { hintSize = myManuallyResized ? myHint.getSize() : DimensionService.getInstance().getSize(DocumentationManager.NEW_JAVADOC_LOCATION_AND_SIZE, myManager.myProject); if (hintSize == null) { hintSize = new Dimension(MIN_DEFAULT); } else { hintSize.width = Math.max(hintSize.width, MIN_DEFAULT.width); hintSize.height = Math.max(hintSize.height, MIN_DEFAULT.height); } } myHint.setSize(hintSize); } private Component getPopupAnchor() { LookupEx lookup = LookupManager.getActiveLookup(myManager.getEditor()); if (lookup != null && lookup.getCurrentItem() != null && lookup.getComponent().isShowing()) { return lookup.getComponent(); } Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); JBPopup popup = PopupUtil.getPopupContainerFor(focusOwner); if (popup != null && popup != myHint && !popup.isDisposed()) { return popup.getContent(); } return null; } private void registerSizeTracker() { AbstractPopup hint = myHint; if (hint == null || mySizeTrackerRegistered) return; mySizeTrackerRegistered = true; hint.addResizeListener(this::onManualResizing, this); ApplicationManager.getApplication().getMessageBus().connect(this).subscribe(AnActionListener.TOPIC, new AnActionListener() { @Override public void afterActionPerformed(@NotNull AnAction action, @NotNull DataContext dataContext, @NotNull AnActionEvent event) { if (action instanceof WindowAction) onManualResizing(); } }); } private void onManualResizing() { myManuallyResized = true; if (myStoreSize && myHint != null) { myHint.setDimensionServiceKey(DocumentationManager.NEW_JAVADOC_LOCATION_AND_SIZE); myHint.storeDimensionSize(); } } private int definitionPreferredWidth() { TextUI ui = myEditorPane.getUI(); View view = ui.getRootView(myEditorPane); View definition = findDefinition(view); return definition != null ? (int)definition.getPreferredSpan(View.X_AXIS) : -1; } private static View findDefinition(View view) { if ("definition".equals(view.getElement().getAttributes().getAttribute(HTML.Attribute.CLASS))) { return view; } for (int i = 0; i < view.getViewCount(); i++) { View definition = findDefinition(view.getView(i)); if (definition != null) return definition; } return null; } private String decorate(String text) { text = StringUtil.replaceIgnoreCase(text, "</html>", ""); text = StringUtil.replaceIgnoreCase(text, "</body>", ""); text = StringUtil.replaceIgnoreCase(text, DocumentationMarkup.SECTIONS_START + DocumentationMarkup.SECTIONS_END, ""); text = StringUtil.replaceIgnoreCase(text, DocumentationMarkup.SECTIONS_START + "<p>" + DocumentationMarkup.SECTIONS_END, ""); boolean hasContent = text.contains(DocumentationMarkup.CONTENT_START); if (!hasContent) { if (!text.contains(DocumentationMarkup.DEFINITION_START)) { int bodyStart = findContentStart(text); if (bodyStart > 0) { text = text.substring(0, bodyStart) + DocumentationMarkup.CONTENT_START + text.substring(bodyStart) + DocumentationMarkup.CONTENT_END; } else { text = DocumentationMarkup.CONTENT_START + text + DocumentationMarkup.CONTENT_END; } hasContent = true; } else if (!text.contains(DocumentationMarkup.SECTIONS_START)){ text = StringUtil.replaceIgnoreCase(text, DocumentationMarkup.DEFINITION_START, "<div class='definition-only'><pre>"); } } String location = getLocationText(); if (location != null) { text = text + getBottom(hasContent) + location + "</div>"; } String links = getExternalText(myManager, getElement(), myExternalUrl, myProvider); if (links != null) { text = text + getBottom(location != null) + links; } //workaround for Swing html renderer not removing empty paragraphs before non-inline tags text = text.replaceAll("<p>\\s*(<(?:[uo]l|h\\d|p))", "$1"); text = addExternalLinksIcon(text); return text; } @Nullable private static String getExternalText(@NotNull DocumentationManager manager, @Nullable PsiElement element, @Nullable String externalUrl, @Nullable DocumentationProvider provider) { if (element == null || provider == null) return null; PsiElement originalElement = DocumentationManager.getOriginalElement(element); if (!shouldShowExternalDocumentationLink(provider, element, originalElement)) { return null; } String title = manager.getTitle(element); if (title != null) { title = StringUtil.escapeXmlEntities(title); } if (externalUrl == null) { List<String> urls = provider.getUrlFor(element, originalElement); if (urls != null) { boolean hasBadUrl = false; StringBuilder result = new StringBuilder(); for (String url : urls) { String link = getLink(title, url); if (link == null) { hasBadUrl = true; break; } if (result.length() > 0) result.append("<p>"); result.append(link); } if (!hasBadUrl) return result.toString(); } else { return null; } } else { String link = getLink(title, externalUrl); if (link != null) return link; } return "<a href='external_doc'>External documentation" + (title == null ? "" : (" for `" + title + "`")) + "<icon src='AllIcons.Ide.External_link_arrow'></a></div>"; } private static String getLink(String title, String url) { StringBuilder result = new StringBuilder(); String hostname = getHostname(url); if (hostname == null) { return null; } result.append("<a href='").append(url).append("'>"); if (title == null) { result.append("Documentation"); } else { result.append("`").append(title).append("`"); } result.append(" on ").append(hostname).append("</a>"); return result.toString(); } static boolean shouldShowExternalDocumentationLink(DocumentationProvider provider, PsiElement element, PsiElement originalElement) { if (provider instanceof CompositeDocumentationProvider) { List<DocumentationProvider> providers = ((CompositeDocumentationProvider)provider).getProviders(); for (DocumentationProvider p : providers) { if (p instanceof ExternalDocumentationHandler) { return ((ExternalDocumentationHandler)p).canHandleExternal(element, originalElement); } } } else if (provider instanceof ExternalDocumentationHandler) { return ((ExternalDocumentationHandler)provider).canHandleExternal(element, originalElement); } return true; } private static String getHostname(String url) { try { return new URL(url).toURI().getHost(); } catch (URISyntaxException | MalformedURLException ignored) { } return null; } private static int findContentStart(String text) { int index = StringUtil.indexOfIgnoreCase(text, "<body>", 0); if (index >= 0) return index + 6; index = StringUtil.indexOfIgnoreCase(text, "</head>", 0); if (index >= 0) return index + 7; index = StringUtil.indexOfIgnoreCase(text, "</style>", 0); if (index >= 0) return index + 8; index = StringUtil.indexOfIgnoreCase(text, "<html>", 0); if (index >= 0) return index + 6; return -1; } @NotNull private static String getBottom(boolean hasContent) { return "<div class='" + (hasContent ? "bottom" : "bottom-no-content") + "'>"; } private static String addExternalLinksIcon(String text) { return text.replaceAll("(<a\\s*href=[\"']http[^>]*>)([^>]*)(</a>)", "$1$2<icon src='AllIcons.Ide.External_link_arrow'>$3"); } private String getLocationText() { PsiElement element = getElement(); if (element != null) { PsiFile file = element.getContainingFile(); VirtualFile vfile = file == null ? null : file.getVirtualFile(); if (vfile == null) return null; ProjectFileIndex fileIndex = ProjectRootManager.getInstance(element.getProject()).getFileIndex(); Module module = fileIndex.getModuleForFile(vfile); if (module != null) { if (ModuleManager.getInstance(element.getProject()).getModules().length == 1) return null; return "<icon src='" + ModuleType.get(module).getId() + "'>&nbsp;" + module.getName().replace("<", "&lt;"); } else { List<OrderEntry> entries = fileIndex.getOrderEntriesForFile(vfile); for (OrderEntry order : entries) { if (order instanceof LibraryOrderEntry || order instanceof JdkOrderEntry) { return "<icon src='AllIcons.Nodes.PpLibFolder" + "'>&nbsp;" + order.getPresentableName().replace("<", "&lt;"); } } } } return null; } private void applyFontProps() { Document document = myEditorPane.getDocument(); if (!(document instanceof StyledDocument)) { return; } String fontName = Registry.is("documentation.component.editor.font") ? EditorColorsManager.getInstance().getGlobalScheme().getEditorFontName() : myEditorPane.getFont().getFontName(); // changing font will change the doc's CSS as myEditorPane has JEditorPane.HONOR_DISPLAY_PROPERTIES via UIUtil.getHTMLEditorKit myEditorPane.setFont(UIUtil.getFontWithFallback(fontName, Font.PLAIN, JBUIScale.scale(getQuickDocFontSize().getSize()))); } @Nullable private Image getImageByKeyImpl(Object key) { if (myManager == null || key == null) return null; PsiElement element = getElement(); if (element == null) return null; URL url = (URL)key; Image inMemory = myManager.getElementImage(element, url.toExternalForm()); if (inMemory != null) { return inMemory; } Url parsedUrl = Urls.parseEncoded(url.toExternalForm()); BuiltInServerManager builtInServerManager = BuiltInServerManager.getInstance(); if (parsedUrl != null && builtInServerManager.isOnBuiltInWebServer(parsedUrl)) { try { url = new URL(builtInServerManager.addAuthToken(parsedUrl).toExternalForm()); } catch (MalformedURLException e) { LOG.warn(e); } } URL imageUrl = url; return Toolkit.getDefaultToolkit().createImage(new RenderableImageProducer(new RenderableImage() { private Image myImage; private boolean myImageLoaded; @Override public Vector<RenderableImage> getSources() { return null; } @Override public Object getProperty(String name) { return null; } @Override public String[] getPropertyNames() { return ArrayUtilRt.EMPTY_STRING_ARRAY; } @Override public boolean isDynamic() { return false; } @Override public float getWidth() { return getImage().getWidth(null); } @Override public float getHeight() { return getImage().getHeight(null); } @Override public float getMinX() { return 0; } @Override public float getMinY() { return 0; } @Override public RenderedImage createScaledRendering(int w, int h, RenderingHints hints) { return createDefaultRendering(); } @Override public RenderedImage createDefaultRendering() { return (RenderedImage)getImage(); } @Override public RenderedImage createRendering(RenderContext renderContext) { return createDefaultRendering(); } private Image getImage() { if (!myImageLoaded) { Image image = ImageLoader.loadFromUrl(imageUrl); myImage = ImageUtil.toBufferedImage(image != null ? image : ((ImageIcon)UIManager.getLookAndFeelDefaults().get("html.missingImage")).getImage()); myImageLoaded = true; } return myImage; } }, null)); } private void goBack() { if (myBackStack.isEmpty()) return; Context context = myBackStack.pop(); myForwardStack.push(saveContext()); restoreContext(context); } private void goForward() { if (myForwardStack.isEmpty()) return; Context context = myForwardStack.pop(); myBackStack.push(saveContext()); restoreContext(context); } private Context saveContext() { Rectangle rect = myScrollPane.getViewport().getViewRect(); return new Context(myElement, myText, myExternalUrl, myProvider, rect, myHighlightedLink); } private void restoreContext(@NotNull Context context) { myExternalUrl = context.externalUrl; myProvider = context.provider; setDataInternal(context.element, context.text, context.viewRect, null); highlightLink(context.highlightedLink); if (myManager != null) { PsiElement element = context.element.getElement(); if (element != null) { myManager.updateToolWindowTabName(element); } } } private void updateControlState() { if (needsToolbar()) { myToolBar.updateActionsImmediately(); // update faster setControlPanelVisible(); removeCornerMenu(); } else { myControlPanelVisible = false; remove(myControlPanel); if (myManager.myToolWindow != null) return; myCorner.setVisible(true); } } private boolean needsToolbar() { return myManager.myToolWindow == null && Registry.is("documentation.show.toolbar"); } private static class MyGearActionGroup extends DefaultActionGroup implements HintManagerImpl.ActionToIgnore { MyGearActionGroup(@NotNull AnAction... actions) { super(actions); setPopup(true); } } private class BackAction extends AnAction implements HintManagerImpl.ActionToIgnore { BackAction() { super(CodeInsightBundle.message("javadoc.action.back"), null, AllIcons.Actions.Back); } @Override public void actionPerformed(@NotNull AnActionEvent e) { goBack(); } @Override public void update(@NotNull AnActionEvent e) { Presentation presentation = e.getPresentation(); presentation.setEnabled(!myBackStack.isEmpty()); if (!isToolbar(e)) { presentation.setVisible(presentation.isEnabled()); } } } private class ForwardAction extends AnAction implements HintManagerImpl.ActionToIgnore { ForwardAction() { super(CodeInsightBundle.message("javadoc.action.forward"), null, AllIcons.Actions.Forward); } @Override public void actionPerformed(@NotNull AnActionEvent e) { goForward(); } @Override public void update(@NotNull AnActionEvent e) { Presentation presentation = e.getPresentation(); presentation.setEnabled(!myForwardStack.isEmpty()); if (!isToolbar(e)) { presentation.setVisible(presentation.isEnabled()); } } } private class EditDocumentationSourceAction extends BaseNavigateToSourceAction { private EditDocumentationSourceAction() { super(true); getTemplatePresentation().setIcon(AllIcons.Actions.EditSource); getTemplatePresentation().setText("Edit Source"); } @Override public void actionPerformed(@NotNull AnActionEvent e) { super.actionPerformed(e); JBPopup hint = myHint; if (hint != null && hint.isVisible()) { hint.cancel(); } } @Nullable @Override protected Navigatable[] getNavigatables(DataContext dataContext) { SmartPsiElementPointer element = myElement; if (element != null) { PsiElement psiElement = element.getElement(); return psiElement instanceof Navigatable ? new Navigatable[]{(Navigatable)psiElement} : null; } return null; } } private static boolean isToolbar(@NotNull AnActionEvent e) { return ActionPlaces.JAVADOC_TOOLBAR.equals(e.getPlace()); } private class ExternalDocAction extends AnAction implements HintManagerImpl.ActionToIgnore { private ExternalDocAction() { super(CodeInsightBundle.message("javadoc.action.view.external"), null, AllIcons.Actions.PreviousOccurence); registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_EXTERNAL_JAVADOC).getShortcutSet(), null); } @Override public void actionPerformed(@NotNull AnActionEvent e) { if (myElement == null) { return; } PsiElement element = myElement.getElement(); PsiElement originalElement = DocumentationManager.getOriginalElement(element); ExternalJavaDocAction.showExternalJavadoc(element, originalElement, myExternalUrl, e.getDataContext()); } @Override public void update(@NotNull AnActionEvent e) { Presentation presentation = e.getPresentation(); presentation.setEnabled(hasExternalDoc()); } } private boolean hasExternalDoc() { boolean enabled = false; if (myElement != null && myProvider != null) { PsiElement element = myElement.getElement(); PsiElement originalElement = DocumentationManager.getOriginalElement(element); enabled = element != null && CompositeDocumentationProvider.hasUrlsFor(myProvider, element, originalElement); } return enabled; } private void registerActions() { // With screen readers, we want the default keyboard behavior inside // the document text editor, i.e. the caret moves with cursor keys, etc. if (!ScreenReader.isActive()) { myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getVerticalScrollBar(); int value = scrollBar.getValue() - scrollBar.getUnitIncrement(-1); value = Math.max(value, 0); scrollBar.setValue(value); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getVerticalScrollBar(); int value = scrollBar.getValue() + scrollBar.getUnitIncrement(+1); value = Math.min(value, scrollBar.getMaximum()); scrollBar.setValue(value); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar(); int value = scrollBar.getValue() - scrollBar.getUnitIncrement(-1); value = Math.max(value, 0); scrollBar.setValue(value); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar(); int value = scrollBar.getValue() + scrollBar.getUnitIncrement(+1); value = Math.min(value, scrollBar.getMaximum()); scrollBar.setValue(value); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getVerticalScrollBar(); int value = scrollBar.getValue() - scrollBar.getBlockIncrement(-1); value = Math.max(value, 0); scrollBar.setValue(value); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getVerticalScrollBar(); int value = scrollBar.getValue() + scrollBar.getBlockIncrement(+1); value = Math.min(value, scrollBar.getMaximum()); scrollBar.setValue(value); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar(); scrollBar.setValue(0); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_END, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar(); scrollBar.setValue(scrollBar.getMaximum()); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, InputEvent.CTRL_MASK), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getVerticalScrollBar(); scrollBar.setValue(0); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_END, InputEvent.CTRL_MASK), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getVerticalScrollBar(); scrollBar.setValue(scrollBar.getMaximum()); } }); } } public String getText() { return myText; } public String getDecoratedText() { return myDecoratedText; } @Override public void dispose() { myEditorPane.getCaret().setVisible(false); // Caret, if blinking, has to be deactivated. myBackStack.clear(); myForwardStack.clear(); myKeyboardActions.clear(); myElement = null; myManager = null; myHint = null; } private int getLinkCount() { HTMLDocument document = (HTMLDocument)myEditorPane.getDocument(); int linkCount = 0; for (HTMLDocument.Iterator it = document.getIterator(HTML.Tag.A); it.isValid(); it.next()) { if (it.getAttributes().isDefined(HTML.Attribute.HREF)) linkCount++; } return linkCount; } @Nullable private HTMLDocument.Iterator getLink(int n) { if (n >= 0) { HTMLDocument document = (HTMLDocument)myEditorPane.getDocument(); int linkCount = 0; for (HTMLDocument.Iterator it = document.getIterator(HTML.Tag.A); it.isValid(); it.next()) { if (it.getAttributes().isDefined(HTML.Attribute.HREF) && linkCount++ == n) return it; } } return null; } private void highlightLink(int n) { myHighlightedLink = n; Highlighter highlighter = myEditorPane.getHighlighter(); HTMLDocument.Iterator link = getLink(n); if (link != null) { int startOffset = link.getStartOffset(); int endOffset = link.getEndOffset(); try { if (myHighlightingTag == null) { myHighlightingTag = highlighter.addHighlight(startOffset, endOffset, LINK_HIGHLIGHTER); } else { highlighter.changeHighlight(myHighlightingTag, startOffset, endOffset); } myEditorPane.setCaretPosition(startOffset); } catch (BadLocationException e) { LOG.warn("Error highlighting link", e); } } else if (myHighlightingTag != null) { highlighter.removeHighlight(myHighlightingTag); myHighlightingTag = null; } } private void activateLink(int n) { HTMLDocument.Iterator link = getLink(n); if (link != null) { String href = (String)link.getAttributes().getAttribute(HTML.Attribute.HREF); myManager.navigateByLink(this, href); } } private static class Context { final SmartPsiElementPointer element; final String text; final String externalUrl; final DocumentationProvider provider; final Rectangle viewRect; final int highlightedLink; Context(SmartPsiElementPointer element, String text, String externalUrl, DocumentationProvider provider, Rectangle viewRect, int highlightedLink) { this.element = element; this.text = text; this.externalUrl = externalUrl; this.provider = provider; this.viewRect = viewRect; this.highlightedLink = highlightedLink; } @NotNull Context withText(@NotNull String text) { return new Context(element, text, externalUrl, provider, viewRect, highlightedLink); } } private class MyShowSettingsAction extends AnAction implements HintManagerImpl.ActionToIgnore { private final boolean myOnToolbar; MyShowSettingsAction(boolean onToolbar) { super("Adjust font size..."); myOnToolbar = onToolbar; } @Override public void update(@NotNull AnActionEvent e) { if (myManager == null || myOnToolbar && myManager.myToolWindow != null) { e.getPresentation().setEnabledAndVisible(false); } } @Override public void actionPerformed(@NotNull AnActionEvent e) { JBPopup popup = JBPopupFactory.getInstance().createComponentPopupBuilder(mySettingsPanel, myFontSizeSlider).createPopup(); setFontSizeSliderSize(getQuickDocFontSize()); mySettingsPanel.setVisible(true); Point location = MouseInfo.getPointerInfo().getLocation(); popup.show(new RelativePoint(new Point(location.x - mySettingsPanel.getPreferredSize().width / 2, location.y - mySettingsPanel.getPreferredSize().height / 2))); } } private abstract static class MyDictionary<K, V> extends Dictionary<K, V> { @Override public int size() { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { throw new UnsupportedOperationException(); } @Override public Enumeration<K> keys() { throw new UnsupportedOperationException(); } @Override public Enumeration<V> elements() { throw new UnsupportedOperationException(); } @Override public V put(K key, V value) { throw new UnsupportedOperationException(); } @Override public V remove(Object key) { throw new UnsupportedOperationException(); } } private class PreviousLinkAction extends AnAction implements HintManagerImpl.ActionToIgnore { @Override public void actionPerformed(@NotNull AnActionEvent e) { int linkCount = getLinkCount(); if (linkCount <= 0) return; highlightLink(myHighlightedLink < 0 ? (linkCount - 1) : (myHighlightedLink + linkCount - 1) % linkCount); } } private class NextLinkAction extends AnAction implements HintManagerImpl.ActionToIgnore { @Override public void actionPerformed(@NotNull AnActionEvent e) { int linkCount = getLinkCount(); if (linkCount <= 0) return; highlightLink((myHighlightedLink + 1) % linkCount); } } private class ActivateLinkAction extends AnAction implements HintManagerImpl.ActionToIgnore { @Override public void actionPerformed(@NotNull AnActionEvent e) { activateLink(myHighlightedLink); } } private static class LinkHighlighter implements Highlighter.HighlightPainter { private static final Stroke STROKE = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1, new float[]{1}, 0); @Override public void paint(Graphics g, int p0, int p1, Shape bounds, JTextComponent c) { try { Rectangle target = c.getUI().getRootView(c).modelToView(p0, Position.Bias.Forward, p1, Position.Bias.Backward, bounds).getBounds(); Graphics2D g2d = (Graphics2D)g.create(); try { g2d.setStroke(STROKE); g2d.setColor(c.getSelectionColor()); g2d.drawRect(target.x, target.y, target.width - 1, target.height - 1); } finally { g2d.dispose(); } } catch (Exception e) { LOG.warn("Error painting link highlight", e); } } } private class ShowToolbarAction extends ToggleAction implements HintManagerImpl.ActionToIgnore { ShowToolbarAction() { super("Show Toolbar"); } @Override public void update(@NotNull AnActionEvent e) { super.update(e); if (myManager == null || myManager.myToolWindow != null) { e.getPresentation().setEnabledAndVisible(false); } } @Override public boolean isSelected(@NotNull AnActionEvent e) { return Registry.get("documentation.show.toolbar").asBoolean(); } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { Registry.get("documentation.show.toolbar").setValue(state); updateControlState(); showHint(); } } private class MyScrollPane extends JBScrollPane { MyScrollPane() { super(myEditorPane, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED); setLayout(new Layout() { @Override public void layoutContainer(Container parent) { super.layoutContainer(parent); if (!myCorner.isVisible()) return; if (vsb != null) { Rectangle bounds = vsb.getBounds(); vsb.setBounds(bounds.x, bounds.y, bounds.width, bounds.height - myCorner.getPreferredSize().height - 3); } if (hsb != null) { Rectangle bounds = hsb.getBounds(); int vsbOffset = vsb != null ? vsb.getBounds().width : 0; hsb.setBounds(bounds.x, bounds.y, bounds.width - myCorner.getPreferredSize().width - 3 + vsbOffset, bounds.height); } } }); } @Override public Border getViewportBorder() { return null; } @Override protected void processMouseWheelEvent(MouseWheelEvent e) { if (!EditorSettingsExternalizable.getInstance().isWheelFontChangeEnabled() || !EditorUtil.isChangeFontSize(e)) { super.processMouseWheelEvent(e); return; } int rotation = e.getWheelRotation(); if (rotation == 0) return; int change = Math.abs(rotation); boolean increase = rotation <= 0; FontSize newFontSize = getQuickDocFontSize(); for (; change > 0; change--) { if (increase) { newFontSize = newFontSize.larger(); } else { newFontSize = newFontSize.smaller(); } } if (newFontSize == getQuickDocFontSize()) { return; } setQuickDocFontSize(newFontSize); applyFontProps(); setFontSizeSliderSize(newFontSize); } } private class ShowAsToolwindowAction extends AnAction implements HintManagerImpl.ActionToIgnore { ShowAsToolwindowAction() { super("Open as Tool Window"); } @Override public void update(@NotNull AnActionEvent e) { e.getPresentation().setIcon(ToolWindowManagerEx.getInstanceEx(myManager.myProject).getLocationIcon(ToolWindowId.DOCUMENTATION, EmptyIcon.ICON_16)); e.getPresentation().setEnabledAndVisible(myToolwindowCallback != null); } @Override public void actionPerformed(@NotNull AnActionEvent e) { myToolwindowCallback.run(); } } private class RestoreDefaultSizeAction extends AnAction implements HintManagerImpl.ActionToIgnore { RestoreDefaultSizeAction() { super("Restore Size"); } @Override public void update(@NotNull AnActionEvent e) { e.getPresentation().setEnabledAndVisible(myHint != null && (myManuallyResized || myHint.getDimensionServiceKey() != null)); } @Override public void actionPerformed(@NotNull AnActionEvent e) { myManuallyResized = false; if (myStoreSize) { DimensionService.getInstance().setSize(DocumentationManager.NEW_JAVADOC_LOCATION_AND_SIZE, null, myManager.myProject); myHint.setDimensionServiceKey(null); } showHint(); } } }
platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.documentation; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.hint.HintManagerImpl; import com.intellij.codeInsight.lookup.LookupEx; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.icons.AllIcons; import com.intellij.ide.DataManager; import com.intellij.ide.actions.BaseNavigateToSourceAction; import com.intellij.ide.actions.ExternalJavaDocAction; import com.intellij.ide.actions.WindowAction; import com.intellij.ide.util.PropertiesComponent; import com.intellij.lang.documentation.CompositeDocumentationProvider; import com.intellij.lang.documentation.DocumentationMarkup; import com.intellij.lang.documentation.DocumentationProvider; import com.intellij.lang.documentation.ExternalDocumentationHandler; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.AnActionListener; import com.intellij.openapi.actionSystem.impl.ActionButton; import com.intellij.openapi.actionSystem.impl.ActionManagerImpl; import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl; import com.intellij.openapi.actionSystem.impl.MenuItemPresentationFactory; import com.intellij.openapi.application.ApplicationBundle; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.colors.ColorKey; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.EditorColorsUtil; import com.intellij.openapi.editor.ex.EditorSettingsExternalizable; import com.intellij.openapi.editor.ex.util.EditorUtil; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.keymap.ex.KeymapManagerEx; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.module.ModuleTypeManager; import com.intellij.openapi.options.FontSize; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.*; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.util.PopupUtil; import com.intellij.openapi.util.DimensionService; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.ToolWindowId; import com.intellij.openapi.wm.ex.ToolWindowManagerEx; import com.intellij.openapi.wm.ex.WindowManagerEx; import com.intellij.pom.Navigatable; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.SmartPointerManager; import com.intellij.psi.SmartPsiElementPointer; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.reference.SoftReference; import com.intellij.ui.*; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.components.JBLayeredPane; import com.intellij.ui.components.JBScrollPane; import com.intellij.ui.popup.AbstractPopup; import com.intellij.ui.popup.PopupPositionManager; import com.intellij.ui.scale.JBUIScale; import com.intellij.ui.scale.ScaleContext; import com.intellij.util.ArrayUtilRt; import com.intellij.util.ImageLoader; import com.intellij.util.Url; import com.intellij.util.Urls; import com.intellij.util.ui.*; import com.intellij.util.ui.accessibility.ScreenReader; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.ide.BuiltInServerManager; import javax.swing.*; import javax.swing.border.Border; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.plaf.TextUI; import javax.swing.text.*; import javax.swing.text.html.HTML; import javax.swing.text.html.HTMLDocument; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.ImageView; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.awt.image.RenderedImage; import java.awt.image.renderable.RenderContext; import java.awt.image.renderable.RenderableImage; import java.awt.image.renderable.RenderableImageProducer; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.List; import java.util.*; public class DocumentationComponent extends JPanel implements Disposable, DataProvider { private static final Logger LOG = Logger.getInstance(DocumentationComponent.class); private static final String DOCUMENTATION_TOPIC_ID = "reference.toolWindows.Documentation"; private static final Color DOCUMENTATION_COLOR = new JBColor(new Color(0xf7f7f7), new Color(0x46484a)); private static final JBColor BORDER_COLOR = new JBColor(new Color(0xadadad), new Color(0x616366)); public static final ColorKey COLOR_KEY = ColorKey.createColorKey("DOCUMENTATION_COLOR", DOCUMENTATION_COLOR); public static final Color SECTION_COLOR = Gray.get(0x90); private static final Highlighter.HighlightPainter LINK_HIGHLIGHTER = new LinkHighlighter(); private static final int PREFERRED_HEIGHT_MAX_EM = 10; private static final JBDimension MAX_DEFAULT = new JBDimension(650, 500); private static final JBDimension MIN_DEFAULT = new JBDimension(300, 20); private final ExternalDocAction myExternalDocAction; private DocumentationManager myManager; private SmartPsiElementPointer myElement; private long myModificationCount; public static final String QUICK_DOC_FONT_SIZE_PROPERTY = "quick.doc.font.size"; private final Stack<Context> myBackStack = new Stack<>(); private final Stack<Context> myForwardStack = new Stack<>(); private final ActionToolbarImpl myToolBar; private volatile boolean myIsEmpty; private boolean mySizeTrackerRegistered; private JSlider myFontSizeSlider; private final JComponent mySettingsPanel; private boolean myIgnoreFontSizeSliderChange; private String myExternalUrl; private DocumentationProvider myProvider; private Reference<Component> myReferenceComponent; private final MyDictionary<String, Image> myImageProvider = new MyDictionary<String, Image>() { @Override public Image get(Object key) { return getImageByKeyImpl(key); } }; private Runnable myToolwindowCallback; private final ActionButton myCorner; private final MyScrollPane myScrollPane; private final JEditorPane myEditorPane; private String myText; // myEditorPane.getText() surprisingly crashes.., let's cache the text private String myDecoratedText; // myEditorPane.getText() surprisingly crashes.., let's cache the text private final JComponent myControlPanel; private boolean myControlPanelVisible; private int myHighlightedLink = -1; private Object myHighlightingTag; private final boolean myStoreSize; private boolean myManuallyResized; private AbstractPopup myHint; private final Map<KeyStroke, ActionListener> myKeyboardActions = new HashMap<>(); @NotNull public static DocumentationComponent createAndFetch(@NotNull Project project, @NotNull PsiElement element, @NotNull Disposable disposable) { DocumentationManager manager = DocumentationManager.getInstance(project); DocumentationComponent component = new DocumentationComponent(manager); Disposer.register(disposable, component); manager.fetchDocInfo(element, component); return component; } public DocumentationComponent(DocumentationManager manager) { this(manager, true); } public DocumentationComponent(DocumentationManager manager, boolean storeSize) { myManager = manager; myIsEmpty = true; myStoreSize = storeSize; myEditorPane = new JEditorPane(UIUtil.HTML_MIME, "") { { enableEvents(AWTEvent.KEY_EVENT_MASK); } @Override protected void processKeyEvent(KeyEvent e) { KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(e); ActionListener listener = myKeyboardActions.get(keyStroke); if (listener != null) { listener.actionPerformed(new ActionEvent(DocumentationComponent.this, 0, "")); e.consume(); return; } super.processKeyEvent(e); } Point initialClick; @Override protected void processMouseEvent(MouseEvent e) { if (e.getID() == MouseEvent.MOUSE_PRESSED && myHint != null) { //DocumentationComponent.this.requestFocus(); initialClick = null; StyledDocument document = (StyledDocument)getDocument(); int x = e.getX(); int y = e.getY(); if (!hasTextAt(document, x, y) && !hasTextAt(document, x + 3, y) && !hasTextAt(document, x - 3, y) && !hasTextAt(document, x, y + 3) && !hasTextAt(document, x, y - 3)) { initialClick = e.getPoint(); } } super.processMouseEvent(e); } private boolean hasTextAt(StyledDocument document, int x, int y) { Element element = document.getCharacterElement(viewToModel(new Point(x, y))); try { String text = document.getText(element.getStartOffset(), element.getEndOffset() - element.getStartOffset()); if (StringUtil.isEmpty(text.trim())) { return false; } } catch (BadLocationException ignored) { return false; } return true; } @Override protected void processMouseMotionEvent(MouseEvent e) { if (e.getID() == MouseEvent.MOUSE_DRAGGED && myHint != null && initialClick != null) { Point location = myHint.getLocationOnScreen(); myHint.setLocation(new Point(location.x + e.getX() - initialClick.x, location.y + e.getY() - initialClick.y)); e.consume(); return; } super.processMouseMotionEvent(e); } @Override protected void paintComponent(Graphics g) { GraphicsUtil.setupAntialiasing(g); super.paintComponent(g); } @Override public void setDocument(Document doc) { super.setDocument(doc); doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE); if (doc instanceof StyledDocument) { doc.putProperty("imageCache", myImageProvider); } } }; DataProvider helpDataProvider = dataId -> PlatformDataKeys.HELP_ID.is(dataId) ? DOCUMENTATION_TOPIC_ID : null; myEditorPane.putClientProperty(DataManager.CLIENT_PROPERTY_DATA_PROVIDER, helpDataProvider); myText = ""; myDecoratedText = ""; myEditorPane.setEditable(false); if (ScreenReader.isActive()) { // Note: Making the caret visible is merely for convenience myEditorPane.getCaret().setVisible(true); } myEditorPane.setBackground(EditorColorsUtil.getGlobalOrDefaultColor(COLOR_KEY)); HTMLEditorKit editorKit = new JBHtmlEditorKit(true) { @Override public ViewFactory getViewFactory() { return new HTMLFactory() { @Override public View create(Element elem) { if ("icon".equals(elem.getName())) { Object src = elem.getAttributes().getAttribute(HTML.Attribute.SRC); Icon icon = src != null ? IconLoader.findIcon((String)src, false) : null; if (icon == null) { ModuleType id = ModuleTypeManager.getInstance().findByID((String)src); if (id != null) icon = id.getIcon(); } if (icon != null) { Icon viewIcon = icon; return new View(elem) { @Override public float getPreferredSpan(int axis) { switch (axis) { case View.X_AXIS: return viewIcon.getIconWidth(); case View.Y_AXIS: return viewIcon.getIconHeight(); default: throw new IllegalArgumentException("Invalid axis: " + axis); } } @Override public String getToolTipText(float x, float y, Shape allocation) { return (String)getElement().getAttributes().getAttribute(HTML.Attribute.ALT); } @Override public void paint(Graphics g, Shape allocation) { viewIcon.paintIcon(null, g, allocation.getBounds().x, allocation.getBounds().y - 4); } @Override public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException { int p0 = getStartOffset(); int p1 = getEndOffset(); if ((pos >= p0) && (pos <= p1)) { Rectangle r = a.getBounds(); if (pos == p1) { r.x += r.width; } r.width = 0; return r; } throw new BadLocationException(pos + " not in range " + p0 + "," + p1, pos); } @Override public int viewToModel(float x, float y, Shape a, Position.Bias[] bias) { Rectangle alloc = (Rectangle)a; if (x < alloc.x + (alloc.width / 2f)) { bias[0] = Position.Bias.Forward; return getStartOffset(); } bias[0] = Position.Bias.Backward; return getEndOffset(); } }; } } View view = super.create(elem); if (view instanceof ImageView) { // we have to work with raw image, apply scaling manually return new ImageView(elem) { @Override public float getMaximumSpan(int axis) { return super.getMaximumSpan(axis) / JBUIScale.sysScale(myEditorPane); } @Override public float getMinimumSpan(int axis) { return super.getMinimumSpan(axis) / JBUIScale.sysScale(myEditorPane); } @Override public float getPreferredSpan(int axis) { return super.getPreferredSpan(axis) / JBUIScale.sysScale(myEditorPane); } @Override public void paint(Graphics g, Shape a) { Rectangle bounds = a.getBounds(); int width = (int)super.getPreferredSpan(View.X_AXIS); int height = (int)super.getPreferredSpan(View.Y_AXIS); if (width <= 0 || height <= 0) return; @SuppressWarnings("UndesirableClassUsage") BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = image.createGraphics(); super.paint(graphics, new Rectangle(image.getWidth(), image.getHeight())); UIUtil.drawImage(g, ImageUtil.ensureHiDPI(image, ScaleContext.create(myEditorPane)), bounds.x, bounds.y, null); } }; } return view; } }; } }; prepareCSS(editorKit); myEditorPane.setEditorKit(editorKit); myEditorPane.setBorder(JBUI.Borders.empty()); myScrollPane = new MyScrollPane(); myScrollPane.putClientProperty(DataManager.CLIENT_PROPERTY_DATA_PROVIDER, helpDataProvider); FocusListener focusAdapter = new FocusAdapter() { @Override public void focusLost(FocusEvent e) { Component previouslyFocused = WindowManagerEx.getInstanceEx().getFocusedComponent(manager.getProject(getElement())); if (previouslyFocused != myEditorPane) { if (myHint != null && !myHint.isDisposed()) myHint.cancel(); } } }; myEditorPane.addFocusListener(focusAdapter); Disposer.register(this, new Disposable() { @Override public void dispose() { myEditorPane.removeFocusListener(focusAdapter); } }); setLayout(new BorderLayout()); mySettingsPanel = createSettingsPanel(); //add(myScrollPane, BorderLayout.CENTER); setOpaque(true); myScrollPane.setBorder(JBUI.Borders.empty()); DefaultActionGroup actions = new DefaultActionGroup(); BackAction back = new BackAction(); ForwardAction forward = new ForwardAction(); EditDocumentationSourceAction edit = new EditDocumentationSourceAction(); myExternalDocAction = new ExternalDocAction(); actions.add(back); actions.add(forward); actions.add(edit); try { String backKey = ScreenReader.isActive() ? "alt LEFT" : "LEFT"; CustomShortcutSet backShortcutSet = new CustomShortcutSet(KeyboardShortcut.fromString(backKey), KeymapUtil.parseMouseShortcut("button4")); String forwardKey = ScreenReader.isActive() ? "alt RIGHT" : "RIGHT"; CustomShortcutSet forwardShortcutSet = new CustomShortcutSet(KeyboardShortcut.fromString(forwardKey), KeymapUtil.parseMouseShortcut("button5")); back.registerCustomShortcutSet(backShortcutSet, this); forward.registerCustomShortcutSet(forwardShortcutSet, this); // mouse actions are checked only for exact component over which click was performed, // so we need to register shortcuts for myEditorPane as well back.registerCustomShortcutSet(backShortcutSet, myEditorPane); forward.registerCustomShortcutSet(forwardShortcutSet, myEditorPane); } catch (InvalidDataException e) { LOG.error(e); } myExternalDocAction.registerCustomShortcutSet(CustomShortcutSet.fromString("UP"), this); myExternalDocAction.registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_EXTERNAL_JAVADOC).getShortcutSet(), myEditorPane); edit.registerCustomShortcutSet(CommonShortcuts.getEditSource(), this); ActionPopupMenu contextMenu = ((ActionManagerImpl)ActionManager.getInstance()).createActionPopupMenu( ActionPlaces.JAVADOC_TOOLBAR, actions, new MenuItemPresentationFactory(true)); PopupHandler popupHandler = new PopupHandler() { @Override public void invokePopup(Component comp, int x, int y) { contextMenu.getComponent().show(comp, x, y); } }; myEditorPane.addMouseListener(popupHandler); Disposer.register(this, () -> myEditorPane.removeMouseListener(popupHandler)); new NextLinkAction().registerCustomShortcutSet(CustomShortcutSet.fromString("TAB"), this); new PreviousLinkAction().registerCustomShortcutSet(CustomShortcutSet.fromString("shift TAB"), this); new ActivateLinkAction().registerCustomShortcutSet(CustomShortcutSet.fromString("ENTER"), this); DefaultActionGroup toolbarActions = new DefaultActionGroup(); toolbarActions.add(actions); toolbarActions.addAction(new ShowAsToolwindowAction()).setAsSecondary(true); toolbarActions.addAction(new MyShowSettingsAction(true)).setAsSecondary(true); toolbarActions.addAction(new ShowToolbarAction()).setAsSecondary(true); toolbarActions.addAction(new RestoreDefaultSizeAction()).setAsSecondary(true); myToolBar = new ActionToolbarImpl(ActionPlaces.JAVADOC_TOOLBAR, toolbarActions, true, KeymapManagerEx.getInstanceEx()) { Point initialClick; @Override protected void processMouseEvent(MouseEvent e) { if (e.getID() == MouseEvent.MOUSE_PRESSED && myHint != null) { initialClick = e.getPoint(); } super.processMouseEvent(e); } @Override protected void processMouseMotionEvent(MouseEvent e) { if (e.getID() == MouseEvent.MOUSE_DRAGGED && myHint != null && initialClick != null) { Point location = myHint.getLocationOnScreen(); myHint.setLocation(new Point(location.x + e.getX() - initialClick.x, location.y + e.getY() - initialClick.y)); e.consume(); return; } super.processMouseMotionEvent(e); } }; myToolBar.setSecondaryActionsIcon(AllIcons.Actions.More, true); JLayeredPane layeredPane = new JBLayeredPane() { @Override public void doLayout() { Rectangle r = getBounds(); for (Component component : getComponents()) { if (component instanceof JScrollPane) { component.setBounds(0, 0, r.width, r.height); } else { Dimension d = component.getPreferredSize(); component.setBounds(r.width - d.width - 2, r.height - d.height - 3, d.width, d.height); } } } @Override public Dimension getPreferredSize() { Dimension size = myScrollPane.getPreferredSize(); if (myHint == null && myManager != null && myManager.myToolWindow == null) { int em = myEditorPane.getFont().getSize(); int prefHeightMax = PREFERRED_HEIGHT_MAX_EM * em; return new Dimension(size.width, Math.min(prefHeightMax, size.height + (needsToolbar() ? myControlPanel.getPreferredSize().height : 0))); } return size; } }; layeredPane.add(myScrollPane); layeredPane.setLayer(myScrollPane, 0); DefaultActionGroup gearActions = new MyGearActionGroup(); ShowAsToolwindowAction showAsToolwindowAction = new ShowAsToolwindowAction(); gearActions.add(showAsToolwindowAction); gearActions.add(new MyShowSettingsAction(false)); gearActions.add(new ShowToolbarAction()); gearActions.add(new RestoreDefaultSizeAction()); gearActions.addSeparator(); gearActions.addAll(actions); Presentation presentation = new Presentation(); presentation.setIcon(AllIcons.Actions.More); presentation.putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, Boolean.TRUE); myCorner = new ActionButton(gearActions, presentation, ActionPlaces.UNKNOWN, new Dimension(20, 20)) { @Override protected DataContext getDataContext() { return DataManager.getInstance().getDataContext(myCorner); } }; myCorner.setNoIconsInPopup(true); showAsToolwindowAction.registerCustomShortcutSet(KeymapUtil.getActiveKeymapShortcuts("QuickJavaDoc"), myCorner); layeredPane.add(myCorner); layeredPane.setLayer(myCorner, JLayeredPane.POPUP_LAYER); add(layeredPane, BorderLayout.CENTER); myControlPanel = myToolBar.getComponent(); myControlPanel.setBorder(IdeBorderFactory.createBorder(SideBorder.BOTTOM)); myControlPanelVisible = false; HyperlinkListener hyperlinkListener = new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent e) { HyperlinkEvent.EventType type = e.getEventType(); if (type == HyperlinkEvent.EventType.ACTIVATED) { manager.navigateByLink(DocumentationComponent.this, e.getDescription()); } } }; myEditorPane.addHyperlinkListener(hyperlinkListener); Disposer.register(this, new Disposable() { @Override public void dispose() { myEditorPane.removeHyperlinkListener(hyperlinkListener); } }); if (myHint != null) { Disposer.register(myHint, this); } else if (myManager.myToolWindow != null) { Disposer.register(myManager.myToolWindow.getContentManager(), this); } registerActions(); updateControlState(); } public AnAction[] getActions() { return myToolBar.getActions().stream().filter((action -> !(action instanceof Separator))).toArray(AnAction[]::new); } public AnAction getFontSizeAction() { return new MyShowSettingsAction(false); } public void removeCornerMenu() { myCorner.setVisible(false); } public void setToolwindowCallback(Runnable callback) { myToolwindowCallback = callback; } public void showExternalDoc() { DataContext dataContext = DataManager.getInstance().getDataContext(this); myExternalDocAction.actionPerformed(AnActionEvent.createFromDataContext(ActionPlaces.UNKNOWN, null, dataContext)); } @Override public boolean requestFocusInWindow() { // With a screen reader active, set the focus directly to the editor because // it makes it easier for users to read/navigate the documentation contents. if (ScreenReader.isActive()) { return myEditorPane.requestFocusInWindow(); } else { return myScrollPane.requestFocusInWindow(); } } @Override public void requestFocus() { // With a screen reader active, set the focus directly to the editor because // it makes it easier for users to read/navigate the documentation contents. IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> { if (ScreenReader.isActive()) { IdeFocusManager.getGlobalInstance().requestFocus(myEditorPane, true); } else { IdeFocusManager.getGlobalInstance().requestFocus(myScrollPane, true); } }); } private static void prepareCSS(HTMLEditorKit editorKit) { Color borderColor = ColorUtil.mix(DOCUMENTATION_COLOR, BORDER_COLOR, 0.5); String editorFontName = StringUtil.escapeQuotes(EditorColorsManager.getInstance().getGlobalScheme().getEditorFontName()); editorKit.getStyleSheet().addRule("code {font-family:\"" + editorFontName + "\"}"); editorKit.getStyleSheet().addRule("pre {font-family:\"" + editorFontName + "\"}"); editorKit.getStyleSheet().addRule(".pre {font-family:\"" + editorFontName + "\"}"); editorKit.getStyleSheet().addRule("html { padding-bottom: 5px; }"); editorKit.getStyleSheet().addRule("h1, h2, h3, h4, h5, h6 { margin-top: 0; padding-top: 1px; }"); editorKit.getStyleSheet().addRule("a { color: #" + ColorUtil.toHex(getLinkColor()) + "; text-decoration: none;}"); editorKit.getStyleSheet().addRule(".definition { padding: 3px 17px 1px 7px; border-bottom: thin solid #" + ColorUtil.toHex(borderColor) + "; }"); editorKit.getStyleSheet().addRule(".definition-only { padding: 3px 17px 0 7px; }"); editorKit.getStyleSheet().addRule(".content { padding: 5px 16px 0 7px; max-width: 100% }"); editorKit.getStyleSheet().addRule(".bottom { padding: 3px 16px 0 7px; }"); editorKit.getStyleSheet().addRule(".bottom-no-content { padding: 5px 16px 0 7px; }"); editorKit.getStyleSheet().addRule("p { padding: 1px 0 2px 0; }"); editorKit.getStyleSheet().addRule("ol { padding: 0 16px 0 0; }"); editorKit.getStyleSheet().addRule("ul { padding: 0 16px 0 0; }"); editorKit.getStyleSheet().addRule("li { padding: 1px 0 2px 0; }"); editorKit.getStyleSheet().addRule(".grayed { color: #909090; display: inline;}"); editorKit.getStyleSheet().addRule(".centered { text-align: center}"); // sections table editorKit.getStyleSheet().addRule(".sections { padding: 0 16px 0 7px; border-spacing: 0; }"); editorKit.getStyleSheet().addRule("tr { margin: 0 0 0 0; padding: 0 0 0 0; }"); editorKit.getStyleSheet().addRule("td { margin: 2px 0 3.5px 0; padding: 0 0 0 0; }"); editorKit.getStyleSheet().addRule("th { text-align: left; }"); editorKit.getStyleSheet().addRule(".section { color: " + ColorUtil.toHtmlColor(SECTION_COLOR) + "; padding-right: 4px}"); } private static Color getLinkColor() { return JBUI.CurrentTheme.Link.linkColor(); } @Override public Object getData(@NotNull @NonNls String dataId) { if (DocumentationManager.SELECTED_QUICK_DOC_TEXT.getName().equals(dataId)) { // Javadocs often contain &nbsp; symbols (non-breakable white space). We don't want to copy them as is and replace // with raw white spaces. See IDEA-86633 for more details. String selectedText = myEditorPane.getSelectedText(); return selectedText == null ? null : selectedText.replace((char)160, ' '); } return null; } private JComponent createSettingsPanel() { JPanel result = new JPanel(new FlowLayout(FlowLayout.RIGHT, 3, 0)); result.add(new JLabel(ApplicationBundle.message("label.font.size"))); myFontSizeSlider = new JSlider(SwingConstants.HORIZONTAL, 0, FontSize.values().length - 1, 3); myFontSizeSlider.setMinorTickSpacing(1); myFontSizeSlider.setPaintTicks(true); myFontSizeSlider.setPaintTrack(true); myFontSizeSlider.setSnapToTicks(true); UIUtil.setSliderIsFilled(myFontSizeSlider, true); result.add(myFontSizeSlider); result.setBorder(BorderFactory.createLineBorder(JBColor.border(), 1)); myFontSizeSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (myIgnoreFontSizeSliderChange) { return; } setQuickDocFontSize(FontSize.values()[myFontSizeSlider.getValue()]); applyFontProps(); // resize popup according to new font size, if user didn't set popup size manually if (!myManuallyResized && myHint != null && myHint.getDimensionServiceKey() == null) showHint(); } }); String tooltipText = ApplicationBundle.message("quickdoc.tooltip.font.size.by.wheel"); result.setToolTipText(tooltipText); myFontSizeSlider.setToolTipText(tooltipText); result.setVisible(false); result.setOpaque(true); myFontSizeSlider.setOpaque(true); return result; } @NotNull public static FontSize getQuickDocFontSize() { String strValue = PropertiesComponent.getInstance().getValue(QUICK_DOC_FONT_SIZE_PROPERTY); if (strValue != null) { try { return FontSize.valueOf(strValue); } catch (IllegalArgumentException iae) { // ignore, fall back to default font. } } return FontSize.SMALL; } public void setQuickDocFontSize(@NotNull FontSize fontSize) { PropertiesComponent.getInstance().setValue(QUICK_DOC_FONT_SIZE_PROPERTY, fontSize.toString()); } private void setFontSizeSliderSize(FontSize fontSize) { myIgnoreFontSizeSliderChange = true; try { FontSize[] sizes = FontSize.values(); for (int i = 0; i < sizes.length; i++) { if (fontSize == sizes[i]) { myFontSizeSlider.setValue(i); break; } } } finally { myIgnoreFontSizeSliderChange = false; } } public boolean isEmpty() { return myIsEmpty; } public void startWait() { myIsEmpty = true; } private void setControlPanelVisible() { if (myControlPanelVisible) return; add(myControlPanel, BorderLayout.NORTH); myControlPanelVisible = true; } public void setHint(JBPopup hint) { myHint = (AbstractPopup)hint; } public JBPopup getHint() { return myHint; } public JComponent getComponent() { return myEditorPane; } @Nullable public PsiElement getElement() { return myElement != null ? myElement.getElement() : null; } private void setElement(SmartPsiElementPointer element) { myElement = element; myModificationCount = getCurrentModificationCount(); } public boolean isUpToDate() { return getElement() != null && myModificationCount == getCurrentModificationCount(); } private long getCurrentModificationCount() { return myElement != null ? PsiModificationTracker.SERVICE.getInstance(myElement.getProject()).getModificationCount() : -1; } public void setText(@NotNull String text, @Nullable PsiElement element, @Nullable DocumentationProvider provider) { setData(element, text, null, null, provider); } public void replaceText(@NotNull String text, @Nullable PsiElement element) { PsiElement current = getElement(); if (current == null || !current.getManager().areElementsEquivalent(current, element)) return; restoreContext(saveContext().withText(text)); } public void clearHistory() { myForwardStack.clear(); myBackStack.clear(); } private void pushHistory() { if (myElement != null) { myBackStack.push(saveContext()); myForwardStack.clear(); } } public void setData(@Nullable PsiElement element, @NotNull String text, @Nullable String effectiveExternalUrl, @Nullable String ref, @Nullable DocumentationProvider provider) { pushHistory(); myExternalUrl = effectiveExternalUrl; myProvider = provider; SmartPsiElementPointer pointer = null; if (element != null && element.isValid()) { pointer = SmartPointerManager.getInstance(element.getProject()).createSmartPsiElementPointer(element); } setDataInternal(pointer, text, new Rectangle(0, 0), ref); } private void setDataInternal(@Nullable SmartPsiElementPointer element, @NotNull String text, @NotNull Rectangle viewRect, @Nullable String ref) { myIsEmpty = false; if (myManager == null) return; myText = text; myDecoratedText = decorate(text); setElement(element); showHint(viewRect, ref); } protected void showHint(@NotNull Rectangle viewRect, @Nullable String ref) { String refToUse; Rectangle viewRectToUse; if (DocumentationManagerProtocol.KEEP_SCROLLING_POSITION_REF.equals(ref)) { refToUse = null; viewRectToUse = myScrollPane.getViewport().getViewRect(); } else { refToUse = ref; viewRectToUse = viewRect; } updateControlState(); highlightLink(-1); myEditorPane.setText(myDecoratedText); applyFontProps(); showHint(); //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> { myEditorPane.scrollRectToVisible(viewRectToUse); // if ref is defined but is not found in document, this provides a default location if (refToUse != null) { myEditorPane.scrollToReference(refToUse); } else if (ScreenReader.isActive()) { myEditorPane.setCaretPosition(0); } }); } private void showHint() { if (myHint == null) return; setHintSize(); DataContext dataContext = getDataContext(); PopupPositionManager.positionPopupInBestPosition(myHint, myManager.getEditor(), dataContext, PopupPositionManager.Position.RIGHT, PopupPositionManager.Position.LEFT); Window window = myHint.getPopupWindow(); if (window != null) window.setFocusableWindowState(true); if (myHint.getDimensionServiceKey() == null) { registerSizeTracker(); } } private DataContext getDataContext() { Component referenceComponent; if (myReferenceComponent == null) { referenceComponent = IdeFocusManager.getInstance(myManager.myProject).getFocusOwner(); myReferenceComponent = new WeakReference<>(referenceComponent); } else { referenceComponent = SoftReference.dereference(myReferenceComponent); if (referenceComponent == null || ! referenceComponent.isShowing()) referenceComponent = myHint.getComponent(); } return DataManager.getInstance().getDataContext(referenceComponent); } private void setHintSize() { Dimension hintSize; if (!myManuallyResized && myHint.getDimensionServiceKey() == null) { int minWidth = JBUIScale.scale(300); int maxWidth = getPopupAnchor() != null ? JBUIScale.scale(435) : MAX_DEFAULT.width; int width = definitionPreferredWidth(); if (width < 0) { // no definition found width = myEditorPane.getPreferredSize().width; } else { width = Math.max(width, myEditorPane.getMinimumSize().width); } width = Math.min(maxWidth, Math.max(minWidth, width)); myEditorPane.setBounds(0, 0, width, MAX_DEFAULT.height); myEditorPane.setText(myDecoratedText); Dimension preferredSize = myEditorPane.getPreferredSize(); int height = preferredSize.height + (needsToolbar() ? myControlPanel.getPreferredSize().height : 0); height = Math.min(MAX_DEFAULT.height, Math.max(MIN_DEFAULT.height, height)); hintSize = new Dimension(width, height); } else { hintSize = myManuallyResized ? myHint.getSize() : DimensionService.getInstance().getSize(DocumentationManager.NEW_JAVADOC_LOCATION_AND_SIZE, myManager.myProject); if (hintSize == null) { hintSize = new Dimension(MIN_DEFAULT); } else { hintSize.width = Math.max(hintSize.width, MIN_DEFAULT.width); hintSize.height = Math.max(hintSize.height, MIN_DEFAULT.height); } } myHint.setSize(hintSize); } private Component getPopupAnchor() { LookupEx lookup = LookupManager.getActiveLookup(myManager.getEditor()); if (lookup != null && lookup.getCurrentItem() != null && lookup.getComponent().isShowing()) { return lookup.getComponent(); } Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); JBPopup popup = PopupUtil.getPopupContainerFor(focusOwner); if (popup != null && popup != myHint && !popup.isDisposed()) { return popup.getContent(); } return null; } private void registerSizeTracker() { AbstractPopup hint = myHint; if (hint == null || mySizeTrackerRegistered) return; mySizeTrackerRegistered = true; hint.addResizeListener(this::onManualResizing, this); ApplicationManager.getApplication().getMessageBus().connect(this).subscribe(AnActionListener.TOPIC, new AnActionListener() { @Override public void afterActionPerformed(@NotNull AnAction action, @NotNull DataContext dataContext, @NotNull AnActionEvent event) { if (action instanceof WindowAction) onManualResizing(); } }); } private void onManualResizing() { myManuallyResized = true; if (myStoreSize && myHint != null) { myHint.setDimensionServiceKey(DocumentationManager.NEW_JAVADOC_LOCATION_AND_SIZE); myHint.storeDimensionSize(); } } private int definitionPreferredWidth() { TextUI ui = myEditorPane.getUI(); View view = ui.getRootView(myEditorPane); View definition = findDefinition(view); return definition != null ? (int)definition.getPreferredSpan(View.X_AXIS) : -1; } private static View findDefinition(View view) { if ("definition".equals(view.getElement().getAttributes().getAttribute(HTML.Attribute.CLASS))) { return view; } for (int i = 0; i < view.getViewCount(); i++) { View definition = findDefinition(view.getView(i)); if (definition != null) return definition; } return null; } private String decorate(String text) { text = StringUtil.replaceIgnoreCase(text, "</html>", ""); text = StringUtil.replaceIgnoreCase(text, "</body>", ""); text = StringUtil.replaceIgnoreCase(text, DocumentationMarkup.SECTIONS_START + DocumentationMarkup.SECTIONS_END, ""); text = StringUtil.replaceIgnoreCase(text, DocumentationMarkup.SECTIONS_START + "<p>" + DocumentationMarkup.SECTIONS_END, ""); boolean hasContent = text.contains(DocumentationMarkup.CONTENT_START); if (!hasContent) { if (!text.contains(DocumentationMarkup.DEFINITION_START)) { int bodyStart = findContentStart(text); if (bodyStart > 0) { text = text.substring(0, bodyStart) + DocumentationMarkup.CONTENT_START + text.substring(bodyStart) + DocumentationMarkup.CONTENT_END; } else { text = DocumentationMarkup.CONTENT_START + text + DocumentationMarkup.CONTENT_END; } hasContent = true; } else if (!text.contains(DocumentationMarkup.SECTIONS_START)){ text = StringUtil.replaceIgnoreCase(text, DocumentationMarkup.DEFINITION_START, "<div class='definition-only'><pre>"); } } String location = getLocationText(); if (location != null) { text = text + getBottom(hasContent) + location + "</div>"; } String links = getExternalText(myManager, getElement(), myExternalUrl, myProvider); if (links != null) { text = text + getBottom(location != null) + links; } //workaround for Swing html renderer not removing empty paragraphs before non-inline tags text = text.replaceAll("<p>\\s*(<(?:[uo]l|h\\d|p))", "$1"); text = addExternalLinksIcon(text); return text; } @Nullable private static String getExternalText(@NotNull DocumentationManager manager, @Nullable PsiElement element, @Nullable String externalUrl, @Nullable DocumentationProvider provider) { if (element == null || provider == null) return null; PsiElement originalElement = DocumentationManager.getOriginalElement(element); if (!shouldShowExternalDocumentationLink(provider, element, originalElement)) { return null; } String title = manager.getTitle(element); if (title != null) { title = StringUtil.escapeXmlEntities(title); } if (externalUrl == null) { List<String> urls = provider.getUrlFor(element, originalElement); if (urls != null) { boolean hasBadUrl = false; StringBuilder result = new StringBuilder(); for (String url : urls) { String link = getLink(title, url); if (link == null) { hasBadUrl = true; break; } if (result.length() > 0) result.append("<p>"); result.append(link); } if (!hasBadUrl) return result.toString(); } else { return null; } } else { String link = getLink(title, externalUrl); if (link != null) return link; } return "<a href='external_doc'>External documentation" + (title == null ? "" : (" for `" + title + "`")) + "<icon src='AllIcons.Ide.External_link_arrow'></a></div>"; } private static String getLink(String title, String url) { StringBuilder result = new StringBuilder(); String hostname = getHostname(url); if (hostname == null) { return null; } result.append("<a href='").append(url).append("'>"); if (title == null) { result.append("Documentation"); } else { result.append("`").append(title).append("`"); } result.append(" on ").append(hostname).append("</a>"); return result.toString(); } static boolean shouldShowExternalDocumentationLink(DocumentationProvider provider, PsiElement element, PsiElement originalElement) { if (provider instanceof CompositeDocumentationProvider) { List<DocumentationProvider> providers = ((CompositeDocumentationProvider)provider).getProviders(); for (DocumentationProvider p : providers) { if (p instanceof ExternalDocumentationHandler) { return ((ExternalDocumentationHandler)p).canHandleExternal(element, originalElement); } } } else if (provider instanceof ExternalDocumentationHandler) { return ((ExternalDocumentationHandler)provider).canHandleExternal(element, originalElement); } return true; } private static String getHostname(String url) { try { return new URL(url).toURI().getHost(); } catch (URISyntaxException | MalformedURLException ignored) { } return null; } private static int findContentStart(String text) { int index = StringUtil.indexOfIgnoreCase(text, "<body>", 0); if (index >= 0) return index + 6; index = StringUtil.indexOfIgnoreCase(text, "</head>", 0); if (index >= 0) return index + 7; index = StringUtil.indexOfIgnoreCase(text, "</style>", 0); if (index >= 0) return index + 8; index = StringUtil.indexOfIgnoreCase(text, "<html>", 0); if (index >= 0) return index + 6; return -1; } @NotNull private static String getBottom(boolean hasContent) { return "<div class='" + (hasContent ? "bottom" : "bottom-no-content") + "'>"; } private static String addExternalLinksIcon(String text) { return text.replaceAll("(<a\\s*href=[\"']http[^>]*>)([^>]*)(</a>)", "$1$2<icon src='AllIcons.Ide.External_link_arrow'>$3"); } private String getLocationText() { PsiElement element = getElement(); if (element != null) { PsiFile file = element.getContainingFile(); VirtualFile vfile = file == null ? null : file.getVirtualFile(); if (vfile == null) return null; ProjectFileIndex fileIndex = ProjectRootManager.getInstance(element.getProject()).getFileIndex(); Module module = fileIndex.getModuleForFile(vfile); if (module != null) { if (ModuleManager.getInstance(element.getProject()).getModules().length == 1) return null; return "<icon src='" + ModuleType.get(module).getId() + "'>&nbsp;" + module.getName().replace("<", "&lt;"); } else { List<OrderEntry> entries = fileIndex.getOrderEntriesForFile(vfile); for (OrderEntry order : entries) { if (order instanceof LibraryOrderEntry || order instanceof JdkOrderEntry) { return "<icon src='AllIcons.Nodes.PpLibFolder" + "'>&nbsp;" + order.getPresentableName().replace("<", "&lt;"); } } } } return null; } private void applyFontProps() { Document document = myEditorPane.getDocument(); if (!(document instanceof StyledDocument)) { return; } String fontName = Registry.is("documentation.component.editor.font") ? EditorColorsManager.getInstance().getGlobalScheme().getEditorFontName() : myEditorPane.getFont().getFontName(); // changing font will change the doc's CSS as myEditorPane has JEditorPane.HONOR_DISPLAY_PROPERTIES via UIUtil.getHTMLEditorKit myEditorPane.setFont(UIUtil.getFontWithFallback(fontName, Font.PLAIN, JBUIScale.scale(getQuickDocFontSize().getSize()))); } @Nullable private Image getImageByKeyImpl(Object key) { if (myManager == null || key == null) return null; PsiElement element = getElement(); if (element == null) return null; URL url = (URL)key; Image inMemory = myManager.getElementImage(element, url.toExternalForm()); if (inMemory != null) { return inMemory; } Url parsedUrl = Urls.parseEncoded(url.toExternalForm()); BuiltInServerManager builtInServerManager = BuiltInServerManager.getInstance(); if (parsedUrl != null && builtInServerManager.isOnBuiltInWebServer(parsedUrl)) { try { url = new URL(builtInServerManager.addAuthToken(parsedUrl).toExternalForm()); } catch (MalformedURLException e) { LOG.warn(e); } } URL imageUrl = url; return Toolkit.getDefaultToolkit().createImage(new RenderableImageProducer(new RenderableImage() { private Image myImage; private boolean myImageLoaded; @Override public Vector<RenderableImage> getSources() { return null; } @Override public Object getProperty(String name) { return null; } @Override public String[] getPropertyNames() { return ArrayUtilRt.EMPTY_STRING_ARRAY; } @Override public boolean isDynamic() { return false; } @Override public float getWidth() { return getImage().getWidth(null); } @Override public float getHeight() { return getImage().getHeight(null); } @Override public float getMinX() { return 0; } @Override public float getMinY() { return 0; } @Override public RenderedImage createScaledRendering(int w, int h, RenderingHints hints) { return createDefaultRendering(); } @Override public RenderedImage createDefaultRendering() { return (RenderedImage)getImage(); } @Override public RenderedImage createRendering(RenderContext renderContext) { return createDefaultRendering(); } private Image getImage() { if (!myImageLoaded) { Image image = ImageLoader.loadFromUrl(imageUrl); myImage = ImageUtil.toBufferedImage(image != null ? image : ((ImageIcon)UIManager.getLookAndFeelDefaults().get("html.missingImage")).getImage()); myImageLoaded = true; } return myImage; } }, null)); } private void goBack() { if (myBackStack.isEmpty()) return; Context context = myBackStack.pop(); myForwardStack.push(saveContext()); restoreContext(context); } private void goForward() { if (myForwardStack.isEmpty()) return; Context context = myForwardStack.pop(); myBackStack.push(saveContext()); restoreContext(context); } private Context saveContext() { Rectangle rect = myScrollPane.getViewport().getViewRect(); return new Context(myElement, myText, myExternalUrl, myProvider, rect, myHighlightedLink); } private void restoreContext(@NotNull Context context) { myExternalUrl = context.externalUrl; myProvider = context.provider; setDataInternal(context.element, context.text, context.viewRect, null); highlightLink(context.highlightedLink); if (myManager != null) { PsiElement element = context.element.getElement(); if (element != null) { myManager.updateToolWindowTabName(element); } } } private void updateControlState() { if (needsToolbar()) { myToolBar.updateActionsImmediately(); // update faster setControlPanelVisible(); removeCornerMenu(); } else { myControlPanelVisible = false; remove(myControlPanel); if (myManager.myToolWindow != null) return; myCorner.setVisible(true); } } private boolean needsToolbar() { return myManager.myToolWindow == null && Registry.is("documentation.show.toolbar"); } private static class MyGearActionGroup extends DefaultActionGroup implements HintManagerImpl.ActionToIgnore { MyGearActionGroup(@NotNull AnAction... actions) { super(actions); setPopup(true); } } private class BackAction extends AnAction implements HintManagerImpl.ActionToIgnore { BackAction() { super(CodeInsightBundle.message("javadoc.action.back"), null, AllIcons.Actions.Back); } @Override public void actionPerformed(@NotNull AnActionEvent e) { goBack(); } @Override public void update(@NotNull AnActionEvent e) { Presentation presentation = e.getPresentation(); presentation.setEnabled(!myBackStack.isEmpty()); if (!isToolbar(e)) { presentation.setVisible(presentation.isEnabled()); } } } private class ForwardAction extends AnAction implements HintManagerImpl.ActionToIgnore { ForwardAction() { super(CodeInsightBundle.message("javadoc.action.forward"), null, AllIcons.Actions.Forward); } @Override public void actionPerformed(@NotNull AnActionEvent e) { goForward(); } @Override public void update(@NotNull AnActionEvent e) { Presentation presentation = e.getPresentation(); presentation.setEnabled(!myForwardStack.isEmpty()); if (!isToolbar(e)) { presentation.setVisible(presentation.isEnabled()); } } } private class EditDocumentationSourceAction extends BaseNavigateToSourceAction { private EditDocumentationSourceAction() { super(true); getTemplatePresentation().setIcon(AllIcons.Actions.EditSource); getTemplatePresentation().setText("Edit Source"); } @Override public void actionPerformed(@NotNull AnActionEvent e) { super.actionPerformed(e); JBPopup hint = myHint; if (hint != null && hint.isVisible()) { hint.cancel(); } } @Nullable @Override protected Navigatable[] getNavigatables(DataContext dataContext) { SmartPsiElementPointer element = myElement; if (element != null) { PsiElement psiElement = element.getElement(); return psiElement instanceof Navigatable ? new Navigatable[]{(Navigatable)psiElement} : null; } return null; } } private static boolean isToolbar(@NotNull AnActionEvent e) { return ActionPlaces.JAVADOC_TOOLBAR.equals(e.getPlace()); } private class ExternalDocAction extends AnAction implements HintManagerImpl.ActionToIgnore { private ExternalDocAction() { super(CodeInsightBundle.message("javadoc.action.view.external"), null, AllIcons.Actions.PreviousOccurence); registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_EXTERNAL_JAVADOC).getShortcutSet(), null); } @Override public void actionPerformed(@NotNull AnActionEvent e) { if (myElement == null) { return; } PsiElement element = myElement.getElement(); PsiElement originalElement = DocumentationManager.getOriginalElement(element); ExternalJavaDocAction.showExternalJavadoc(element, originalElement, myExternalUrl, e.getDataContext()); } @Override public void update(@NotNull AnActionEvent e) { Presentation presentation = e.getPresentation(); presentation.setEnabled(hasExternalDoc()); } } private boolean hasExternalDoc() { boolean enabled = false; if (myElement != null && myProvider != null) { PsiElement element = myElement.getElement(); PsiElement originalElement = DocumentationManager.getOriginalElement(element); enabled = element != null && CompositeDocumentationProvider.hasUrlsFor(myProvider, element, originalElement); } return enabled; } private void registerActions() { // With screen readers, we want the default keyboard behavior inside // the document text editor, i.e. the caret moves with cursor keys, etc. if (!ScreenReader.isActive()) { myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getVerticalScrollBar(); int value = scrollBar.getValue() - scrollBar.getUnitIncrement(-1); value = Math.max(value, 0); scrollBar.setValue(value); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getVerticalScrollBar(); int value = scrollBar.getValue() + scrollBar.getUnitIncrement(+1); value = Math.min(value, scrollBar.getMaximum()); scrollBar.setValue(value); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar(); int value = scrollBar.getValue() - scrollBar.getUnitIncrement(-1); value = Math.max(value, 0); scrollBar.setValue(value); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar(); int value = scrollBar.getValue() + scrollBar.getUnitIncrement(+1); value = Math.min(value, scrollBar.getMaximum()); scrollBar.setValue(value); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getVerticalScrollBar(); int value = scrollBar.getValue() - scrollBar.getBlockIncrement(-1); value = Math.max(value, 0); scrollBar.setValue(value); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getVerticalScrollBar(); int value = scrollBar.getValue() + scrollBar.getBlockIncrement(+1); value = Math.min(value, scrollBar.getMaximum()); scrollBar.setValue(value); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar(); scrollBar.setValue(0); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_END, 0), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar(); scrollBar.setValue(scrollBar.getMaximum()); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, InputEvent.CTRL_MASK), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getVerticalScrollBar(); scrollBar.setValue(0); } }); myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_END, InputEvent.CTRL_MASK), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = myScrollPane.getVerticalScrollBar(); scrollBar.setValue(scrollBar.getMaximum()); } }); } } public String getText() { return myText; } public String getDecoratedText() { return myDecoratedText; } @Override public void dispose() { myEditorPane.getCaret().setVisible(false); // Caret, if blinking, has to be deactivated. myBackStack.clear(); myForwardStack.clear(); myKeyboardActions.clear(); myElement = null; myManager = null; myHint = null; } private int getLinkCount() { HTMLDocument document = (HTMLDocument)myEditorPane.getDocument(); int linkCount = 0; for (HTMLDocument.Iterator it = document.getIterator(HTML.Tag.A); it.isValid(); it.next()) { if (it.getAttributes().isDefined(HTML.Attribute.HREF)) linkCount++; } return linkCount; } @Nullable private HTMLDocument.Iterator getLink(int n) { if (n >= 0) { HTMLDocument document = (HTMLDocument)myEditorPane.getDocument(); int linkCount = 0; for (HTMLDocument.Iterator it = document.getIterator(HTML.Tag.A); it.isValid(); it.next()) { if (it.getAttributes().isDefined(HTML.Attribute.HREF) && linkCount++ == n) return it; } } return null; } private void highlightLink(int n) { myHighlightedLink = n; Highlighter highlighter = myEditorPane.getHighlighter(); HTMLDocument.Iterator link = getLink(n); if (link != null) { int startOffset = link.getStartOffset(); int endOffset = link.getEndOffset(); try { if (myHighlightingTag == null) { myHighlightingTag = highlighter.addHighlight(startOffset, endOffset, LINK_HIGHLIGHTER); } else { highlighter.changeHighlight(myHighlightingTag, startOffset, endOffset); } myEditorPane.setCaretPosition(startOffset); } catch (BadLocationException e) { LOG.warn("Error highlighting link", e); } } else if (myHighlightingTag != null) { highlighter.removeHighlight(myHighlightingTag); myHighlightingTag = null; } } private void activateLink(int n) { HTMLDocument.Iterator link = getLink(n); if (link != null) { String href = (String)link.getAttributes().getAttribute(HTML.Attribute.HREF); myManager.navigateByLink(this, href); } } private static class Context { final SmartPsiElementPointer element; final String text; final String externalUrl; final DocumentationProvider provider; final Rectangle viewRect; final int highlightedLink; Context(SmartPsiElementPointer element, String text, String externalUrl, DocumentationProvider provider, Rectangle viewRect, int highlightedLink) { this.element = element; this.text = text; this.externalUrl = externalUrl; this.provider = provider; this.viewRect = viewRect; this.highlightedLink = highlightedLink; } @NotNull Context withText(@NotNull String text) { return new Context(element, text, externalUrl, provider, viewRect, highlightedLink); } } private class MyShowSettingsAction extends AnAction implements HintManagerImpl.ActionToIgnore { private final boolean myOnToolbar; MyShowSettingsAction(boolean onToolbar) { super("Adjust font size..."); myOnToolbar = onToolbar; } @Override public void update(@NotNull AnActionEvent e) { if (myManager == null || myOnToolbar && myManager.myToolWindow != null) { e.getPresentation().setEnabledAndVisible(false); } } @Override public void actionPerformed(@NotNull AnActionEvent e) { JBPopup popup = JBPopupFactory.getInstance().createComponentPopupBuilder(mySettingsPanel, myFontSizeSlider).createPopup(); setFontSizeSliderSize(getQuickDocFontSize()); mySettingsPanel.setVisible(true); Point location = MouseInfo.getPointerInfo().getLocation(); popup.show(new RelativePoint(new Point(location.x - mySettingsPanel.getPreferredSize().width / 2, location.y - mySettingsPanel.getPreferredSize().height / 2))); } } private abstract static class MyDictionary<K, V> extends Dictionary<K, V> { @Override public int size() { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { throw new UnsupportedOperationException(); } @Override public Enumeration<K> keys() { throw new UnsupportedOperationException(); } @Override public Enumeration<V> elements() { throw new UnsupportedOperationException(); } @Override public V put(K key, V value) { throw new UnsupportedOperationException(); } @Override public V remove(Object key) { throw new UnsupportedOperationException(); } } private class PreviousLinkAction extends AnAction implements HintManagerImpl.ActionToIgnore { @Override public void actionPerformed(@NotNull AnActionEvent e) { int linkCount = getLinkCount(); if (linkCount <= 0) return; highlightLink(myHighlightedLink < 0 ? (linkCount - 1) : (myHighlightedLink + linkCount - 1) % linkCount); } } private class NextLinkAction extends AnAction implements HintManagerImpl.ActionToIgnore { @Override public void actionPerformed(@NotNull AnActionEvent e) { int linkCount = getLinkCount(); if (linkCount <= 0) return; highlightLink((myHighlightedLink + 1) % linkCount); } } private class ActivateLinkAction extends AnAction implements HintManagerImpl.ActionToIgnore { @Override public void actionPerformed(@NotNull AnActionEvent e) { activateLink(myHighlightedLink); } } private static class LinkHighlighter implements Highlighter.HighlightPainter { private static final Stroke STROKE = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1, new float[]{1}, 0); @Override public void paint(Graphics g, int p0, int p1, Shape bounds, JTextComponent c) { try { Rectangle target = c.getUI().getRootView(c).modelToView(p0, Position.Bias.Forward, p1, Position.Bias.Backward, bounds).getBounds(); Graphics2D g2d = (Graphics2D)g.create(); try { g2d.setStroke(STROKE); g2d.setColor(c.getSelectionColor()); g2d.drawRect(target.x, target.y, target.width - 1, target.height - 1); } finally { g2d.dispose(); } } catch (Exception e) { LOG.warn("Error painting link highlight", e); } } } private class ShowToolbarAction extends ToggleAction implements HintManagerImpl.ActionToIgnore { ShowToolbarAction() { super("Show Toolbar"); } @Override public void update(@NotNull AnActionEvent e) { super.update(e); if (myManager == null || myManager.myToolWindow != null) { e.getPresentation().setEnabledAndVisible(false); } } @Override public boolean isSelected(@NotNull AnActionEvent e) { return Registry.get("documentation.show.toolbar").asBoolean(); } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { Registry.get("documentation.show.toolbar").setValue(state); updateControlState(); showHint(); } } private class MyScrollPane extends JBScrollPane { MyScrollPane() { super(myEditorPane, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED); setLayout(new Layout() { @Override public void layoutContainer(Container parent) { super.layoutContainer(parent); if (!myCorner.isVisible()) return; if (vsb != null) { Rectangle bounds = vsb.getBounds(); vsb.setBounds(bounds.x, bounds.y, bounds.width, bounds.height - myCorner.getPreferredSize().height - 3); } if (hsb != null) { Rectangle bounds = hsb.getBounds(); int vsbOffset = vsb != null ? vsb.getBounds().width : 0; hsb.setBounds(bounds.x, bounds.y, bounds.width - myCorner.getPreferredSize().width - 3 + vsbOffset, bounds.height); } } }); } @Override public Border getViewportBorder() { return null; } @Override protected void processMouseWheelEvent(MouseWheelEvent e) { if (!EditorSettingsExternalizable.getInstance().isWheelFontChangeEnabled() || !EditorUtil.isChangeFontSize(e)) { super.processMouseWheelEvent(e); return; } int rotation = e.getWheelRotation(); if (rotation == 0) return; int change = Math.abs(rotation); boolean increase = rotation <= 0; FontSize newFontSize = getQuickDocFontSize(); for (; change > 0; change--) { if (increase) { newFontSize = newFontSize.larger(); } else { newFontSize = newFontSize.smaller(); } } if (newFontSize == getQuickDocFontSize()) { return; } setQuickDocFontSize(newFontSize); applyFontProps(); setFontSizeSliderSize(newFontSize); } } private class ShowAsToolwindowAction extends AnAction implements HintManagerImpl.ActionToIgnore { ShowAsToolwindowAction() { super("Open as Tool Window"); } @Override public void update(@NotNull AnActionEvent e) { e.getPresentation().setIcon(ToolWindowManagerEx.getInstanceEx(myManager.myProject).getLocationIcon(ToolWindowId.DOCUMENTATION, EmptyIcon.ICON_16)); e.getPresentation().setEnabledAndVisible(myToolwindowCallback != null); } @Override public void actionPerformed(@NotNull AnActionEvent e) { myToolwindowCallback.run(); } } private class RestoreDefaultSizeAction extends AnAction implements HintManagerImpl.ActionToIgnore { RestoreDefaultSizeAction() { super("Restore Size"); } @Override public void update(@NotNull AnActionEvent e) { e.getPresentation().setEnabledAndVisible(myHint != null && (myManuallyResized || myHint.getDimensionServiceKey() != null)); } @Override public void actionPerformed(@NotNull AnActionEvent e) { myManuallyResized = false; if (myStoreSize) { DimensionService.getInstance().setSize(DocumentationManager.NEW_JAVADOC_LOCATION_AND_SIZE, null, myManager.myProject); myHint.setDimensionServiceKey(null); } showHint(); } } }
IDEA-218333 Fix separator in quick doc tooltip 'manually' cherry-picked from master (commit bdadd798b477ab624c0b783db9afe187217c951a) review: IDEA-CR-50122 GitOrigin-RevId: 5c0f0c2e8e81a227c457f3c0885ac7d463762e6c
platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java
IDEA-218333 Fix separator in quick doc tooltip
Java
apache-2.0
8b603edcc95c5bc01e95dbe7040cddc7754ff8e8
0
crevete/gwtbootstrap3-extras,gwtbootstrap3/gwtbootstrap3-extras,0x3333/gwtbootstrap3-extras,denis-vilyuzhanin/gwtbootstrap3-extras,bauna/gwtbootstrap3-extras,bauna/gwtbootstrap3-extras,sjardine/gwtbootstrap3-extras,BenDol/gwtbootstrap3-extras,gwtbootstrap3/gwtbootstrap3-extras,davidbuhler/gwtbootstrap3-strongly-typed-bootstrap-select,0x3333/gwtbootstrap3-extras,markonikolic/gwtbootstrap3-extras,denis-vilyuzhanin/gwtbootstrap3-extras,crevete/gwtbootstrap3-extras,markonikolic/gwtbootstrap3-extras,davidbuhler/gwtbootstrap3-strongly-typed-bootstrap-select,crevete/gwtbootstrap3-extras,gwtbootstrap3/gwtbootstrap3-extras,manstis/gwtbootstrap3-extras,markonikolic/gwtbootstrap3-extras,bauna/gwtbootstrap3-extras,0x3333/gwtbootstrap3-extras,manstis/gwtbootstrap3-extras,BenDol/gwtbootstrap3-extras,sjardine/gwtbootstrap3-extras,denis-vilyuzhanin/gwtbootstrap3-extras,manstis/gwtbootstrap3-extras,sjardine/gwtbootstrap3-extras,BenDol/gwtbootstrap3-extras
package org.gwtbootstrap3.extras.datetimepicker.client.ui.base; /* * #%L * GwtBootstrap3 * %% * Copyright (C) 2013 GwtBootstrap3 * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.google.gwt.core.client.Scheduler; import com.google.gwt.dom.client.Element; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.ui.HasEnabled; import com.google.gwt.user.client.ui.HasVisibility; import com.google.gwt.user.client.ui.Widget; import com.google.web.bindery.event.shared.HandlerRegistration; import org.gwtbootstrap3.client.shared.event.HideEvent; import org.gwtbootstrap3.client.shared.event.HideHandler; import org.gwtbootstrap3.client.shared.event.ShowEvent; import org.gwtbootstrap3.client.shared.event.ShowHandler; import org.gwtbootstrap3.client.ui.HasId; import org.gwtbootstrap3.client.ui.HasPlaceholder; import org.gwtbootstrap3.client.ui.HasResponsiveness; import org.gwtbootstrap3.client.ui.TextBox; import org.gwtbootstrap3.client.ui.base.ValueBoxBase; import org.gwtbootstrap3.extras.datetimepicker.client.ui.base.constants.*; import org.gwtbootstrap3.extras.datetimepicker.client.ui.base.events.*; import java.util.Date; /** * @author Joshua Godi */ public class DateTimeBoxBase extends Widget implements HasEnabled, HasId, HasResponsiveness, HasVisibility, HasPlaceholder, HasAutoClose, HasDaysOfWeekDisabled, HasEndDate, HasForceParse, HasFormat, HasHighlightToday, HasKeyboardNavigation, HasMaxView, HasMinuteStep, HasMinView, HasShowMeridian, HasShowTodayButton, HasStartDate, HasStartView, HasViewSelect, HasWeekStart, HasDateTimePickerHandlers { private final TextBox textBox; private DateTimeFormat dateTimeFormat; private DateTimeFormat startEndDateFormat = DateTimeFormat.getFormat("yyyy-MM-dd"); /** * DEFAULT values */ private String format = "mm/dd/yyyy HH:ii"; private DateTimePickerDayOfWeek weekStart = DateTimePickerDayOfWeek.SUNDAY; private DateTimePickerDayOfWeek[] daysOfWeekDisabled = {}; private boolean autoClose = false; private DateTimePickerView startView = DateTimePickerView.MONTH; private DateTimePickerView minView = DateTimePickerView.HOUR; private DateTimePickerView maxView = DateTimePickerView.DECADE; private boolean showTodayButton = false; private boolean highlightToday = false; private boolean keyboardNavigation = true; private boolean forceParse = true; private int minuteStep = 5; private DateTimePickerView viewSelect = DateTimePickerView.HOUR; private boolean showMeridian = false; private Widget container = null; public DateTimeBoxBase() { textBox = new TextBox(); setElement(textBox.getElement()); setFormat(format); setValue(new Date()); } public void setContainer(final Widget container) { this.container = container; } public Widget getContainer() { return container; } public TextBox getTextBox() { return textBox; } public void setAlignment(final ValueBoxBase.TextAlignment align) { textBox.setAlignment(align); } @Override public void setPlaceholder(final String placeHolder) { textBox.setPlaceholder(placeHolder); } @Override public String getPlaceholder() { return textBox.getPlaceholder(); } public void setReadOnly(final boolean readOnly) { textBox.setReadOnly(readOnly); } public boolean isReadOnly() { return textBox.isReadOnly(); } @Override public boolean isEnabled() { return textBox.isEnabled(); } @Override public void setEnabled(final boolean enabled) { textBox.setEnabled(enabled); } @Override public void setId(final String id) { textBox.setId(id); } @Override public String getId() { return textBox.getId(); } @Override public void setVisibleOn(final String deviceSizeString) { textBox.setVisibleOn(deviceSizeString); } @Override public void setHiddenOn(final String deviceSizeString) { textBox.setHiddenOn(deviceSizeString); } /** * Call this whenever changing any settings */ public void reload() { configure(); } public void show() { show(getElement()); } public void hide() { hide(getElement()); } @Override public void setAutoClose(boolean autoClose) { this.autoClose = autoClose; } @Override public void onShow(final Event e) { // On show we put focus on the textbox textBox.setFocus(true); fireEvent(new ShowEvent(e)); } @Override public HandlerRegistration addShowHandler(ShowHandler showHandler) { return addHandler(showHandler, ShowEvent.getType()); } @Override public void onHide(final Event e) { // On hide we remove focus from the textbox textBox.setFocus(false); fireEvent(new HideEvent(e)); } @Override public HandlerRegistration addHideHandler(HideHandler hideHandler) { return addHandler(hideHandler, HideEvent.getType()); } @Override public void onChangeDate(Event e) { fireEvent(new ChangeDateEvent(e)); } @Override public HandlerRegistration addChangeDateHandler(ChangeDateHandler changeDateHandler) { return addHandler(changeDateHandler, ChangeDateEvent.getType()); } @Override public void onChangeYear(Event e) { fireEvent(new ChangeYearEvent(e)); } @Override public HandlerRegistration addChangeYearHandler(ChangeYearHandler changeYearHandler) { return addHandler(changeYearHandler, ChangeYearEvent.getType()); } @Override public void onChangeMonth(Event e) { fireEvent(new ChangeMonthEvent(e)); } @Override public HandlerRegistration addChangeMonthHandler(ChangeMonthHandler changeMonthHandler) { return addHandler(changeMonthHandler, ChangeMonthEvent.getType()); } @Override public void onOutOfRange(Event e) { fireEvent(new OutOfRangeEvent(e)); } @Override public HandlerRegistration addOutOfRangeHandler(OutOfRangeHandler outOfRangeHandler) { return addHandler(outOfRangeHandler, OutOfRangeEvent.getType()); } @Override public void setDaysOfWeekDisabled(DateTimePickerDayOfWeek... daysOfWeekDisabled) { setDaysOfWeekDisabled(getElement(), toDaysOfWeekDisabledString(daysOfWeekDisabled)); } @Override public void setEndDate(Date endDate) { // Has to be in the format YYYY-MM-DD setEndDate(startEndDateFormat.format(endDate)); } @Override public void setEndDate(String endDate) { // Has to be in the format YYYY-MM-DD setEndDate(getElement(), endDate); } @Override public void setForceParse(boolean forceParse) { this.forceParse = forceParse; } @Override public void setHighlightToday(boolean highlightToday) { this.highlightToday = highlightToday; } @Override public void setHasKeyboardNavigation(boolean hasKeyboardNavigation) { this.keyboardNavigation = hasKeyboardNavigation; } @Override public void setMaxView(DateTimePickerView dateTimePickerView) { this.maxView = dateTimePickerView; } @Override public void setMinView(DateTimePickerView dateTimePickerView) { this.minView = dateTimePickerView; // We keep the view select the same as the min view if (viewSelect != minView) { setViewSelect(dateTimePickerView); } } @Override public void setMinuteStep(int minuteStep) { this.minuteStep = minuteStep; } @Override public void setShowMeridian(boolean showMeridian) { this.showMeridian = showMeridian; } @Override public void setShowTodayButton(boolean showTodayButton) { this.showTodayButton = showTodayButton; } @Override public void setStartDate(Date startDate) { // Has to be in the format YYYY-MM-DD setStartDate(startEndDateFormat.format(startDate)); } @Override public void setStartDate(String startDate) { // Has to be in the format YYYY-MM-DD setStartDate(getElement(), startDate); } @Override public void setStartView(DateTimePickerView dateTimePickerView) { this.startView = dateTimePickerView; } @Override public void setViewSelect(DateTimePickerView dateTimePickerView) { this.viewSelect = dateTimePickerView; // We keep the min view the same as the view select if (viewSelect != minView) { setMinView(dateTimePickerView); } } @Override public void setWeekStart(DateTimePickerDayOfWeek weekStart) { this.weekStart = weekStart; } @Override public void setFormat(final String format) { this.format = format; // Get the old value final Date oldValue = getValue(); // Make the new DateTimeFormat setDateTimeFormat(format); if (oldValue != null) { setValue(oldValue); } } private void setDateTimeFormat(String format) { // Check http://www.gwtproject.org/javadoc/latest/com/google/gwt/i18n/client/DateTimeFormat.html // for more information on syntax // Need to replace m with M for months format = format.replaceAll("m", "M"); // Need to replace all i with m for minutes format = format.replaceAll("i", "m"); // Need to replace P or p with a for meridian format = format.replaceAll("p", "a"); format = format.replaceAll("P", "a"); this.dateTimeFormat = DateTimeFormat.getFormat(format); } public Date getValue() { try { return dateTimeFormat != null && textBox.getValue() != null ? dateTimeFormat.parse(textBox.getValue()) : null; } catch (Exception e) { return null; } } public String getBaseValue() { return textBox.getValue(); } public void setValue(final Date value) { setValue(value, false); } public void setValue(final Date value, final boolean fireEvents) { // We schedule a fixed delay to that we can make sure the element is properly loaded // so that we can set the value on it Scheduler.get().scheduleFixedDelay(new Scheduler.RepeatingCommand() { @Override public boolean execute() { if (DateTimeBoxBase.this.isAttached()) { textBox.setValue(value != null ? dateTimeFormat.format(value) : null); update(textBox.getElement()); if (fireEvents) { // ValueChangeEvent.fire(DateTimeBoxBase.this, value); } return false; } else { return true; } } }, 200); } /** * {@inheritDoc} */ @Override protected void onLoad() { super.onLoad(); configure(); } @Override protected void onUnload() { super.onUnload(); remove(getElement()); } protected void configure() { // If the user hasn't specified the container, default to the widget's parent // This makes sure the modal scroll with the content correctly if (container == null) { configure(this, this.getParent()); } else { configure(this, container); } } protected void configure(final Widget w, final Widget container) { w.getElement().setAttribute("data-date-format", format); configure(w.getElement(), container.getElement(), format, weekStart.getValue(), toDaysOfWeekDisabledString(daysOfWeekDisabled), autoClose, startView.getValue(), minView.getValue(), maxView.getValue(), showTodayButton, highlightToday, keyboardNavigation, forceParse, minuteStep, viewSelect.getValue(), showMeridian); } protected void execute(final String cmd) { execute(getElement(), cmd); } private native void execute(Element e, String cmd) /*-{ $wnd.jQuery(e).datetimepicker(cmd); }-*/; private native void remove(Element e) /*-{ $wnd.jQuery(e).datetimepicker('remove'); $wnd.jQuery(e).off('show'); $wnd.jQuery(e).off('hide'); $wnd.jQuery(e).off('changeDate'); $wnd.jQuery(e).off('changeYear'); $wnd.jQuery(e).off('changeMonth'); $wnd.jQuery(e).off('outOfRange'); }-*/; private native void show(Element e) /*-{ $wnd.jQuery(e).datetimepicker('show'); }-*/; private native void hide(Element e) /*-{ $wnd.jQuery(e).datetimepicker('hide'); }-*/; private native void update(Element e) /*-{ $wnd.jQuery(e).datetimepicker('update'); }-*/; private native void setStartDate(Element e, String startDate) /*-{ $wnd.jQuery(e).datetimepicker('setStartDate', startDate); }-*/; private native void setEndDate(Element e, String endDate) /*-{ $wnd.jQuery(e).datetimepicker('setEndDate', endDate); }-*/; private native void setDaysOfWeekDisabled(Element e, String daysOfWeekDisabled) /*-{ $wnd.jQuery(e).datetimepicker('setDaysOfWeekDisabled', daysOfWeekDisabled); }-*/; protected native void configure(Element e, Element p, String format, int weekStart, String daysOfWeekDisabled, boolean autoClose, int startView, int minView, int maxView, boolean todayBtn, boolean highlightToday, boolean keyboardNavigation, boolean forceParse, int minuteStep, int viewSelect, boolean showMeridian) /*-{ var that = this; $wnd.jQuery(e).datetimepicker({ format: format, weekStart: weekStart, daysOfWeekDisabled: daysOfWeekDisabled, autoclose: autoClose, startView: startView, minView: minView, maxView: maxView, todayBtn: todayBtn, todayHighlight: highlightToday, keyboardNavigation: keyboardNavigation, forceParse: forceParse, minuteStep: minuteStep, showMeridian: showMeridian, container: p }) .on('show', function (e) { that.@org.gwtbootstrap3.extras.datetimepicker.client.ui.base.DateTimeBoxBase::onShow(Lcom/google/gwt/user/client/Event;)(e); }) .on("hide", function (e) { that.@org.gwtbootstrap3.extras.datetimepicker.client.ui.base.DateTimeBoxBase::onHide(Lcom/google/gwt/user/client/Event;)(e); }) .on("changeDate", function (e) { that.@org.gwtbootstrap3.extras.datetimepicker.client.ui.base.DateTimeBoxBase::onChangeDate(Lcom/google/gwt/user/client/Event;)(e); }) .on("changeYear", function (e) { that.@org.gwtbootstrap3.extras.datetimepicker.client.ui.base.DateTimeBoxBase::onChangeYear(Lcom/google/gwt/user/client/Event;)(e); }) .on("changeMonth", function (e) { that.@org.gwtbootstrap3.extras.datetimepicker.client.ui.base.DateTimeBoxBase::onChangeMonth(Lcom/google/gwt/user/client/Event;)(e); }) .on("outOfRange", function (e) { that.@org.gwtbootstrap3.extras.datetimepicker.client.ui.base.DateTimeBoxBase::onOutOfRange(Lcom/google/gwt/user/client/Event;)(e); }); }-*/; protected String toDaysOfWeekDisabledString(DateTimePickerDayOfWeek... dateTimePickerDayOfWeeks) { this.daysOfWeekDisabled = dateTimePickerDayOfWeeks; StringBuilder builder = new StringBuilder(); if (dateTimePickerDayOfWeeks != null) { int i = 0; for (DateTimePickerDayOfWeek dayOfWeek : dateTimePickerDayOfWeeks) { builder.append(dayOfWeek.getValue()); i++; if (i < dateTimePickerDayOfWeeks.length) { builder.append(","); } } } return builder.toString(); } }
src/main/java/org/gwtbootstrap3/extras/datetimepicker/client/ui/base/DateTimeBoxBase.java
package org.gwtbootstrap3.extras.datetimepicker.client.ui.base; /* * #%L * GwtBootstrap3 * %% * Copyright (C) 2013 GwtBootstrap3 * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.google.gwt.core.client.Scheduler; import com.google.gwt.dom.client.Element; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.ui.HasEnabled; import com.google.gwt.user.client.ui.HasVisibility; import com.google.gwt.user.client.ui.Widget; import com.google.web.bindery.event.shared.HandlerRegistration; import org.gwtbootstrap3.client.shared.event.HideEvent; import org.gwtbootstrap3.client.shared.event.HideHandler; import org.gwtbootstrap3.client.shared.event.ShowEvent; import org.gwtbootstrap3.client.shared.event.ShowHandler; import org.gwtbootstrap3.client.ui.HasId; import org.gwtbootstrap3.client.ui.HasPlaceholder; import org.gwtbootstrap3.client.ui.HasResponsiveness; import org.gwtbootstrap3.client.ui.TextBox; import org.gwtbootstrap3.client.ui.base.ValueBoxBase; import org.gwtbootstrap3.extras.datetimepicker.client.ui.base.constants.*; import org.gwtbootstrap3.extras.datetimepicker.client.ui.base.events.*; import java.util.Date; /** * @author Joshua Godi */ public class DateTimeBoxBase extends Widget implements HasEnabled, HasId, HasResponsiveness, HasVisibility, HasPlaceholder, HasAutoClose, HasDaysOfWeekDisabled, HasEndDate, HasForceParse, HasFormat, HasHighlightToday, HasKeyboardNavigation, HasMaxView, HasMinuteStep, HasMinView, HasShowMeridian, HasShowTodayButton, HasStartDate, HasStartView, HasViewSelect, HasWeekStart, HasDateTimePickerHandlers { private final TextBox textBox; private DateTimeFormat dateTimeFormat; private DateTimeFormat startEndDateFormat = DateTimeFormat.getFormat("yyyy-MM-dd"); /** * DEFAULT values */ private String format = "mm/dd/yyyy HH:ii"; private DateTimePickerDayOfWeek weekStart = DateTimePickerDayOfWeek.SUNDAY; private DateTimePickerDayOfWeek[] daysOfWeekDisabled = {}; private boolean autoClose = false; private DateTimePickerView startView = DateTimePickerView.MONTH; private DateTimePickerView minView = DateTimePickerView.HOUR; private DateTimePickerView maxView = DateTimePickerView.DECADE; private boolean showTodayButton = false; private boolean highlightToday = false; private boolean keyboardNavigation = true; private boolean forceParse = true; private int minuteStep = 5; private DateTimePickerView viewSelect = DateTimePickerView.HOUR; private boolean showMeridian = false; private Widget parent = null; public DateTimeBoxBase() { textBox = new TextBox(); setElement(textBox.getElement()); setFormat(format); setValue(new Date()); } public void setParent(final Widget parent) { this.parent = parent; } public Widget getParent() { return parent; } public TextBox getTextBox() { return textBox; } public void setAlignment(final ValueBoxBase.TextAlignment align) { textBox.setAlignment(align); } @Override public void setPlaceholder(final String placeHolder) { textBox.setPlaceholder(placeHolder); } @Override public String getPlaceholder() { return textBox.getPlaceholder(); } public void setReadOnly(final boolean readOnly) { textBox.setReadOnly(readOnly); } public boolean isReadOnly() { return textBox.isReadOnly(); } @Override public boolean isEnabled() { return textBox.isEnabled(); } @Override public void setEnabled(final boolean enabled) { textBox.setEnabled(enabled); } @Override public void setId(final String id) { textBox.setId(id); } @Override public String getId() { return textBox.getId(); } @Override public void setVisibleOn(final String deviceSizeString) { textBox.setVisibleOn(deviceSizeString); } @Override public void setHiddenOn(final String deviceSizeString) { textBox.setHiddenOn(deviceSizeString); } /** * Call this whenever changing any settings */ public void reload() { configure(); } public void show() { show(getElement()); } public void hide() { hide(getElement()); } @Override public void setAutoClose(boolean autoClose) { this.autoClose = autoClose; } @Override public void onShow(final Event e) { // On show we put focus on the textbox textBox.setFocus(true); fireEvent(new ShowEvent(e)); } @Override public HandlerRegistration addShowHandler(ShowHandler showHandler) { return addHandler(showHandler, ShowEvent.getType()); } @Override public void onHide(final Event e) { // On hide we remove focus from the textbox textBox.setFocus(false); fireEvent(new HideEvent(e)); } @Override public HandlerRegistration addHideHandler(HideHandler hideHandler) { return addHandler(hideHandler, HideEvent.getType()); } @Override public void onChangeDate(Event e) { fireEvent(new ChangeDateEvent(e)); } @Override public HandlerRegistration addChangeDateHandler(ChangeDateHandler changeDateHandler) { return addHandler(changeDateHandler, ChangeDateEvent.getType()); } @Override public void onChangeYear(Event e) { fireEvent(new ChangeYearEvent(e)); } @Override public HandlerRegistration addChangeYearHandler(ChangeYearHandler changeYearHandler) { return addHandler(changeYearHandler, ChangeYearEvent.getType()); } @Override public void onChangeMonth(Event e) { fireEvent(new ChangeMonthEvent(e)); } @Override public HandlerRegistration addChangeMonthHandler(ChangeMonthHandler changeMonthHandler) { return addHandler(changeMonthHandler, ChangeMonthEvent.getType()); } @Override public void onOutOfRange(Event e) { fireEvent(new OutOfRangeEvent(e)); } @Override public HandlerRegistration addOutOfRangeHandler(OutOfRangeHandler outOfRangeHandler) { return addHandler(outOfRangeHandler, OutOfRangeEvent.getType()); } @Override public void setDaysOfWeekDisabled(DateTimePickerDayOfWeek... daysOfWeekDisabled) { setDaysOfWeekDisabled(getElement(), toDaysOfWeekDisabledString(daysOfWeekDisabled)); } @Override public void setEndDate(Date endDate) { // Has to be in the format YYYY-MM-DD setEndDate(startEndDateFormat.format(endDate)); } @Override public void setEndDate(String endDate) { // Has to be in the format YYYY-MM-DD setEndDate(getElement(), endDate); } @Override public void setForceParse(boolean forceParse) { this.forceParse = forceParse; } @Override public void setHighlightToday(boolean highlightToday) { this.highlightToday = highlightToday; } @Override public void setHasKeyboardNavigation(boolean hasKeyboardNavigation) { this.keyboardNavigation = hasKeyboardNavigation; } @Override public void setMaxView(DateTimePickerView dateTimePickerView) { this.maxView = dateTimePickerView; } @Override public void setMinView(DateTimePickerView dateTimePickerView) { this.minView = dateTimePickerView; // We keep the view select the same as the min view if (viewSelect != minView) { setViewSelect(dateTimePickerView); } } @Override public void setMinuteStep(int minuteStep) { this.minuteStep = minuteStep; } @Override public void setShowMeridian(boolean showMeridian) { this.showMeridian = showMeridian; } @Override public void setShowTodayButton(boolean showTodayButton) { this.showTodayButton = showTodayButton; } @Override public void setStartDate(Date startDate) { // Has to be in the format YYYY-MM-DD setStartDate(startEndDateFormat.format(startDate)); } @Override public void setStartDate(String startDate) { // Has to be in the format YYYY-MM-DD setStartDate(getElement(), startDate); } @Override public void setStartView(DateTimePickerView dateTimePickerView) { this.startView = dateTimePickerView; } @Override public void setViewSelect(DateTimePickerView dateTimePickerView) { this.viewSelect = dateTimePickerView; // We keep the min view the same as the view select if (viewSelect != minView) { setMinView(dateTimePickerView); } } @Override public void setWeekStart(DateTimePickerDayOfWeek weekStart) { this.weekStart = weekStart; } @Override public void setFormat(final String format) { this.format = format; // Get the old value final Date oldValue = getValue(); // Make the new DateTimeFormat setDateTimeFormat(format); if (oldValue != null) { setValue(oldValue); } } private void setDateTimeFormat(String format) { // Check http://www.gwtproject.org/javadoc/latest/com/google/gwt/i18n/client/DateTimeFormat.html // for more information on syntax // Need to replace m with M for months format = format.replaceAll("m", "M"); // Need to replace all i with m for minutes format = format.replaceAll("i", "m"); // Need to replace P or p with a for meridian format = format.replaceAll("p", "a"); format = format.replaceAll("P", "a"); this.dateTimeFormat = DateTimeFormat.getFormat(format); } public Date getValue() { try { return dateTimeFormat != null && textBox.getValue() != null ? dateTimeFormat.parse(textBox.getValue()) : null; } catch (Exception e) { return null; } } public String getBaseValue() { return textBox.getValue(); } public void setValue(final Date value) { setValue(value, false); } public void setValue(final Date value, final boolean fireEvents) { // We schedule a fixed delay to that we can make sure the element is properly loaded // so that we can set the value on it Scheduler.get().scheduleFixedDelay(new Scheduler.RepeatingCommand() { @Override public boolean execute() { if (DateTimeBoxBase.this.isAttached()) { textBox.setValue(value != null ? dateTimeFormat.format(value) : null); update(textBox.getElement()); if (fireEvents) { // ValueChangeEvent.fire(DateTimeBoxBase.this, value); } return false; } else { return true; } } }, 200); } /** * {@inheritDoc} */ @Override protected void onLoad() { super.onLoad(); configure(); } @Override protected void onUnload() { super.onUnload(); remove(getElement()); } protected void configure() { // If the user hasn't specified the parent, default to the widget's parent // This makes sure the modal scroll with the content correctly if (parent == null) { configure(this, this.getParent()); } else { configure(this, parent); } } protected void configure(final Widget w, final Widget widgetParent) { w.getElement().setAttribute("data-date-format", format); configure(w.getElement(), widgetParent.getElement(), format, weekStart.getValue(), toDaysOfWeekDisabledString(daysOfWeekDisabled), autoClose, startView.getValue(), minView.getValue(), maxView.getValue(), showTodayButton, highlightToday, keyboardNavigation, forceParse, minuteStep, viewSelect.getValue(), showMeridian); } protected void execute(final String cmd) { execute(getElement(), cmd); } private native void execute(Element e, String cmd) /*-{ $wnd.jQuery(e).datetimepicker(cmd); }-*/; private native void remove(Element e) /*-{ $wnd.jQuery(e).datetimepicker('remove'); $wnd.jQuery(e).off('show'); $wnd.jQuery(e).off('hide'); $wnd.jQuery(e).off('changeDate'); $wnd.jQuery(e).off('changeYear'); $wnd.jQuery(e).off('changeMonth'); $wnd.jQuery(e).off('outOfRange'); }-*/; private native void show(Element e) /*-{ $wnd.jQuery(e).datetimepicker('show'); }-*/; private native void hide(Element e) /*-{ $wnd.jQuery(e).datetimepicker('hide'); }-*/; private native void update(Element e) /*-{ $wnd.jQuery(e).datetimepicker('update'); }-*/; private native void setStartDate(Element e, String startDate) /*-{ $wnd.jQuery(e).datetimepicker('setStartDate', startDate); }-*/; private native void setEndDate(Element e, String endDate) /*-{ $wnd.jQuery(e).datetimepicker('setEndDate', endDate); }-*/; private native void setDaysOfWeekDisabled(Element e, String daysOfWeekDisabled) /*-{ $wnd.jQuery(e).datetimepicker('setDaysOfWeekDisabled', daysOfWeekDisabled); }-*/; protected native void configure(Element e, Element p, String format, int weekStart, String daysOfWeekDisabled, boolean autoClose, int startView, int minView, int maxView, boolean todayBtn, boolean highlightToday, boolean keyboardNavigation, boolean forceParse, int minuteStep, int viewSelect, boolean showMeridian) /*-{ var that = this; $wnd.jQuery(e).datetimepicker({ format: format, weekStart: weekStart, daysOfWeekDisabled: daysOfWeekDisabled, autoclose: autoClose, startView: startView, minView: minView, maxView: maxView, todayBtn: todayBtn, todayHighlight: highlightToday, keyboardNavigation: keyboardNavigation, forceParse: forceParse, minuteStep: minuteStep, showMeridian: showMeridian, container: p }) .on('show', function (e) { that.@org.gwtbootstrap3.extras.datetimepicker.client.ui.base.DateTimeBoxBase::onShow(Lcom/google/gwt/user/client/Event;)(e); }) .on("hide", function (e) { that.@org.gwtbootstrap3.extras.datetimepicker.client.ui.base.DateTimeBoxBase::onHide(Lcom/google/gwt/user/client/Event;)(e); }) .on("changeDate", function (e) { that.@org.gwtbootstrap3.extras.datetimepicker.client.ui.base.DateTimeBoxBase::onChangeDate(Lcom/google/gwt/user/client/Event;)(e); }) .on("changeYear", function (e) { that.@org.gwtbootstrap3.extras.datetimepicker.client.ui.base.DateTimeBoxBase::onChangeYear(Lcom/google/gwt/user/client/Event;)(e); }) .on("changeMonth", function (e) { that.@org.gwtbootstrap3.extras.datetimepicker.client.ui.base.DateTimeBoxBase::onChangeMonth(Lcom/google/gwt/user/client/Event;)(e); }) .on("outOfRange", function (e) { that.@org.gwtbootstrap3.extras.datetimepicker.client.ui.base.DateTimeBoxBase::onOutOfRange(Lcom/google/gwt/user/client/Event;)(e); }); }-*/; protected String toDaysOfWeekDisabledString(DateTimePickerDayOfWeek... dateTimePickerDayOfWeeks) { this.daysOfWeekDisabled = dateTimePickerDayOfWeeks; StringBuilder builder = new StringBuilder(); if (dateTimePickerDayOfWeeks != null) { int i = 0; for (DateTimePickerDayOfWeek dayOfWeek : dateTimePickerDayOfWeeks) { builder.append(dayOfWeek.getValue()); i++; if (i < dateTimePickerDayOfWeeks.length) { builder.append(","); } } } return builder.toString(); } }
Updating with different naming convention to match JS.
src/main/java/org/gwtbootstrap3/extras/datetimepicker/client/ui/base/DateTimeBoxBase.java
Updating with different naming convention to match JS.
Java
apache-2.0
f3d99939c94a1916571ea694e7c8ef8e3b55bd05
0
rmagen/incubator-tinkerpop,samiunn/incubator-tinkerpop,gdelafosse/incubator-tinkerpop,gdelafosse/incubator-tinkerpop,robertdale/tinkerpop,n-tran/incubator-tinkerpop,dalaro/incubator-tinkerpop,artem-aliev/tinkerpop,jorgebay/tinkerpop,krlohnes/tinkerpop,apache/tinkerpop,newkek/incubator-tinkerpop,apache/tinkerpop,apache/tinkerpop,BrynCooke/incubator-tinkerpop,jorgebay/tinkerpop,apache/tinkerpop,dalaro/incubator-tinkerpop,gdelafosse/incubator-tinkerpop,artem-aliev/tinkerpop,n-tran/incubator-tinkerpop,rmagen/incubator-tinkerpop,RussellSpitzer/incubator-tinkerpop,BrynCooke/incubator-tinkerpop,velo/incubator-tinkerpop,robertdale/tinkerpop,velo/incubator-tinkerpop,velo/incubator-tinkerpop,RedSeal-co/incubator-tinkerpop,artem-aliev/tinkerpop,apache/tinkerpop,newkek/incubator-tinkerpop,edgarRd/incubator-tinkerpop,krlohnes/tinkerpop,robertdale/tinkerpop,artem-aliev/tinkerpop,rmagen/incubator-tinkerpop,jorgebay/tinkerpop,PommeVerte/incubator-tinkerpop,krlohnes/tinkerpop,apache/tinkerpop,mike-tr-adamson/incubator-tinkerpop,apache/incubator-tinkerpop,RussellSpitzer/incubator-tinkerpop,newkek/incubator-tinkerpop,BrynCooke/incubator-tinkerpop,RussellSpitzer/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,artem-aliev/tinkerpop,mike-tr-adamson/incubator-tinkerpop,pluradj/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,jorgebay/tinkerpop,pluradj/incubator-tinkerpop,RedSeal-co/incubator-tinkerpop,vtslab/incubator-tinkerpop,robertdale/tinkerpop,samiunn/incubator-tinkerpop,mike-tr-adamson/incubator-tinkerpop,robertdale/tinkerpop,vtslab/incubator-tinkerpop,vtslab/incubator-tinkerpop,edgarRd/incubator-tinkerpop,krlohnes/tinkerpop,apache/incubator-tinkerpop,samiunn/incubator-tinkerpop,apache/incubator-tinkerpop,dalaro/incubator-tinkerpop,RedSeal-co/incubator-tinkerpop,n-tran/incubator-tinkerpop,krlohnes/tinkerpop,edgarRd/incubator-tinkerpop,pluradj/incubator-tinkerpop,apache/tinkerpop
package org.apache.tinkerpop.gremlin.util.iterator; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; /** * @author Stephen Mallette (http://stephen.genoprime.com) */ public class IteratorUtilsTest { @Test public void shouldIterateSingleObject() { assertIterator(IteratorUtils.of("test1"), 1); } @Test public void shouldIteratePairOfObjects() { assertIterator(IteratorUtils.of("test1", "test2"), 2); } @Test public void shouldConvertIterableToIterator() { final List<String> iterable = new ArrayList<>(); iterable.add("test1"); iterable.add("test2"); iterable.add("test3"); assertIterator(IteratorUtils.convertToIterator(iterable), iterable.size()); } @Test public void shouldConvertIteratorToIterator() { final List<String> iterable = new ArrayList<>(); iterable.add("test1"); iterable.add("test2"); iterable.add("test3"); assertIterator(IteratorUtils.convertToIterator(iterable.iterator()), iterable.size()); } @Test public void shouldConvertArrayToIterator() { final String[] iterable = new String[3]; iterable[0] = "test1"; iterable[1] = "test2"; iterable[2] = "test3"; assertIterator(IteratorUtils.convertToIterator(iterable), iterable.length); } @Test public void shouldConvertThrowableToIterator() { final Exception ex = new Exception("test1"); assertIterator(IteratorUtils.convertToIterator(ex), 1); } @Test public void shouldConvertStreamToIterator() { final List<String> iterable = new ArrayList<>(); iterable.add("test1"); iterable.add("test2"); iterable.add("test3"); assertIterator(IteratorUtils.convertToIterator(iterable.stream()), iterable.size()); } @Test public void shouldConvertMapToIterator() { final Map<String,String> m = new HashMap<>(); m.put("key1", "val1"); m.put("key2", "val2"); m.put("key3", "val3"); final Iterator itty = IteratorUtils.convertToIterator(m); for (int ix = 0; ix < m.size(); ix++) { final Map.Entry entry = (Map.Entry) itty.next(); assertEquals("key" + (ix + 1), entry.getKey()); assertEquals("val" + (ix + 1), entry.getValue()); } assertFalse(itty.hasNext()); } @Test public void shouldConvertAnythingElseToIteratorByWrapping() { assertIterator(IteratorUtils.convertToIterator("test1"), 1); } public <S> void assertIterator(final Iterator<S> itty, final int size) { for (int ix = 0; ix < size; ix++) { assertEquals("test" + (ix + 1), itty.next()); } assertFalse(itty.hasNext()); } }
gremlin-test/src/test/java/org/apache/tinkerpop/gremlin/util/iterator/IteratorUtilsTest.java
package org.apache.tinkerpop.gremlin.util.iterator; import org.junit.Test; import java.util.Iterator; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; /** * @author Stephen Mallette (http://stephen.genoprime.com) */ public class IteratorUtilsTest { @Test public void shouldIterateSingleObject() { final Iterator<String> itty = IteratorUtils.of("test"); assertEquals("test", itty.next()); assertFalse(itty.hasNext()); } @Test public void shouldIteratePairOfObjects() { final Iterator<String> itty = IteratorUtils.of("test1", "test2"); assertEquals("test1", itty.next()); assertEquals("test2", itty.next()); assertFalse(itty.hasNext()); } }
Add IteratorUtils tests for converting arbitrary objects to iterator.
gremlin-test/src/test/java/org/apache/tinkerpop/gremlin/util/iterator/IteratorUtilsTest.java
Add IteratorUtils tests for converting arbitrary objects to iterator.
Java
apache-2.0
4d1d167d90b1f01681904d517897f1768aa7a762
0
Donnerbart/hazelcast,dbrimley/hazelcast,tombujok/hazelcast,dbrimley/hazelcast,lmjacksoniii/hazelcast,tombujok/hazelcast,dsukhoroslov/hazelcast,emre-aydin/hazelcast,lmjacksoniii/hazelcast,emrahkocaman/hazelcast,emre-aydin/hazelcast,tufangorel/hazelcast,Donnerbart/hazelcast,Donnerbart/hazelcast,tufangorel/hazelcast,mdogan/hazelcast,mesutcelik/hazelcast,dbrimley/hazelcast,juanavelez/hazelcast,juanavelez/hazelcast,emrahkocaman/hazelcast,mdogan/hazelcast,tkountis/hazelcast,tkountis/hazelcast,mesutcelik/hazelcast,tufangorel/hazelcast,mesutcelik/hazelcast,dsukhoroslov/hazelcast,tkountis/hazelcast,mdogan/hazelcast,emre-aydin/hazelcast
/* * Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.util.executor; import com.hazelcast.logging.AbstractLogger; import com.hazelcast.logging.LogEvent; import com.hazelcast.test.AssertTask; import com.hazelcast.test.HazelcastParallelClassRunner; import com.hazelcast.test.HazelcastTestSupport; import com.hazelcast.test.annotation.ParallelTest; import com.hazelcast.test.annotation.QuickTest; import com.hazelcast.util.RootCauseMatcher; import com.hazelcast.util.executor.LoggingScheduledExecutor.LoggingDelegatingFuture; import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import static java.util.concurrent.TimeUnit.SECONDS; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; @RunWith(HazelcastParallelClassRunner.class) @Category({QuickTest.class, ParallelTest.class}) public class LoggingScheduledExecutorTest extends HazelcastTestSupport { private TestLogger logger = new TestLogger(); private TestThreadFactory factory = new TestThreadFactory(); private ScheduledExecutorService executor; @Rule public ExpectedException expectedException = ExpectedException.none(); @After public void tearDown() throws Exception { if (executor != null) { executor.shutdownNow(); executor.awaitTermination(5, SECONDS); } } @Test public void testConstructor_withRejectedExecutionHandler() { RejectedExecutionHandler handler = new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable runnable, ThreadPoolExecutor executor) { } }; executor = new LoggingScheduledExecutor(logger, 1, factory, handler); } @Test public void logsExecutionException_withRunnable() { executor = new LoggingScheduledExecutor(logger, 1, factory); executor.submit(new FailedRunnable()); assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { assertInstanceOf(RuntimeException.class, logger.getThrowable()); String message = logger.getMessage(); assertTrue("Found message: '" + message + "'", message.contains("FailedRunnable")); } }); } @Test public void throwsExecutionException_withCallable() throws Exception { executor = new LoggingScheduledExecutor(logger, 1, factory); Future<Integer> future = executor.submit(new FailedCallable()); expectedException.expect(new RootCauseMatcher(RuntimeException.class)); future.get(); assertNull(logger.getThrowable()); } @Test public void throwsExecutionException_withCallable_withFutureGetTimeout() throws Exception { executor = new LoggingScheduledExecutor(logger, 1, factory); Future<Integer> future = executor.submit(new FailedCallable()); expectedException.expect(new RootCauseMatcher(RuntimeException.class)); future.get(1, SECONDS); assertNull(logger.getThrowable()); } @Test public void testFuture_withCancellation() throws Exception { final CountDownLatch blocker = new CountDownLatch(1); executor = new LoggingScheduledExecutor(logger, 1, factory); Future<Integer> future = executor.submit(new BlockingCallable(blocker)); assertFalse(future.isCancelled()); assertTrue(future.cancel(true)); expectedException.expect(CancellationException.class); future.get(); } @Test public void testLoggingDelegatingFuture() { executor = new LoggingScheduledExecutor(logger, 1, factory); Runnable task = new FailedRunnable(); ScheduledFuture<?> scheduledFuture1 = executor.schedule(task, 0, SECONDS); ScheduledFuture<?> scheduledFuture2 = executor.scheduleAtFixedRate(task, 0, 1, SECONDS); assertInstanceOf(LoggingDelegatingFuture.class, scheduledFuture1); assertInstanceOf(LoggingDelegatingFuture.class, scheduledFuture2); LoggingDelegatingFuture future1 = (LoggingDelegatingFuture) scheduledFuture1; LoggingDelegatingFuture future2 = (LoggingDelegatingFuture) scheduledFuture2; assertFalse(future1.isPeriodic()); assertTrue(future2.isPeriodic()); assertEquals(future1, future1); assertNotEquals(future1, future2); assertNotEquals(future1, null); assertEquals(future1.hashCode(), future1.hashCode()); assertNotEquals(future1.hashCode(), future2.hashCode()); } private static class FailedRunnable implements Runnable { @Override public void run() { throw new RuntimeException(); } @Override public String toString() { return "FailedRunnable{}"; } } private static class FailedCallable implements Callable<Integer> { @Override public Integer call() throws Exception { throw new RuntimeException(); } @Override public String toString() { return "FailedCallable{}"; } } private static class BlockingCallable implements Callable<Integer> { private final CountDownLatch blocker; BlockingCallable(CountDownLatch blocker) { this.blocker = blocker; } @Override public Integer call() throws Exception { blocker.await(); return 42; } } private static class TestThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { return new Thread(r); } } private static class TestLogger extends AbstractLogger { private final AtomicReference<Throwable> throwableHolder = new AtomicReference<Throwable>(); private final AtomicReference<String> messageHolder = new AtomicReference<String>(); @Override public void log(Level level, String message) { throw new UnsupportedOperationException(); } @Override public void log(Level level, String message, Throwable thrown) { throwableHolder.set(thrown); messageHolder.set(message); } @Override public void log(LogEvent logEvent) { throw new UnsupportedOperationException(); } @Override public Level getLevel() { return null; } @Override public boolean isLoggable(Level level) { return false; } public Throwable getThrowable() { return throwableHolder.get(); } public String getMessage() { return messageHolder.get(); } } }
hazelcast/src/test/java/com/hazelcast/util/executor/LoggingScheduledExecutorTest.java
/* * Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.util.executor; import com.hazelcast.logging.AbstractLogger; import com.hazelcast.logging.LogEvent; import com.hazelcast.test.AssertTask; import com.hazelcast.test.HazelcastParallelClassRunner; import com.hazelcast.test.HazelcastTestSupport; import com.hazelcast.test.annotation.ParallelTest; import com.hazelcast.test.annotation.QuickTest; import com.hazelcast.util.RootCauseMatcher; import com.hazelcast.util.executor.LoggingScheduledExecutor.LoggingDelegatingFuture; import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import static java.util.concurrent.TimeUnit.SECONDS; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; @RunWith(HazelcastParallelClassRunner.class) @Category({QuickTest.class, ParallelTest.class}) public class LoggingScheduledExecutorTest extends HazelcastTestSupport { private TestLogger logger = new TestLogger(); private TestThreadFactory factory = new TestThreadFactory(); private ScheduledExecutorService executor; @Rule public ExpectedException expectedException = ExpectedException.none(); @After public void tearDown() throws Exception { if (executor != null) { executor.shutdownNow(); executor.awaitTermination(5, SECONDS); } } @Test public void testConstructor_withRejectedExecutionHandler() { RejectedExecutionHandler handler = new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable runnable, ThreadPoolExecutor executor) { } }; executor = new LoggingScheduledExecutor(logger, 1, factory, handler); } @Test public void logsExecutionException_withRunnable() { executor = new LoggingScheduledExecutor(logger, 1, factory); executor.submit(new FailedRunnable()); assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { assertInstanceOf(RuntimeException.class, logger.getThrowable()); String message = logger.getMessage(); assertTrue("Found message: '" + message + "'", message.contains("FailedRunnable")); } }); } @Test public void throwsExecutionException_withCallable() throws Exception { executor = new LoggingScheduledExecutor(logger, 1, factory); Future<Integer> future = executor.submit(new FailedCallable()); expectedException.expect(new RootCauseMatcher(RuntimeException.class)); future.get(); assertNull(logger.getThrowable()); } @Test public void throwsExecutionException_withCallable_withFutureGetTimeout() throws Exception { executor = new LoggingScheduledExecutor(logger, 1, factory); Future<Integer> future = executor.submit(new FailedCallable()); expectedException.expect(new RootCauseMatcher(RuntimeException.class)); future.get(1, SECONDS); assertNull(logger.getThrowable()); } @Test public void testFuture_withCancellation() throws Exception { final CountDownLatch blocker = new CountDownLatch(1); executor = new LoggingScheduledExecutor(logger, 1, factory); Future<Integer> future = executor.submit(new BlockingCallable(blocker)); assertFalse(future.isCancelled()); assertTrue(future.cancel(true)); expectedException.expect(CancellationException.class); future.get(); } @Test public void testLoggingDelegatingFuture() { executor = new LoggingScheduledExecutor(logger, 1, factory); Runnable task = new FailedRunnable(); ScheduledFuture<?> scheduledFuture1 = executor.schedule(task, 0, SECONDS); ScheduledFuture<?> scheduledFuture2 = executor.scheduleAtFixedRate(task, 0, 1, SECONDS); assertInstanceOf(LoggingDelegatingFuture.class, scheduledFuture1); assertInstanceOf(LoggingDelegatingFuture.class, scheduledFuture2); LoggingDelegatingFuture future1 = (LoggingDelegatingFuture) scheduledFuture1; LoggingDelegatingFuture future2 = (LoggingDelegatingFuture) scheduledFuture2; assertFalse(future1.isPeriodic()); assertTrue(future2.isPeriodic()); assertEquals(future1, future1); assertNotEquals(future1, future2); assertNotEquals(future1, null); assertEquals(future1.hashCode(), future1.hashCode()); assertNotEquals(future1.hashCode(), future2.hashCode()); future1.cancel(true); future2.cancel(true); } private static class FailedRunnable implements Runnable { @Override public void run() { throw new RuntimeException(); } @Override public String toString() { return "FailedRunnable{}"; } } private static class FailedCallable implements Callable<Integer> { @Override public Integer call() throws Exception { throw new RuntimeException(); } @Override public String toString() { return "FailedCallable{}"; } } private static class BlockingCallable implements Callable<Integer> { private final CountDownLatch blocker; BlockingCallable(CountDownLatch blocker) { this.blocker = blocker; } @Override public Integer call() throws Exception { blocker.await(); return 42; } } private static class TestThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { return new Thread(r); } } private static class TestLogger extends AbstractLogger { private final AtomicReference<Throwable> throwableHolder = new AtomicReference<Throwable>(); private final AtomicReference<String> messageHolder = new AtomicReference<String>(); @Override public void log(Level level, String message) { throw new UnsupportedOperationException(); } @Override public void log(Level level, String message, Throwable thrown) { throwableHolder.set(thrown); messageHolder.set(message); } @Override public void log(LogEvent logEvent) { throw new UnsupportedOperationException(); } @Override public Level getLevel() { return null; } @Override public boolean isLoggable(Level level) { return false; } public Throwable getThrowable() { return throwableHolder.get(); } public String getMessage() { return messageHolder.get(); } } }
Minimal cleanup of LoggingScheduledExecutorTest.
hazelcast/src/test/java/com/hazelcast/util/executor/LoggingScheduledExecutorTest.java
Minimal cleanup of LoggingScheduledExecutorTest.
Java
apache-2.0
95cdae52b91e2bee338920e11b77c9cbd98719e0
0
ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE
package uk.ac.ebi.quickgo.annotation.model; import uk.ac.ebi.quickgo.rest.controller.ControllerValidationHelper; import uk.ac.ebi.quickgo.rest.controller.ControllerValidationHelperImpl; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; /** * A data structure for the annotation filtering parameters passed in from the client. * Here are the list of parameters filtering will require. The values shown are the ones the FE currently uses * Nearly all the parameters can take multiple values, separated by commas. These types are named as plural. * Exceptions exists however * * @author Tony Wardell * Date: 25/04/2016 * Time: 11:23 * Created with IntelliJ IDEA. */ public class AnnotationFilter { public static final String DEFAULT_ENTRIES_PER_PAGE = "25"; public static final String DEFAULT_PAGE_NUMBER = "1"; public static final int MAX_PAGE_RESULTS = 100; private List<String> taxon; // Taxon ids E.g. 1234,343434 private List<String> gp; // Gene Product ids; E.g. A0A000,A0A001,.. private List<String> gpSet; // Gene Product Sets E.g. BHF-UCL,Exosome,.. private List<String> gpType; // Gene Product Types I.E protein,rna,.. (3 choices) //Choices of gpType private static Map<String, Object> gpTypeChoices = Arrays.asList("proteins","RNAs","complexes").stream().collect (Collectors.toMap(Function.identity(),Function.identity())); //Choices of gpSets todo these values in the beta are NOT lowercased.. needs to be for the new version private static Map<String, Object> gpSetChoices = Arrays.asList("bhf-ucl","exsome","kruk", "parkinsonsuk-ucl", "referencegenome").stream().collect(Collectors.toMap(Function.identity(),Function.identity())); //Go Terms private List<String> goTerm; // Go Term ids E.g. GO:0016021,GO:0016022,.. private List<String> goTermSet; // Go Term Set ids E.g. goslim_chembl,goSlimGeneric,.. //..the following 2 members are only applicable if goTerm ids or sets have been selected private String goTermUse; // Go Term use I.e. ancestor or slim or exact (singular) private String goTermRelationship; // Go Term relationship I.e. I or IPO or IPOR (singular) private List<String> aspect; //Aspect I.e. F, P or C (singular) private static Map<String, Object> aspectChoices = Arrays.asList("c","f","p").stream() .collect(Collectors.toMap(Function.identity(),Function.identity())); private List<String> ecoEvidence; //Eco evidence ids E.g. ECO:12345, ECO:34535,.. private List<String> goEvidence; //Go evidence ids E.g. IEA,.. //..the following is only applicable if an evidence code has been requested private String evidenceRelationship; //Evidence relationships I.e. ancestor or exact (singular) // Qualifier specifies the relationship between the annotated gene product and the GO term private List<String> qualifier; // E.g enables, not_enables,.. private List<String> reference; // E.g. DOI,GO_REF,.. private List<String> with; // E.g. AGI_LocusCode,CGD,.. private List<String> assignedby; // E.g. ASPGD,Agbase,.. //Non-data parameters private String limit = DEFAULT_ENTRIES_PER_PAGE; private String page = DEFAULT_PAGE_NUMBER; //Defaults for required values private static final String DEFAULT_GO_TERM_USE="Ancestor"; private static final String DEFAULT_EVIDENCE_RELATIONSHIP ="Ancestor"; //todo @Autowired public ControllerValidationHelper validationHelper = new ControllerValidationHelperImpl(MAX_PAGE_RESULTS); /** * After filters have been loaded, ensure values are valid and defaults are in place. */ public void validation() { //Some filters have a small number of potential values, defined by enums verifyField(gpType, gpTypeChoices, " is an invalid option for gene product type"); verifyField(gpSet, gpSetChoices, " is an invalid option for gene product set."); verifyField(aspect, aspectChoices, " is an invalid option for aspect."); //If go terms or sets are entered, then use the default relationship if none is specified if(((goTerm != null && goTerm.size()>0) || (goTermSet !=null && goTermSet.size()>0))&& goTermUse==null){ goTermUse = DEFAULT_GO_TERM_USE; } //If eco codes or go evidence codes are entered, then use the default relationship if none is specified if(((ecoEvidence !=null && ecoEvidence.size()>0) || (goEvidence !=null && goEvidence.size()>0)) && evidenceRelationship==null){ evidenceRelationship = DEFAULT_EVIDENCE_RELATIONSHIP; } validationHelper.validateRequestedResults(Integer.parseInt(limit)); } private void verifyField(List<String> args, Map<String, Object> choices, String message) { if(args!=null){ args.stream() .map(e -> { if(!choices.containsKey(e.toLowerCase())){ throw new IllegalArgumentException(e + message); } return e; }); } } public void setTaxon(String taxon) { this.taxon = validationHelper.csvToList(taxon); } public void setGp(String gp) { this.gp = validationHelper.csvToList(gp); } public void setGpSet(String gpSet) { this.gpSet = validationHelper.csvToList(gpSet); } public void setGpType(String gpType) { this.gpType = validationHelper.csvToList(gpType); } public void setGoTerm(String goTerm) { this.goTerm = validationHelper.csvToList(goTerm); } public void setGoTermSet(String goTermSet) { this.goTermSet = validationHelper.csvToList(goTermSet); } public void setGoTermUse(String goTermUse) { this.goTermUse = goTermUse; } public void setGoTermRelationship(String goTermRelationship) { this.goTermRelationship = goTermRelationship; } public void setAspect(String aspect) { this.aspect = validationHelper.csvToList(aspect); } public void setEcoEvidence(String ecoEvidence) { this.ecoEvidence = validationHelper.csvToList(ecoEvidence); } public void setGoEvidence(String goEvidence) { this.goEvidence = validationHelper.csvToList(goEvidence); } public void setEvidenceRelationship(String evidenceRelationship) { this.evidenceRelationship = evidenceRelationship; } public void setQualifier(String qualifier) { this.qualifier = validationHelper.csvToList(qualifier); } public void setReference(String reference) { this.reference = validationHelper.csvToList(reference); } public void setWith(String with) { this.with = validationHelper.csvToList(with); } public void setAssignedby(String assignedby) { this.assignedby = validationHelper.csvToList(assignedby); } public void setPage(String page) { this.page = page; } public void setLimit(String limit) { this.limit = limit; } public List<String> getTaxon() { return taxon; } public List<String> getGp() { return gp; } public List<String> getGpSet() { return gpSet; } public List<String> getGpType() { return gpType; } public List<String> getGoTerm() { return goTerm; } public List<String> getGoTermSet() { return goTermSet; } public String getGoTermUse() { return goTermUse; } public String getGoTermRelationship() { return goTermRelationship; } public List<String> getAspect() { return aspect; } public List<String> getEcoEvidence() { return ecoEvidence; } public List<String> getGoEvidence() { return goEvidence; } public String getEvidenceRelationship() { return evidenceRelationship; } public List<String> getQualifier() { return qualifier; } public List<String> getReference() { return reference; } public List<String> getWith() { return with; } public List<String> getAssignedby() { return assignedby; } public String getLimit() { return limit; } public String getPage() { return page; } }
annotation-rest/src/main/java/uk/ac/ebi/quickgo/annotation/model/AnnotationFilter.java
package uk.ac.ebi.quickgo.annotation.model; import uk.ac.ebi.quickgo.rest.controller.ControllerValidationHelper; import uk.ac.ebi.quickgo.rest.controller.ControllerValidationHelperImpl; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; /** * A data structure for the annotation filtering parameters passed in from the client. * Here are the list of parameters filtering will require. The values shown are the ones the FE currently uses * Nearly all the parameters can take multiple values, separated by commas. These types are named as plural. * Exceptions exists however * * @author Tony Wardell * Date: 25/04/2016 * Time: 11:23 * Created with IntelliJ IDEA. */ public class AnnotationFilter { private static final String DEFAULT_ENTRIES_PER_PAGE = "25"; private static final String DEFAULT_PAGE_NUMBER = "1"; public static final int MAX_PAGE_RESULTS = 100; private List<String> taxon; // Taxon ids E.g. 1234,343434 private List<String> gp; // Gene Product ids; E.g. A0A000,A0A001,.. private List<String> gpSet; // Gene Product Sets E.g. BHF-UCL,Exosome,.. private List<String> gpType; // Gene Product Types I.E protein,rna,.. (3 choices) //Choices of gpType private static Map<String, Object> gpTypeChoices = Arrays.asList("proteins","RNAs","complexes").stream().collect (Collectors.toMap(Function.identity(),Function.identity())); //Choices of gpSets todo these values in the beta are NOT lowercased.. needs to be for the new version private static Map<String, Object> gpSetChoices = Arrays.asList("bhf-ucl","exsome","kruk", "parkinsonsuk-ucl", "referencegenome").stream().collect(Collectors.toMap(Function.identity(),Function.identity())); //Go Terms private List<String> goTerm; // Go Term ids E.g. GO:0016021,GO:0016022,.. private List<String> goTermSet; // Go Term Set ids E.g. goslim_chembl,goSlimGeneric,.. //..the following 2 members are only applicable if goTerm ids or sets have been selected private String goTermUse; // Go Term use I.e. ancestor or slim or exact (singular) private String goTermRelationship; // Go Term relationship I.e. I or IPO or IPOR (singular) private List<String> aspect; //Aspect I.e. F, P or C (singular) private static Map<String, Object> aspectChoices = Arrays.asList("c","f","p").stream() .collect(Collectors.toMap(Function.identity(),Function.identity())); private List<String> ecoEvidence; //Eco evidence ids E.g. ECO:12345, ECO:34535,.. private List<String> goEvidence; //Go evidence ids E.g. IEA,.. //..the following is only applicable if an evidence code has been requested private String evidenceRelationship; //Evidence relationships I.e. ancestor or exact (singular) // Qualifier specifies the relationship between the annotated gene product and the GO term private List<String> qualifier; // E.g enables, not_enables,.. private List<String> reference; // E.g. DOI,GO_REF,.. private List<String> with; // E.g. AGI_LocusCode,CGD,.. private List<String> assignedby; // E.g. ASPGD,Agbase,.. //Non-data parameters private String limit = DEFAULT_ENTRIES_PER_PAGE; private String page = DEFAULT_PAGE_NUMBER; //Defaults for required values private static final String DEFAULT_GO_TERM_USE="Ancestor"; private static final String DEFAULT_EVIDENCE_RELATIONSHIP ="Ancestor"; //todo @Autowired public ControllerValidationHelper validationHelper = new ControllerValidationHelperImpl(MAX_PAGE_RESULTS); /** * After filters have been loaded, ensure values are valid and defaults are in place. */ public void validation() { //Some filters have a small number of potential values, defined by enums verifyField(gpType, gpTypeChoices, " is an invalid option for gene product type"); verifyField(gpSet, gpSetChoices, " is an invalid option for gene product set."); verifyField(aspect, aspectChoices, " is an invalid option for aspect."); //If go terms or sets are entered, then use the default relationship if none is specified if(((goTerm != null && goTerm.size()>0) || (goTermSet !=null && goTermSet.size()>0))&& goTermUse==null){ goTermUse = DEFAULT_GO_TERM_USE; } //If eco codes or go evidence codes are entered, then use the default relationship if none is specified if(((ecoEvidence !=null && ecoEvidence.size()>0) || (goEvidence !=null && goEvidence.size()>0)) && evidenceRelationship==null){ evidenceRelationship = DEFAULT_EVIDENCE_RELATIONSHIP; } validationHelper.validateRequestedResults(Integer.parseInt(limit)); } private void verifyField(List<String> args, Map<String, Object> choices, String message) { if(args!=null){ args.stream() .map(e -> { if(!choices.containsKey(e.toLowerCase())){ throw new IllegalArgumentException(e + message); } return e; }); } } public void setTaxon(String taxon) { this.taxon = validationHelper.csvToList(taxon); } public void setGp(String gp) { this.gp = validationHelper.csvToList(gp); } public void setGpSet(String gpSet) { this.gpSet = validationHelper.csvToList(gpSet); } public void setGpType(String gpType) { this.gpType = validationHelper.csvToList(gpType); } public void setGoTerm(String goTerm) { this.goTerm = validationHelper.csvToList(goTerm); } public void setGoTermSet(String goTermSet) { this.goTermSet = validationHelper.csvToList(goTermSet); } public void setGoTermUse(String goTermUse) { this.goTermUse = goTermUse; } public void setGoTermRelationship(String goTermRelationship) { this.goTermRelationship = goTermRelationship; } public void setAspect(String aspect) { this.aspect = validationHelper.csvToList(aspect); } public void setEcoEvidence(String ecoEvidence) { this.ecoEvidence = validationHelper.csvToList(ecoEvidence); } public void setGoEvidence(String goEvidence) { this.goEvidence = validationHelper.csvToList(goEvidence); } public void setEvidenceRelationship(String evidenceRelationship) { this.evidenceRelationship = evidenceRelationship; } public void setQualifier(String qualifier) { this.qualifier = validationHelper.csvToList(qualifier); } public void setReference(String reference) { this.reference = validationHelper.csvToList(reference); } public void setWith(String with) { this.with = validationHelper.csvToList(with); } public void setAssignedby(String assignedby) { this.assignedby = validationHelper.csvToList(assignedby); } public void setPage(String page) { this.page = page; } public void setLimit(String limit) { this.limit = limit; } public List<String> getTaxon() { return taxon; } public List<String> getGp() { return gp; } public List<String> getGpSet() { return gpSet; } public List<String> getGpType() { return gpType; } public List<String> getGoTerm() { return goTerm; } public List<String> getGoTermSet() { return goTermSet; } public String getGoTermUse() { return goTermUse; } public String getGoTermRelationship() { return goTermRelationship; } public List<String> getAspect() { return aspect; } public List<String> getEcoEvidence() { return ecoEvidence; } public List<String> getGoEvidence() { return goEvidence; } public String getEvidenceRelationship() { return evidenceRelationship; } public List<String> getQualifier() { return qualifier; } public List<String> getReference() { return reference; } public List<String> getWith() { return with; } public List<String> getAssignedby() { return assignedby; } public String getLimit() { return limit; } public String getPage() { return page; } }
Make static final defaults public.
annotation-rest/src/main/java/uk/ac/ebi/quickgo/annotation/model/AnnotationFilter.java
Make static final defaults public.
Java
apache-2.0
a3bf4fd77ce4417a765757adedce813cd7790b1d
0
bmaupin/android-sms-plus
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package src.com.android.mms; import com.android.mms.R; import com.android.mms.ui.ComposeMessageActivity; import android.app.Instrumentation; import android.test.suitebuilder.annotation.LargeTest; import android.test.ActivityInstrumentationTestCase2; import android.util.Log; import android.view.KeyEvent; import android.widget.Button; /** * * Junit / Instrumentation test case for mms stability test * */ public class MmsStability extends ActivityInstrumentationTestCase2 <ComposeMessageActivity> { private static String TAG = "MmsStability"; private static int NO_OF_MESSAGE_SEND = 5; //Total number of messages private static String MESSAGE_CONTENT = "This is a system stability " + "test for MMS. This test case send 5 message " + "to the number which will reply automatically"; private static int WAIT_TIME = 2000; //Set the short wait time for 2 sec. private static String RECIPIENT_NUMBER = "46645"; public MmsStability() { super("com.android.mms", ComposeMessageActivity.class); } @Override protected void setUp() throws Exception { getActivity(); super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } // Create the object with the run() method Runnable runnable = new sendMms(); class sendMms implements Runnable { // This method is called when the thread runs public void run() { Instrumentation inst = getInstrumentation(); Button mSendButton = (Button) getActivity().getWindow().findViewById(R.id.send_button); mSendButton.performClick(); boolean messageSend = mSendButton.performClick(); if (!messageSend) { assertTrue("Fails to send mms", false); Log.v(TAG, "messageSend is true"); } } } // Send 5 mms to the same contact. @LargeTest public void testSend5MMS(){ try{ Instrumentation inst = getInstrumentation(); //This number will send automatic reply inst.sendStringSync(RECIPIENT_NUMBER); inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN); inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_CENTER); for (int i = 0; i < NO_OF_MESSAGE_SEND; i++) { // Enter the message inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN); inst.sendStringSync(MESSAGE_CONTENT); // Send the mms message inst.runOnMainSync(runnable); Thread.sleep(WAIT_TIME); } assertTrue("Send MMS", true); } catch (Exception e){ assertTrue("Fails to send mms", false); Log.v(TAG, e.toString()); } } @LargeTest public void testLaunchMMS() { // Added a do nothing test case to capture // the mms power usage base line. try { Thread.sleep(WAIT_TIME); } catch (Exception e) { assertTrue("MMS do nothing", false); } assertTrue("MMS do nothing", true); } }
tests/src/com/android/mms/MmsStability.java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package src.com.android.mms; import com.android.mms.R; import com.android.mms.ui.ComposeMessageActivity; import android.app.Instrumentation; import android.test.suitebuilder.annotation.LargeTest; import android.test.ActivityInstrumentationTestCase2; import android.util.Log; import android.view.KeyEvent; import android.widget.Button; /** * * Junit / Instrumentation test case for mms stability test * */ public class MmsStability extends ActivityInstrumentationTestCase2 <ComposeMessageActivity> { private static String TAG = "MmsStability"; private static int NO_OF_MESSAGE_SEND = 5; //Total number of messages private static String MESSAGE_CONTENT = "This is a system stability " + "test for MMS. This test case send 5 message " + "to the number which will reply automatically"; private static int WAIT_TIME = 2000; //Set the short wait time for 2 sec. private static String RECIPIENT_NUMBER = "46645"; public MmsStability() { super("com.android.mms", ComposeMessageActivity.class); } @Override protected void setUp() throws Exception { getActivity(); super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } // Create the object with the run() method Runnable runnable = new sendMms(); class sendMms implements Runnable { // This method is called when the thread runs public void run() { Instrumentation inst = getInstrumentation(); Button mSendButton = (Button) getActivity().getWindow().findViewById(R.id.send_button); mSendButton.performClick(); boolean messageSend = mSendButton.performClick(); if (!messageSend) { assertTrue("Fails to send mms", false); Log.v(TAG, "messageSend is true"); } } } // Send 5 mms to the same contact. @LargeTest public void testSendMMS(){ try{ Instrumentation inst = getInstrumentation(); //This number will send automatic reply inst.sendStringSync(RECIPIENT_NUMBER); inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN); inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_CENTER); for (int i = 0; i < NO_OF_MESSAGE_SEND; i++) { // Enter the message inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN); inst.sendStringSync(MESSAGE_CONTENT); // Send the mms message inst.runOnMainSync(runnable); Thread.sleep(WAIT_TIME); } assertTrue("Send MMS", true); } catch (Exception e){ assertTrue("Fails to send mms", false); Log.v(TAG, e.toString()); } } @LargeTest public void testMMSDoNothing() { // Added a do nothing test case to capture // the mms power usage base line. try { Thread.sleep(WAIT_TIME); } catch (Exception e) { assertTrue("MMS do nothing", false); } assertTrue("MMS do nothing", true); } }
am d05ca43f: am c964b53d: Merge change 27012 into eclair Merge commit 'd05ca43f66cf357850ce8f233195df4a8604408a' * commit 'd05ca43f66cf357850ce8f233195df4a8604408a': Modified the test case name and make it more meaningful.
tests/src/com/android/mms/MmsStability.java
am d05ca43f: am c964b53d: Merge change 27012 into eclair
Java
apache-2.0
132d68fa89f2812a0eee4b5c4ec969ebaa61a033
0
consulo/consulo-csharp,consulo/consulo-csharp,consulo/consulo-csharp
/* * Copyright 2013-2014 must-be.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mustbe.consulo.csharp.lang.psi.impl.msil; import java.util.Map; import org.jetbrains.annotations.Nullable; import org.mustbe.consulo.csharp.lang.psi.CSharpModifier; import org.mustbe.consulo.csharp.lang.psi.impl.source.resolve.type.CSharpArrayTypeRef; import org.mustbe.consulo.csharp.lang.psi.impl.source.resolve.type.CSharpNativeTypeRef; import org.mustbe.consulo.csharp.lang.psi.impl.source.resolve.type.CSharpRefTypeRef; import org.mustbe.consulo.dotnet.DotNetTypes; import org.mustbe.consulo.dotnet.psi.DotNetInheritUtil; import org.mustbe.consulo.dotnet.lang.psi.impl.source.resolve.type.DotNetGenericWrapperTypeRef; import org.mustbe.consulo.dotnet.lang.psi.impl.source.resolve.type.DotNetPointerTypeRefImpl; import org.mustbe.consulo.dotnet.psi.DotNetAttribute; import org.mustbe.consulo.dotnet.psi.DotNetNamedElement; import org.mustbe.consulo.dotnet.psi.DotNetTypeDeclaration; import org.mustbe.consulo.dotnet.resolve.DotNetPointerTypeRef; import org.mustbe.consulo.dotnet.resolve.DotNetRefTypeRef; import org.mustbe.consulo.dotnet.resolve.DotNetTypeRef; import org.mustbe.consulo.msil.lang.psi.MsilClassEntry; import org.mustbe.consulo.msil.lang.psi.MsilEntry; import org.mustbe.consulo.msil.lang.psi.MsilMethodEntry; import org.mustbe.consulo.msil.lang.psi.MsilModifierElementType; import org.mustbe.consulo.msil.lang.psi.MsilModifierList; import org.mustbe.consulo.msil.lang.psi.MsilTokens; import org.mustbe.consulo.msil.lang.psi.impl.type.MsilArrayTypRefImpl; import org.mustbe.consulo.msil.lang.psi.impl.type.MsilNativeTypeRefImpl; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Condition; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.IElementType; import com.intellij.util.containers.ConcurrentHashMap; import com.intellij.util.containers.ContainerUtil; import lombok.val; /** * @author VISTALL * @since 22.05.14 */ public class MsilToCSharpUtil { private static Map<MsilEntry, PsiElement> ourCache = new ConcurrentHashMap<MsilEntry, PsiElement>(); public static boolean hasCSharpInMsilModifierList(CSharpModifier modifier, MsilModifierList modifierList) { MsilModifierElementType elementType = null; switch(modifier) { case PUBLIC: elementType = MsilTokens.PUBLIC_KEYWORD; break; case PRIVATE: elementType = MsilTokens.PRIVATE_KEYWORD; break; case PROTECTED: elementType = MsilTokens.PROTECTED_KEYWORD; break; case STATIC: elementType = MsilTokens.STATIC_KEYWORD; break; case SEALED: elementType = MsilTokens.SEALED_KEYWORD; break; case INTERNAL: elementType = MsilTokens.ASSEMBLY_KEYWORD; break; case OUT: elementType = MsilTokens.BRACKET_OUT_KEYWORD; break; case VIRTUAL: elementType = MsilTokens.VIRTUAL_KEYWORD; break; case READONLY: elementType = MsilTokens.INITONLY_KEYWORD; break; case UNSAFE: break; case PARAMS: return hasAttribute(modifierList, DotNetTypes.System_ParamArrayAttribute); case THIS: return hasAttribute(modifierList, DotNetTypes.System_Runtime_CompilerServices_ExtensionAttribute); case ABSTRACT: elementType = MsilTokens.ABSTRACT_KEYWORD; break; } return elementType != null && modifierList.hasModifier(elementType); } private static boolean hasAttribute(MsilModifierList modifierList, String qName) { for(DotNetAttribute attribute : modifierList.getAttributes()) { DotNetTypeDeclaration typeDeclaration = attribute.resolveToType(); if(typeDeclaration != null && Comparing.equal(typeDeclaration.getPresentableQName(), qName)) { return true; } } return false; } @Nullable public static PsiElement wrap(PsiElement element) { if(element instanceof MsilClassEntry) { PsiElement cache = ourCache.get(element); if(cache != null) { return cache; } if(DotNetInheritUtil.isInheritor((MsilClassEntry) element, DotNetTypes.System_MulticastDelegate, true)) { val msilMethodEntry = (MsilMethodEntry) ContainerUtil.find(((MsilClassEntry) element).getMembers(), new Condition<DotNetNamedElement>() { @Override public boolean value(DotNetNamedElement element) { return element instanceof MsilMethodEntry && Comparing.equal(element.getName(), "Invoke"); } }); assert msilMethodEntry != null : ((MsilClassEntry) element).getPresentableQName(); cache = new MsilMethodAsCSharpMethodDeclaration(null, (MsilClassEntry) element, msilMethodEntry); } else { cache = new MsilClassAsCSharpTypeDefinition(null, (MsilClassEntry) element); } ourCache.put((MsilClassEntry) element, cache); return cache; } return element; } public static DotNetTypeRef extractToCSharp(DotNetTypeRef typeRef, PsiElement scope) { if(typeRef == DotNetTypeRef.ERROR_TYPE) { return DotNetTypeRef.ERROR_TYPE; } if(typeRef instanceof MsilNativeTypeRefImpl) { IElementType elementType = ((MsilNativeTypeRefImpl) typeRef).getElementType(); if(elementType == MsilTokens.INT8_KEYWORD) { return CSharpNativeTypeRef.SBYTE; } else if(elementType == MsilTokens.UINT8_KEYWORD) { return CSharpNativeTypeRef.BYTE; } else if(elementType == MsilTokens.INT16_KEYWORD) { return CSharpNativeTypeRef.SHORT; } else if(elementType == MsilTokens.UINT16_KEYWORD) { return CSharpNativeTypeRef.USHORT; } else if(elementType == MsilTokens.INT32_KEYWORD) { return CSharpNativeTypeRef.INT; } else if(elementType == MsilTokens.UINT32_KEYWORD) { return CSharpNativeTypeRef.UINT; } else if(elementType == MsilTokens.INT64_KEYWORD) { return CSharpNativeTypeRef.LONG; } else if(elementType == MsilTokens.UINT64_KEYWORD) { return CSharpNativeTypeRef.ULONG; } else if(elementType == MsilTokens.STRING_KEYWORD) { return CSharpNativeTypeRef.STRING; } else if(elementType == MsilTokens.OBJECT_KEYWORD) { return CSharpNativeTypeRef.OBJECT; } else if(elementType == MsilTokens.CHAR_KEYWORD) { return CSharpNativeTypeRef.CHAR; } else if(elementType == MsilTokens.BOOL_KEYWORD) { return CSharpNativeTypeRef.BOOL; } else if(elementType == MsilTokens.FLOAT_KEYWORD) { return CSharpNativeTypeRef.FLOAT; } else if(elementType == MsilTokens.FLOAT64_KEYWORD) { return CSharpNativeTypeRef.DOUBLE; } else if(elementType == MsilTokens.VOID_KEYWORD) { return CSharpNativeTypeRef.VOID; } } else if(typeRef instanceof MsilArrayTypRefImpl) { return new CSharpArrayTypeRef(extractToCSharp(((MsilArrayTypRefImpl) typeRef).getInnerTypeRef(), scope), 0); } else if(typeRef instanceof DotNetPointerTypeRef) { return new DotNetPointerTypeRefImpl(extractToCSharp(((DotNetPointerTypeRef) typeRef).getInnerTypeRef(), scope)); } else if(typeRef instanceof DotNetRefTypeRef) { return new CSharpRefTypeRef(CSharpRefTypeRef.Type.ref, extractToCSharp(((DotNetRefTypeRef) typeRef).getInnerTypeRef(), scope)); } else if(typeRef instanceof DotNetGenericWrapperTypeRef) { val inner = extractToCSharp(((DotNetGenericWrapperTypeRef) typeRef).getInnerTypeRef(), scope); DotNetTypeRef[] arguments = ((DotNetGenericWrapperTypeRef) typeRef).getArgumentTypeRefs(); DotNetTypeRef[] newArguments = new DotNetTypeRef[arguments.length]; for(int i = 0; i < newArguments.length; i++) { newArguments[i] = extractToCSharp(arguments[i], scope); } return new DotNetGenericWrapperTypeRef(inner, newArguments); } return new MsilDelegateTypeRef(typeRef); } }
csharp-psi-impl/src/org/mustbe/consulo/csharp/lang/psi/impl/msil/MsilToCSharpUtil.java
/* * Copyright 2013-2014 must-be.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mustbe.consulo.csharp.lang.psi.impl.msil; import java.util.Map; import org.jetbrains.annotations.Nullable; import org.mustbe.consulo.csharp.lang.psi.CSharpModifier; import org.mustbe.consulo.csharp.lang.psi.impl.source.resolve.type.CSharpArrayTypeRef; import org.mustbe.consulo.csharp.lang.psi.impl.source.resolve.type.CSharpNativeTypeRef; import org.mustbe.consulo.csharp.lang.psi.impl.source.resolve.type.CSharpRefTypeRef; import org.mustbe.consulo.dotnet.DotNetTypes; import org.mustbe.consulo.dotnet.psi.DotNetInheritUtil; import org.mustbe.consulo.dotnet.lang.psi.impl.source.resolve.type.DotNetGenericWrapperTypeRef; import org.mustbe.consulo.dotnet.lang.psi.impl.source.resolve.type.DotNetPointerTypeRefImpl; import org.mustbe.consulo.dotnet.psi.DotNetAttribute; import org.mustbe.consulo.dotnet.psi.DotNetNamedElement; import org.mustbe.consulo.dotnet.psi.DotNetTypeDeclaration; import org.mustbe.consulo.dotnet.resolve.DotNetPointerTypeRef; import org.mustbe.consulo.dotnet.resolve.DotNetRefTypeRef; import org.mustbe.consulo.dotnet.resolve.DotNetTypeRef; import org.mustbe.consulo.msil.lang.psi.MsilClassEntry; import org.mustbe.consulo.msil.lang.psi.MsilEntry; import org.mustbe.consulo.msil.lang.psi.MsilMethodEntry; import org.mustbe.consulo.msil.lang.psi.MsilModifierElementType; import org.mustbe.consulo.msil.lang.psi.MsilModifierList; import org.mustbe.consulo.msil.lang.psi.MsilTokens; import org.mustbe.consulo.msil.lang.psi.impl.type.MsilArrayTypRefImpl; import org.mustbe.consulo.msil.lang.psi.impl.type.MsilNativeTypeRefImpl; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Condition; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.IElementType; import com.intellij.util.containers.ConcurrentHashMap; import com.intellij.util.containers.ContainerUtil; import lombok.val; /** * @author VISTALL * @since 22.05.14 */ public class MsilToCSharpUtil { private static Map<MsilEntry, PsiElement> ourCache = new ConcurrentHashMap<MsilEntry, PsiElement>(); public static boolean hasCSharpInMsilModifierList(CSharpModifier modifier, MsilModifierList modifierList) { MsilModifierElementType elementType = null; switch(modifier) { case PUBLIC: elementType = MsilTokens.PUBLIC_KEYWORD; break; case PRIVATE: elementType = MsilTokens.PRIVATE_KEYWORD; break; case PROTECTED: elementType = MsilTokens.PROTECTED_KEYWORD; break; case STATIC: elementType = MsilTokens.STATIC_KEYWORD; break; case SEALED: elementType = MsilTokens.SEALED_KEYWORD; break; case INTERNAL: elementType = MsilTokens.ASSEMBLY_KEYWORD; break; case OUT: elementType = MsilTokens.BRACKET_OUT_KEYWORD; break; case VIRTUAL: elementType = MsilTokens.VIRTUAL_KEYWORD; break; case READONLY: break; case UNSAFE: break; case PARAMS: return hasAttribute(modifierList, DotNetTypes.System_ParamArrayAttribute); case THIS: return hasAttribute(modifierList, DotNetTypes.System_Runtime_CompilerServices_ExtensionAttribute); case ABSTRACT: elementType = MsilTokens.ABSTRACT_KEYWORD; break; } return elementType != null && modifierList.hasModifier(elementType); } private static boolean hasAttribute(MsilModifierList modifierList, String qName) { for(DotNetAttribute attribute : modifierList.getAttributes()) { DotNetTypeDeclaration typeDeclaration = attribute.resolveToType(); if(typeDeclaration != null && Comparing.equal(typeDeclaration.getPresentableQName(), qName)) { return true; } } return false; } @Nullable public static PsiElement wrap(PsiElement element) { if(element instanceof MsilClassEntry) { PsiElement cache = ourCache.get(element); if(cache != null) { return cache; } if(DotNetInheritUtil.isInheritor((MsilClassEntry) element, DotNetTypes.System_MulticastDelegate, true)) { val msilMethodEntry = (MsilMethodEntry) ContainerUtil.find(((MsilClassEntry) element).getMembers(), new Condition<DotNetNamedElement>() { @Override public boolean value(DotNetNamedElement element) { return element instanceof MsilMethodEntry && Comparing.equal(element.getName(), "Invoke"); } }); assert msilMethodEntry != null : ((MsilClassEntry) element).getPresentableQName(); cache = new MsilMethodAsCSharpMethodDeclaration(null, (MsilClassEntry) element, msilMethodEntry); } else { cache = new MsilClassAsCSharpTypeDefinition(null, (MsilClassEntry) element); } ourCache.put((MsilClassEntry) element, cache); return cache; } return element; } public static DotNetTypeRef extractToCSharp(DotNetTypeRef typeRef, PsiElement scope) { if(typeRef == DotNetTypeRef.ERROR_TYPE) { return DotNetTypeRef.ERROR_TYPE; } if(typeRef instanceof MsilNativeTypeRefImpl) { IElementType elementType = ((MsilNativeTypeRefImpl) typeRef).getElementType(); if(elementType == MsilTokens.INT8_KEYWORD) { return CSharpNativeTypeRef.SBYTE; } else if(elementType == MsilTokens.UINT8_KEYWORD) { return CSharpNativeTypeRef.BYTE; } else if(elementType == MsilTokens.INT16_KEYWORD) { return CSharpNativeTypeRef.SHORT; } else if(elementType == MsilTokens.UINT16_KEYWORD) { return CSharpNativeTypeRef.USHORT; } else if(elementType == MsilTokens.INT32_KEYWORD) { return CSharpNativeTypeRef.INT; } else if(elementType == MsilTokens.UINT32_KEYWORD) { return CSharpNativeTypeRef.UINT; } else if(elementType == MsilTokens.INT64_KEYWORD) { return CSharpNativeTypeRef.LONG; } else if(elementType == MsilTokens.UINT64_KEYWORD) { return CSharpNativeTypeRef.ULONG; } else if(elementType == MsilTokens.STRING_KEYWORD) { return CSharpNativeTypeRef.STRING; } else if(elementType == MsilTokens.OBJECT_KEYWORD) { return CSharpNativeTypeRef.OBJECT; } else if(elementType == MsilTokens.CHAR_KEYWORD) { return CSharpNativeTypeRef.CHAR; } else if(elementType == MsilTokens.BOOL_KEYWORD) { return CSharpNativeTypeRef.BOOL; } else if(elementType == MsilTokens.FLOAT_KEYWORD) { return CSharpNativeTypeRef.FLOAT; } else if(elementType == MsilTokens.FLOAT64_KEYWORD) { return CSharpNativeTypeRef.DOUBLE; } else if(elementType == MsilTokens.VOID_KEYWORD) { return CSharpNativeTypeRef.VOID; } } else if(typeRef instanceof MsilArrayTypRefImpl) { return new CSharpArrayTypeRef(extractToCSharp(((MsilArrayTypRefImpl) typeRef).getInnerTypeRef(), scope), 0); } else if(typeRef instanceof DotNetPointerTypeRef) { return new DotNetPointerTypeRefImpl(extractToCSharp(((DotNetPointerTypeRef) typeRef).getInnerTypeRef(), scope)); } else if(typeRef instanceof DotNetRefTypeRef) { return new CSharpRefTypeRef(CSharpRefTypeRef.Type.ref, extractToCSharp(((DotNetRefTypeRef) typeRef).getInnerTypeRef(), scope)); } else if(typeRef instanceof DotNetGenericWrapperTypeRef) { val inner = extractToCSharp(((DotNetGenericWrapperTypeRef) typeRef).getInnerTypeRef(), scope); DotNetTypeRef[] arguments = ((DotNetGenericWrapperTypeRef) typeRef).getArgumentTypeRefs(); DotNetTypeRef[] newArguments = new DotNetTypeRef[arguments.length]; for(int i = 0; i < newArguments.length; i++) { newArguments[i] = extractToCSharp(arguments[i], scope); } return new DotNetGenericWrapperTypeRef(inner, newArguments); } return new MsilDelegateTypeRef(typeRef); } }
handle readonly modifier
csharp-psi-impl/src/org/mustbe/consulo/csharp/lang/psi/impl/msil/MsilToCSharpUtil.java
handle readonly modifier
Java
apache-2.0
20cf98df8a73a138e674bd5d3da94495583f5511
0
gnodet/aries,gnodet/aries,gnodet/aries,gnodet/aries
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.internal; import java.util.EnumSet; import org.osgi.service.subsystem.Subsystem.State; public class UninstallAction extends AbstractAction { public UninstallAction(BasicSubsystem requestor, BasicSubsystem target, boolean disableRootCheck) { super(requestor, target, disableRootCheck); } @Override public Object run() { // Protect against re-entry now that cycles are supported. if (!LockingStrategy.set(State.UNINSTALLING, target)) { return null; } try { // Acquire the global write lock to prevent all other operations until // the installation is complete. There is no need to hold any other locks. LockingStrategy.writeLock(); try { checkRoot(); checkValid(); State state = target.getState(); if (EnumSet.of(State.UNINSTALLED).contains(state)) { return null; } if (state.equals(State.ACTIVE)) { new StopAction(requestor, target, disableRootCheck).run(); } ResourceUninstaller.newInstance(requestor, target).uninstall(); } finally { // Release the global write lock. LockingStrategy.writeUnlock(); } } finally { // Protection against re-entry no longer required. LockingStrategy.unset(State.UNINSTALLING, target); } return null; } }
subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/UninstallAction.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.internal; import java.util.EnumSet; import org.osgi.service.subsystem.Subsystem.State; public class UninstallAction extends AbstractAction { public UninstallAction(BasicSubsystem requestor, BasicSubsystem target, boolean disableRootCheck) { super(requestor, target, disableRootCheck); } @Override public Object run() { // Protect against re-entry now that cycles are supported. if (!LockingStrategy.set(State.STOPPING, target)) { return null; } try { // Acquire the global write lock to prevent all other operations until // the installation is complete. There is no need to hold any other locks. LockingStrategy.writeLock(); try { checkRoot(); checkValid(); State state = target.getState(); if (EnumSet.of(State.UNINSTALLED).contains(state)) { return null; } if (state.equals(State.ACTIVE)) { new StopAction(requestor, target, disableRootCheck).run(); } ResourceUninstaller.newInstance(requestor, target).uninstall(); } finally { // Release the global write lock. LockingStrategy.writeUnlock(); } } finally { // Protection against re-entry no longer required. LockingStrategy.unset(State.STOPPING, target); } return null; } }
[ARIES-1383] Provide option to disable the provisioning of dependencies at install time. Use the correct state when flagging an uninstall for re-entry protection. git-svn-id: f3027bd689517dd712b868b0d3f5f59c3162b83d@1728542 13f79535-47bb-0310-9956-ffa450edef68
subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/UninstallAction.java
[ARIES-1383] Provide option to disable the provisioning of dependencies at install time.
Java
apache-2.0
f65da6a0f76a120152e55c6d2eced6a765a247d8
0
nelt/poom-services,nelt/poom-services
package org.codingmatters.poom.servives.domain.entities; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; /** * Created by nelt on 6/5/17. */ public interface PagedEntityList<V> extends List<Entity<V>> { long startIndex(); long endIndex(); long total(); List<V> valueList(); class DefaultPagedEntityList<V> extends LinkedList<Entity<V>> implements PagedEntityList<V> { private final long startIndex; private final long endIndex; private final long total; public DefaultPagedEntityList(long startIndex, long endIndex, long total, Collection<Entity<V>> collection) { super(collection); this.startIndex = startIndex; this.endIndex = endIndex; this.total = total; } @Override public long startIndex() { return this.startIndex; } @Override public long endIndex() { return this.endIndex; } @Override public long total() { return this.total; } @Override public List<V> valueList() { return this.stream().map(entity -> entity.value()).collect(Collectors.toList()); } } }
poom-services-domain/src/main/java/org/codingmatters/poom/servives/domain/entities/PagedEntityList.java
package org.codingmatters.poom.servives.domain.entities; import java.util.Collection; import java.util.LinkedList; import java.util.List; /** * Created by nelt on 6/5/17. */ public interface PagedEntityList<V> extends List<Entity<V>> { long startIndex(); long endIndex(); long total(); class DefaultPagedEntityList<V> extends LinkedList<Entity<V>> implements PagedEntityList<V> { private final long startIndex; private final long endIndex; private final long total; public DefaultPagedEntityList(long startIndex, long endIndex, long total, Collection<Entity<V>> collection) { super(collection); this.startIndex = startIndex; this.endIndex = endIndex; this.total = total; } @Override public long startIndex() { return this.startIndex; } @Override public long endIndex() { return this.endIndex; } @Override public long total() { return this.total; } } }
paged entity list valueList method
poom-services-domain/src/main/java/org/codingmatters/poom/servives/domain/entities/PagedEntityList.java
paged entity list valueList method
Java
apache-2.0
44be8b51cd714f6ac780fee64f3ed9d8d931d1cf
0
ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE
package uk.ac.ebi.quickgo.geneproduct.service; import uk.ac.ebi.quickgo.common.loader.DbXRefLoader; import uk.ac.ebi.quickgo.common.validator.DbXRefEntityValidation; import uk.ac.ebi.quickgo.geneproduct.common.GeneProductRepoConfig; import uk.ac.ebi.quickgo.geneproduct.common.GeneProductRepository; import uk.ac.ebi.quickgo.geneproduct.service.converter.GeneProductDocConverter; import uk.ac.ebi.quickgo.geneproduct.service.converter.GeneProductDocConverterImpl; import uk.ac.ebi.quickgo.rest.controller.ControllerValidationHelper; import uk.ac.ebi.quickgo.rest.controller.ControllerValidationHelperImpl; import uk.ac.ebi.quickgo.rest.search.QueryStringSanitizer; import uk.ac.ebi.quickgo.rest.search.SolrQueryStringSanitizer; import uk.ac.ebi.quickgo.rest.service.ServiceHelper; import uk.ac.ebi.quickgo.rest.service.ServiceHelperImpl; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import static uk.ac.ebi.quickgo.rest.controller.ControllerValidationHelperImpl.MAX_PAGE_RESULTS; /** * * Spring configuration for the service layer, which depends on the repositories * made available by {@link GeneProductRepoConfig}. Services * to additionally make accessible are defined in specified the {@link ComponentScan} packages. * * @author Tony Wardell * Date: 04/04/2016 * Time: 11:42 * Created with IntelliJ IDEA. */ @Configuration @ComponentScan({"uk.ac.ebi.quickgo.geneproduct.service"}) @Import({GeneProductRepoConfig.class}) public class ServiceConfig { private static final boolean DEFAULT_XREF_VALIDATION_IS_CASE_SENSITIVE = true; @Value("${geneproduct.db.xref.valid.casesensitive:"+DEFAULT_XREF_VALIDATION_IS_CASE_SENSITIVE+"}") boolean xrefValidationCaseSensitive; @Value("${geneproduct.db.xref.valid.regexes}") private String xrefValidationRegexFile; @Bean public GeneProductService goGeneProductService(GeneProductRepository geneProductRepository) { return new GeneProductServiceImpl( serviceHelper(), geneProductRepository, geneProductDocConverter()); } @Bean public ControllerValidationHelper geneProductValidator() { return new ControllerValidationHelperImpl(MAX_PAGE_RESULTS, idValidator()); } private ServiceHelper serviceHelper() { return new ServiceHelperImpl(queryStringSanitizer()); } private GeneProductDocConverter geneProductDocConverter() { return new GeneProductDocConverterImpl(); } private QueryStringSanitizer queryStringSanitizer() { return new SolrQueryStringSanitizer(); } private DbXRefEntityValidation idValidator() { return DbXRefEntityValidation.createWithData(geneProductLoader().load()); } private DbXRefLoader geneProductLoader() { return new DbXRefLoader(this.xrefValidationRegexFile, xrefValidationCaseSensitive); } }
geneproduct-rest/src/main/java/uk/ac/ebi/quickgo/geneproduct/service/ServiceConfig.java
package uk.ac.ebi.quickgo.geneproduct.service; import uk.ac.ebi.quickgo.common.loader.DbXRefLoader; import uk.ac.ebi.quickgo.common.validator.DbXRefEntityValidation; import uk.ac.ebi.quickgo.geneproduct.common.GeneProductRepoConfig; import uk.ac.ebi.quickgo.geneproduct.common.GeneProductRepository; import uk.ac.ebi.quickgo.geneproduct.service.converter.GeneProductDocConverter; import uk.ac.ebi.quickgo.geneproduct.service.converter.GeneProductDocConverterImpl; import uk.ac.ebi.quickgo.rest.controller.ControllerValidationHelper; import uk.ac.ebi.quickgo.rest.controller.ControllerValidationHelperImpl; import uk.ac.ebi.quickgo.rest.search.QueryStringSanitizer; import uk.ac.ebi.quickgo.rest.search.SolrQueryStringSanitizer; import uk.ac.ebi.quickgo.rest.service.ServiceHelper; import uk.ac.ebi.quickgo.rest.service.ServiceHelperImpl; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import static uk.ac.ebi.quickgo.rest.controller.ControllerValidationHelperImpl.MAX_PAGE_RESULTS; /** * * Spring configuration for the service layer, which depends on the repositories * made available by {@link GeneProductRepoConfig}. Services * to additionally make accessible are defined in specified the {@link ComponentScan} packages. * * @author Tony Wardell * Date: 04/04/2016 * Time: 11:42 * Created with IntelliJ IDEA. */ @Configuration @ComponentScan({"uk.ac.ebi.quickgo.geneproduct.service"}) @Import({GeneProductRepoConfig.class}) public class ServiceConfig { @Value("${geneproduct.db.xref.valid.regexes}") private String xrefValidationRegexFile; private static final boolean DEFAULT_XREF_VALIDATION_IS_CASE_SENSITIVE = true; @Value("${geneproduct.db.xref.valid.casesensitive:"+DEFAULT_XREF_VALIDATION_IS_CASE_SENSITIVE+"}") boolean xrefValidationCaseSensitive; @Bean public GeneProductService goGeneProductService(GeneProductRepository geneProductRepository) { return new GeneProductServiceImpl( serviceHelper(), geneProductRepository, geneProductDocConverter()); } private ServiceHelper serviceHelper() { return new ServiceHelperImpl(queryStringSanitizer()); } private GeneProductDocConverter geneProductDocConverter() { return new GeneProductDocConverterImpl(); } private QueryStringSanitizer queryStringSanitizer() { return new SolrQueryStringSanitizer(); } @Bean public ControllerValidationHelper geneProductValidator() { return new ControllerValidationHelperImpl(MAX_PAGE_RESULTS, idValidator()); } private DbXRefEntityValidation idValidator() { return DbXRefEntityValidation.createWithData(geneProductLoader().load()); } private DbXRefLoader geneProductLoader() { return new DbXRefLoader(this.xrefValidationRegexFile, xrefValidationCaseSensitive); } }
Order methods public then private.
geneproduct-rest/src/main/java/uk/ac/ebi/quickgo/geneproduct/service/ServiceConfig.java
Order methods public then private.
Java
apache-2.0
3d4113651034d60b67e4b28825370d193804fbf8
0
robgil/Aleph2,robgil/Aleph2
/******************************************************************************* * Copyright 2015, The IKANOW Open Source Project. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.ikanow.aleph2.management_db.services; import java.sql.Timestamp; //(provides a short cut for some datetime manipulation that doesn't confusingly refer to timezones) import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.google.inject.Inject; import com.google.inject.Module; import com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService; import com.ikanow.aleph2.data_model.interfaces.shared_services.ICrudService; import com.ikanow.aleph2.data_model.interfaces.shared_services.IExtraDependencyLoader; import com.ikanow.aleph2.data_model.interfaces.shared_services.IManagementCrudService; import com.ikanow.aleph2.data_model.interfaces.shared_services.IServiceContext; import com.ikanow.aleph2.data_model.objects.data_import.DataBucketBean; import com.ikanow.aleph2.data_model.objects.data_import.DataBucketStatusBean; import com.ikanow.aleph2.data_model.objects.shared.AssetStateDirectoryBean; import com.ikanow.aleph2.data_model.objects.shared.AssetStateDirectoryBean.StateDirectoryType; import com.ikanow.aleph2.data_model.objects.shared.AuthorizationBean; import com.ikanow.aleph2.data_model.objects.shared.BasicMessageBean; import com.ikanow.aleph2.data_model.objects.shared.ProcessingTestSpecBean; import com.ikanow.aleph2.data_model.objects.shared.ProjectBean; import com.ikanow.aleph2.data_model.objects.shared.SharedLibraryBean; import com.ikanow.aleph2.data_model.utils.BeanTemplateUtils; import com.ikanow.aleph2.data_model.utils.BucketUtils; import com.ikanow.aleph2.data_model.utils.FutureUtils; import com.ikanow.aleph2.data_model.utils.FutureUtils.ManagementFuture; import com.ikanow.aleph2.data_model.utils.Lambdas; import com.ikanow.aleph2.management_db.controllers.actors.BucketActionSupervisor; import com.ikanow.aleph2.management_db.controllers.actors.BucketDeletionActor; import com.ikanow.aleph2.management_db.data_model.BucketActionMessage; import com.ikanow.aleph2.management_db.data_model.BucketActionRetryMessage; import com.ikanow.aleph2.management_db.data_model.BucketMgmtMessage.BucketDeletionMessage; import com.ikanow.aleph2.management_db.data_model.BucketMgmtMessage.BucketTimeoutMessage; import com.ikanow.aleph2.management_db.module.CoreManagementDbModule; import com.ikanow.aleph2.management_db.utils.MgmtCrudUtils; import fj.Unit; /** A layer that sits in between the managers and modules on top, and the actual database technology underneath, * and performs control activities (launching into Akka) and an additional layer of validation * @author acp */ public class CoreManagementDbService implements IManagementDbService, IExtraDependencyLoader { private static final Logger _logger = LogManager.getLogger(); protected final IServiceContext _service_context; protected final IManagementDbService _underlying_management_db; protected final DataBucketCrudService _data_bucket_service; protected final DataBucketStatusCrudService _data_bucket_status_service; protected final SharedLibraryCrudService _shared_library_service; protected final ManagementDbActorContext _actor_context; protected final Optional<AuthorizationBean> _auth; protected final Optional<ProjectBean> _project; protected final boolean _read_only; /** Guice invoked constructor * @param underlying_management_db * @param data_bucket_service */ @Inject public CoreManagementDbService(final IServiceContext service_context, final DataBucketCrudService data_bucket_service, final DataBucketStatusCrudService data_bucket_status_service, final SharedLibraryCrudService shared_library_service, final ManagementDbActorContext actor_context ) { //(just return null here if underlying management not present, things will fail catastrophically unless this is a test) _service_context = service_context; _underlying_management_db = service_context.getService(IManagementDbService.class, Optional.empty()).orElse(null); _data_bucket_service = data_bucket_service; _data_bucket_status_service = data_bucket_status_service; _shared_library_service = shared_library_service; _actor_context = actor_context; _auth = Optional.empty(); _project = Optional.empty(); _read_only = false; //DEBUG //System.out.println("Hello world from: " + this.getClass() + ": bucket=" + _data_bucket_service); //System.out.println("Hello world from: " + this.getClass() + ": underlying=" + _underlying_management_db); } /** User constructor for building a cloned version with different auth settings * @param crud_factory * @param auth_fieldname * @param auth * @param project */ public CoreManagementDbService(final IServiceContext service_context, final IManagementDbService underlying_management_db, final DataBucketCrudService data_bucket_service, final DataBucketStatusCrudService data_bucket_status_service, final SharedLibraryCrudService shared_library_service, final ManagementDbActorContext actor_context, final Optional<AuthorizationBean> auth, final Optional<ProjectBean> project, boolean read_only) { _service_context = service_context; _underlying_management_db = underlying_management_db; _data_bucket_service = data_bucket_service; _data_bucket_status_service = data_bucket_status_service; _shared_library_service = shared_library_service; _actor_context = actor_context; _auth = auth; _project = project; _read_only = read_only; } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getFilteredDb(java.lang.String, java.util.Optional, java.util.Optional) */ public IManagementDbService getFilteredDb(final Optional<AuthorizationBean> client_auth, final Optional<ProjectBean> project_auth) { return new CoreManagementDbService(_service_context, _underlying_management_db, _data_bucket_service, _data_bucket_status_service, _shared_library_service, _actor_context, client_auth, project_auth, _read_only); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getSecureddDb(java.lang.String, java.util.Optional, java.util.Optional) */ public IManagementDbService getSecuredDb(AuthorizationBean client_auth) { return new SecuredCoreManagementDbService(_service_context, _underlying_management_db, _data_bucket_service, _data_bucket_status_service, _shared_library_service, _actor_context ,client_auth); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getSharedLibraryStore() */ public IManagementCrudService<SharedLibraryBean> getSharedLibraryStore() { if (!_read_only) ManagementDbActorContext.get().getDistributedServices().waitForAkkaJoin(Optional.empty()); return _shared_library_service.readOnlyVersion(_read_only); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getPerLibraryState(java.lang.Class, com.ikanow.aleph2.data_model.objects.shared.SharedLibraryBean, java.util.Optional) */ public <T> ICrudService<T> getPerLibraryState(Class<T> clazz, SharedLibraryBean library, Optional<String> sub_collection) { return _underlying_management_db.getPerLibraryState(clazz, library, sub_collection).readOnlyVersion(_read_only); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getDataBucketStore() */ public IManagementCrudService<DataBucketBean> getDataBucketStore() { if (!_read_only) ManagementDbActorContext.get().getDistributedServices().waitForAkkaJoin(Optional.empty()); return _data_bucket_service.readOnlyVersion(_read_only); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getDataBucketStatusStore() */ public IManagementCrudService<DataBucketStatusBean> getDataBucketStatusStore() { if (!_read_only) ManagementDbActorContext.get().getDistributedServices().waitForAkkaJoin(Optional.empty()); return _data_bucket_status_service.readOnlyVersion(_read_only); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getPerBucketState(java.lang.Class, com.ikanow.aleph2.data_model.objects.data_import.DataBucketBean, java.util.Optional) */ public <T> ICrudService<T> getBucketHarvestState(Class<T> clazz, DataBucketBean bucket, Optional<String> sub_collection) { // (note: don't need to join the akka cluster in order to use the state objects) return _underlying_management_db.getBucketHarvestState(clazz, bucket, sub_collection).readOnlyVersion(_read_only); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getPerBucketState(java.lang.Class, com.ikanow.aleph2.data_model.objects.data_import.DataBucketBean, java.util.Optional) */ public <T> ICrudService<T> getBucketEnrichmentState(Class<T> clazz, DataBucketBean bucket, Optional<String> sub_collection) { // (note: don't need to join the akka cluster in order to use the state objects) return _underlying_management_db.getBucketEnrichmentState(clazz, bucket, sub_collection).readOnlyVersion(_read_only); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getPerAnalyticThreadState(java.lang.Class, com.ikanow.aleph2.data_model.objects.data_analytics.AnalyticThreadBean, java.util.Optional) */ public <T> ICrudService<T> getBucketAnalyticThreadState(Class<T> clazz, DataBucketBean bucket, Optional<String> sub_collection) { // (note: don't need to join the akka cluster in order to use the state objects) return _underlying_management_db.getBucketAnalyticThreadState(clazz, bucket, sub_collection).readOnlyVersion(_read_only); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getUnderlyingPlatformDriver(java.lang.Class, java.util.Optional) */ public <T> Optional<T> getUnderlyingPlatformDriver(Class<T> driver_class, Optional<String> driver_options) { throw new RuntimeException("No underlying drivers for CoreManagementDbService - did you want to get the underlying IManagementDbService? Use IServiceContext.getService(IManagementDbService.class, ...) if so."); } /** This service needs to load some additional classes via Guice. Here's the module that defines the bindings * @return */ public static List<Module> getExtraDependencyModules() { return Arrays.asList((Module)new CoreManagementDbModule()); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.shared_services.IExtraDependencyLoader#youNeedToImplementTheStaticFunctionCalled_getExtraDependencyModules() */ @Override public void youNeedToImplementTheStaticFunctionCalled_getExtraDependencyModules() { // (done see above) } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getRetryStore(java.lang.Class) */ @Override public <T> ICrudService<T> getRetryStore( Class<T> retry_message_clazz) { if (!_read_only) ManagementDbActorContext.get().getDistributedServices().waitForAkkaJoin(Optional.empty()); return _underlying_management_db.getRetryStore(retry_message_clazz).readOnlyVersion(_read_only); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getBucketDeletionQueue(java.lang.Class) */ @Override public <T> ICrudService<T> getBucketDeletionQueue( Class<T> deletion_queue_clazz) { if (!_read_only) ManagementDbActorContext.get().getDistributedServices().waitForAkkaJoin(Optional.empty()); return _underlying_management_db.getBucketDeletionQueue(deletion_queue_clazz).readOnlyVersion(_read_only); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getStateDirectory(java.util.Optional) */ @Override public ICrudService<AssetStateDirectoryBean> getStateDirectory( Optional<DataBucketBean> bucket_filter, Optional<StateDirectoryType> type_filter) { // (note: don't need to join the akka cluster in order to use the state objects) return _underlying_management_db.getStateDirectory(bucket_filter, type_filter).readOnlyVersion(_read_only); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getUnderlyingArtefacts() */ @Override public Collection<Object> getUnderlyingArtefacts() { final LinkedList<Object> ll = new LinkedList<Object>(); ll.add(this); ll.addAll(_underlying_management_db.getUnderlyingArtefacts()); return ll; } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#readOnlyVersion() */ @Override public IManagementDbService readOnlyVersion() { return new CoreManagementDbService(_service_context, _underlying_management_db, _data_bucket_service, _data_bucket_status_service, _shared_library_service, _actor_context, _auth, _project, true); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#purgeBucket(com.ikanow.aleph2.data_model.objects.data_import.DataBucketBean, java.util.Optional) */ @Override public ManagementFuture<Boolean> purgeBucket(DataBucketBean to_purge, Optional<Duration> in) { if (!_read_only) ManagementDbActorContext.get().getDistributedServices().waitForAkkaJoin(Optional.empty()); //TODO (ALEPH-23): decide .. only allow this if bucket is suspended? if (in.isPresent()) { // perform scheduled purge final Date to_purge_date = Timestamp.from(Instant.now().plus(in.get().getSeconds(), ChronoUnit.SECONDS)); return FutureUtils.createManagementFuture(this.getBucketDeletionQueue(BucketDeletionMessage.class).storeObject(new BucketDeletionMessage(to_purge, to_purge_date, true), false) .thenApply(__ -> true) .exceptionally(___ -> false)) // (fail if already present) ; } else { // purge now... final CompletableFuture<Collection<BasicMessageBean>> sys_res = BucketDeletionActor.deleteAllDataStoresForBucket(to_purge, _service_context, false); final CompletableFuture<Collection<BasicMessageBean>> user_res = BucketDeletionActor.notifyHarvesterOfPurge(to_purge, this.getDataBucketStatusStore(), this.getRetryStore(BucketActionRetryMessage.class)); //(longer term I wonder if should allow the harvester reply to dictate the level of deletion, eg could return an _id and then only delete up to that id?) final CompletableFuture<Collection<BasicMessageBean>> combined_res = sys_res.thenCombine(user_res, (a, b) -> { return Stream.concat(a.stream(), b.stream()).collect(Collectors.toList()); }); return FutureUtils.createManagementFuture( combined_res.thenApply(msgs -> msgs.stream().allMatch(m -> m.success())) , combined_res); } } /** * Performs a test run for a bucket. A test run is a processing cycle that only runs as * long as test_spec specifies and/or to the amount of results that test_spec specifies, whichever * occurs first. * * Changes a buckets name to not overwrite an existing job, then sends out a start test message. * If that message is picked up, this throws an object on both the test queue and delete queue that * will timeout the test and delete the results respectively after a certain amount of time. * */ @Override public ManagementFuture<Boolean> testBucket(DataBucketBean to_test, ProcessingTestSpecBean test_spec) { //create a test bucket to put data into instead of the specified bucket DataBucketBean test_bucket = BucketUtils.convertDataBucketBeanToTest(to_test, to_test.owner_id()); // - validate the bucket DataBucketBean validated_test_bucket = validateBucket(test_bucket); // - is there any test data already present for this user, delete if so (?) CompletableFuture<BasicMessageBean> base_future = Lambdas.get(() -> { if ( test_spec.overwrite_existing_data() ) { return purgeBucket(validated_test_bucket, Optional.empty()).exceptionally( t -> { _logger.error("Error clearing output datastore, probably okay: " + "ingest."+validated_test_bucket._id(), t); return false; }); } else { return CompletableFuture.completedFuture(Unit.unit()); } }).thenCompose(___ -> { return MgmtCrudUtils.getSuccessfulNodes(BucketActionSupervisor.askDistributionActor( _actor_context.getBucketActionSupervisor(), _actor_context.getActorSystem(), new BucketActionMessage.TestBucketActionMessage(validated_test_bucket, test_spec), Optional.empty()) .thenApply(msg -> msg.replies())) .thenApply(hostnames -> { //make sure there is at least 1 hostname result, otherwise throw error //TODO switch this to CompletableFuture<Collection<BasicMessageBean>> and add messages from queues if ( !hostnames.isEmpty() ) { //TODO add message about adding to test queue // - add to the test queue ICrudService<BucketTimeoutMessage> test_service = getBucketTestQueue(BucketTimeoutMessage.class); test_service.storeObject(new BucketTimeoutMessage(validated_test_bucket, new Date(System.currentTimeMillis()+(test_spec.max_run_time_secs()*1000)), hostnames)); //TODO add message about adding to delete queue // - add to the delete queue final ICrudService<BucketDeletionMessage> delete_queue = getBucketDeletionQueue(BucketDeletionMessage.class); delete_queue.storeObject(new BucketDeletionMessage(validated_test_bucket, new Date(System.currentTimeMillis()+(test_spec.max_storage_time_secs()*1000)), false)); _logger.debug("Got hostnames successfully, added test to test queue and delete queue"); return new BasicMessageBean(new Date(), true, "source", "command", 0, "Got hostnames successfully, added test to test queue and delete queue", null); } else { _logger.error("Error, hostnames was empty, probably did not finish setting job up (storm can take a long time to receive jar)"); return new BasicMessageBean(new Date(), false, "source", "command", 0, "Error, hostnames was empty, probably did not finish setting job up (storm can take a long time to receive jar)", null); } }) .exceptionally(t -> { //return error _logger.error("Error getting hostnames", t); return new BasicMessageBean(new Date(), false, "source", "command", 0, "Error getting hostnames: " + t.getMessage(), null); }); }); return FutureUtils.createManagementFuture(CompletableFuture.completedFuture(true), base_future.thenApply(bf -> Stream.of(bf).collect(Collectors.toList()))); } /** TODO * @param data_bucket * @return */ private DataBucketBean validateBucket(DataBucketBean data_bucket) { // TODO Auto-generated method stub return BeanTemplateUtils.clone(data_bucket) .done(); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getBucketTestQueue(java.lang.Class) */ @Override public <T> ICrudService<T> getBucketTestQueue(Class<T> test_queue_clazz) { return _underlying_management_db.getBucketTestQueue(test_queue_clazz); } }
aleph2_management_db_service/src/com/ikanow/aleph2/management_db/services/CoreManagementDbService.java
/******************************************************************************* * Copyright 2015, The IKANOW Open Source Project. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.ikanow.aleph2.management_db.services; import java.sql.Timestamp; //(provides a short cut for some datetime manipulation that doesn't confusingly refer to timezones) import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.google.inject.Inject; import com.google.inject.Module; import com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService; import com.ikanow.aleph2.data_model.interfaces.shared_services.ICrudService; import com.ikanow.aleph2.data_model.interfaces.shared_services.IExtraDependencyLoader; import com.ikanow.aleph2.data_model.interfaces.shared_services.IManagementCrudService; import com.ikanow.aleph2.data_model.interfaces.shared_services.IServiceContext; import com.ikanow.aleph2.data_model.objects.data_import.DataBucketBean; import com.ikanow.aleph2.data_model.objects.data_import.DataBucketStatusBean; import com.ikanow.aleph2.data_model.objects.shared.AssetStateDirectoryBean; import com.ikanow.aleph2.data_model.objects.shared.AssetStateDirectoryBean.StateDirectoryType; import com.ikanow.aleph2.data_model.objects.shared.AuthorizationBean; import com.ikanow.aleph2.data_model.objects.shared.BasicMessageBean; import com.ikanow.aleph2.data_model.objects.shared.ProcessingTestSpecBean; import com.ikanow.aleph2.data_model.objects.shared.ProjectBean; import com.ikanow.aleph2.data_model.objects.shared.SharedLibraryBean; import com.ikanow.aleph2.data_model.utils.BeanTemplateUtils; import com.ikanow.aleph2.data_model.utils.BucketUtils; import com.ikanow.aleph2.data_model.utils.FutureUtils; import com.ikanow.aleph2.data_model.utils.FutureUtils.ManagementFuture; import com.ikanow.aleph2.management_db.controllers.actors.BucketActionSupervisor; import com.ikanow.aleph2.management_db.controllers.actors.BucketDeletionActor; import com.ikanow.aleph2.management_db.data_model.BucketActionMessage; import com.ikanow.aleph2.management_db.data_model.BucketActionReplyMessage.BucketActionCollectedRepliesMessage; import com.ikanow.aleph2.management_db.data_model.BucketActionRetryMessage; import com.ikanow.aleph2.management_db.data_model.BucketMgmtMessage.BucketDeletionMessage; import com.ikanow.aleph2.management_db.data_model.BucketMgmtMessage.BucketTimeoutMessage; import com.ikanow.aleph2.management_db.module.CoreManagementDbModule; import com.ikanow.aleph2.management_db.utils.MgmtCrudUtils; /** A layer that sits in between the managers and modules on top, and the actual database technology underneath, * and performs control activities (launching into Akka) and an additional layer of validation * @author acp */ public class CoreManagementDbService implements IManagementDbService, IExtraDependencyLoader { private static final Logger _logger = LogManager.getLogger(); protected final IServiceContext _service_context; protected final IManagementDbService _underlying_management_db; protected final DataBucketCrudService _data_bucket_service; protected final DataBucketStatusCrudService _data_bucket_status_service; protected final SharedLibraryCrudService _shared_library_service; protected final ManagementDbActorContext _actor_context; protected final Optional<AuthorizationBean> _auth; protected final Optional<ProjectBean> _project; protected final boolean _read_only; /** Guice invoked constructor * @param underlying_management_db * @param data_bucket_service */ @Inject public CoreManagementDbService(final IServiceContext service_context, final DataBucketCrudService data_bucket_service, final DataBucketStatusCrudService data_bucket_status_service, final SharedLibraryCrudService shared_library_service, final ManagementDbActorContext actor_context ) { //(just return null here if underlying management not present, things will fail catastrophically unless this is a test) _service_context = service_context; _underlying_management_db = service_context.getService(IManagementDbService.class, Optional.empty()).orElse(null); _data_bucket_service = data_bucket_service; _data_bucket_status_service = data_bucket_status_service; _shared_library_service = shared_library_service; _actor_context = actor_context; _auth = Optional.empty(); _project = Optional.empty(); _read_only = false; //DEBUG //System.out.println("Hello world from: " + this.getClass() + ": bucket=" + _data_bucket_service); //System.out.println("Hello world from: " + this.getClass() + ": underlying=" + _underlying_management_db); } /** User constructor for building a cloned version with different auth settings * @param crud_factory * @param auth_fieldname * @param auth * @param project */ public CoreManagementDbService(final IServiceContext service_context, final IManagementDbService underlying_management_db, final DataBucketCrudService data_bucket_service, final DataBucketStatusCrudService data_bucket_status_service, final SharedLibraryCrudService shared_library_service, final ManagementDbActorContext actor_context, final Optional<AuthorizationBean> auth, final Optional<ProjectBean> project, boolean read_only) { _service_context = service_context; _underlying_management_db = underlying_management_db; _data_bucket_service = data_bucket_service; _data_bucket_status_service = data_bucket_status_service; _shared_library_service = shared_library_service; _actor_context = actor_context; _auth = auth; _project = project; _read_only = read_only; } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getFilteredDb(java.lang.String, java.util.Optional, java.util.Optional) */ public IManagementDbService getFilteredDb(final Optional<AuthorizationBean> client_auth, final Optional<ProjectBean> project_auth) { return new CoreManagementDbService(_service_context, _underlying_management_db, _data_bucket_service, _data_bucket_status_service, _shared_library_service, _actor_context, client_auth, project_auth, _read_only); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getSecureddDb(java.lang.String, java.util.Optional, java.util.Optional) */ public IManagementDbService getSecuredDb(AuthorizationBean client_auth) { return new SecuredCoreManagementDbService(_service_context, _underlying_management_db, _data_bucket_service, _data_bucket_status_service, _shared_library_service, _actor_context ,client_auth); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getSharedLibraryStore() */ public IManagementCrudService<SharedLibraryBean> getSharedLibraryStore() { if (!_read_only) ManagementDbActorContext.get().getDistributedServices().waitForAkkaJoin(Optional.empty()); return _shared_library_service.readOnlyVersion(_read_only); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getPerLibraryState(java.lang.Class, com.ikanow.aleph2.data_model.objects.shared.SharedLibraryBean, java.util.Optional) */ public <T> ICrudService<T> getPerLibraryState(Class<T> clazz, SharedLibraryBean library, Optional<String> sub_collection) { return _underlying_management_db.getPerLibraryState(clazz, library, sub_collection).readOnlyVersion(_read_only); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getDataBucketStore() */ public IManagementCrudService<DataBucketBean> getDataBucketStore() { if (!_read_only) ManagementDbActorContext.get().getDistributedServices().waitForAkkaJoin(Optional.empty()); return _data_bucket_service.readOnlyVersion(_read_only); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getDataBucketStatusStore() */ public IManagementCrudService<DataBucketStatusBean> getDataBucketStatusStore() { if (!_read_only) ManagementDbActorContext.get().getDistributedServices().waitForAkkaJoin(Optional.empty()); return _data_bucket_status_service.readOnlyVersion(_read_only); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getPerBucketState(java.lang.Class, com.ikanow.aleph2.data_model.objects.data_import.DataBucketBean, java.util.Optional) */ public <T> ICrudService<T> getBucketHarvestState(Class<T> clazz, DataBucketBean bucket, Optional<String> sub_collection) { // (note: don't need to join the akka cluster in order to use the state objects) return _underlying_management_db.getBucketHarvestState(clazz, bucket, sub_collection).readOnlyVersion(_read_only); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getPerBucketState(java.lang.Class, com.ikanow.aleph2.data_model.objects.data_import.DataBucketBean, java.util.Optional) */ public <T> ICrudService<T> getBucketEnrichmentState(Class<T> clazz, DataBucketBean bucket, Optional<String> sub_collection) { // (note: don't need to join the akka cluster in order to use the state objects) return _underlying_management_db.getBucketEnrichmentState(clazz, bucket, sub_collection).readOnlyVersion(_read_only); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getPerAnalyticThreadState(java.lang.Class, com.ikanow.aleph2.data_model.objects.data_analytics.AnalyticThreadBean, java.util.Optional) */ public <T> ICrudService<T> getBucketAnalyticThreadState(Class<T> clazz, DataBucketBean bucket, Optional<String> sub_collection) { // (note: don't need to join the akka cluster in order to use the state objects) return _underlying_management_db.getBucketAnalyticThreadState(clazz, bucket, sub_collection).readOnlyVersion(_read_only); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getUnderlyingPlatformDriver(java.lang.Class, java.util.Optional) */ public <T> Optional<T> getUnderlyingPlatformDriver(Class<T> driver_class, Optional<String> driver_options) { throw new RuntimeException("No underlying drivers for CoreManagementDbService - did you want to get the underlying IManagementDbService? Use IServiceContext.getService(IManagementDbService.class, ...) if so."); } /** This service needs to load some additional classes via Guice. Here's the module that defines the bindings * @return */ public static List<Module> getExtraDependencyModules() { return Arrays.asList((Module)new CoreManagementDbModule()); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.shared_services.IExtraDependencyLoader#youNeedToImplementTheStaticFunctionCalled_getExtraDependencyModules() */ @Override public void youNeedToImplementTheStaticFunctionCalled_getExtraDependencyModules() { // (done see above) } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getRetryStore(java.lang.Class) */ @Override public <T> ICrudService<T> getRetryStore( Class<T> retry_message_clazz) { if (!_read_only) ManagementDbActorContext.get().getDistributedServices().waitForAkkaJoin(Optional.empty()); return _underlying_management_db.getRetryStore(retry_message_clazz).readOnlyVersion(_read_only); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getBucketDeletionQueue(java.lang.Class) */ @Override public <T> ICrudService<T> getBucketDeletionQueue( Class<T> deletion_queue_clazz) { if (!_read_only) ManagementDbActorContext.get().getDistributedServices().waitForAkkaJoin(Optional.empty()); return _underlying_management_db.getBucketDeletionQueue(deletion_queue_clazz).readOnlyVersion(_read_only); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getStateDirectory(java.util.Optional) */ @Override public ICrudService<AssetStateDirectoryBean> getStateDirectory( Optional<DataBucketBean> bucket_filter, Optional<StateDirectoryType> type_filter) { // (note: don't need to join the akka cluster in order to use the state objects) return _underlying_management_db.getStateDirectory(bucket_filter, type_filter).readOnlyVersion(_read_only); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getUnderlyingArtefacts() */ @Override public Collection<Object> getUnderlyingArtefacts() { final LinkedList<Object> ll = new LinkedList<Object>(); ll.add(this); ll.addAll(_underlying_management_db.getUnderlyingArtefacts()); return ll; } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#readOnlyVersion() */ @Override public IManagementDbService readOnlyVersion() { return new CoreManagementDbService(_service_context, _underlying_management_db, _data_bucket_service, _data_bucket_status_service, _shared_library_service, _actor_context, _auth, _project, true); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#purgeBucket(com.ikanow.aleph2.data_model.objects.data_import.DataBucketBean, java.util.Optional) */ @Override public ManagementFuture<Boolean> purgeBucket(DataBucketBean to_purge, Optional<Duration> in) { if (!_read_only) ManagementDbActorContext.get().getDistributedServices().waitForAkkaJoin(Optional.empty()); //TODO (ALEPH-23): decide .. only allow this if bucket is suspended? if (in.isPresent()) { // perform scheduled purge final Date to_purge_date = Timestamp.from(Instant.now().plus(in.get().getSeconds(), ChronoUnit.SECONDS)); return FutureUtils.createManagementFuture(this.getBucketDeletionQueue(BucketDeletionMessage.class).storeObject(new BucketDeletionMessage(to_purge, to_purge_date, true), false) .thenApply(__ -> true) .exceptionally(___ -> false)) // (fail if already present) ; } else { // purge now... final CompletableFuture<Collection<BasicMessageBean>> sys_res = BucketDeletionActor.deleteAllDataStoresForBucket(to_purge, _service_context, false); final CompletableFuture<Collection<BasicMessageBean>> user_res = BucketDeletionActor.notifyHarvesterOfPurge(to_purge, this.getDataBucketStatusStore(), this.getRetryStore(BucketActionRetryMessage.class)); //(longer term I wonder if should allow the harvester reply to dictate the level of deletion, eg could return an _id and then only delete up to that id?) final CompletableFuture<Collection<BasicMessageBean>> combined_res = sys_res.thenCombine(user_res, (a, b) -> { return Stream.concat(a.stream(), b.stream()).collect(Collectors.toList()); }); return FutureUtils.createManagementFuture( combined_res.thenApply(msgs -> msgs.stream().allMatch(m -> m.success())) , combined_res); } } /** * Performs a test run for a bucket. A test run is a processing cycle that only runs as * long as test_spec specifies and/or to the amount of results that test_spec specifies, whichever * occurs first. * * Changes a buckets name to not overwrite an existing job, then sends out a start test message. * If that message is picked up, this throws an object on both the test queue and delete queue that * will timeout the test and delete the results respectively after a certain amount of time. * */ @Override public ManagementFuture<Boolean> testBucket(DataBucketBean to_test, ProcessingTestSpecBean test_spec) { //create a test bucket to put data into instead of the specified bucket DataBucketBean test_bucket = BucketUtils.convertDataBucketBeanToTest(to_test, to_test.owner_id()); // - validate the bucket DataBucketBean validated_test_bucket = validateBucket(test_bucket); // - is there any test data already present for this user, delete if so (?) if ( test_spec.overwrite_existing_data() ) { //TODO delete test data, wait for completion // (I'm writing deletion logic atm so may need to TODO that out for now until I'm done) } // - send messages to start the test (ie like other messages, via the BucketActionSupervisor) final BucketActionMessage.TestBucketActionMessage test_message = new BucketActionMessage.TestBucketActionMessage(validated_test_bucket, test_spec); CompletableFuture<BucketActionCollectedRepliesMessage> test_future = BucketActionSupervisor.askDistributionActor( _actor_context.getBucketActionSupervisor(), _actor_context.getActorSystem(), test_message, Optional.empty()); //get the hostnames of the actor nodes so we can process our timeout message CompletableFuture<BasicMessageBean> base_future = MgmtCrudUtils.getSuccessfulNodes(test_future.thenApply(msg -> msg.replies())) .thenApply(hostnames -> { //make sure there is at least 1 hostname result, otherwise throw error if ( !hostnames.isEmpty() ) { //TODO add message about adding to test queue // - add to the test queue ICrudService<BucketTimeoutMessage> test_service = getBucketTestQueue(BucketTimeoutMessage.class); test_service.storeObject(new BucketTimeoutMessage(validated_test_bucket, new Date(System.currentTimeMillis()+(test_spec.max_run_time_secs()*1000)), hostnames)); //TODO add message about adding to delete queue // - add to the delete queue final ICrudService<BucketDeletionMessage> delete_queue = getBucketDeletionQueue(BucketDeletionMessage.class); delete_queue.storeObject(new BucketDeletionMessage(validated_test_bucket, new Date(System.currentTimeMillis()+(test_spec.max_storage_time_secs()*1000)), false)); _logger.debug("Got hostnames successfully, added test to test queue and delete queue"); //return true; return new BasicMessageBean(new Date(), true, "source", "command", 0, "Got hostnames successfully, added test to test queue and delete queue", null); } else { //TODO need to get error messages out of here and into test response message _logger.error("Error, hostnames was empty, probably did not finish setting job up (storm can take a long time to receive jar)"); return new BasicMessageBean(new Date(), false, "source", "command", 0, "Error, hostnames was empty, probably did not finish setting job up (storm can take a long time to receive jar)", null); } }) .exceptionally(t -> { //return error _logger.error("Error getting hostnames", t); return new BasicMessageBean(new Date(), false, "source", "command", 0, "Error getting hostnames: " + t.getMessage(), null); }); final CompletableFuture<Collection<BasicMessageBean>> cf = test_future.thenCombine(base_future, (tf, bf) -> {return Stream.concat(tf.replies().stream(), Stream.of(bf)).collect(Collectors.toList());}); return FutureUtils.createManagementFuture(test_future.thenCombine(base_future, (tf, bf) -> {return !tf.replies().isEmpty() && bf.success();}), cf); } /** TODO * @param data_bucket * @return */ private DataBucketBean validateBucket(DataBucketBean data_bucket) { // TODO Auto-generated method stub return BeanTemplateUtils.clone(data_bucket) .done(); } /* (non-Javadoc) * @see com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService#getBucketTestQueue(java.lang.Class) */ @Override public <T> ICrudService<T> getBucketTestQueue(Class<T> test_queue_clazz) { return _underlying_management_db.getBucketTestQueue(test_queue_clazz); } }
ALEPH-25 #comment updated test bucket to delete v2 test data before running
aleph2_management_db_service/src/com/ikanow/aleph2/management_db/services/CoreManagementDbService.java
ALEPH-25 #comment updated test bucket to delete v2 test data before running
Java
apache-2.0
fb471d2423769f8bfc4821b60143af407c7d240e
0
sjaco002/vxquery,westmann/vxquery,innovimax/vxquery,ecarm002/vxquery,shivani1494/vxquery,JavierJia/vxquery,innovimax/vxquery,ecarm002/vxquery,ecarm002/vxquery,westmann/vxquery,westmann/vxquery,JavierJia/vxquery,sjaco002/vxquery,apache/vxquery,innovimax/vxquery,erandiganepola/vxquery,efikalti/vxquery,shivani1494/vxquery,prestoncarman/vxquery,apache/vxquery,erandiganepola/vxquery,apache/vxquery,efikalti/vxquery,JavierJia/vxquery,sjaco002/vxquery,efikalti/vxquery,erandiganepola/vxquery,shivani1494/vxquery,prestoncarman/vxquery,prestoncarman/vxquery
package org.apache.vxquery.datamodel.accessors.atomic; import org.apache.vxquery.datamodel.api.ITime; import org.apache.vxquery.datamodel.api.ITimezone; import edu.uci.ics.hyracks.api.dataflow.value.ITypeTraits; import edu.uci.ics.hyracks.data.std.api.AbstractPointable; import edu.uci.ics.hyracks.data.std.api.IPointable; import edu.uci.ics.hyracks.data.std.api.IPointableFactory; import edu.uci.ics.hyracks.data.std.primitive.BytePointable; import edu.uci.ics.hyracks.data.std.primitive.IntegerPointable; /** * The time is split up into five sections. Due to leap year, we have decided to keep the * storage simple by saving each date section separately. For calculations you can access * DayTime (milliseconds) values. * * @author prestoncarman */ public class XSTimePointable extends AbstractPointable implements ITime, ITimezone { public final static int HOUR_OFFSET = 0; public final static int MINUTE_OFFSET = 1; public final static int MILLISECOND_OFFSET = 2; public final static int TIMEZONE_HOUR_OFFSET = 6; public final static int TIMEZONE_MINUTE_OFFSET = 7; public static final ITypeTraits TYPE_TRAITS = new ITypeTraits() { private static final long serialVersionUID = 1L; @Override public boolean isFixedLength() { return true; } @Override public int getFixedLength() { return 8; } }; public static final IPointableFactory FACTORY = new IPointableFactory() { private static final long serialVersionUID = 1L; @Override public IPointable createPointable() { return new XSTimePointable(); } @Override public ITypeTraits getTypeTraits() { return TYPE_TRAITS; } }; public void setTime(long hour, long minute, long second, long timezoneHour, long timezoneMinute) { setTime(bytes, start, hour, minute, second, timezoneHour, timezoneMinute); } public static void setTime(byte[] bytes, int start, long hour, long minute, long second, long timezoneHour, long timezoneMinute) { BytePointable.setByte(bytes, start + HOUR_OFFSET, (byte) hour); BytePointable.setByte(bytes, start + MINUTE_OFFSET, (byte) minute); IntegerPointable.setInteger(bytes, start + MILLISECOND_OFFSET, (byte) second); BytePointable.setByte(bytes, start + TIMEZONE_HOUR_OFFSET, (byte) timezoneHour); BytePointable.setByte(bytes, start + TIMEZONE_MINUTE_OFFSET, (byte) timezoneMinute); } @Override public long getHour() { return getHour(bytes, start); } public static long getHour(byte[] bytes, int start) { return (long) BytePointable.getByte(bytes, start + HOUR_OFFSET); } @Override public long getMinute() { return getMinute(bytes, start); } public static long getMinute(byte[] bytes, int start) { return (long) BytePointable.getByte(bytes, start + MINUTE_OFFSET); } @Override public long getMilliSecond() { return getMilliSecond(bytes, start); } public static long getMilliSecond(byte[] bytes, int start) { return (long) IntegerPointable.getInteger(bytes, start + MILLISECOND_OFFSET); } @Override public long getTimezoneHour() { return getTimezoneHour(bytes, start); } public static long getTimezoneHour(byte[] bytes, int start) { return (long) BytePointable.getByte(bytes, start + TIMEZONE_HOUR_OFFSET); } @Override public long getTimezoneMinute() { return getTimezoneMinute(bytes, start); } public static long getTimezoneMinute(byte[] bytes, int start) { return (long) BytePointable.getByte(bytes, start + TIMEZONE_MINUTE_OFFSET); } @Override public long getTimezone() { return getTimezone(bytes, start); } public static long getTimezone(byte[] bytes, int start) { return (getTimezoneHour(bytes, start) * 60 + getTimezoneMinute(bytes, start)); } @Override public long getDayTime() { return getDayTime(bytes, start); } public static long getDayTime(byte[] bytes, int start) { return (((getHour(bytes, start)) * 60 + getMinute(bytes, start)) * 60 * 1000 + getMilliSecond(bytes, start)); } @Override public long getYearMonth() { return getYearMonth(bytes, start); } public static long getYearMonth(byte[] bytes, int start) { return 0; } }
vxquery-core/src/main/java/org/apache/vxquery/datamodel/accessors/atomic/XSTimePointable.java
package org.apache.vxquery.datamodel.accessors.atomic; import org.apache.vxquery.datamodel.api.ITime; import org.apache.vxquery.datamodel.api.ITimezone; import edu.uci.ics.hyracks.api.dataflow.value.ITypeTraits; import edu.uci.ics.hyracks.data.std.api.AbstractPointable; import edu.uci.ics.hyracks.data.std.api.IPointable; import edu.uci.ics.hyracks.data.std.api.IPointableFactory; import edu.uci.ics.hyracks.data.std.primitive.BytePointable; import edu.uci.ics.hyracks.data.std.primitive.IntegerPointable; /** * The time is split up into five sections. Due to leap year, we have decided to keep the * storage simple by saving each date section separately. For calculations you can access * DayTime (milliseconds) values. * * @author prestoncarman */ public class XSTimePointable extends AbstractPointable implements ITime, ITimezone { public final static int HOUR_OFFSET = 0; public final static int MINUTE_OFFSET = 1; public final static int MILLISECOND_OFFSET = 2; public final static int TIMEZONE_HOUR_OFFSET = 6; public final static int TIMEZONE_MINUTE_OFFSET = 7; public static final ITypeTraits TYPE_TRAITS = new ITypeTraits() { private static final long serialVersionUID = 1L; @Override public boolean isFixedLength() { return true; } @Override public int getFixedLength() { return 4; } }; public static final IPointableFactory FACTORY = new IPointableFactory() { private static final long serialVersionUID = 1L; @Override public IPointable createPointable() { return new XSTimePointable(); } @Override public ITypeTraits getTypeTraits() { return TYPE_TRAITS; } }; public void setTime(long hour, long minute, long second, long timezoneHour, long timezoneMinute) { setTime(bytes, start, hour, minute, second, timezoneHour, timezoneMinute); } public static void setTime(byte[] bytes, int start, long hour, long minute, long second, long timezoneHour, long timezoneMinute) { BytePointable.setByte(bytes, start + HOUR_OFFSET, (byte) hour); BytePointable.setByte(bytes, start + MINUTE_OFFSET, (byte) minute); IntegerPointable.setInteger(bytes, start + MILLISECOND_OFFSET, (byte) second); BytePointable.setByte(bytes, start + TIMEZONE_HOUR_OFFSET, (byte) timezoneHour); BytePointable.setByte(bytes, start + TIMEZONE_MINUTE_OFFSET, (byte) timezoneMinute); } @Override public long getHour() { return getHour(bytes, start); } public static long getHour(byte[] bytes, int start) { return (long) BytePointable.getByte(bytes, start + HOUR_OFFSET); } @Override public long getMinute() { return getMinute(bytes, start); } public static long getMinute(byte[] bytes, int start) { return (long) BytePointable.getByte(bytes, start + MINUTE_OFFSET); } @Override public long getMilliSecond() { return getMilliSecond(bytes, start); } public static long getMilliSecond(byte[] bytes, int start) { return (long) IntegerPointable.getInteger(bytes, start + MILLISECOND_OFFSET); } @Override public long getTimezoneHour() { return getTimezoneHour(bytes, start); } public static long getTimezoneHour(byte[] bytes, int start) { return (long) BytePointable.getByte(bytes, start + TIMEZONE_HOUR_OFFSET); } @Override public long getTimezoneMinute() { return getTimezoneMinute(bytes, start); } public static long getTimezoneMinute(byte[] bytes, int start) { return (long) BytePointable.getByte(bytes, start + TIMEZONE_MINUTE_OFFSET); } @Override public long getTimezone() { return getTimezone(bytes, start); } public static long getTimezone(byte[] bytes, int start) { return (getTimezoneHour(bytes, start) * 60 + getTimezoneMinute(bytes, start)); } @Override public long getDayTime() { return getDayTime(bytes, start); } public static long getDayTime(byte[] bytes, int start) { return (((getHour(bytes, start)) * 60 + getMinute(bytes, start)) * 60 * 1000 + getMilliSecond(bytes, start)); } @Override public long getYearMonth() { return getYearMonth(bytes, start); } public static long getYearMonth(byte[] bytes, int start) { return 0; } }
Wrong length stored. git-svn-id: 577f56b988395b4c4a087ab41a6af3288056d860@1377903 13f79535-47bb-0310-9956-ffa450edef68
vxquery-core/src/main/java/org/apache/vxquery/datamodel/accessors/atomic/XSTimePointable.java
Wrong length stored.
Java
apache-2.0
a597d78d99a5f804bba6831fdc8db66ef62bc4e0
0
jcechace/apiman,jcechace/apiman,kahboom/apiman,kahboom/apiman,msavy/apiman,EricWittmann/apiman,apiman/apiman,apiman/apiman,jcechace/apiman,apiman/apiman,EricWittmann/apiman,kahboom/apiman,EricWittmann/apiman,msavy/apiman,kahboom/apiman,msavy/apiman,msavy/apiman,jcechace/apiman,EricWittmann/apiman,apiman/apiman,apiman/apiman,msavy/apiman,jcechace/apiman,EricWittmann/apiman,kahboom/apiman
/* * Copyright 2017 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.apiman.gateway.engine.vertx.polling; import io.apiman.gateway.engine.IEngineConfig; import io.apiman.gateway.engine.async.AsyncInitialize; import io.apiman.gateway.engine.async.AsyncResultImpl; import io.apiman.gateway.engine.async.IAsyncHandler; import io.apiman.gateway.engine.async.IAsyncResultHandler; import io.apiman.gateway.engine.beans.Api; import io.apiman.gateway.engine.beans.Client; import io.apiman.gateway.engine.impl.InMemoryRegistry; import io.apiman.gateway.engine.vertx.polling.exceptions.UnsupportedProtocolException; import io.apiman.gateway.engine.vertx.polling.fetchers.AccessTokenResourceFetcher; import io.apiman.gateway.engine.vertx.polling.fetchers.FileResourceFetcher; import io.apiman.gateway.engine.vertx.polling.fetchers.HttpResourceFetcher; import io.apiman.gateway.engine.vertx.polling.fetchers.ResourceFetcher; import io.apiman.gateway.platforms.vertx3.common.verticles.Json; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.impl.Arguments; import io.vertx.core.json.DecodeException; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import java.net.URI; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.lang3.StringUtils; /** * URI loading registry that pulls configuration from a specified JSON file. * <ul> * <li>configUri: apiman policy config to load from JSON via file * ({@link FileResourceFetcher}) or HTTP/S ({@link HttpResourceFetcher}). * See the corresponding fetcher for additional options.</li> * </ul> * * @author Marc Savy {@literal <[email protected]>} * @see FileResourceFetcher * @see HttpResourceFetcher * @see AccessTokenResourceFetcher */ @SuppressWarnings("nls") public class URILoadingRegistry extends InMemoryRegistry implements AsyncInitialize { // Protected by DCL, use #getUriLoader private static volatile OneShotURILoader instance; private URI uri; private Vertx vertx; private Map<String, String> options; public URILoadingRegistry(Vertx vertx, IEngineConfig vxConfig, Map<String, String> options) { super(); this.vertx = vertx; this.options = options; Arguments.require(options.containsKey("configUri"), "configUri is required in configuration"); uri = URI.create(options.get("configUri")); } public URILoadingRegistry(Map<String, String> options) { this(Vertx.vertx(), null, options); } @Override public void initialize(IAsyncResultHandler<Void> resultHandler) { getURILoader(vertx, uri, options).subscribe(this, resultHandler); } private static OneShotURILoader getURILoader(Vertx vertx, URI uri, Map<String, String> options) { if (instance == null) { synchronized(URILoadingRegistry.class) { if (instance == null) { instance = new OneShotURILoader(vertx, uri, options); } } } return instance; } // For testing only. Reloads rather than full restart. public static void reloadData(IAsyncHandler<Void> doneHandler) { synchronized(URILoadingRegistry.class) { Map<URILoadingRegistry, IAsyncResultHandler<Void>> regs = instance.handlers; Vertx vertx = instance.vertx; URI uri = instance.uri; Map<String, String> config = instance.config; AtomicInteger ctr = new AtomicInteger(regs.size()); OneShotURILoader newLoader = new OneShotURILoader(vertx, uri, config); regs.entrySet().stream().forEach(pair -> { // Clear the registrys' internal maps to prepare for reload. // NB: If we add production hot reloading, we'll need to work around this (e.g. clone?). pair.getKey().getMap().clear(); // Re-subscribe the registry. newLoader.subscribe(pair.getKey(), result -> { checkAndFlip(ctr.decrementAndGet(), newLoader, doneHandler); }); }); checkAndFlip(ctr.get(), newLoader, doneHandler); } } private static void checkAndFlip(int ctr, OneShotURILoader instance, IAsyncHandler<Void> doneHandler) { if (ctr == 0) { doneHandler.handle((Void) null); URILoadingRegistry.instance = instance; } } public static void reset() { synchronized(URILoadingRegistry.class) { instance = null; } } @Override public void publishApi(Api api, IAsyncResultHandler<Void> handler) { throw new UnsupportedOperationException(); } @Override public void retireApi(Api api, IAsyncResultHandler<Void> handler) { throw new UnsupportedOperationException(); } @Override public void registerClient(Client client, IAsyncResultHandler<Void> handler) { throw new UnsupportedOperationException(); } @Override public void unregisterClient(Client client, IAsyncResultHandler<Void> handler) { throw new UnsupportedOperationException(); } protected void publishApiInternal(Api api, IAsyncResultHandler<Void> handler) { super.publishApi(api, handler); } protected void registerClientInternal(Client client, IAsyncResultHandler<Void> handler) { super.registerClient(client, handler); } private static final class OneShotURILoader { Vertx vertx; URI uri; Map<String, String> config; Map<URILoadingRegistry, IAsyncResultHandler<Void>> handlers = new LinkedHashMap<>(); private Deque<URILoadingRegistry> awaiting = new ArrayDeque<>(); private List<URILoadingRegistry> allRegistries = new ArrayList<>(); private Buffer rawData; private boolean dataProcessed = false; private List<Client> clients = Collections.emptyList(); private List<Api> apis = Collections.emptyList(); private Logger log = LoggerFactory.getLogger(OneShotURILoader.class); private IAsyncHandler<Void> reloadHandler; private boolean failed; public OneShotURILoader(Vertx vertx, URI uri, Map<String, String> config) { this.config = config; this.vertx = vertx; this.uri = uri; fetchResource(); } private void fetchResource() { getResourceFetcher() .exceptionHandler(this::failAll) .fetch(data -> { rawData = data; processData(); }); } private ResourceFetcher getResourceFetcher() { String scheme = uri.getScheme() == null ? "file" : uri.getScheme().toLowerCase(); switch (scheme) { case "http": return new HttpResourceFetcher(vertx, uri, config, false); case "https": return new HttpResourceFetcher(vertx, uri, config, true); case "file": return new FileResourceFetcher(vertx, uri, config); default: throw new UnsupportedProtocolException(String.format("%s is not supported. Available: http, https and file.", uri.getScheme())); } } private void processData() { if (rawData.length() == 0) { log.warn("File loaded into registry was empty. No entities created."); allRegistries.stream().forEach(this::checkSuccess); dataProcessed = true; return; } try { JsonObject json = new JsonObject(rawData.toString("UTF-8").trim()); log.trace("Processing JSON: {0}", json); clients = requireJsonArray("clients", json, Client.class); apis = requireJsonArray("apis", json, Api.class); dataProcessed = true; checkQueue(); } catch (DecodeException e) { failAll(e); } } @SuppressWarnings("unchecked") private <T, K> List<T> requireJsonArray(String keyName, JsonObject json, Class<K> klazz) { // Contains key. Arguments.require(json.containsKey(keyName), String.format("Must provide array of %s objects for key '%s'", StringUtils.capitalize(keyName), keyName)); // Is of type array. Arguments.require(json.getValue(keyName) instanceof JsonArray, String.format("'%s' must be a Json array", keyName)); // Transform into List<T>. return Json.decodeValue(json.getJsonArray(keyName).encode(), List.class, klazz); } public synchronized void subscribe(URILoadingRegistry registry, IAsyncResultHandler<Void> handler) { Objects.requireNonNull(registry, "registry must be non-null."); Objects.requireNonNull(handler, "handler must be non-null."); handlers.put(registry, handler); allRegistries.add(registry); awaiting.add(registry); vertx.runOnContext(action -> checkQueue()); } private void checkQueue() { if (dataProcessed && awaiting.size()>0) { loadDataIntoRegistries(); } } private void loadDataIntoRegistries() { URILoadingRegistry reg = null; while ((reg = awaiting.poll()) != null) { log.debug("Loading data into registry {0}:", reg); for (Api api : apis) { reg.publishApiInternal(api, handleAnyFailure()); log.debug("Publishing: {0} ", api); } for (Client client : clients) { reg.registerClientInternal(client, handleAnyFailure()); log.debug("Registering: {0} ", client); } checkSuccess(reg); } if (reloadHandler != null) reloadHandler.handle((Void) null); } private IAsyncResultHandler<Void> handleAnyFailure() { return result -> { if (result.isError()) { log.error(result.getError()); failAll(result.getError()); } }; } private void failAll(Throwable cause) { failed = true; AsyncResultImpl<Void> failure = AsyncResultImpl.create(cause); handlers.values().stream().forEach(failureHandler -> { vertx.runOnContext(run -> failureHandler.handle(failure)); }); } private void checkSuccess(URILoadingRegistry reg) { if (!failed) { handlers.get(reg).handle(AsyncResultImpl.create((Void) null)); } } } }
gateway/engine/vertx-polling/src/main/java/io/apiman/gateway/engine/vertx/polling/URILoadingRegistry.java
/* * Copyright 2017 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.apiman.gateway.engine.vertx.polling; import io.apiman.gateway.engine.IEngineConfig; import io.apiman.gateway.engine.async.AsyncInitialize; import io.apiman.gateway.engine.async.AsyncResultImpl; import io.apiman.gateway.engine.async.IAsyncHandler; import io.apiman.gateway.engine.async.IAsyncResultHandler; import io.apiman.gateway.engine.beans.Api; import io.apiman.gateway.engine.beans.Client; import io.apiman.gateway.engine.impl.InMemoryRegistry; import io.apiman.gateway.engine.vertx.polling.exceptions.UnsupportedProtocolException; import io.apiman.gateway.engine.vertx.polling.fetchers.AccessTokenResourceFetcher; import io.apiman.gateway.engine.vertx.polling.fetchers.FileResourceFetcher; import io.apiman.gateway.engine.vertx.polling.fetchers.HttpResourceFetcher; import io.apiman.gateway.engine.vertx.polling.fetchers.ResourceFetcher; import io.apiman.gateway.platforms.vertx3.common.verticles.Json; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.impl.Arguments; import io.vertx.core.json.DecodeException; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import java.net.URI; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.lang3.StringUtils; /** * URI loading registry that pulls configuration from a specified JSON file. * <ul> * <li>configUri: apiman policy config to load from JSON via file * ({@link FileResourceFetcher}) or HTTP/S ({@link HttpResourceFetcher}). * See the corresponding fetcher for additional options.</li> * </ul> * * @author Marc Savy {@literal <[email protected]>} * @see FileResourceFetcher * @see HttpResourceFetcher * @see AccessTokenResourceFetcher */ @SuppressWarnings("nls") public class URILoadingRegistry extends InMemoryRegistry implements AsyncInitialize { // Protected by DCL, use #getUriLoader private static volatile OneShotURILoader instance; private URI uri; private Vertx vertx; private Map<String, String> options; public URILoadingRegistry(Vertx vertx, IEngineConfig vxConfig, Map<String, String> options) { super(); this.vertx = vertx; this.options = options; Arguments.require(options.containsKey("configUri"), "configUri is required in configuration"); uri = URI.create(options.get("configUri")); } public URILoadingRegistry(Map<String, String> options) { this(Vertx.vertx(), null, options); } @Override public void initialize(IAsyncResultHandler<Void> resultHandler) { getURILoader(vertx, uri, options).subscribe(this, resultHandler); } private static OneShotURILoader getURILoader(Vertx vertx, URI uri, Map<String, String> options) { if (instance == null) { synchronized(URILoadingRegistry.class) { if (instance == null) { instance = new OneShotURILoader(vertx, uri, options); } } } return instance; } // For testing only. Reloads rather than full restart. public static void reloadData(IAsyncHandler<Void> doneHandler) { synchronized(URILoadingRegistry.class) { Map<URILoadingRegistry, IAsyncResultHandler<Void>> regs = instance.handlers; Vertx vertx = instance.vertx; URI uri = instance.uri; Map<String, String> config = instance.config; AtomicInteger ctr = new AtomicInteger(regs.size()); OneShotURILoader newLoader = new OneShotURILoader(vertx, uri, config); regs.entrySet().stream().forEach(pair -> { // Clear the registrys' internal maps to prepare for reload. // NB: If we add production hot reloading, we'll need to work around this (e.g. clone?). pair.getKey().getMap().clear(); // Re-subscribe the registry. newLoader.subscribe(pair.getKey(), result -> { checkAndFlip(ctr.decrementAndGet(), newLoader, doneHandler); }); }); checkAndFlip(ctr.get(), newLoader, doneHandler); } } private static void checkAndFlip(int ctr, OneShotURILoader instance, IAsyncHandler<Void> doneHandler) { if (ctr == 0) { doneHandler.handle((Void) null); URILoadingRegistry.instance = instance; } } public static void reset() { synchronized(URILoadingRegistry.class) { instance = null; } } @Override public void publishApi(Api api, IAsyncResultHandler<Void> handler) { throw new UnsupportedOperationException(); } @Override public void retireApi(Api api, IAsyncResultHandler<Void> handler) { throw new UnsupportedOperationException(); } @Override public void registerClient(Client client, IAsyncResultHandler<Void> handler) { throw new UnsupportedOperationException(); } @Override public void unregisterClient(Client client, IAsyncResultHandler<Void> handler) { throw new UnsupportedOperationException(); } protected void publishApiInternal(Api api, IAsyncResultHandler<Void> handler) { super.publishApi(api, handler); } protected void registerClientInternal(Client client, IAsyncResultHandler<Void> handler) { super.registerClient(client, handler); } private static final class OneShotURILoader { Vertx vertx; URI uri; Map<String, String> config; Map<URILoadingRegistry, IAsyncResultHandler<Void>> handlers = new LinkedHashMap<>(); private Deque<URILoadingRegistry> awaiting = new ArrayDeque<>(); private List<URILoadingRegistry> allRegistries = new ArrayList<>(); private Buffer rawData; private boolean dataProcessed = false; private List<Client> clients = Collections.emptyList(); private List<Api> apis = Collections.emptyList(); private Logger log = LoggerFactory.getLogger(OneShotURILoader.class); private IAsyncHandler<Void> reloadHandler; private boolean failed; public OneShotURILoader(Vertx vertx, URI uri, Map<String, String> config) { this.config = config; this.vertx = vertx; this.uri = uri; fetchResource(); } private void fetchResource() { getResourceFetcher() .exceptionHandler(this::failAll) .fetch(data -> { rawData = data; processData(); }); } private ResourceFetcher getResourceFetcher() { String scheme = uri.getScheme() == null ? "file" : uri.getScheme().toLowerCase(); switch (scheme) { case "http": return new HttpResourceFetcher(vertx, uri, config, false); case "https": return new HttpResourceFetcher(vertx, uri, config, true); case "file": return new FileResourceFetcher(vertx, uri, config); default: throw new UnsupportedProtocolException(String.format("%s is not supported. Available: http, https and file.", uri.getScheme())); } } private void processData() { if (rawData.length() == 0) { log.warn("File loaded into registry was empty. No entities created."); allRegistries.stream().forEach(this::checkSuccess); dataProcessed = true; return; } try { JsonObject json = new JsonObject(rawData.toString("UTF-8").trim()); log.trace("Processing JSON: {0}", json); clients = requireJsonArray("clients", json, Client.class); apis = requireJsonArray("apis", json, Api.class); dataProcessed = true; checkQueue(); } catch (DecodeException e) { failAll(e); } } @SuppressWarnings("unchecked") private <T, K> List<T> requireJsonArray(String keyName, JsonObject json, Class<K> klazz) { // Contains key. Arguments.require(json.containsKey(keyName), String.format("Must provide array of %s objects for key '%s'", StringUtils.capitalize(keyName), keyName)); // Is of type array. Arguments.require(json.getValue(keyName) instanceof JsonArray, String.format("'%s' must be a Json array", keyName)); // Transform into List<T>. return Json.decodeValue(json.getJsonArray(keyName).encode(), List.class, klazz); } public synchronized void subscribe(URILoadingRegistry registry, IAsyncResultHandler<Void> handler) { Objects.requireNonNull(registry, "registry must be non-null."); Objects.requireNonNull(handler, "handler must be non-null."); handlers.put(registry, handler); allRegistries.add(registry); awaiting.add(registry); System.out.println("Adding " + registry + " with handler " + handler); vertx.runOnContext(action -> checkQueue()); } private void checkQueue() { System.out.println("Checking queue.... "); System.out.println("dataProcessed " + dataProcessed); System.out.println("awaiting.size() " + awaiting.size()); if (dataProcessed && awaiting.size()>0) { loadDataIntoRegistries(); } } private void loadDataIntoRegistries() { URILoadingRegistry reg = null; while ((reg = awaiting.poll()) != null) { log.debug("Loading data into registry {0}:", reg); for (Api api : apis) { reg.publishApiInternal(api, handleAnyFailure()); log.debug("Publishing: {0} ", api); } for (Client client : clients) { reg.registerClientInternal(client, handleAnyFailure()); log.debug("Registering: {0} ", client); } checkSuccess(reg); } if (reloadHandler != null) reloadHandler.handle((Void) null); } private IAsyncResultHandler<Void> handleAnyFailure() { return result -> { if (result.isError()) { log.error(result.getError()); failAll(result.getError()); } }; } private void failAll(Throwable cause) { failed = true; AsyncResultImpl<Void> failure = AsyncResultImpl.create(cause); handlers.values().stream().forEach(failureHandler -> { vertx.runOnContext(run -> failureHandler.handle(failure)); }); } private void checkSuccess(URILoadingRegistry reg) { if (!failed) { handlers.get(reg).handle(AsyncResultImpl.create((Void) null)); } } } }
Remove errant debug statement
gateway/engine/vertx-polling/src/main/java/io/apiman/gateway/engine/vertx/polling/URILoadingRegistry.java
Remove errant debug statement
Java
apache-2.0
3947fbfbd39ca723e111e703ae65e8dd00bedc24
0
Nimco/sling,ist-dresden/sling,ieb/sling,roele/sling,nleite/sling,headwirecom/sling,plutext/sling,Nimco/sling,tyge68/sling,Sivaramvt/sling,trekawek/sling,JEBailey/sling,sdmcraft/sling,ffromm/sling,plutext/sling,mmanski/sling,tyge68/sling,sdmcraft/sling,nleite/sling,sdmcraft/sling,Sivaramvt/sling,mikibrv/sling,klcodanr/sling,anchela/sling,mcdan/sling,cleliameneghin/sling,sdmcraft/sling,SylvesterAbreu/sling,plutext/sling,nleite/sling,SylvesterAbreu/sling,ffromm/sling,awadheshv/sling,SylvesterAbreu/sling,plutext/sling,trekawek/sling,Nimco/sling,mikibrv/sling,vladbailescu/sling,tyge68/sling,mikibrv/sling,JEBailey/sling,cleliameneghin/sling,awadheshv/sling,JEBailey/sling,anchela/sling,tteofili/sling,ffromm/sling,SylvesterAbreu/sling,mcdan/sling,wimsymons/sling,Nimco/sling,wimsymons/sling,cleliameneghin/sling,labertasch/sling,plutext/sling,ieb/sling,ist-dresden/sling,Sivaramvt/sling,gutsy/sling,trekawek/sling,trekawek/sling,klcodanr/sling,labertasch/sling,mmanski/sling,Sivaramvt/sling,dulvac/sling,tmaret/sling,mmanski/sling,roele/sling,klcodanr/sling,tmaret/sling,Nimco/sling,wimsymons/sling,wimsymons/sling,vladbailescu/sling,roele/sling,tyge68/sling,SylvesterAbreu/sling,wimsymons/sling,dulvac/sling,dulvac/sling,tteofili/sling,nleite/sling,headwirecom/sling,ieb/sling,klcodanr/sling,gutsy/sling,sdmcraft/sling,roele/sling,Nimco/sling,labertasch/sling,ieb/sling,JEBailey/sling,wimsymons/sling,mmanski/sling,ffromm/sling,mmanski/sling,labertasch/sling,klcodanr/sling,dulvac/sling,ffromm/sling,anchela/sling,cleliameneghin/sling,ist-dresden/sling,tteofili/sling,headwirecom/sling,sdmcraft/sling,ist-dresden/sling,Sivaramvt/sling,tmaret/sling,tteofili/sling,ieb/sling,mikibrv/sling,nleite/sling,ist-dresden/sling,mcdan/sling,awadheshv/sling,JEBailey/sling,klcodanr/sling,mmanski/sling,vladbailescu/sling,headwirecom/sling,tteofili/sling,mcdan/sling,SylvesterAbreu/sling,awadheshv/sling,mcdan/sling,vladbailescu/sling,tmaret/sling,mikibrv/sling,roele/sling,gutsy/sling,labertasch/sling,mcdan/sling,headwirecom/sling,gutsy/sling,trekawek/sling,awadheshv/sling,tyge68/sling,trekawek/sling,ieb/sling,plutext/sling,tyge68/sling,cleliameneghin/sling,Sivaramvt/sling,tmaret/sling,ffromm/sling,gutsy/sling,anchela/sling,gutsy/sling,dulvac/sling,anchela/sling,awadheshv/sling,nleite/sling,tteofili/sling,mikibrv/sling,vladbailescu/sling,dulvac/sling
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.apache.sling.launchpad.installer.impl; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.net.URL; import java.util.Collection; import java.util.Dictionary; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Set; import org.apache.sling.installer.api.InstallableResource; import org.apache.sling.installer.api.OsgiInstaller; import org.apache.sling.launchpad.api.LaunchpadContentProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class scans the launchpad resources folder and provides the artifacts * to the OSGi installer. */ public class LaunchpadConfigInstaller { /** Logger */ private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); /** * Resources supplied under this path by * LaunchpadContentProvider are considered for installation */ private static final String ROOT_PATH = "resources"; /** * Resources supplied under this path by * LaunchpadContentProvider are considered for installation * as configurations */ private static final String CONFIG_NAME = "config"; /** * Resources supplied under this path by * LaunchpadContentProvider are considered for installation * as files */ private static final String INSTALL_NAME = "install"; private static final String INSTALL_PREFIX = "install."; /** Artifact priority. */ private static final Integer PRIORITY = new Integer(50); private static final int PRIORITY_BOOST = 5; /** * Check the path for installable artifacts. */ private boolean checkPath(final String rootPath, final String resourceType, final Integer prio) { int count = 0; final Iterator<String> configPaths = resourceProvider.getChildren(rootPath); if ( configPaths != null ) { final int hintPos = rootPath.lastIndexOf('/'); final String hint = rootPath.substring(hintPos + 1); while (configPaths.hasNext()) { String path = configPaths.next(); if ( path.endsWith("/") ) { path = path.substring(0, path.length() - 1); } if ( !checkPath(path, resourceType, prio) ) { count++; final URL url = resourceProvider.getResource(path); Dictionary<String, Object> dict = null; if ( InstallableResource.TYPE_FILE.equals(resourceType) ) { dict = new Hashtable<String, Object>(); if ( !hint.startsWith(INSTALL_NAME) ) { dict.put(InstallableResource.INSTALLATION_HINT, hint); } try { dict.put(InstallableResource.RESOURCE_URI_HINT, url.toURI().toString()); } catch (final URISyntaxException e) { // we just ignore this } } else if ( !hint.equals(CONFIG_NAME) && isActive(hint) == 0 ) { logger.debug("Launchpad ignoring {} : {} due to unactivated run mode: {}", new Object[] {resourceType, path, hint}); continue; } long lastModified = -1; try { lastModified = url.openConnection().getLastModified(); } catch (final IOException e) { // we ignore this } logger.debug("Launchpad {} will be installed: {}", resourceType, path); final String digest = (lastModified > 0 ? String.valueOf(lastModified) : null); final InputStream stream = resourceProvider.getResourceAsStream(path); installables.add(new InstallableResource(path, stream, dict, digest, resourceType, prio)); } } } return count > 0; } private int isActive(final String runModesString) { final String[] runModes = runModesString.split("\\."); boolean active = true; for(final String mode : runModes) { if ( !activeRunModes.contains(mode) ) { active = false; } } return active ? runModes.length : 0; } /** * Install artifacts */ public static void install(final OsgiInstaller installer, final LaunchpadContentProvider resourceProvider, final Set<String> activeRunModes) { new LaunchpadConfigInstaller(resourceProvider, activeRunModes).install(installer); } private final LaunchpadContentProvider resourceProvider; private final Set<String> activeRunModes; private final Collection<InstallableResource> installables = new HashSet<InstallableResource>(); private LaunchpadConfigInstaller(final LaunchpadContentProvider resourceProvider, final Set<String> activeRunModes) { this.resourceProvider = resourceProvider; this.activeRunModes = activeRunModes; } private void install(final OsgiInstaller installer) { logger.info("Activating launchpad config installer, configuration path={}/{}, install path={}/{}", new Object[] {ROOT_PATH, CONFIG_NAME, ROOT_PATH, INSTALL_NAME}); final Iterator<String> configPaths = resourceProvider.getChildren(ROOT_PATH); if ( configPaths != null ) { while ( configPaths.hasNext() ) { String path = configPaths.next(); logger.debug("Found launchpad resource {}", path); if ( path.endsWith("/") ) { path = path.substring(0, path.length() - 1); } final int namePos = path.lastIndexOf('/'); String name = path.substring(namePos + 1); if ( name.equals(CONFIG_NAME) ) { // configurations checkPath(path, InstallableResource.TYPE_PROPERTIES, PRIORITY); } else if ( name.equals(INSTALL_NAME) ) { // files checkPath(path, InstallableResource.TYPE_FILE, PRIORITY); } else if ( name.startsWith(INSTALL_PREFIX) ) { final int activeModes = isActive(name.substring(INSTALL_PREFIX.length())); if ( activeModes > 0 ) { // files final int prio = PRIORITY + PRIORITY_BOOST * activeModes; checkPath(path, InstallableResource.TYPE_FILE, prio); } else { logger.debug("Ignoring path {} due to unactivated run mode: {}", path, name.substring(INSTALL_PREFIX.length())); } } else { logger.debug("Ignoring path {} - not an installation path", path); } } } else { logger.warn("Run mode dependent installation not supported by launchpad content provider {}", resourceProvider); // revert to old behavior checkPath(ROOT_PATH + '/' + CONFIG_NAME, InstallableResource.TYPE_PROPERTIES, PRIORITY); checkPath(ROOT_PATH + '/' + INSTALL_NAME, InstallableResource.TYPE_FILE, PRIORITY); } final InstallableResource [] toInstall = installables.toArray(new InstallableResource []{}); installer.registerResources("launchpad", (toInstall)); logger.info("{} resources registered with OsgiInstaller", toInstall.length); } }
launchpad/installer/src/main/java/org/apache/sling/launchpad/installer/impl/LaunchpadConfigInstaller.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.apache.sling.launchpad.installer.impl; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.net.URL; import java.util.Collection; import java.util.Dictionary; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Set; import org.apache.sling.installer.api.InstallableResource; import org.apache.sling.installer.api.OsgiInstaller; import org.apache.sling.launchpad.api.LaunchpadContentProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class scans the launchpad resources folder and provides the artifacts * to the OSGi installer. */ public class LaunchpadConfigInstaller { /** * Resources supplied under this path by * LaunchpadContentProvider are considered for installation */ private static final String ROOT_PATH = "resources"; /** * Resources supplied under this path by * LaunchpadContentProvider are considered for installation * as configurations */ private static final String CONFIG_NAME = "config"; /** * Resources supplied under this path by * LaunchpadContentProvider are considered for installation * as files */ private static final String INSTALL_NAME = "install"; private static final String INSTALL_PREFIX = "install."; /** Artifact priority. */ private static final Integer PRIORITY = new Integer(50); private static final int PRIORITY_BOOST = 5; /** * Check the path for installable artifacts. */ private static boolean checkPath(final LaunchpadContentProvider resourceProvider, final Set<String> activeRunModes, final Collection<InstallableResource> installables, final String rootPath, final String resourceType, final Integer prio) { int count = 0; final Logger logger = LoggerFactory.getLogger(LaunchpadConfigInstaller.class); final Iterator<String> configPaths = resourceProvider.getChildren(rootPath); if ( configPaths != null ) { final int hintPos = rootPath.lastIndexOf('/'); final String hint = rootPath.substring(hintPos + 1); while (configPaths.hasNext()) { String path = configPaths.next(); if ( path.endsWith("/") ) { path = path.substring(0, path.length() - 1); } if ( !checkPath(resourceProvider, activeRunModes, installables, path, resourceType, prio) ) { final URL url = resourceProvider.getResource(path); Dictionary<String, Object> dict = null; if ( InstallableResource.TYPE_FILE.equals(resourceType) ) { dict = new Hashtable<String, Object>(); if ( !hint.startsWith(INSTALL_NAME) ) { dict.put(InstallableResource.INSTALLATION_HINT, hint); } try { dict.put(InstallableResource.RESOURCE_URI_HINT, url.toURI().toString()); } catch (final URISyntaxException e) { // we just ignore this } } else { // if this is a configuration, hint could be run Modes if ( !hint.equals(CONFIG_NAME) ) { if ( isActive(hint, activeRunModes) == 0 ) { logger.debug("Launchpad ignoring {} : {} due to unactivated run mode: {}", new Object[] {resourceType, path, hint}); continue; } } } long lastModified = -1; try { lastModified = url.openConnection().getLastModified(); } catch (final IOException e) { // we ignore this } logger.debug("Launchpad {} will be installed: {}", resourceType, path); final String digest = (lastModified > 0 ? String.valueOf(lastModified) : null); final InputStream stream = resourceProvider.getResourceAsStream(path); installables.add(new InstallableResource(path, stream, dict, digest, resourceType, prio)); count++; } } } return count > 0; } private static int isActive(final String runModesString, final Set<String> activeRunModes) { final String[] runModes = runModesString.split("\\."); boolean active = true; for(final String mode : runModes) { if ( !activeRunModes.contains(mode) ) { active = false; } } return active ? runModes.length : 0; } /** * Install artifacts */ public static void install(final OsgiInstaller installer, final LaunchpadContentProvider resourceProvider, final Set<String> activeRunModes) { final Logger logger = LoggerFactory.getLogger(LaunchpadConfigInstaller.class); logger.info("Activating launchpad config installer, configuration path={}/{}, install path={}/{}", new Object[] {ROOT_PATH, CONFIG_NAME, ROOT_PATH, INSTALL_NAME}); final Collection<InstallableResource> installables = new HashSet<InstallableResource>(); final Iterator<String> configPaths = resourceProvider.getChildren(ROOT_PATH); if ( configPaths != null ) { while ( configPaths.hasNext() ) { String path = configPaths.next(); logger.debug("Found launchpad resource {}", path); if ( path.endsWith("/") ) { path = path.substring(0, path.length() - 1); } final int namePos = path.lastIndexOf('/'); String name = path.substring(namePos + 1); if ( name.equals(CONFIG_NAME) ) { // configurations checkPath(resourceProvider, activeRunModes, installables, path, InstallableResource.TYPE_PROPERTIES, PRIORITY); } else if ( name.equals(INSTALL_NAME) ) { // files checkPath(resourceProvider, activeRunModes, installables, path, InstallableResource.TYPE_FILE, PRIORITY); } else if ( name.startsWith(INSTALL_PREFIX) ) { final int activeModes = isActive(name.substring(INSTALL_PREFIX.length()), activeRunModes); if ( activeModes > 0 ) { // files final int prio = PRIORITY + PRIORITY_BOOST * activeModes; checkPath(resourceProvider, activeRunModes, installables, path, InstallableResource.TYPE_FILE, prio); } else { logger.debug("Ignoring path {} due to unactivated run mode: {}", path, name.substring(INSTALL_PREFIX.length())); } } else { logger.debug("Ignoring path {} - not an installation path", path); } } } else { logger.warn("Run mode dependent installation not supported by launchpad content provider {}", resourceProvider); // revert to old behaviour checkPath(resourceProvider, activeRunModes, installables, ROOT_PATH + '/' + CONFIG_NAME, InstallableResource.TYPE_PROPERTIES, PRIORITY); checkPath(resourceProvider, activeRunModes, installables, ROOT_PATH + '/' + INSTALL_NAME, InstallableResource.TYPE_FILE, PRIORITY); } final InstallableResource [] toInstall = installables.toArray(new InstallableResource []{}); installer.registerResources("launchpad", (toInstall)); logger.info("{} resources registered with OsgiInstaller", toInstall.length); } }
SLING-2649 : Add support for run modes git-svn-id: 6eed74fe9a15c8da84b9a8d7f2960c0406113ece@1409682 13f79535-47bb-0310-9956-ffa450edef68
launchpad/installer/src/main/java/org/apache/sling/launchpad/installer/impl/LaunchpadConfigInstaller.java
SLING-2649 : Add support for run modes
Java
apache-2.0
ded77d86a99442e963a106854f93f82b591279ac
0
cherryhill/collectionspace-application
package org.collectionspace.chain.csp.webui.authorities; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.collectionspace.chain.csp.schema.Instance; import org.collectionspace.chain.csp.schema.Record; import org.collectionspace.chain.csp.schema.Spec; import org.collectionspace.chain.csp.webui.main.Request; import org.collectionspace.chain.csp.webui.main.WebMethod; import org.collectionspace.chain.csp.webui.main.WebUI; import org.collectionspace.csp.api.persistence.ExistException; import org.collectionspace.csp.api.persistence.Storage; import org.collectionspace.csp.api.persistence.UnderlyingStorageException; import org.collectionspace.csp.api.persistence.UnimplementedException; import org.collectionspace.csp.api.ui.UIException; import org.collectionspace.csp.api.ui.UIRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class VocabulariesRead implements WebMethod { private static final Logger log=LoggerFactory.getLogger(VocabulariesRead.class); private Instance n; private String base; private Map<String,String> type_to_url=new HashMap<String,String>(); public VocabulariesRead(Instance n) { this.base=n.getID(); this.n=n; } public void configure(WebUI ui,Spec spec) { for(Record r : spec.getAllRecords()) { type_to_url.put(r.getID(),r.getWebURL()); } } /** * Returns all the Authorities that are associated to a vocabulary item * @param storage * @param path * @return * @throws ExistException * @throws UnimplementedException * @throws UnderlyingStorageException * @throws JSONException */ @SuppressWarnings("unchecked") private JSONArray getTermsUsed(Storage storage,String path) throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException { JSONObject mini=storage.retrieveJSON(path+"/authorityrefs"); JSONArray out=new JSONArray(); Iterator t=mini.keys(); while(t.hasNext()) { String field=(String)t.next(); if(mini.get(field) instanceof JSONArray){ JSONArray array = (JSONArray)mini.get(field); for(int i=0;i<array.length();i++) { JSONObject in = array.getJSONObject(i); JSONObject entry=getTermsUsedData(in); out.put(entry); } } else{ JSONObject in=mini.getJSONObject(field); JSONObject entry=getTermsUsedData(in); out.put(entry); } } return out; } private JSONObject getTermsUsedData(JSONObject in) throws JSONException{ JSONObject entry=new JSONObject(); entry.put("csid",in.getString("csid")); entry.put("recordtype",in.getString("recordtype")); //entry.put("sourceFieldName",field); entry.put("sourceFieldselector",in.getString("sourceFieldselector")); entry.put("sourceFieldName",in.getString("sourceFieldName")); entry.put("sourceFieldType",in.getString("sourceFieldType")); entry.put("number",in.getString("displayName")); return entry; } /** * Returns all the objects that are linked to a vocabulary item * @param storage * @param path * @return * @throws ExistException * @throws UnimplementedException * @throws UnderlyingStorageException * @throws JSONException */ @SuppressWarnings("unchecked") private JSONArray getRefObj(Storage storage,String path) throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException { JSONArray out=new JSONArray(); JSONObject mini = storage.retrieveJSON(path+"/refObjs"); if(mini != null){ Iterator t=mini.keys(); while(t.hasNext()) { String field=(String)t.next(); JSONObject in=mini.getJSONObject(field); /* JSONObject entry=new JSONObject(); entry.put("csid",in.getString("csid")); entry.put("recordtype",in.getString("sourceFieldType")); entry.put("sourceFieldName",field); entry.put("number",in.getString("sourceFieldName")); */ out.put(in); } } return out; } private JSONObject generateMiniRecord(Storage storage,String type,String csid) throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException { JSONObject out=storage.retrieveJSON(type+"/"+csid+"/view"); out.put("csid",csid); out.put("recordtype",type_to_url.get(type)); return out; } private JSONObject generateRelationEntry(Storage storage,String csid) throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException { /* Retrieve entry */ JSONObject in=storage.retrieveJSON("relations/main/"+csid); String[] dstid=in.getString("dst").split("/"); String type=in.getString("type"); JSONObject mini=generateMiniRecord(storage,dstid[0],dstid[1]); mini.put("relationshiptype",type); mini.put("relid",in.getString("csid")); return mini; } private JSONObject createRelations(Storage storage,String csid) throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException { JSONObject recordtypes=new JSONObject(); JSONObject restrictions=new JSONObject(); restrictions.put("src",base+"/"+csid); // XXX needs pagination support CSPACE-1819 JSONObject data = storage.getPathsJSON("relations/main",restrictions); String[] relations = (String[]) data.get("listItems"); for(String r : relations) { try { JSONObject relateitem = generateRelationEntry(storage,r); String type = relateitem.getString("recordtype"); if(!recordtypes.has(type)){ recordtypes.put(type, new JSONArray()); } recordtypes.getJSONArray(type).put(relateitem); } catch(Exception e) { // Never mind. } } return recordtypes; } /* Wrapper exists to decomplexify exceptions: also used inCreateUpdate, hence not private */ JSONObject getJSON(Storage storage,String csid) throws UIException { JSONObject out=new JSONObject(); try { String refPath = n.getRecord().getID()+"/"+n.getTitleRef()+"/"; JSONObject fields=storage.retrieveJSON(refPath+csid); csid = fields.getString("csid"); //fields.put("csid",csid); //JSONObject relations=createRelations(storage,csid); out.put("csid",csid); out.put("fields",fields); out.put("relations",new JSONArray()); //out.put("relations",relations); out.put("termsUsed",getTermsUsed(storage,refPath+csid)); out.put("refobjs",getRefObj(storage,refPath+csid)); } catch (ExistException e) { throw new UIException("JSON Not found "+e,e); } catch (UnimplementedException e) { throw new UIException("Unimplemented",e); } catch (UnderlyingStorageException e) { throw new UIException("Problem getting",e); } catch (JSONException e) { throw new UIException("Could not create JSON"+e,e); } if (out == null) { throw new UIException("No JSON Found"); } return out; } private void store_get(Storage storage,UIRequest request,String path) throws UIException { // Get the data JSONObject outputJSON = getJSON(storage,path); // Write the requested JSON out request.sendJSONResponse(outputJSON); } public void run(Object in, String[] tail) throws UIException { Request q=(Request)in; store_get(q.getStorage(),q.getUIRequest(),StringUtils.join(tail,"/")); } }
cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/authorities/VocabulariesRead.java
package org.collectionspace.chain.csp.webui.authorities; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.collectionspace.chain.csp.schema.Instance; import org.collectionspace.chain.csp.schema.Record; import org.collectionspace.chain.csp.schema.Spec; import org.collectionspace.chain.csp.webui.main.Request; import org.collectionspace.chain.csp.webui.main.WebMethod; import org.collectionspace.chain.csp.webui.main.WebUI; import org.collectionspace.csp.api.persistence.ExistException; import org.collectionspace.csp.api.persistence.Storage; import org.collectionspace.csp.api.persistence.UnderlyingStorageException; import org.collectionspace.csp.api.persistence.UnimplementedException; import org.collectionspace.csp.api.ui.UIException; import org.collectionspace.csp.api.ui.UIRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class VocabulariesRead implements WebMethod { private static final Logger log=LoggerFactory.getLogger(VocabulariesRead.class); private Instance n; private String base; private Map<String,String> type_to_url=new HashMap<String,String>(); public VocabulariesRead(Instance n) { this.base=n.getID(); this.n=n; } public void configure(WebUI ui,Spec spec) { for(Record r : spec.getAllRecords()) { type_to_url.put(r.getID(),r.getWebURL()); } } /** * Returns all the Authorities that are associated to a vocabulary item * @param storage * @param path * @return * @throws ExistException * @throws UnimplementedException * @throws UnderlyingStorageException * @throws JSONException */ @SuppressWarnings("unchecked") private JSONArray getTermsUsed(Storage storage,String path) throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException { JSONObject mini=storage.retrieveJSON(path+"/authorityrefs"); JSONArray out=new JSONArray(); Iterator t=mini.keys(); while(t.hasNext()) { String field=(String)t.next(); if(mini.get(field) instanceof JSONArray){ JSONArray array = (JSONArray)mini.get(field); for(int i=0;i<array.length();i++) { JSONObject in = array.getJSONObject(i); JSONObject entry=getTermsUsedData(in); out.put(entry); } } else{ JSONObject in=mini.getJSONObject(field); JSONObject entry=getTermsUsedData(in); out.put(entry); } } return out; } private JSONObject getTermsUsedData(JSONObject in) throws JSONException{ JSONObject entry=new JSONObject(); entry.put("csid",in.getString("csid")); entry.put("recordtype",in.getString("recordtype")); //entry.put("sourceFieldName",field); entry.put("sourceFieldselector",in.getString("sourceFieldselector")); entry.put("sourceFieldName",in.getString("sourceFieldName")); entry.put("sourceFieldType",in.getString("sourceFieldType")); entry.put("number",in.getString("displayName")); return entry; } /** * Returns all the objects that are linked to a vocabulary item * @param storage * @param path * @return * @throws ExistException * @throws UnimplementedException * @throws UnderlyingStorageException * @throws JSONException */ @SuppressWarnings("unchecked") private JSONArray getRefObj(Storage storage,String path) throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException { JSONArray out=new JSONArray(); JSONObject mini = storage.retrieveJSON(path+"/refObjs"); if(mini != null){ Iterator t=mini.keys(); while(t.hasNext()) { String field=(String)t.next(); JSONObject in=mini.getJSONObject(field); /* JSONObject entry=new JSONObject(); entry.put("csid",in.getString("csid")); entry.put("recordtype",in.getString("sourceFieldType")); entry.put("sourceFieldName",field); entry.put("number",in.getString("sourceFieldName")); */ out.put(in); } } return out; } private JSONObject generateMiniRecord(Storage storage,String type,String csid) throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException { JSONObject out=storage.retrieveJSON(type+"/"+csid+"/view"); out.put("csid",csid); out.put("recordtype",type_to_url.get(type)); return out; } private JSONObject generateRelationEntry(Storage storage,String csid) throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException { /* Retrieve entry */ JSONObject in=storage.retrieveJSON("relations/main/"+csid); String[] dstid=in.getString("dst").split("/"); String type=in.getString("type"); JSONObject mini=generateMiniRecord(storage,dstid[0],dstid[1]); mini.put("relationshiptype",type); mini.put("relid",in.getString("csid")); return mini; } private JSONObject createRelations(Storage storage,String csid) throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException { JSONObject recordtypes=new JSONObject(); JSONObject restrictions=new JSONObject(); restrictions.put("src",base+"/"+csid); // XXX needs pagination support CSPACE-1819 JSONObject data = storage.getPathsJSON("relations/main",restrictions); String[] relations = (String[]) data.get("listItems"); for(String r : relations) { try { JSONObject relateitem = generateRelationEntry(storage,r); String type = relateitem.getString("recordtype"); if(!recordtypes.has(type)){ recordtypes.put(type, new JSONArray()); } recordtypes.getJSONArray(type).put(relateitem); } catch(Exception e) { // Never mind. } } return recordtypes; } /* Wrapper exists to decomplexify exceptions: also used inCreateUpdate, hence not private */ JSONObject getJSON(Storage storage,String csid) throws UIException { JSONObject out=new JSONObject(); try { String refPath = n.getRecord().getID()+"/"+n.getTitleRef()+"/"; JSONObject fields=storage.retrieveJSON(refPath+csid); csid = fields.getString("csid"); //fields.put("csid",csid); //JSONObject relations=createRelations(storage,csid); out.put("fields",fields); out.put("relations",new JSONArray()); //out.put("relations",relations); out.put("termsUsed",getTermsUsed(storage,refPath+csid)); out.put("refobjs",getRefObj(storage,refPath+csid)); } catch (ExistException e) { throw new UIException("JSON Not found "+e,e); } catch (UnimplementedException e) { throw new UIException("Unimplemented",e); } catch (UnderlyingStorageException e) { throw new UIException("Problem getting",e); } catch (JSONException e) { throw new UIException("Could not create JSON"+e,e); } if (out == null) { throw new UIException("No JSON Found"); } return out; } private void store_get(Storage storage,UIRequest request,String path) throws UIException { // Get the data JSONObject outputJSON = getJSON(storage,path); try { outputJSON.put("csid",path); } catch (JSONException e1) { throw new UIException("Cannot add csid",e1); } // Write the requested JSON out request.sendJSONResponse(outputJSON); } public void run(Object in, String[] tail) throws UIException { Request q=(Request)in; store_get(q.getStorage(),q.getUIRequest(),StringUtils.join(tail,"/")); } }
CSPACE-2131 - fix get for urn:name vs id
cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/authorities/VocabulariesRead.java
CSPACE-2131 - fix get for urn:name vs id
Java
apache-2.0
1ef1119f64ec5002f9664b232a257e0a472b0941
0
fstahnke/arx-new-algorithms
/* * Benchmark of risk-based anonymization in ARX 3.0.0 * Copyright 2015 - Fabian Prasser * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.deidentifier.arx.benchmark; import java.io.File; import java.io.IOException; import org.deidentifier.arx.ARXAnonymizer; import org.deidentifier.arx.ARXConfiguration; import org.deidentifier.arx.ARXLattice; import org.deidentifier.arx.ARXLattice.ARXNode; import org.deidentifier.arx.ARXResult; import org.deidentifier.arx.Data; import org.deidentifier.arx.benchmark.BenchmarkSetup.BenchmarkDataset; import org.deidentifier.arx.benchmark.BenchmarkSetup.BenchmarkPrivacyModel; import org.deidentifier.arx.benchmark.BenchmarkSetup.BenchmarkUtilityMeasure; import de.linearbits.subframe.Benchmark; import de.linearbits.subframe.analyzer.ValueBuffer; import de.linearbits.subframe.analyzer.buffered.BufferedArithmeticMeanAnalyzer; import de.linearbits.subframe.analyzer.buffered.BufferedStandardDeviationAnalyzer; /** * Main benchmark class. * * @author Fabian Prasser */ public class BenchmarkExperiment2 { /** The benchmark instance */ private static final Benchmark BENCHMARK = new Benchmark(new String[] { "Dataset", "UtilityMeasure", "Algorithm", "Suppression" }); /** TOTAL */ //public static final int TOTAL = BENCHMARK.addMeasure("Total"); /** CHECK */ //public static final int CHECK = BENCHMARK.addMeasure("Check"); /** UTILITY */ public static final int UTILITY = BENCHMARK.addMeasure("Utility"); /** Repetitions */ private static final int REPETITIONS = 2; /** * Main entry point * * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // Init BENCHMARK.addAnalyzer(UTILITY, new BufferedArithmeticMeanAnalyzer()); BENCHMARK.addAnalyzer(UTILITY, new BufferedStandardDeviationAnalyzer()); //BENCHMARK.addAnalyzer(TOTAL, new ValueBuffer()); //BENCHMARK.addAnalyzer(CHECK, new ValueBuffer()); // Repeat for each data set for (BenchmarkDataset data : BenchmarkSetup.getDatasets()) { // New run BENCHMARK.addRun(data.toString(), BenchmarkPrivacyModel.K_ANONYMITY, "RGR", 0.3d); anonymize(data, false); // Write after each experiment BENCHMARK.getResults().write(new File("results/experiment2.csv")); } } /** * Performs the experiments * * @param dataset * @throws IOException */ private static void anonymize(BenchmarkDataset dataset, boolean usePolygamma) throws IOException { Data data = BenchmarkSetup.getData(dataset, BenchmarkPrivacyModel.K_ANONYMITY); ARXConfiguration config = BenchmarkSetup.getConfiguration(dataset, BenchmarkUtilityMeasure.LOSS, BenchmarkPrivacyModel.K_ANONYMITY, 0.01d); ARXAnonymizer anonymizer = new ARXAnonymizer(); // Warmup ARXResult result = anonymizer.anonymize(data, config); data.getHandle().release(); // Benchmark long time = System.currentTimeMillis(); for (int i = 0; i < REPETITIONS; i++) { System.out.println(" - Run-1 " + (i + 1) + " of " + REPETITIONS); data.getHandle().release(); result = anonymizer.anonymize(data, config); } time = System.currentTimeMillis() - time; BENCHMARK.addValue(UTILITY, BenchmarkMetadata.getRelativeLoss(data.getHandle(), result.getOutput(), result.getGlobalOptimum().getTransformation(), dataset, BenchmarkUtilityMeasure.LOSS)); //BENCHMARK.addValue(TOTAL, (int) time); //BENCHMARK.addValue(CHECK, (int) ((double) time / (double) getNumChecks(result))); } /** * Returns the number of checks * @param result * @return */ private static int getNumChecks(ARXResult result) { int checks = 0; ARXLattice lattice = result.getLattice(); for (ARXNode[] level : lattice.getLevels()) { for (ARXNode node : level) { checks += node.isChecked() ? 1 : 0; } } return checks; } }
src/org/deidentifier/arx/benchmark/BenchmarkExperiment2.java
/* * Benchmark of risk-based anonymization in ARX 3.0.0 * Copyright 2015 - Fabian Prasser * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.deidentifier.arx.benchmark; import java.io.File; import java.io.IOException; import org.deidentifier.arx.ARXAnonymizer; import org.deidentifier.arx.ARXConfiguration; import org.deidentifier.arx.ARXLattice; import org.deidentifier.arx.ARXLattice.ARXNode; import org.deidentifier.arx.ARXResult; import org.deidentifier.arx.Data; import org.deidentifier.arx.benchmark.BenchmarkSetup.BenchmarkDataset; import org.deidentifier.arx.benchmark.BenchmarkSetup.BenchmarkPrivacyModel; import org.deidentifier.arx.benchmark.BenchmarkSetup.BenchmarkUtilityMeasure; import de.linearbits.subframe.Benchmark; import de.linearbits.subframe.analyzer.ValueBuffer; import de.linearbits.subframe.analyzer.buffered.BufferedArithmeticMeanAnalyzer; import de.linearbits.subframe.analyzer.buffered.BufferedStandardDeviationAnalyzer; /** * Main benchmark class. * * @author Fabian Prasser */ public class BenchmarkExperiment2 { /** The benchmark instance */ private static final Benchmark BENCHMARK = new Benchmark(new String[] { "Dataset", "Polygamma" }); /** TOTAL */ public static final int TOTAL = BENCHMARK.addMeasure("Total"); /** CHECK */ public static final int CHECK = BENCHMARK.addMeasure("Check"); /** UTILITY */ public static final int UTILITY = BENCHMARK.addMeasure("Utility"); /** Repetitions */ private static final int REPETITIONS = 5; /** * Main entry point * * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // Init BENCHMARK.addAnalyzer(UTILITY, new BufferedArithmeticMeanAnalyzer()); BENCHMARK.addAnalyzer(UTILITY, new BufferedStandardDeviationAnalyzer()); BENCHMARK.addAnalyzer(TOTAL, new ValueBuffer()); BENCHMARK.addAnalyzer(CHECK, new ValueBuffer()); // Repeat for each data set for (BenchmarkDataset data : BenchmarkSetup.getDatasets()) { // New run BENCHMARK.addRun(data.toString(), "true"); anonymize(data, true); // New run BENCHMARK.addRun(data.toString(), "false"); anonymize(data, false); // Write after each experiment BENCHMARK.getResults().write(new File("results/experiment2.csv")); } } /** * Performs the experiments * * @param dataset * @throws IOException */ private static void anonymize(BenchmarkDataset dataset, boolean usePolygamma) throws IOException { Data data = BenchmarkSetup.getData(dataset, BenchmarkPrivacyModel.UNIQUENESS_PITMAN); ARXConfiguration config = BenchmarkSetup.getConfiguration(dataset, BenchmarkUtilityMeasure.LOSS, BenchmarkPrivacyModel.UNIQUENESS_PITMAN, 0.01d); ARXAnonymizer anonymizer = new ARXAnonymizer(); // Warmup ARXResult result = anonymizer.anonymize(data, config); data.getHandle().release(); // Benchmark long time = System.currentTimeMillis(); for (int i = 0; i < REPETITIONS; i++) { System.out.println(" - Run-1 " + (i + 1) + " of " + REPETITIONS); data.getHandle().release(); result = anonymizer.anonymize(data, config); } time = System.currentTimeMillis() - time; BENCHMARK.addValue(UTILITY, BenchmarkMetadata.getRelativeLoss(data.getHandle(), result.getOutput(), result.getGlobalOptimum().getTransformation(), dataset, BenchmarkUtilityMeasure.LOSS)); BENCHMARK.addValue(TOTAL, (int) time); BENCHMARK.addValue(CHECK, (int) ((double) time / (double) getNumChecks(result))); } /** * Returns the number of checks * @param result * @return */ private static int getNumChecks(ARXResult result) { int checks = 0; ARXLattice lattice = result.getLattice(); for (ARXNode[] level : lattice.getLevels()) { for (ARXNode node : level) { checks += node.isChecked() ? 1 : 0; } } return checks; } }
Clean out unnecessary stuff
src/org/deidentifier/arx/benchmark/BenchmarkExperiment2.java
Clean out unnecessary stuff