answer
stringlengths
17
10.2M
//package mainPackage; import javafx.event.EventHandler; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.geometry.Insets; import javafx.geometry.Orientation; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.BorderPane; import javafx.scene.layout.FlowPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.TilePane; import javafx.scene.layout.VBox; import javafx.stage.Stage; import javafx.scene.paint.*; import javafx.scene.canvas.*; public class Pencil implements Brush { private int size; private Color color = Brush.DEFAULT_COLOR; final GraphicsContext graphicsContext = Frame.canvas.getGraphicsContext2D(); public Pencil(int size){ this.size = size; } public Pencil(int size, Color color){ this.size=size; this.color=color; } @Override public void draw() { Frame.gc.setFill(color); Frame.canvas.setOnMouseDragged(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent e) { graphicsContext.lineTo(e.getX(), e.getY()); graphicsContext.stroke(); } }); Frame.canvas.setOnMousePressed(new EventHandler<MouseEvent>(){ @Override public void handle(MouseEvent e){ graphicsContext.beginPath(); graphicsContext.moveTo(e.getX(), e.getY()); graphicsContext.stroke(); } }); } @Override public void setSize(int size){ this.size = size; } public void setColor(Color newColor){ color = newColor; } }
import java.util.LinkedHashMap; import java.util.Map; public class Person { private static final int SHORT_LENGTH_CAP = 10; private static final int LONG_LENGTH_CAP = 14; static final LinkedHashMap<String, String> STATE_MAP = new LinkedHashMap<>(); static { STATE_MAP.put("Alabama", "AL"); STATE_MAP.put("Missouri", "MO"); STATE_MAP.put("Alaska", "AK"); STATE_MAP.put("Montana", "MT"); STATE_MAP.put("Arizona", "AZ"); STATE_MAP.put("Nebraska", "NE"); STATE_MAP.put("Arkansas", "AR"); STATE_MAP.put("Nevada", "NV"); STATE_MAP.put("California", "CA"); STATE_MAP.put("New Hampshire", "NH"); STATE_MAP.put("Colorado", "CO"); STATE_MAP.put("New Jersey", "NJ"); STATE_MAP.put("Connecticut", "CT"); STATE_MAP.put("New Mexico", "NM"); STATE_MAP.put("Delaware", "DE"); STATE_MAP.put("New York", "NY"); STATE_MAP.put("North Carolina", "NC"); STATE_MAP.put("Florida", "FL"); STATE_MAP.put("North Dakota", "ND"); STATE_MAP.put("Georgia", "GA"); STATE_MAP.put("Ohio", "OH"); STATE_MAP.put("Hawaii", "HI"); STATE_MAP.put("Oklahoma", "OK"); STATE_MAP.put("Idaho", "ID"); STATE_MAP.put("Oregon", "OR"); STATE_MAP.put("Illinois", "IL"); STATE_MAP.put("Pennsylvania", "PA"); STATE_MAP.put("Indiana", "IN"); STATE_MAP.put("Rhode Island", "RI"); STATE_MAP.put("Iowa", "IA"); STATE_MAP.put("South Carolina", "SC"); STATE_MAP.put("Kansas", "KS"); STATE_MAP.put("South Dakota", "SD"); STATE_MAP.put("Kentucky", "KY"); STATE_MAP.put("Tennessee", "TN"); STATE_MAP.put("Louisiana", "LA"); STATE_MAP.put("Texas", "TX"); STATE_MAP.put("Maine", "ME"); STATE_MAP.put("Utah", "UT"); STATE_MAP.put("Maryland", "MD"); STATE_MAP.put("Vermont", "VT"); STATE_MAP.put("Massachusetts", "MA"); STATE_MAP.put("Virginia", "VA"); STATE_MAP.put("Michigan", "MI"); STATE_MAP.put("Washington", "WA"); STATE_MAP.put("Minnesota", "MN"); STATE_MAP.put("West Virginia", "WV"); STATE_MAP.put("Mississippi", "MS"); STATE_MAP.put("Wisconsin", "WI"); } private String shortFirstName; private String longFirstName; private String firstName; private String shortLastName; private String longLastName; private String lastName; private int age; private String shortStateName; private String longStateName; /** * Initialize this Person to the given parameters. * * @param fName first name * @param lName last name * @param age age of this person * @param state state where this person was born */ public Person(String fName, String lName, int age, String state) throws IllegalArgumentException { this.firstName = fName; this.shortFirstName = (fName.length() > SHORT_LENGTH_CAP) ? fName.substring(0, SHORT_LENGTH_CAP) : fName; this.longFirstName = (fName.length() > LONG_LENGTH_CAP) ? fName.substring(0, LONG_LENGTH_CAP) : fName; this.lastName = lName; this.shortLastName = (lName.length() > SHORT_LENGTH_CAP) ? lName.substring(0, SHORT_LENGTH_CAP) : lName; this.longLastName = (lName.length() > LONG_LENGTH_CAP) ? lName.substring(0, LONG_LENGTH_CAP) : lName; this.age = age; if(STATE_MAP.containsKey(state) || STATE_MAP.containsValue(state)) { if(state.length() == 2) { shortStateName = state; longStateName = getKeyByValue(STATE_MAP, state); } else { shortStateName = STATE_MAP.get(state); longStateName = state; } } else { throw new IllegalArgumentException("State not found"); } } public Person(String fName, String lName) { this.firstName = fName; this.shortFirstName = (fName.length() > SHORT_LENGTH_CAP) ? fName.substring(0, SHORT_LENGTH_CAP) : fName; this.longFirstName = (fName.length() > LONG_LENGTH_CAP) ? fName.substring(0, LONG_LENGTH_CAP) : fName; this.lastName = lName; this.shortLastName = (lName.length() > SHORT_LENGTH_CAP) ? lName.substring(0, SHORT_LENGTH_CAP) : lName; this.longLastName = (lName.length() > LONG_LENGTH_CAP) ? lName.substring(0, LONG_LENGTH_CAP) : lName; this.age = 18; this.shortStateName = "VA"; this.longStateName = "Virginia"; } public Person(String[] parse) throws IllegalArgumentException { if (parse.length == 2) { this.firstName = parse[0]; this.shortFirstName = (parse[0].length() > SHORT_LENGTH_CAP) ? parse[0].substring(0, SHORT_LENGTH_CAP) : parse[0]; this.longFirstName = (parse[0].length() > LONG_LENGTH_CAP) ? parse[0].substring(0, LONG_LENGTH_CAP) : parse[0]; this.lastName = parse[1]; this.shortLastName = (parse[1].length() > SHORT_LENGTH_CAP) ? parse[1].substring(0, SHORT_LENGTH_CAP) : parse[1]; this.longLastName = (parse[1].length() > LONG_LENGTH_CAP) ? parse[1].substring(0, LONG_LENGTH_CAP) : parse[1]; this.age = 18; this.shortStateName = "VA"; this.longStateName = "Virginia"; } else { this.firstName = parse[0]; this.shortFirstName = (parse[0].length() > SHORT_LENGTH_CAP) ? parse[0].substring(0, SHORT_LENGTH_CAP) : parse[0]; this.longFirstName = (parse[0].length() > LONG_LENGTH_CAP) ? parse[0].substring(0, LONG_LENGTH_CAP) : parse[0]; this.lastName = parse[1]; this.shortLastName = (parse[1].length() > SHORT_LENGTH_CAP) ? parse[1].substring(0, SHORT_LENGTH_CAP) : parse[1]; this.longLastName = (parse[1].length() > LONG_LENGTH_CAP) ? parse[1].substring(0, LONG_LENGTH_CAP) : parse[1]; this.age = Integer.parseInt(parse[2]); if(STATE_MAP.containsKey(parse[3]) || STATE_MAP.containsValue(parse[3])) { if(parse[3].length() == 2) { shortStateName = parse[3]; longStateName = getKeyByValue(STATE_MAP, parse[3]); } else { shortStateName = STATE_MAP.get(parse[3]); longStateName = parse[3]; } } else { throw new IllegalArgumentException("State not found"); } } } private String getKeyByValue(Map<String,String> c, String value) { for (Map.Entry<String, String> entry : c.entrySet()) { if(entry.getValue().equals(value)) { return entry.getKey(); } } return ""; } /** * Get the key used for sorting Persons. The key is the lastname concatenated with the first name. For example if * the last name is Smith and the first name is John, then the key is SmithJohn. * * @return the key used for sorting Persons */ public String sortKey() { return firstName + "" + lastName; } /** * Get all the fields of this Person as a String with a capped length. * * @return <code>fistName + lastName + age + stateFrom;</code> */ public String allFields() { return shortFirstName + "," + shortLastName + "," + age + "," + shortStateName; } /** * Get all the fields of this Person as a String with a higher capped length. * @return <code>fistName + lastName + age + stateFrom;</code> */ public String allLongFields() { return longFirstName + "," + longLastName + "," + age + "," + longStateName; } /** * Compare the sort key of this Person to the sort key of the Person given as parameter. Return -1, 0, 1 according * as this Person's sort key is less than, equal to, or greater than the sort key of the Person given as parameter. * The table below illustrates how this works. Note that the comparison is CASE-SENSITIVE. * * @param otherPerson whose key is to be compared * @return -1, 0, 1 as described above */ public int compareTo(Person otherPerson) { return Math.max(-1, Math.min(1, sortKey().compareTo(otherPerson.sortKey()))); } public String toString() { return sortKey(); } }
/* * @author <a href="mailto:novotny@aei.mpg.de">Jason Novotny</a> * @version $Id$ */ package org.gridlab.gridsphere.portletcontainer; import org.gridlab.gridsphere.core.persistence.PersistenceManagerFactory; import org.gridlab.gridsphere.core.persistence.PersistenceManagerException; import org.gridlab.gridsphere.core.persistence.hibernate.DatabaseTask; import org.gridlab.gridsphere.layout.*; import org.gridlab.gridsphere.portlet.*; import org.gridlab.gridsphere.portlet.impl.*; import org.gridlab.gridsphere.portlet.service.PortletServiceException; import org.gridlab.gridsphere.portlet.service.spi.impl.SportletServiceFactory; import org.gridlab.gridsphere.portletcontainer.impl.GridSphereEventImpl; import org.gridlab.gridsphere.portletcontainer.impl.SportletMessageManager; import org.gridlab.gridsphere.services.core.registry.PortletManagerService; import org.gridlab.gridsphere.services.core.security.acl.AccessControlManagerService; import org.gridlab.gridsphere.services.core.security.auth.AuthorizationException; import org.gridlab.gridsphere.services.core.user.LoginService; import org.gridlab.gridsphere.services.core.user.UserManagerService; import org.gridlab.gridsphere.services.core.user.UserSessionManager; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.servlet.*; import javax.servlet.http.*; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; /** * The <code>GridSphereServlet</code> is the GridSphere portlet container. * All portlet requests get proccessed by the GridSphereServlet before they * are rendered. */ public class GridSphereServlet extends HttpServlet implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener, HttpSessionActivationListener { /* GridSphere logger */ private static PortletLog log = SportletLog.getInstance(GridSphereServlet.class); /* GridSphere service factory */ private static SportletServiceFactory factory = null; /* GridSphere Portlet Registry Service */ private static PortletManagerService portletManager = null; /* GridSphere Access Control Service */ private static AccessControlManagerService aclService = null; private static UserManagerService userManagerService = null; private static LoginService loginService = null; private PortletMessageManager messageManager = SportletMessageManager.getInstance(); /* GridSphere Portlet layout Engine handles rendering */ private static PortletLayoutEngine layoutEngine = null; /* Session manager maps users to sessions */ private UserSessionManager userSessionManager = UserSessionManager.getInstance(); private PortletContext context = null; private static Boolean firstDoGet = Boolean.TRUE; private static PortletSessionManager sessionManager = PortletSessionManager.getInstance(); private static PortletRegistry registry = PortletRegistry.getInstance(); int testpageNo = 1; private boolean isTCK = false; /** * Initializes the GridSphere portlet container * * @param config the <code>ServletConfig</code> * @throws ServletException if an error occurs during initialization */ public final void init(ServletConfig config) throws ServletException { super.init(config); GridSphereConfig.setServletConfig(config); this.context = new SportletContext(config); factory = SportletServiceFactory.getInstance(); log.debug("in init of GridSphereServlet"); } public synchronized void initializeServices() throws PortletServiceException { // discover portlets log.debug("Creating portlet manager service"); portletManager = (PortletManagerService) factory.createUserPortletService(PortletManagerService.class, GuestUser.getInstance(), getServletConfig().getServletContext(), true); // create groups from portlet web apps log.debug("Creating access control manager service"); aclService = (AccessControlManagerService) factory.createUserPortletService(AccessControlManagerService.class, GuestUser.getInstance(), getServletConfig().getServletContext(), true); // create root user in default group if necessary log.debug("Creating user manager service"); userManagerService = (UserManagerService) factory.createUserPortletService(UserManagerService.class, GuestUser.getInstance(), getServletConfig().getServletContext(), true); loginService = (LoginService) factory.createUserPortletService(LoginService.class, GuestUser.getInstance(), getServletConfig().getServletContext(), true); } /** * Processes GridSphere portal framework requests * * @param req the <code>HttpServletRequest</code> * @param res the <code>HttpServletResponse</code> * @throws IOException if an I/O error occurs * @throws ServletException if a servlet error occurs */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { processRequest(req, res); } public void processRequest(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { GridSphereEvent event = new GridSphereEventImpl(aclService, context, req, res); PortletRequest portletReq = event.getPortletRequest(); PortletResponse portletRes = event.getPortletResponse(); boolean database = true; // If first time being called, instantiate all portlets if (firstDoGet.equals(Boolean.TRUE)) { synchronized (firstDoGet) { log.debug("Testing Database"); // checking if database setup is correct DatabaseTask dt = new DatabaseTask(); try { dt.checkDBSetup(GridSphereConfig.getServletContext().getRealPath("/WEB-INF/persistence/")); } catch (PersistenceManagerException e) { RequestDispatcher rd = req.getRequestDispatcher("/jsp/dberror.jsp"); log.error("Check DB failed: ", e); req.setAttribute("error", "DB Error! Please contact your GridSphere/Database Administrator!"); rd.forward(req, res); return; } log.debug("Initializing portlets and services"); try { // initialize needed services initializeServices(); // initialize all portlets PortletInvoker.initAllPortlets(portletReq, portletRes); } catch (PortletException e) { req.setAttribute(SportletProperties.ERROR, e); } layoutEngine = PortletLayoutEngine.getInstance(); firstDoGet = Boolean.FALSE; } } setUserAndGroups(portletReq); setTCKUser(portletReq); // Handle user login and logout if (event.hasAction()) { if (event.getAction().getName().equals(SportletProperties.LOGIN)) { login(event); //event = new GridSphereEventImpl(aclService, context, req, res); } if (event.getAction().getName().equals(SportletProperties.LOGOUT)) { logout(event); // since event is now invalidated, must create new one event = new GridSphereEventImpl(aclService, context, req, res); } } layoutEngine.actionPerformed(event); // is this a file download operation? downloadFile(event); // Handle any outstanding messages // This needs work certainly!!! Map portletMessageLists = messageManager.retrieveAllMessages(); if (!portletMessageLists.isEmpty()) { Set keys = portletMessageLists.keySet(); Iterator it = keys.iterator(); String concPortletID = null; List messages = null; while (it.hasNext()) { concPortletID = (String) it.next(); messages = (List) portletMessageLists.get(concPortletID); Iterator newit = messages.iterator(); while (newit.hasNext()) { PortletMessage msg = (PortletMessage) newit.next(); layoutEngine.messageEvent(concPortletID, msg, event); } } messageManager.removeAllMessages(); } setUserAndGroups(portletReq); setTCKUser(portletReq); layoutEngine.service(event); log.debug("Session stats"); userSessionManager.dumpSessions(); log.debug("Portlet service factory stats"); factory.logStatistics(); log.debug("Portlet page factory stats"); try { PortletPageFactory pageFactory = PortletPageFactory.getInstance(); pageFactory.logStatistics(); } catch (Exception e) { log.error("Unable to get page factory", e); } } public void setTCKUser(PortletRequest req) { //String tck = (String)req.getPortletSession(true).getAttribute("tck"); String[] portletNames = req.getParameterValues("portletName"); if ((isTCK) || (portletNames != null)) { System.err.println("Setting a TCK user"); SportletUserImpl u = new SportletUserImpl(); u.setUserName("tckuser"); u.setUserID("tckuser"); Map l = new HashMap(); l.put(SportletGroup.CORE, PortletRole.USER); req.setAttribute(SportletProperties.PORTLET_USER, u); req.setAttribute(SportletProperties.PORTLETGROUPS, l); req.setAttribute(SportletProperties.PORTLET_ROLE, PortletRole.USER); isTCK = true; } } public void setUserAndGroups(PortletRequest req) { // Retrieve user if there is one User user = null; if (req.getPortletSession() != null) { String uid = (String) req.getPortletSession().getAttribute(SportletProperties.PORTLET_USER); if (uid != null) { user = userManagerService.getUser(uid); } } HashMap groups = new HashMap(); PortletRole role = PortletRole.GUEST; if (user == null) { user = GuestUser.getInstance(); groups = new HashMap(); groups.put(PortletGroupFactory.GRIDSPHERE_GROUP, PortletRole.GUEST); } else { List mygroups = aclService.getGroups(user); Iterator it = mygroups.iterator(); while (it.hasNext()) { PortletGroup g = (PortletGroup)it.next(); role = aclService.getRoleInGroup(user, g); groups.put(g, role); } } // set user, role and groups in request req.setAttribute(SportletProperties.PORTLET_USER, user); req.setAttribute(SportletProperties.PORTLETGROUPS, groups); req.setAttribute(SportletProperties.PORTLET_ROLE, role); } /** * Handles login requests * * @param event a <code>GridSphereEvent</code> */ protected void login(GridSphereEvent event) { log.debug("in login of GridSphere Servlet"); String LOGIN_ERROR_FLAG = "LOGIN_FAILED"; PortletRequest req = event.getPortletRequest(); PortletSession session = req.getPortletSession(true); String username = req.getParameter("ui_tf_username_"); String password = req.getParameter("ui_pb_password_"); try { User user = loginService.login(username, password); // null out passwd password = null; req.setAttribute(SportletProperties.PORTLET_USER, user); session.setAttribute(SportletProperties.PORTLET_USER, user.getID()); if (aclService.hasSuperRole(user)) { log.debug("User: " + user.getUserName() + " logged in as SUPER"); } setUserAndGroups(req); log.debug("Adding User: " + user.getID() + " with session:" + session.getId() + " to usersessionmanager"); userSessionManager.addSession(user, session); layoutEngine.loginPortlets(event); } catch (AuthorizationException err) { log.debug(err.getMessage()); req.setAttribute(LOGIN_ERROR_FLAG, err.getMessage()); } } /** * Handles logout requests * * @param event a <code>GridSphereEvent</code> */ protected void logout(GridSphereEvent event) { log.debug("in logout of GridSphere Servlet"); PortletRequest req = event.getPortletRequest(); PortletSession session = req.getPortletSession(); session.removeAttribute(SportletProperties.PORTLET_USER); userSessionManager.removeSessions(req.getUser()); layoutEngine.logoutPortlets(event); } /** * Method to set the response headers to perform file downloads to a browser * * @param event the gridsphere event * @throws PortletException */ public void downloadFile(GridSphereEvent event) throws PortletException { PortletResponse res = event.getPortletResponse(); PortletRequest req = event.getPortletRequest(); try { String fileName = (String) req.getAttribute(SportletProperties.FILE_DOWNLOAD_NAME); String path = (String) req.getAttribute(SportletProperties.FILE_DOWNLOAD_PATH); if ((fileName == null) || (path == null)) return; log.debug("in downloadFile"); log.debug("filename: " + fileName + " filepath= " + path); File f = new File(path); FileDataSource fds = new FileDataSource(f); res.setContentType(fds.getContentType()); res.setHeader("Content-Disposition", "attachment; filename=" + fileName); DataHandler handler = new DataHandler(fds); handler.writeTo(res.getOutputStream()); } catch (FileNotFoundException e) { log.error("Unable to find file!", e); } catch (SecurityException e) { // this gets thrown if a security policy applies to the file. see java.io.File for details. log.error("A security exception occured!", e); } catch (IOException e) { log.error("Caught IOException", e); //response.sendError(HttpServletResponse.SC_INTERNAL_SERVER,e.getMessage()); } } /** * @see #doGet */ public final void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { doGet(req, res); } /** * Return the servlet info. * * @return a string with the servlet information. */ public final String getServletInfo() { return "GridSphere Servlet 0.9"; } /** * Shuts down the GridSphere portlet container */ public final void destroy() { log.debug("in destroy: Shutting down services"); userSessionManager.destroy(); layoutEngine.destroy(); // Shutdown services factory.shutdownServices(); // shutdown the persistencemanagers PersistenceManagerFactory.shutdown(); System.gc(); } /** * Record the fact that a servlet context attribute was added. * * @param event The session attribute event */ public void attributeAdded(HttpSessionBindingEvent event) { log.debug("attributeAdded('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that a servlet context attribute was removed. * * @param event The session attribute event */ public void attributeRemoved(HttpSessionBindingEvent event) { log.debug("attributeRemoved('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that a servlet context attribute was replaced. * * @param event The session attribute event */ public void attributeReplaced(HttpSessionBindingEvent event) { log.debug("attributeReplaced('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that this ui application has been destroyed. * * @param event The servlet context event */ public void contextDestroyed(ServletContextEvent event) { ServletContext ctx = event.getServletContext(); log.debug("contextDestroyed()"); log.debug("contextName: " + ctx.getServletContextName()); log.debug("context path: " + ctx.getRealPath("")); } /** * Record the fact that this ui application has been initialized. * * @param event The servlet context event */ public void contextInitialized(ServletContextEvent event) { log.debug("contextInitialized()"); ServletContext ctx = event.getServletContext(); log.debug("contextName: " + ctx.getServletContextName()); log.debug("context path: " + ctx.getRealPath("")); } /** * Record the fact that a session has been created. * * @param event The session event */ public void sessionCreated(HttpSessionEvent event) { log.debug("sessionCreated('" + event.getSession().getId() + "')"); sessionManager.sessionCreated(event); } /** * Record the fact that a session has been destroyed. * * @param event The session event */ public void sessionDestroyed(HttpSessionEvent event) { sessionManager.sessionDestroyed(event); log.debug("sessionDestroyed('" + event.getSession().getId() + "')"); } /** * Record the fact that a session has been created. * * @param event The session event */ public void sessionDidActivate(HttpSessionEvent event) { log.debug("sessionDidActivate('" + event.getSession().getId() + "')"); sessionManager.sessionCreated(event); } /** * Record the fact that a session has been destroyed. * * @param event The session event */ public void sessionWillPassivate(HttpSessionEvent event) { sessionManager.sessionDestroyed(event); log.debug("sessionWillPassivate('" + event.getSession().getId() + "')"); } }
package jsceneviewer.inventor.qt; import org.eclipse.swt.SWT; import jscenegraph.database.inventor.SbBasic; import jscenegraph.database.inventor.SbBox3f; import jscenegraph.database.inventor.SbLine; import jscenegraph.database.inventor.SbMatrix; import jscenegraph.database.inventor.SbName; import jscenegraph.database.inventor.SbPlane; import jscenegraph.database.inventor.SbRotation; import jscenegraph.database.inventor.SbSphere; import jscenegraph.database.inventor.SbTime; import jscenegraph.database.inventor.SbVec2f; import jscenegraph.database.inventor.SbVec2s; import jscenegraph.database.inventor.SbVec3f; import jscenegraph.database.inventor.SbViewVolume; import jscenegraph.database.inventor.SbViewportRegion; import jscenegraph.database.inventor.SbXfBox3f; import jscenegraph.database.inventor.SoDB; import jscenegraph.database.inventor.SoFullPath; import jscenegraph.database.inventor.SoPickedPoint; import jscenegraph.database.inventor.SoType; import jscenegraph.database.inventor.actions.SoGetBoundingBoxAction; import jscenegraph.database.inventor.actions.SoRayPickAction; import jscenegraph.database.inventor.actions.SoSearchAction; import jscenegraph.database.inventor.errors.SoDebugError; import jscenegraph.database.inventor.fields.SoSFTime; import jscenegraph.database.inventor.nodes.SoCamera; import jscenegraph.database.inventor.nodes.SoDirectionalLight; import jscenegraph.database.inventor.nodes.SoGroup; import jscenegraph.database.inventor.nodes.SoNode; import jscenegraph.database.inventor.nodes.SoOrthographicCamera; import jscenegraph.database.inventor.nodes.SoPerspectiveCamera; import jscenegraph.database.inventor.nodes.SoResetTransform; import jscenegraph.database.inventor.nodes.SoRotation; import jscenegraph.database.inventor.nodes.SoSwitch; import jscenegraph.database.inventor.projectors.SbSphereSheetProjector; import jscenegraph.database.inventor.sensors.SoFieldSensor; import jscenegraph.database.inventor.sensors.SoNodeSensor; import jscenegraph.database.inventor.sensors.SoSensor; /** * @author Yves Boyadjian * */ //! This class encapsulates the camera (and headlight) handling functions //! for SoQtViewer and derived classes. public abstract class SoQtCameraController { // size of the rotation buffer, which is used to animate the spinning ball. public static final int ROT_BUFF_SIZE = 3; //! An EDITOR viewer will create a camera under the user supplied scene //! graph (specified in setSceneGraph()) if it cannot find one in the //! scene and will leave the camera behind when supplied with a new scene. //! A BROWSER viewer will also create a camera if it cannot find one in //! the scene, but will place it above the scene graph node (camera will //! not appear in the user supplied scene graph), and will automatically //! remove it when another scene is supplied to the viewer. public enum Type { BROWSER, // default viewer type EDITOR }; //! variables used for interpolating seek animations protected float seekDistance; protected boolean seekDistAsPercentage; //! percentage/absolute flag protected boolean computeSeekVariables; protected final SbVec3f seekPoint = new SbVec3f(), seekNormal = new SbVec3f(); protected final SbRotation oldCamOrientation = new SbRotation(), newCamOrientation = new SbRotation(); protected final SbVec3f oldCamPosition = new SbVec3f(), newCamPosition = new SbVec3f(); //! global vars protected Type type; protected SoCamera camera; //! camera being edited protected static SoSFTime realTime; //! pointer to "realTime" global field //! local tree variables protected SoGroup sceneRoot; //! root node given to the RA public SoNode sceneGraph; //! user supplied scene graph protected int cameraIndex; //! where to insert the camera in the sceneRoot in BROWSER mode //! auto clipping vars and routines protected boolean autoClipFlag; protected float minimumNearPlane; //! minimum near plane as percentage of far protected SoGetBoundingBoxAction autoClipBboxAction; //! current state vars private final SoType cameraType = new SoType(); private final SbVec2s sceneSize = new SbVec2s(); //! camera original values, used to restore the camera private boolean createdCamera; private final SbVec3f origPosition = new SbVec3f(); private final SbRotation origOrientation = new SbRotation(); private float origNearDistance; private float origFarDistance; private float origFocalDistance; private float origHeight; //! seek animation vars private boolean seekModeFlag; //! true when seek turned on externally private SoFieldSensor seekAnimationSensor; private boolean detailSeekFlag; private float seekAnimTime; private final SbTime seekStartTime = new SbTime(); //! headlight variables private SoDirectionalLight headlightNode; private SoGroup headlightGroup; private SoGroup headlightParent; private SoRotation headlightRot; private boolean headlightFlag; //! true when headlight in turned on private SoNodeSensor headlightParentSensor; private final SbVec2s startPos = new SbVec2s(); // starting mouse position private SbSphereSheetProjector sphereSheet; private float zoomSensitivity; // variables used for doing spinning animation private SbRotation[] rotBuffer; private int firstIndex, lastIndex; private final SbRotation averageRotation = new SbRotation(); private boolean computeAverage; // camera panning vars private final SbVec3f locator3D = new SbVec3f(); private final SbPlane focalplane = new SbPlane(); public SoQtCameraController(Type t) { sceneSize.copyFrom( new SbVec2s((short)0,(short)0)); // init local vars type = t; sceneGraph = null; sceneRoot = null; cameraIndex = 0; camera = null; cameraType.copyFrom(SoPerspectiveCamera.getClassTypeId()); createdCamera = false; // init auto clipping stuff autoClipFlag = true; minimumNearPlane = 0.001f; autoClipBboxAction = new SoGetBoundingBoxAction(new SbViewportRegion(new SbVec2s((short)1,(short)1))); // ??? no valid size yet // init seek animation variables seekDistance = 50.0f; seekDistAsPercentage = true; seekModeFlag = false; detailSeekFlag = true; seekAnimTime = 2.0f; seekAnimationSensor = new SoFieldSensor(SoQtCameraController::seekAnimationSensorCB, this); // headlightGroup - we have a rotation which keeps the headlight // moving whenever the camera moves, and a reset xform so // that the rest of the scene is not affected by the first rot. // these leaves the direction field in the headlight open for the // user to edit, allowing for the direction to change w.r.t. the camera. headlightGroup = new SoGroup(3); headlightRot = new SoRotation(); headlightNode = new SoDirectionalLight(); headlightGroup.ref(); headlightGroup.addChild(headlightRot); headlightGroup.addChild(headlightNode); headlightGroup.addChild(new SoResetTransform()); headlightNode.direction.setValue(new SbVec3f(.2f, -.2f, -.9797958971f)); headlightFlag = true; headlightParent = null; headlightParentSensor = new SoNodeSensor(); headlightParentSensor.setDeleteCallback(SoQtCameraController::headlightParentDeletedCB, this); rotBuffer = new SbRotation[ROT_BUFF_SIZE]; // init the projector class final SbViewVolume vv = new SbViewVolume(); vv.ortho(-1, 1, -1, 1, -10, 10); sphereSheet = new SbSphereSheetProjector(); sphereSheet.setViewVolume( vv ); sphereSheet.setSphere( new SbSphere( new SbVec3f(0, 0, 0), .7f) ); zoomSensitivity = 1.0f; } public void destructor() { // delete everything sphereSheet = null; rotBuffer = null; seekAnimationSensor.destructor(); seekAnimationSensor = null; headlightParentSensor.destructor(); headlightParentSensor = null; autoClipBboxAction.destructor(); autoClipBboxAction = null; headlightGroup.unref(); } //! Set scene root node and at which index to insert the camera in BROWSER mode public void setSceneRoot(SoGroup root, int camIndex) { sceneRoot = root; cameraIndex = camIndex; } public void setSceneGraph(SoNode newScene) { // detach everything that depends on the old sceneGraph if ( sceneGraph != null ) { setCamera(null, false); sceneRoot.removeChild(sceneGraph); } sceneGraph = newScene; // now assign the new sceneGraph, find or create the new camera // and attach things back. if ( sceneGraph != null ) { sceneRoot.addChild(sceneGraph); // search for first camera in the scene final SoSearchAction sa = new SoSearchAction(); sa.setType(SoCamera.getClassTypeId()); sa.setSearchingAll(false); // don't look under off switches sa.apply(sceneGraph); SoCamera newCamera = null; if (sa.getPath() != null) { newCamera = (SoCamera )( new SoFullPath (sa.getPath())).getTail(); } // if no camera found create one of the right kind... if ( newCamera == null ) { newCamera = (SoCamera) cameraType.createInstance(); if (newCamera == null) { //#ifdef DEBUG SoDebugError.post("SoQtCameraController::setSceneGraph", "unknown camera type!"); //#endif // ??? what should we do here ? cameraType.copyFrom(SoPerspectiveCamera.getClassTypeId()); newCamera = new SoPerspectiveCamera(); } if (type == SoQtCameraController.Type.BROWSER) { // add camera after drawstyle stuff sceneRoot.insertChild(newCamera, cameraIndex); } else { // check to make sure scene starts with at least a group node if ( sceneGraph.isOfType(SoGroup.getClassTypeId()) ) { ((SoGroup )sceneGraph).insertChild(newCamera, 0); } else { // make scene start with a group node SoGroup group = new SoGroup(); group.addChild(newCamera); group.addChild(sceneGraph); sceneRoot.addChild(group); sceneRoot.removeChild(sceneGraph); sceneGraph = group; } } newCamera.viewAll(sceneGraph, new SbViewportRegion(sceneSize)); setCamera(newCamera, true); } else { setCamera(newCamera, false); } } } //! Set and get the edited camera. setCamera() is only needed if the //! first camera found when setSceneGraph() is called isn't the one //! the user really wants to edit. //! cameraCreated should be true if the camera was only created for this viewer. public abstract void setCamera(SoCamera newCamera, boolean cameraCreated); public void doSetCamera(SoCamera newCamera, boolean cameraCreated) { // check for trivual return if (camera == newCamera) { return; } // detach everything that depended on the old camera if ( camera != null ) { if (headlightFlag) { setHeadlight(false); headlightFlag = true; // can later be turned on } // scene graph. if (this.createdCamera && type == SoQtCameraController.Type.BROWSER) { if (sceneRoot.findChild(camera) >= 0) { sceneRoot.removeChild(camera); } this.createdCamera = false; } camera.unref(); } camera = newCamera; // attach everything that depends on the new camera if ( camera != null) { camera.ref(); this.createdCamera = cameraCreated; if (headlightFlag) { headlightFlag = false; // enables the routine to be called setHeadlight(true); } saveHomePosition(); } } public SoCamera getCamera() { return camera; } //! This routine will toggle the current camera from perspective to //! orthographic, and from orthographic back to perspective. public void toggleCameraType() { if (camera == null) { return; } // create the camera of the opposite kind and compute the wanted height // or heightAngle of the new camera. SoCamera newCam; if (camera.isOfType(SoPerspectiveCamera.getClassTypeId())) { float angle = ((SoPerspectiveCamera )camera).heightAngle.getValue(); float height = camera.focalDistance.getValue() * (float)Math.tan(angle/2); newCam = new SoOrthographicCamera(); ((SoOrthographicCamera )newCam).height.setValue( 2 * height); } else if (camera.isOfType(SoOrthographicCamera.getClassTypeId())) { float height = ((SoOrthographicCamera )camera).height.getValue() / 2; float angle = (float)Math.atan(height / camera.focalDistance.getValue()); newCam = new SoPerspectiveCamera(); ((SoPerspectiveCamera )newCam).heightAngle.setValue( 2 * angle); } else { //#ifdef DEBUG SoDebugError.post("SoQtCameraController::toggleCameraType", "unknown camera type!"); //#endif return; } newCam.ref(); // copy common stuff from the old to the new camera newCam.viewportMapping.setValue( camera.viewportMapping.getValue()); newCam.position.setValue( camera.position.getValue()); newCam.orientation.setValue( camera.orientation.getValue()); newCam.aspectRatio.setValue( camera.aspectRatio.getValue()); newCam.focalDistance.setValue( camera.focalDistance.getValue()); // search for the old camera and replace it by the new camera final SoSearchAction sa = new SoSearchAction(); sa.setNode(camera); sa.apply(sceneRoot); SoFullPath fullCamPath = new SoFullPath ( sa.getPath()); if (fullCamPath != null) { SoGroup parent = (SoGroup )fullCamPath.getNode(fullCamPath.getLength() - 2); parent.insertChild(newCam, parent.findChild(camera)); SoCamera oldCam = camera; setCamera(newCam, true); // remove the old camera if it is still there (setCamera() might // have removed it) and set the created flag to true (for next time) if (parent.findChild(oldCam) >= 0) { parent.removeChild(oldCam); } //#ifdef DEBUG } else { SoDebugError.post("SoQtCameraController::toggleCameraType", "camera not found!"); //#endif } newCam.unref(); } public void arrowKeyPressed (int key) { if (camera == null) { return; } // get the camera near plane height value float dist = 0.0f; if (camera.isOfType(SoPerspectiveCamera.getClassTypeId())) { float angle = ((SoPerspectiveCamera )camera).heightAngle.getValue(); float length = camera.nearDistance.getValue(); dist = length * (float)Math.tan(angle); } else if (camera.isOfType(SoOrthographicCamera.getClassTypeId())) { dist = ((SoOrthographicCamera )camera).height.getValue(); } dist /= 2.0; // get camera right/left/up/down direction final SbMatrix mx = new SbMatrix(); mx.copyFrom( camera.orientation.getValue().getMatrix()); final SbVec3f dir = new SbVec3f(); switch(key) { case SWT.ARROW_UP: dir.setValue(mx.getValue()[1][0], mx.getValue()[1][1], mx.getValue()[1][2]); break; case SWT.ARROW_DOWN: dir.setValue(-mx.getValue()[1][0], -mx.getValue()[1][1], -mx.getValue()[1][2]); break; case SWT.ARROW_RIGHT: dir.setValue(mx.getValue()[0][0], mx.getValue()[0][1], mx.getValue()[0][2]); dist *= camera.aspectRatio.getValue(); break; case SWT.ARROW_LEFT: dir.setValue(-mx.getValue()[0][0], -mx.getValue()[0][1], -mx.getValue()[0][2]); dist *= camera.aspectRatio.getValue(); break; } // finally reposition the camera camera.position.setValue(camera.position.getValue().operator_add(dir.operator_mul(dist))); } public void viewAll() { if ( camera != null ) { camera.viewAll(sceneGraph, new SbViewportRegion(sceneSize)); } } public void updateHeadlight() { // update the headlight if necessary if (headlightFlag && camera != null) { // only update if the value is different, otherwise we get ping-pong effects // if the same camera is used for different viewers if (headlightRot.rotation.getValue() != camera.orientation.getValue()) { headlightRot.rotation.setValue(camera.orientation.getValue()); } } } public void saveHomePosition() { if (camera == null) { return; } origPosition.copyFrom(camera.position.getValue()); origOrientation.copyFrom(camera.orientation.getValue()); origNearDistance = camera.nearDistance.getValue(); origFarDistance = camera.farDistance.getValue(); origFocalDistance = camera.focalDistance.getValue(); // save camera height (changed by zooming) if (camera.isOfType(SoPerspectiveCamera.getClassTypeId())) { origHeight = ((SoPerspectiveCamera )camera).heightAngle.getValue(); } else if (camera.isOfType(SoOrthographicCamera.getClassTypeId())) { origHeight = ((SoOrthographicCamera )camera).height.getValue(); } } public void resetToHomePosition() { if (camera == null) { return; } camera.position.setValue( origPosition); camera.orientation.setValue( origOrientation); camera.nearDistance.setValue( origNearDistance); camera.farDistance.setValue( origFarDistance); camera.focalDistance.setValue( origFocalDistance); // restore camera height (changed by zooming) if (camera.isOfType(SoPerspectiveCamera.getClassTypeId())) { ((SoPerspectiveCamera )camera).heightAngle.setValue(origHeight); } else if (camera.isOfType(SoOrthographicCamera.getClassTypeId())) { ((SoOrthographicCamera )camera).height.setValue(origHeight); } } public boolean seekToPoint(final SbVec2s mouseLocation) { if (camera == null) { setSeekMode(false); return false; } // do the picking // Use assignment notation to disambiguate from expression (edison) final SoRayPickAction pick = new SoRayPickAction(new SbViewportRegion(sceneSize)); pick.setPoint(mouseLocation); pick.setRadius(1.0f); pick.setPickAll(false); // pick only the closest object pick.apply(sceneRoot); // makes sure something got picked SoPickedPoint pp = pick.getPickedPoint(); if ( pp == null ) { setSeekMode(false); return false; } // Get picked point and normal if detailtSeek if (detailSeekFlag) { seekPoint.copyFrom( pp.getPoint()); seekNormal.copyFrom( pp.getNormal()); // check to make sure normal points torward the camera, else // flip the normal around if ( seekNormal.dot(camera.position.getValue().operator_minus(seekPoint)) < 0 ) { seekNormal.negate(); } } // else get object bounding box as the seek point and the camera // orientation as the normal. else { // get center of object's bounding box // Use assignment notation to disambiguate from expression (edison) final SoGetBoundingBoxAction bba = new SoGetBoundingBoxAction(new SbViewportRegion(sceneSize)); bba.apply(pp.getPath()); final SbBox3f bbox = bba.getBoundingBox(); seekPoint.copyFrom( bbox.getCenter()); // keep the camera oriented the same way final SbMatrix mx = new SbMatrix(); mx.copyFrom( camera.orientation.getValue()); seekNormal.setValue(mx.getValue()[2][0], mx.getValue()[2][1], mx.getValue()[2][2]); } // now check if animation sensor needs to be scheduled computeSeekVariables = true; if (seekAnimTime == 0) { // jump to new location, no animation needed interpolateSeekAnimation(1.0f); } else { // schedule sensor and call viewer start callbacks if ( seekAnimationSensor.getAttachedField() == null ) { seekAnimationSensor.attach(getRealTime()); seekAnimationSensor.schedule(); animationStarted(); } seekStartTime.copyFrom(getRealTime().getValue()); } return true; // successfull } public SoNode getSceneGraph() { return sceneGraph; } public void setSceneSize(final SbVec2s size) { sceneSize.copyFrom( size); } private static void seekAnimationSensorCB(Object p, SoSensor sensor) { SoQtCameraController v = (SoQtCameraController )p; // get the time difference SbTime time = getRealTime().getValue(); float sec = (float)((time.operator_minus(v.seekStartTime)).getValue()); if (sec == 0.0) { sec = 1.0f/72.0f; // at least one frame (needed for first call) } float t = (sec / v.seekAnimTime); // check to make sure the values are correctly clipped if (t > 1.0) { t = 1.0f; } else if ((1.0 - t) < 0.0001) { t = 1.0f; // this will be the last one... } // call subclasses to interpolate the animation v.interpolateSeekAnimation(t); // stops seek if this was the last interval if (t == 1.0) { v.setSeekMode(false); } } private static void headlightParentDeletedCB(Object p, SoSensor sensor) { // headlightParent has been deleted ((SoQtCameraController)p).headlightParent = null; } private static SoSFTime getRealTime() { if ( realTime == null) { realTime = (SoSFTime ) SoDB.getGlobalField(new SbName("realTime")); } return realTime; } //! Externally set the viewer into/out off seek mode (default OFF). Actual //! seeking will not happen until the viewer decides to (ex: mouse click). //! Note: setting the viewer out of seek mode while the camera is being //! animated will stop the animation to the current location. public abstract void setSeekMode(boolean flag); public void doSetSeekMode(boolean flag) { // check if seek is being turned off while seek animation is happening if ( !flag && seekAnimationSensor.getAttachedField() != null ) { seekAnimationSensor.detach(); seekAnimationSensor.unschedule(); animationFinished(); } seekModeFlag = flag; } public boolean isSeekMode() { return seekModeFlag; } protected abstract void animationStarted(); protected abstract void animationFinished(); //! Subclasses CAN redefine this to interpolate camera position/orientation //! while the seek animation is going on (called by animation sensor). //! The parameter t is a [0,1] value corresponding to the animation percentage //! completion. (i.e. a value of 0.25 means that animation is only 1/4 of the way //! through). protected void interpolateSeekAnimation(float t) { if (camera == null) { return; } // check if camera new and old position/orientation have already // been computed. if (computeSeekVariables) { final SbMatrix mx = new SbMatrix(); final SbVec3f viewVector = new SbVec3f(); // save camera starting point oldCamPosition.copyFrom(camera.position.getValue()); oldCamOrientation.copyFrom(camera.orientation.getValue()); // compute the distance the camera will be from the seek point // and update the camera focalDistance. float dist; if ( seekDistAsPercentage ) { final SbVec3f seekVec = new SbVec3f(seekPoint.operator_minus(camera.position.getValue())); dist = seekVec.length() * (seekDistance / 100.0f); } else { dist = seekDistance; } camera.focalDistance.operator_assign(dist); // let subclasses have a chance to redefine what the // camera final orientation should be. computeSeekFinalOrientation(); // find the camera final position based on orientation and distance mx.operator_assign(newCamOrientation); viewVector.setValue(-mx.getValue()[2][0], -mx.getValue()[2][1], -mx.getValue()[2][2]); newCamPosition.copyFrom(seekPoint.operator_minus(viewVector.operator_mul(dist))); computeSeekVariables = false; } // Now position the camera according to the animation time // use and ease-in ease-out approach float cos_t = 0.5f - 0.5f * (float)Math.cos(t * SbBasic.M_PI); // get camera new rotation camera.orientation.operator_assign(SbRotation.slerp(oldCamOrientation, newCamOrientation, cos_t)); // get camera new position camera.position.operator_assign(oldCamPosition.operator_add((newCamPosition.operator_minus(oldCamPosition)).operator_mul(cos_t))); } public void adjustCameraClippingPlanes() { if (camera == null) { return; } // get the scene bounding box autoClipBboxAction.setViewportRegion(new SbViewportRegion(sceneSize)); autoClipBboxAction.apply(sceneRoot); final SbXfBox3f xfbbox = autoClipBboxAction.getXfBoundingBox(); // get camera transformation and apply to xfbbox // to align the bounding box to camera space. // This will enable us to simply use the z values of the // transformed bbox for near and far plane values. final SbMatrix mx = new SbMatrix(); mx.setTranslate(camera.position.getValue().operator_minus()); xfbbox.transform(mx); mx.copyFrom(camera.orientation.getValue().inverse().getMatrix()); xfbbox.transform(mx); // get screen align bbox and figure the near and far plane values SbBox3f bbox = xfbbox.project(); // take negative value and opposite to what one might think // because the camera points down the -Z axis float farDist = - bbox.getMin().getValue()[2]; float nearDist = - bbox.getMax().getValue()[2]; // scene is behind the camera so don't change the planes if (farDist < 0) { return; } // check for minimum near plane value (Value will be negative // when the camera is inside the bounding box). // Note: there needs to be a minimum near value for perspective // camera because of zbuffer resolution problem (plus the values // has to be positive). There is no such restriction for // an Orthographic camera (you can see behind you). if (! camera.isOfType(SoOrthographicCamera.getClassTypeId())) { if (nearDist < (minimumNearPlane * farDist)) { nearDist = minimumNearPlane * farDist; } } // give the near and far distances a little bit of slack in case // the object lies against the bounding box, otherwise the object // will be poping in and out of view. // (example: a cube is the same as it's bbox) nearDist *= 0.999; farDist *= 1.001; // finally assign camera plane values if (camera.nearDistance.getValue() != nearDist) camera.nearDistance.setValue(nearDist); if (camera.farDistance.getValue() != farDist) camera.farDistance.setValue(farDist); } protected void computeSeekFinalOrientation() { final SbMatrix mx = new SbMatrix(); final SbVec3f viewVector = new SbVec3f(); // find the camera final orientation if ( isDetailSeek() ) { // get the camera new orientation mx.operator_assign( camera.orientation.getValue()); viewVector.setValue(-mx.getValue()[2][0], -mx.getValue()[2][1], -mx.getValue()[2][2]); final SbRotation changeOrient = new SbRotation(); changeOrient.setValue(viewVector, seekPoint.operator_minus( camera.position.getValue())); newCamOrientation.copyFrom( camera.orientation.getValue().operator_mul( changeOrient)); } else { newCamOrientation.copyFrom( camera.orientation.getValue()); } } //! Seek methods //! Routine to determine whether or not to orient camera on //! picked point (detail on) or center of the object's bounding box //! (detail off). Default is detail on. public void setDetailSeek(boolean onOrOff) { detailSeekFlag = onOrOff; }; public boolean isDetailSeek() { return detailSeekFlag; } public void setHeadlight(boolean insertFlag) { // check for trivial return if (camera == null || headlightFlag == insertFlag) { headlightFlag = insertFlag; return; } if (headlightParent != null) { // remove previous headlight if (headlightParent.findChild(headlightGroup) >= 0) { headlightParent.removeChild(headlightGroup); } headlightParentSensor.detach(); headlightParent = null; } // find the camera parent to insert the headlight if (insertFlag) { final SoSearchAction sa = new SoSearchAction(); sa.setNode(camera); sa.apply(sceneRoot); SoFullPath fullPath = new SoFullPath ( sa.getPath()); if (fullPath == null) { //#if DEBUG SoDebugError.post("SoQtCameraController::setHeadlight", "ERROR: cannot find camera in graph"); //#endif // don't update the headlightFlag: return; } headlightParent = (SoGroup ) fullPath.getNodeFromTail(1); // inserts the headlight group node int camIndex; // check to make sure that the camera parent is not a switch node // (VRML camera viewpoints are kept under a switch node). Otherwise // we will insert the headlight right after the switch node. if (headlightParent.isOfType(SoSwitch.getClassTypeId())) { SoNode switchNode = headlightParent; headlightParent = (SoGroup ) fullPath.getNodeFromTail(2); camIndex = headlightParent.findChild(switchNode); } else { camIndex = headlightParent.findChild(camera); } // so we get notified if the headlightParent goes away: headlightParentSensor.attach(headlightParent); if (headlightParent.findChild(headlightGroup) < 0) { // insert the light group right after the camera if (camIndex >= 0) { headlightParent.insertChild(headlightGroup, camIndex+1); } } } // we must still update the headlightFlag headlightFlag = insertFlag; } public boolean isHeadlight() { return headlightFlag; } //! Set and get the auto clipping plane. When auto clipping is ON, the //! camera near and far planes are dynamically adjusted to be as tight //! as possible (least amount of stuff is clipped). When OFF, the user //! is expected to manually set those planes within the preference sheet. //! (default is ON). public void setAutoClipping(boolean flag) { autoClipFlag = flag; } public boolean isAutoClipping() { return autoClipFlag; } public boolean isPerspective() { return (camera != null) && camera.isOfType(SoPerspectiveCamera.getClassTypeId()); } public boolean isOrthographic() { return (camera != null) && camera.isOfType(SoOrthographicCamera.getClassTypeId()); } public void rotateCamera(final SbRotation rot) { if (camera == null) { return; } // get center of rotation SbRotation camRot = camera.orientation.getValue(); float radius = camera.focalDistance.getValue(); final SbMatrix mx = new SbMatrix(); mx.copyFrom(camRot.getMatrix()); final SbVec3f forward = new SbVec3f( -mx.getValue()[2][0], -mx.getValue()[2][1], -mx.getValue()[2][2]); final SbVec3f center = camera.position.getValue().operator_add(forward.operator_mul(radius)); // apply new rotation to the camera camRot = rot.operator_mul(camRot); camera.orientation.setValue(camRot); // reposition camera to look at pt of interest mx.copyFrom(camRot.getMatrix()); forward.setValue( -mx.getValue()[2][0], -mx.getValue()[2][1], -mx.getValue()[2][2]); camera.position.setValue( center.operator_minus(forward.operator_mul(radius))); } public void zoomCamera (float amount) { // NOTE: perhaps make minFocalDist and minCameraHeight configurable later final float minFocalDist = 0.01f; final float minCameraHeight = 0.01f; if (camera == null) { return; } if (camera.isOfType(SoOrthographicCamera.getClassTypeId())) { // change the ortho camera height SoOrthographicCamera cam = (SoOrthographicCamera ) camera; float height = cam.height.getValue() * (float)Math.pow(2.0, amount); height = (height < minCameraHeight) ? minCameraHeight : height; cam.height.setValue( height); } else { // shorter/grow the focal distance given the mouse move float focalDistance = camera.focalDistance.getValue();; float newFocalDist = focalDistance * (float)Math.pow(2.0, amount); newFocalDist = (newFocalDist < minFocalDist) ? minFocalDist : newFocalDist; // finally reposition the camera final SbMatrix mx = new SbMatrix(); mx.copyFrom( camera.orientation.getValue().getMatrix()); final SbVec3f forward = new SbVec3f(-mx.getValue()[2][0], -mx.getValue()[2][1], -mx.getValue()[2][2]); camera.position.setValue(camera.position.getValue().operator_add( forward.operator_mul((focalDistance - newFocalDist)))); camera.focalDistance.setValue( newFocalDist); } } public void panCamera(final SbVec2s newPos) { if (camera == null) { return; } final SbVec2f newLocator = new SbVec2f(newPos.getValue()[0]/(float)(sceneSize.getValue()[0]), newPos.getValue()[1]/(float)(sceneSize.getValue()[1])); // map new mouse location into the camera focal plane final SbViewVolume cameraVolume = new SbViewVolume(); final SbLine line = new SbLine(); final SbVec3f newLocator3D = new SbVec3f(); cameraVolume.copyFrom(camera.getViewVolume(sceneSize.getValue()[0]/(float)(sceneSize.getValue()[1]))); cameraVolume.projectPointToLine(newLocator, line); focalplane.intersect(line, newLocator3D); // move the camera by the delta 3D position amount camera.position.setValue(camera.position.getValue().operator_add( (locator3D.operator_minus(newLocator3D)))); // You would think we would have to set locator3D to // newLocator3D here. But we don't, because moving the camera // essentially makes locator3D equal to newLocator3D in the // transformed space, and we will project the next newLocator3D in // this transformed space. } public void spinCamera(final SbVec2s newPos) { final SbVec2f newLocator = new SbVec2f(newPos.getValue()[0]/(float)(sceneSize.getValue()[0]), newPos.getValue()[1]/(float)(sceneSize.getValue()[1])); // find rotation and rotate camera final SbRotation rot = new SbRotation(); sphereSheet.projectAndGetRotation(newLocator, rot); rot.invert(); rotateCamera(rot); // save rotation for animation lastIndex = ((lastIndex+1) % ROT_BUFF_SIZE); rotBuffer[lastIndex] = rot; computeAverage = true; // check if queue is full if (((lastIndex+1) % ROT_BUFF_SIZE) == firstIndex) { firstIndex = ((firstIndex+1) % ROT_BUFF_SIZE); } } public void dollyCamera(final SbVec2s newPos) { // moving the mouse up/down will move the camera futher/closer. // moving the camera sideway will not move the camera at all zoomCamera ((newPos.getValue()[1] - startPos.getValue()[1]) * zoomSensitivity / 40.0f); startPos.copyFrom( newPos); } static final float maxSpinAngle = (float)(5.0/180.0*3.1415927); // max. 5 degrees per step public boolean doSpinAnimation() { // check if average rotation needs to be computed if (computeAverage) { float averageAngle; final float[] angle = new float[1]; final SbVec3f averageAxis = new SbVec3f(), axis = new SbVec3f(); // get number of samples int num = (((lastIndex - firstIndex) + 1 + ROT_BUFF_SIZE) % ROT_BUFF_SIZE); // check for not enough samples if (num < 2) { return false; } // get average axis of rotation // ??? right now only take one sample rotBuffer[firstIndex].getValue(averageAxis, angle); // get average angle of rotation averageAngle = 0; for (int i=0; i<num; i++) { int n = (firstIndex + i) % ROT_BUFF_SIZE; rotBuffer[n].getValue(axis, angle); averageAngle += angle[0]; } averageAngle /= (float)(num); // make rotation slower: averageAngle *= 0.5; // restrict rotation speed: if (averageAngle > maxSpinAngle) { averageAngle = maxSpinAngle; } averageRotation.setValue(averageAxis, averageAngle); computeAverage = false; } // rotate camera by average rotation rotateCamera(averageRotation); return true; } public void startDrag(final SbVec2s pos) { startPos.copyFrom(pos); final SbVec2f relLocator = new SbVec2f(startPos.getValue()[0]/(float)(sceneSize.getValue()[0]), startPos.getValue()[1]/(float)(sceneSize.getValue()[1])); // set the sphere sheet starting point sphereSheet.project(relLocator); // reset the animation queue firstIndex = 0; lastIndex = -1; if (camera == null) { return; } // Figure out the focal plane final SbMatrix mx = new SbMatrix(); mx.copyFrom(camera.orientation.getValue().getMatrix()); final SbVec3f forward = new SbVec3f(-mx.getValue()[2][0], -mx.getValue()[2][1], -mx.getValue()[2][2]); final SbVec3f fp = camera.position.getValue().operator_add( forward.operator_mul(camera.focalDistance.getValue())); focalplane.copyFrom(new SbPlane(forward, fp)); // map mouse starting position onto the panning plane final SbViewVolume cameraVolume = new SbViewVolume(); final SbLine line = new SbLine(); cameraVolume.copyFrom(camera.getViewVolume(sceneSize.getValue()[0]/(float)(sceneSize.getValue()[1]))); cameraVolume.projectPointToLine(relLocator, line); focalplane.intersect(line, locator3D); } }
package org.opencms.xml.xml2json; import org.opencms.file.CmsObject; import org.opencms.json.JSONArray; import org.opencms.json.JSONException; import org.opencms.json.JSONObject; import org.opencms.main.CmsException; import org.opencms.main.OpenCms; import org.opencms.xml.content.CmsXmlContent; import org.opencms.xml.types.CmsXmlBooleanValue; import org.opencms.xml.types.CmsXmlDateTimeValue; import org.opencms.xml.types.CmsXmlVarLinkValue; import org.opencms.xml.types.CmsXmlVfsFileValue; import org.opencms.xml.types.I_CmsXmlContentValue; import org.opencms.xml.xml2json.CmsXmlContentTree.Field; import org.opencms.xml.xml2json.CmsXmlContentTree.Node; import java.util.List; import java.util.Locale; /** * Converts an XML content to JSON by creating a CmsXmlContentTree and then recursively processing its nodes. * * <p>This specific renderer class does not need to be initialized with a CmsJsonHandlerContext, you can * just initialize it with a CmsObject. */ public class CmsDefaultXmlContentJsonRenderer implements I_CmsXmlContentJsonRenderer { /** The CMS context. */ private CmsObject m_cms; /** The root Cms context. */ private CmsObject m_rootCms; /** * Creates a new instance. * * If this constructor is used, you still have to call one of the initialize() methods before rendering XML content to JSON. */ public CmsDefaultXmlContentJsonRenderer() { // do nothing } /** * Creates a new instance. * * @param cms the CMS context to use * @throws CmsException if something goes wrong */ public CmsDefaultXmlContentJsonRenderer(CmsObject cms) throws CmsException { initialize(cms); } /** * Builds a simple JSON object with link and path fields whose values are taken from the corresponding parameters. * * <p>If path is null, it will not be added to the result JSON. * * @param link the value for the link field * @param path the value for the path field * @return the link-and-path object * @throws JSONException if something goes wrong */ public static JSONObject linkAndPath(String link, String path) throws JSONException { JSONObject result = new JSONObject(); int paramPos = path.indexOf("?"); if (paramPos != -1) { path = path.substring(0, paramPos); } result.put("link", link); if (path != null) { result.put("path", path); } return result; } /** * Helper method to apply renderer to all locales of an XML content, and put the resulting objects into a JSON object with the locales as keys. * * @param content the content * @param renderer the renderer to use * @return the result JSON * @throws JSONException if something goes wrong */ public static JSONObject renderAllLocales(CmsXmlContent content, I_CmsXmlContentJsonRenderer renderer) throws JSONException { List<Locale> locales = content.getLocales(); JSONObject result = new JSONObject(true); for (Locale locale : locales) { Object jsonForLocale = renderer.render(content, locale); result.put(locale.toString(), jsonForLocale); } return result; } /** * @see org.opencms.xml.xml2json.I_CmsXmlContentJsonRenderer#initialize(org.opencms.xml.xml2json.CmsJsonHandlerContext) */ public void initialize(CmsJsonHandlerContext context) throws CmsException { initialize(context.getCms()); } /** * Initializes the renderer. * * @param cms the CMS context to use * * @throws CmsException if something goes wrong */ public void initialize(CmsObject cms) throws CmsException { m_cms = cms; m_rootCms = OpenCms.initCmsObject(m_cms); m_rootCms.getRequestContext().setSiteRoot(""); } /** * @see org.opencms.xml.xml2json.I_CmsXmlContentJsonRenderer#render(org.opencms.xml.content.CmsXmlContent, java.util.Locale) */ @Override public Object render(CmsXmlContent content, Locale locale) throws JSONException { CmsXmlContentTree tree = new CmsXmlContentTree(content, locale); Node root = tree.getRoot(); return renderNode(root); } /** * Renders a tree field as a field in the given JSON object. * * @param field the field to render * @param result the result in which to put the field * * @throws JSONException if something goes wrong */ protected void renderField(Field field, JSONObject result) throws JSONException { String name = field.getName(); if (field.isMultivalue()) { // If field is *potentially* multivalue, // we always generate a JSON array for the sake of consistency, // no matter how many actual values we currently have JSONArray array = new JSONArray(); if (field.getFieldDefinition().isChoiceType()) { // Multiple choice values can be represented by either a multivalued field of single-valued choices, // or a single-valued field of multivalue choices. Using both in combination doesn't seem to make sense. // So we collapse consecutive choice values in a multivalue field to give a uniform JSON syntax for the two // cases to make the JSON easier to work with, but we lose some information about the structure of the XML. for (Node subNode : field.getNodes()) { JSONArray choiceJson = (JSONArray)renderNode(subNode); array.append(choiceJson); } } else { for (Node subNode : field.getNodes()) { array.put(renderNode(subNode)); } } result.put(name, array); } else if (field.getNodes().size() == 1) { if (field.getFieldDefinition().isChoiceType() && !field.isMultiChoice()) { // field *and* choice single-valued, so we can unwrap the single value JSONArray array = (JSONArray)renderNode(field.getNode()); if (array.length() == 1) { result.put(name, array.get(0)); } } else { result.put(name, renderNode(field.getNodes().get(0))); } } } /** * Renders a tree node as JSON. * * @param node the tree node * @return the JSON (may be JSONObject, JSONArray, or String) * * @throws JSONException if something goes wrong */ protected Object renderNode(Node node) throws JSONException { switch (node.getType()) { case sequence: List<Field> fields = node.getFields(); JSONObject result = new JSONObject(true); for (Field field : fields) { renderField(field, result); } return result; case choice: JSONArray array = new JSONArray(); for (Field field : node.getFields()) { JSONObject choiceObj = new JSONObject(true); renderField(field, choiceObj); array.put(choiceObj); } return array; case simple: Object valueJson = renderSimpleValue(node); return valueJson; default: throw new IllegalArgumentException("Unsupported node: " + node.getType()); } } /** * Renders a simple value (i.e. not a nested content). * * @param node the node * @return the JSON representation for the value * @throws JSONException if something goes wrong */ protected Object renderSimpleValue(Node node) throws JSONException { I_CmsXmlContentValue value = node.getValue(); if (value instanceof I_CmsJsonFormattableValue) { return ((I_CmsJsonFormattableValue)value).toJson(m_cms); } else if (value instanceof CmsXmlVfsFileValue) { CmsXmlVfsFileValue fileValue = (CmsXmlVfsFileValue)value; String link = fileValue.getLink(m_cms).getLink(m_cms); String path = fileValue.getStringValue(m_rootCms); return linkAndPath(link, path); } else if (value instanceof CmsXmlVarLinkValue) { CmsXmlVarLinkValue linkValue = (CmsXmlVarLinkValue)value; // Use the CmsObject with current site for the link, so that the resulting link // works in the context (i.e. domain) of the original JSON handler request, // but CmsObject with site set to root site so we get the root path, which // can then be used to construct further JSON handler URLs. String link = linkValue.getLink(m_cms).getLink(m_cms); String path = linkValue.getStringValue(m_rootCms); if (path.startsWith("http")) { // external link path = null; } return linkAndPath(link, path); } else if (value instanceof CmsXmlBooleanValue) { Boolean result = Boolean.valueOf(((CmsXmlBooleanValue)value).getBooleanValue()); return result; } else if (value instanceof CmsXmlDateTimeValue) { return Double.valueOf(((CmsXmlDateTimeValue)value).getDateTimeValue()); } else { return node.getValue().getStringValue(m_cms); } } }
package org.opencraft.server.model.impl.builders; import java.util.Random; import java.util.Queue; import java.awt.Point; import java.util.LinkedList; import java.util.ArrayList; import java.lang.Math; import org.opencraft.server.model.Builder; import org.opencraft.server.model.BlockConstants; import org.opencraft.server.model.Position; import org.opencraft.server.model.Level; import org.slf4j.*; /** * Builds a level. * @author Trever Fischer <tdfischer@fedoraproject.org> */ public class LandscapeBuilder extends Builder { public LandscapeBuilder(Level level) { super(level); } private static final Logger logger = LoggerFactory.getLogger(LandscapeBuilder.class); public void generate() { m_seed = m_random.nextInt(); generateTerrain(); //raiseTerrain(); buildLavaBed(2); simulateOceanFlood(); //plantTrees(); } public void generateTerrain() { for(int x = 0;x<m_width;x++) { for(int y = 0;y<m_height;y++) { double value; value = getValue(x/200.0, y/200.0, m_depth/2/200.0); int height = (int)(Math.max(-1,Math.min(1, value))*m_depth/4); for(int z = 0;z<m_depth/2+height-5;z++) { m_blocks[x][y][z] = BlockConstants.STONE; } for(int z = m_depth/2+height-5;z<m_depth/2+height;z++) { m_blocks[x][y][z] = BlockConstants.DIRT; } m_blocks[x][y][m_depth/2+height] = BlockConstants.GRASS; for(int z = m_depth/2+height+1;z<m_depth;z++) { m_blocks[x][y][z] = BlockConstants.AIR; } } } } private double m_frequency = 3.0; private double m_lacunarity = 2.0; private int m_noiseQuality = 0; private int m_octaveCount = 6; private double m_persistence = 0.5; private int m_seed = 0; private double getValue(double x, double y, double z) { double value = 0.0; double signal = 0.0; double curPersistence = 1.0; double nx, ny, nz; int seed; x *= m_frequency; y *= m_frequency; z *= m_frequency; for(int curOctave = 0;curOctave < m_octaveCount;curOctave++) { nx = MakeInt32Range(x); ny = MakeInt32Range(y); nz = MakeInt32Range(z); seed = (m_seed+curOctave) & 0xffffffff; signal = GradientCoherentNoise3D(nx, ny, nz, seed, m_noiseQuality); value += signal * curPersistence; x *= m_lacunarity; y *= m_lacunarity; z *= m_lacunarity; curPersistence *= m_persistence; } return value; } private double MakeInt32Range(double n) { return n; /*if (n >= 1073741824.0) { return (2.0 * (n % 1073741824.0)) - 1073741824.0; } else if (n <= -1073741824.0) { return (2.0 * (n % 1073741824.0)) + 1073741824.0; } else { return n; }*/ } private double GradientCoherentNoise3D(double x, double y, double z, int seed, int quality) { // Create a unit-length cube aligned along an integer boundary. This cube // surrounds the input point. int x0 = (x > 0.0? (int)x: (int)x - 1); int x1 = x0 + 1; //int y0 = (y > 0.0? (int)y: (int)y - 1); int y0 = (int)y; int y1 = y0 + 1; int z0 = (z > 0.0? (int)z: (int)z - 1); int z1 = z0 + 1; // Map the difference between the coordinates of the input value and the // coordinates of the cube's outer-lower-left vertex onto an S-curve. double xs = 0, ys = 0, zs = 0; switch (quality) { case 0: xs = (x - (double)x0); ys = (y - (double)y0); zs = (z - (double)z0); break; case 1: xs = SCurve3 (x - (double)x0); ys = SCurve3 (y - (double)y0); zs = SCurve3 (z - (double)z0); break; case 2: xs = SCurve5 (x - (double)x0); ys = SCurve5 (y - (double)y0); zs = SCurve5 (z - (double)z0); break; } // Now calculate the noise values at each vertex of the cube. To generate // the coherent-noise value at the input point, interpolate these eight // noise values using the S-curve value as the interpolant (trilinear // interpolation.) double n0, n1, ix0, ix1, iy0, iy1; n0 = GradientNoise3D (x, y, z, x0, y0, z0, seed); n1 = GradientNoise3D (x, y, z, x1, y0, z0, seed); ix0 = LinearInterp (n0, n1, xs); n0 = GradientNoise3D (x, y, z, x0, y1, z0, seed); n1 = GradientNoise3D (x, y, z, x1, y1, z0, seed); ix1 = LinearInterp (n0, n1, xs); iy0 = LinearInterp (ix0, ix1, ys); n0 = GradientNoise3D (x, y, z, x0, y0, z1, seed); n1 = GradientNoise3D (x, y, z, x1, y0, z1, seed); ix0 = LinearInterp (n0, n1, xs); n0 = GradientNoise3D (x, y, z, x0, y1, z1, seed); n1 = GradientNoise3D (x, y, z, x1, y1, z1, seed); ix1 = LinearInterp (n0, n1, xs); iy1 = LinearInterp (ix0, ix1, ys); return LinearInterp (iy0, iy1, zs); //return (iy0+ix0)/2; } public double GradientNoise3D (double fx, double fy, double fz, int ix, int iy, int iz, int seed) { // Randomly generate a gradient vector given the integer coordinates of the // input value. This implementation generates a random number and uses it // as an index into a normalized-vector lookup table. int vectorIndex = ( X_NOISE_GEN * ix + Y_NOISE_GEN * iy + Z_NOISE_GEN * iz + SEED_NOISE_GEN * seed) & 0xffffffff; vectorIndex ^= (vectorIndex >> SHIFT_NOISE_GEN); vectorIndex &= 0xff; double xvGradient = g_randomVectors[(vectorIndex << 2) ]; double yvGradient = g_randomVectors[(vectorIndex << 2) + 1]; double zvGradient = g_randomVectors[(vectorIndex << 2) + 2]; // Set up us another vector equal to the distance between the two vectors // passed to this function. double xvPoint = (fx - (double)ix); double yvPoint = (fy - (double)iy); double zvPoint = (fz - (double)iz); // Now compute the dot product of the gradient vector with the distance // vector. The resulting value is gradient noise. Apply a scaling value // so that this noise value ranges from -1.0 to 1.0. return ((xvGradient * xvPoint) + (yvGradient * yvPoint) + (zvGradient * zvPoint)) * 2.12; } private double LinearInterp(double n0, double n1, double a) { return ((1.0 - a) * n0) + (a * n1); } private double SCurve3(double a) { return (a * a * (3.0 - 2.0 * a)); } private double SCurve5(double a) { double a3 = a * a * a; double a4 = a3 * a; double a5 = a4 * a; return (6.0 * a5) - (15.0 * a4) + (10.0 * a3); } private static final int X_NOISE_GEN = 1619; private static final int Y_NOISE_GEN = 31337; private static final int Z_NOISE_GEN = 6971; private static final int SEED_NOISE_GEN = 1013; private static final int SHIFT_NOISE_GEN = 8; private static final double[] g_randomVectors = { -0.763874, -0.596439, -0.246489, 0.0, 0.396055, 0.904518, -0.158073, 0.0, -0.499004, -0.8665, -0.0131631, 0.0, 0.468724, -0.824756, 0.316346, 0.0, 0.829598, 0.43195, 0.353816, 0.0, -0.454473, 0.629497, -0.630228, 0.0, -0.162349, -0.869962, -0.465628, 0.0, 0.932805, 0.253451, 0.256198, 0.0, -0.345419, 0.927299, -0.144227, 0.0, -0.715026, -0.293698, -0.634413, 0.0, -0.245997, 0.717467, -0.651711, 0.0, -0.967409, -0.250435, -0.037451, 0.0, 0.901729, 0.397108, -0.170852, 0.0, 0.892657, -0.0720622, -0.444938, 0.0, 0.0260084, -0.0361701, 0.999007, 0.0, 0.949107, -0.19486, 0.247439, 0.0, 0.471803, -0.807064, -0.355036, 0.0, 0.879737, 0.141845, 0.453809, 0.0, 0.570747, 0.696415, 0.435033, 0.0, -0.141751, -0.988233, -0.0574584, 0.0, -0.58219, -0.0303005, 0.812488, 0.0, -0.60922, 0.239482, -0.755975, 0.0, 0.299394, -0.197066, -0.933557, 0.0, -0.851615, -0.220702, -0.47544, 0.0, 0.848886, 0.341829, -0.403169, 0.0, -0.156129, -0.687241, 0.709453, 0.0, -0.665651, 0.626724, 0.405124, 0.0, 0.595914, -0.674582, 0.43569, 0.0, 0.171025, -0.509292, 0.843428, 0.0, 0.78605, 0.536414, -0.307222, 0.0, 0.18905, -0.791613, 0.581042, 0.0, -0.294916, 0.844994, 0.446105, 0.0, 0.342031, -0.58736, -0.7335, 0.0, 0.57155, 0.7869, 0.232635, 0.0, 0.885026, -0.408223, 0.223791, 0.0, -0.789518, 0.571645, 0.223347, 0.0, 0.774571, 0.31566, 0.548087, 0.0, -0.79695, -0.0433603, -0.602487, 0.0, -0.142425, -0.473249, -0.869339, 0.0, -0.0698838, 0.170442, 0.982886, 0.0, 0.687815, -0.484748, 0.540306, 0.0, 0.543703, -0.534446, -0.647112, 0.0, 0.97186, 0.184391, -0.146588, 0.0, 0.707084, 0.485713, -0.513921, 0.0, 0.942302, 0.331945, 0.043348, 0.0, 0.499084, 0.599922, 0.625307, 0.0, -0.289203, 0.211107, 0.9337, 0.0, 0.412433, -0.71667, -0.56239, 0.0, 0.87721, -0.082816, 0.47291, 0.0, -0.420685, -0.214278, 0.881538, 0.0, 0.752558, -0.0391579, 0.657361, 0.0, 0.0765725, -0.996789, 0.0234082, 0.0, -0.544312, -0.309435, -0.779727, 0.0, -0.455358, -0.415572, 0.787368, 0.0, -0.874586, 0.483746, 0.0330131, 0.0, 0.245172, -0.0838623, 0.965846, 0.0, 0.382293, -0.432813, 0.81641, 0.0, -0.287735, -0.905514, 0.311853, 0.0, -0.667704, 0.704955, -0.239186, 0.0, 0.717885, -0.464002, -0.518983, 0.0, 0.976342, -0.214895, 0.0240053, 0.0, -0.0733096, -0.921136, 0.382276, 0.0, -0.986284, 0.151224, -0.0661379, 0.0, -0.899319, -0.429671, 0.0812908, 0.0, 0.652102, -0.724625, 0.222893, 0.0, 0.203761, 0.458023, -0.865272, 0.0, -0.030396, 0.698724, -0.714745, 0.0, -0.460232, 0.839138, 0.289887, 0.0, -0.0898602, 0.837894, 0.538386, 0.0, -0.731595, 0.0793784, 0.677102, 0.0, -0.447236, -0.788397, 0.422386, 0.0, 0.186481, 0.645855, -0.740335, 0.0, -0.259006, 0.935463, 0.240467, 0.0, 0.445839, 0.819655, -0.359712, 0.0, 0.349962, 0.755022, -0.554499, 0.0, -0.997078, -0.0359577, 0.0673977, 0.0, -0.431163, -0.147516, -0.890133, 0.0, 0.299648, -0.63914, 0.708316, 0.0, 0.397043, 0.566526, -0.722084, 0.0, -0.502489, 0.438308, -0.745246, 0.0, 0.0687235, 0.354097, 0.93268, 0.0, -0.0476651, -0.462597, 0.885286, 0.0, -0.221934, 0.900739, -0.373383, 0.0, -0.956107, -0.225676, 0.186893, 0.0, -0.187627, 0.391487, -0.900852, 0.0, -0.224209, -0.315405, 0.92209, 0.0, -0.730807, -0.537068, 0.421283, 0.0, -0.0353135, -0.816748, 0.575913, 0.0, -0.941391, 0.176991, -0.287153, 0.0, -0.154174, 0.390458, 0.90762, 0.0, -0.283847, 0.533842, 0.796519, 0.0, -0.482737, -0.850448, 0.209052, 0.0, -0.649175, 0.477748, 0.591886, 0.0, 0.885373, -0.405387, -0.227543, 0.0, -0.147261, 0.181623, -0.972279, 0.0, 0.0959236, -0.115847, -0.988624, 0.0, -0.89724, -0.191348, 0.397928, 0.0, 0.903553, -0.428461, -0.00350461, 0.0, 0.849072, -0.295807, -0.437693, 0.0, 0.65551, 0.741754, -0.141804, 0.0, 0.61598, -0.178669, 0.767232, 0.0, 0.0112967, 0.932256, -0.361623, 0.0, -0.793031, 0.258012, 0.551845, 0.0, 0.421933, 0.454311, 0.784585, 0.0, -0.319993, 0.0401618, -0.946568, 0.0, -0.81571, 0.551307, -0.175151, 0.0, -0.377644, 0.00322313, 0.925945, 0.0, 0.129759, -0.666581, -0.734052, 0.0, 0.601901, -0.654237, -0.457919, 0.0, -0.927463, -0.0343576, -0.372334, 0.0, -0.438663, -0.868301, -0.231578, 0.0, -0.648845, -0.749138, -0.133387, 0.0, 0.507393, -0.588294, 0.629653, 0.0, 0.726958, 0.623665, 0.287358, 0.0, 0.411159, 0.367614, -0.834151, 0.0, 0.806333, 0.585117, -0.0864016, 0.0, 0.263935, -0.880876, 0.392932, 0.0, 0.421546, -0.201336, 0.884174, 0.0, -0.683198, -0.569557, -0.456996, 0.0, -0.117116, -0.0406654, -0.992285, 0.0, -0.643679, -0.109196, -0.757465, 0.0, -0.561559, -0.62989, 0.536554, 0.0, 0.0628422, 0.104677, -0.992519, 0.0, 0.480759, -0.2867, -0.828658, 0.0, -0.228559, -0.228965, -0.946222, 0.0, -0.10194, -0.65706, -0.746914, 0.0, 0.0689193, -0.678236, 0.731605, 0.0, 0.401019, -0.754026, 0.52022, 0.0, -0.742141, 0.547083, -0.387203, 0.0, -0.00210603, -0.796417, -0.604745, 0.0, 0.296725, -0.409909, -0.862513, 0.0, -0.260932, -0.798201, 0.542945, 0.0, -0.641628, 0.742379, 0.192838, 0.0, -0.186009, -0.101514, 0.97729, 0.0, 0.106711, -0.962067, 0.251079, 0.0, -0.743499, 0.30988, -0.592607, 0.0, -0.795853, -0.605066, -0.0226607, 0.0, -0.828661, -0.419471, -0.370628, 0.0, 0.0847218, -0.489815, -0.8677, 0.0, -0.381405, 0.788019, -0.483276, 0.0, 0.282042, -0.953394, 0.107205, 0.0, 0.530774, 0.847413, 0.0130696, 0.0, 0.0515397, 0.922524, 0.382484, 0.0, -0.631467, -0.709046, 0.313852, 0.0, 0.688248, 0.517273, 0.508668, 0.0, 0.646689, -0.333782, -0.685845, 0.0, -0.932528, -0.247532, -0.262906, 0.0, 0.630609, 0.68757, -0.359973, 0.0, 0.577805, -0.394189, 0.714673, 0.0, -0.887833, -0.437301, -0.14325, 0.0, 0.690982, 0.174003, 0.701617, 0.0, -0.866701, 0.0118182, 0.498689, 0.0, -0.482876, 0.727143, 0.487949, 0.0, -0.577567, 0.682593, -0.447752, 0.0, 0.373768, 0.0982991, 0.922299, 0.0, 0.170744, 0.964243, -0.202687, 0.0, 0.993654, -0.035791, -0.106632, 0.0, 0.587065, 0.4143, -0.695493, 0.0, -0.396509, 0.26509, -0.878924, 0.0, -0.0866853, 0.83553, -0.542563, 0.0, 0.923193, 0.133398, -0.360443, 0.0, 0.00379108, -0.258618, 0.965972, 0.0, 0.239144, 0.245154, -0.939526, 0.0, 0.758731, -0.555871, 0.33961, 0.0, 0.295355, 0.309513, 0.903862, 0.0, 0.0531222, -0.91003, -0.411124, 0.0, 0.270452, 0.0229439, -0.96246, 0.0, 0.563634, 0.0324352, 0.825387, 0.0, 0.156326, 0.147392, 0.976646, 0.0, -0.0410141, 0.981824, 0.185309, 0.0, -0.385562, -0.576343, -0.720535, 0.0, 0.388281, 0.904441, 0.176702, 0.0, 0.945561, -0.192859, -0.262146, 0.0, 0.844504, 0.520193, 0.127325, 0.0, 0.0330893, 0.999121, -0.0257505, 0.0, -0.592616, -0.482475, -0.644999, 0.0, 0.539471, 0.631024, -0.557476, 0.0, 0.655851, -0.027319, -0.754396, 0.0, 0.274465, 0.887659, 0.369772, 0.0, -0.123419, 0.975177, -0.183842, 0.0, -0.223429, 0.708045, 0.66989, 0.0, -0.908654, 0.196302, 0.368528, 0.0, -0.95759, -0.00863708, 0.288005, 0.0, 0.960535, 0.030592, 0.276472, 0.0, -0.413146, 0.907537, 0.0754161, 0.0, -0.847992, 0.350849, -0.397259, 0.0, 0.614736, 0.395841, 0.68221, 0.0, -0.503504, -0.666128, -0.550234, 0.0, -0.268833, -0.738524, -0.618314, 0.0, 0.792737, -0.60001, -0.107502, 0.0, -0.637582, 0.508144, -0.579032, 0.0, 0.750105, 0.282165, -0.598101, 0.0, -0.351199, -0.392294, -0.850155, 0.0, 0.250126, -0.960993, -0.118025, 0.0, -0.732341, 0.680909, -0.0063274, 0.0, -0.760674, -0.141009, 0.633634, 0.0, 0.222823, -0.304012, 0.926243, 0.0, 0.209178, 0.505671, 0.836984, 0.0, 0.757914, -0.56629, -0.323857, 0.0, -0.782926, -0.339196, 0.52151, 0.0, -0.462952, 0.585565, 0.665424, 0.0, 0.61879, 0.194119, -0.761194, 0.0, 0.741388, -0.276743, 0.611357, 0.0, 0.707571, 0.702621, 0.0752872, 0.0, 0.156562, 0.819977, 0.550569, 0.0, -0.793606, 0.440216, 0.42, 0.0, 0.234547, 0.885309, -0.401517, 0.0, 0.132598, 0.80115, -0.58359, 0.0, -0.377899, -0.639179, 0.669808, 0.0, -0.865993, -0.396465, 0.304748, 0.0, -0.624815, -0.44283, 0.643046, 0.0, -0.485705, 0.825614, -0.287146, 0.0, -0.971788, 0.175535, 0.157529, 0.0, -0.456027, 0.392629, 0.798675, 0.0, -0.0104443, 0.521623, -0.853112, 0.0, -0.660575, -0.74519, 0.091282, 0.0, -0.0157698, -0.307475, -0.951425, 0.0, -0.603467, -0.250192, 0.757121, 0.0, 0.506876, 0.25006, 0.824952, 0.0, 0.255404, 0.966794, 0.00884498, 0.0, 0.466764, -0.874228, -0.133625, 0.0, 0.475077, -0.0682351, -0.877295, 0.0, -0.224967, -0.938972, -0.260233, 0.0, -0.377929, -0.814757, -0.439705, 0.0, -0.305847, 0.542333, -0.782517, 0.0, 0.26658, -0.902905, -0.337191, 0.0, 0.0275773, 0.322158, -0.946284, 0.0, 0.0185422, 0.716349, 0.697496, 0.0, -0.20483, 0.978416, 0.0273371, 0.0, -0.898276, 0.373969, 0.230752, 0.0, -0.00909378, 0.546594, 0.837349, 0.0, 0.6602, -0.751089, 0.000959236, 0.0, 0.855301, -0.303056, 0.420259, 0.0, 0.797138, 0.0623013, -0.600574, 0.0, 0.48947, -0.866813, 0.0951509, 0.0, 0.251142, 0.674531, 0.694216, 0.0, -0.578422, -0.737373, -0.348867, 0.0, -0.254689, -0.514807, 0.818601, 0.0, 0.374972, 0.761612, 0.528529, 0.0, 0.640303, -0.734271, -0.225517, 0.0, -0.638076, 0.285527, 0.715075, 0.0, 0.772956, -0.15984, -0.613995, 0.0, 0.798217, -0.590628, 0.118356, 0.0, -0.986276, -0.0578337, -0.154644, 0.0, -0.312988, -0.94549, 0.0899272, 0.0, -0.497338, 0.178325, 0.849032, 0.0, -0.101136, -0.981014, 0.165477, 0.0, -0.521688, 0.0553434, -0.851339, 0.0, -0.786182, -0.583814, 0.202678, 0.0, -0.565191, 0.821858, -0.0714658, 0.0, 0.437895, 0.152598, -0.885981, 0.0, -0.92394, 0.353436, -0.14635, 0.0, 0.212189, -0.815162, -0.538969, 0.0, -0.859262, 0.143405, -0.491024, 0.0, 0.991353, 0.112814, 0.0670273, 0.0, 0.0337884, -0.979891, -0.196654, 0.0 }; public void plantTrees() { ArrayList<Position> treeList = new ArrayList<Position>(); for(int x = 0;x<m_width;x++) { for(int y = 0;y<m_height;y++) { boolean tooClose = false; for(Position p : treeList) { double distance = Math.sqrt(Math.pow(p.getX()-x,2)+Math.pow(p.getY()-y,2)); if (distance < 30) tooClose = true; } if (!tooClose) { if (m_random.nextInt(100) <= 5) { for(int z = m_depth-1;z>0;z if ((m_blocks[x][y][z] == BlockConstants.DIRT || m_blocks[x][y][z] == BlockConstants.GRASS) && m_blocks[x][y][z+1] == BlockConstants.AIR) { plantTree(x, y, z); treeList.add(new Position(x, y, z)); break; } else if (z < m_depth-1 && m_blocks[x][y][z+1] != BlockConstants.AIR) { break; } } } } } } } public void plantTree(int rootX, int rootY, int rootZ) { for(int z = rootZ;z < rootZ + 5;z++) { m_blocks[rootX][rootY][z] = BlockConstants.TREE_TRUNK; } for(int width = 4;width>0;width leafLayer(rootX, rootY, rootZ+5+(4-width), width); } } public void leafLayer(int cx, int cy, int cz, int width) { for(int x = Math.max(0, cx-width);x<Math.min(m_width, cx+width);x++) { for(int y = Math.max(0, cy-width);y<Math.min(m_height, cy+width);y++) { m_blocks[x][y][cz] = BlockConstants.LEAVES; } } } public void raiseTerrain() { boolean[][][] prevContour = new boolean[m_width][m_height][m_depth]; boolean[][][] curContour = new boolean[m_width][m_height][m_depth]; for(int x = 0;x<m_width;x++) { for(int y = 0;y<m_height;y++) { for(int z = 0;z<m_depth;z++) { curContour[x][y][z] = (m_random.nextInt(100) <= 45); } } } for(int count = 0;count<3;count++) { System.arraycopy(curContour, 0, prevContour, 0, curContour.length); for(int x = 0;x<m_width;x++) { for(int y = 0;y<m_height;y++) { for(int z = 0;z<m_depth;z++) { curContour[x][y][z] = simulateCell(prevContour, x, y, z); } } } } for(int x = 0;x<m_width;x++) { for(int y = 0;y<m_height;y++) { for(int z = 0;z<m_depth;z++) { byte type = (byte)BlockConstants.AIR; if (curContour[x][y][m_depth-1-z]) { if (z > 1) { if (curContour[x][y][m_depth-z-2]) type = (byte)BlockConstants.DIRT; else type = (byte)BlockConstants.GRASS; } else { type =(byte)BlockConstants.DIRT; } } m_blocks[x][y][z] = type; } } } } private boolean simulateCell(boolean[][][] grid, int x, int y, int z) { double count = 0; boolean isAlive = grid[x][y][z]; if (isAlive) count++; if (x > 0 && x < m_width-1) { if (grid[x-1][y][z]) count++; if (grid[x+1][y][z]) count++; } if (y > 0 && y < m_height-1) { if (grid[x][y+1][z]) count++; if (grid[x][y-1][z]) count++; } if (z > 0 && z < m_depth-1) { if (grid[x][y][z-1]) count+=2; if (grid[x][y][z+1]) count+=0.9; } if (y > 0) { if (x > 0) { if (z > 0) if (grid[x-1][y-1][z-1]) count+=0.7; if (z < m_depth-1) if (grid[x-1][y-1][z+1]) count+=0.5; } if (x < m_width-1) { if (z > 0) if (grid[x+1][y-1][z-1]) count+=0.7; if (z < m_depth-1) if (grid[x+1][y-1][z+1]) count+=0.5; } } if (y < m_height-1) { if (x > 0) { if (z > 0) if (grid[x-1][y+1][z-1]) count+=0.7; if (z < m_depth-1) if (grid[x-1][y+1][z+1]) count+=0.5; } if (x < m_width-1) { if (z > 0) if (grid[x+1][y+1][z-1]) count+=0.7; if (z < m_depth-1) if (grid[x+1][y+1][z+1]) count+=0.5; } } return count >= 5.7; } public byte[][][] getBlocks() { return m_blocks; } /*public void applyContour() { int maxHeight = 1; for (int x = 0;x<m_width;x++) { for (int y = 0;y < m_height;y++) { if (m_contour[x][y] > maxHeight) maxHeight = m_contour[x][y]; } } m_logger.debug("Applying contour"); for(int x = 0; x < m_width; x++) { for(int y = 0; y < m_height; y++) { int h = Math.max(0, Math.min(m_depth-1, (m_depth/2) + m_contour[x][y])); int d = m_random.nextInt(8) - 4; for(int z = 0; z < m_depth; z++) { int type = BlockConstants.AIR; if (z >= h && z < m_depth/2-1) { type = BlockConstants.WATER; } else if (z >= h) { type = BlockConstants.AIR; } else if(z == (h - 1)) { type = BlockConstants.GRASS; } else if(z < (h - 1) && z > (h -5 )) { type = BlockConstants.DIRT; } else if(z <= (h - 5 )) { type = BlockConstants.STONE; } m_blocks[x][y][z] = (byte) type; } } } }*/ public void buildLavaBed(int depth) { m_logger.debug("Building lava bed."); for (int z = 0;z < depth; z++) { for(int x = 0;x < m_width; x++) { for (int y = 0; y < m_height; y++ ) { m_blocks[x][y][z] = (byte) BlockConstants.LAVA; } } } } public void simulateOceanFlood() { if (m_width < 2 || m_height < 2) { return; } LinkedList<Point> toFlood = new LinkedList<Point>(); int oceanLevel = m_depth / 2 - 1; for (int x = 0; x < m_width; x++) { if (m_blocks[x][0][oceanLevel] == BlockConstants.AIR) { floodBlock(x, 0, oceanLevel); floodBlock(x, m_height - 1, oceanLevel); if (m_blocks[x][1][oceanLevel] == BlockConstants.AIR) { toFlood.add(new Point(x, 1)); } else if (m_blocks[x][m_height - 1][oceanLevel] == BlockConstants.AIR) { toFlood.add(new Point(x, m_height - 2)); } } } if (m_blocks[1][0][oceanLevel] == BlockConstants.AIR) { floodBlock(1, 0, oceanLevel); } if (m_blocks[m_width - 2][0][oceanLevel] == BlockConstants.AIR) { floodBlock(m_width - 2, 0, oceanLevel); } if (m_blocks[1][m_height - 2][oceanLevel] == BlockConstants.AIR) { floodBlock(1, m_height - 2, oceanLevel); } if (m_blocks[m_width - 2][m_height - 2][oceanLevel] == BlockConstants.AIR) { floodBlock(m_width - 2, m_height - 2, oceanLevel); } for (int y = 2; y < m_height - 2; y++) { if (m_blocks[0][y][oceanLevel] == BlockConstants.AIR) { floodBlock(0, y, oceanLevel); floodBlock(m_width - 1, y, oceanLevel); if (m_blocks[1][y][oceanLevel] == BlockConstants.AIR) { toFlood.add(new Point(1, y)); } else if (m_blocks[m_width - 2][y][oceanLevel] == BlockConstants.AIR) { toFlood.add(new Point(m_width - 2, y)); } } } while (toFlood.size() > 0) { Point p = toFlood.removeFirst(); if (m_blocks[(int)(p.getX())][(int)(p.getY())][oceanLevel] != BlockConstants.WATER) { floodBlock((int)(p.getX()), (int)(p.getY()), oceanLevel); if (p.getX() > 0 && m_blocks[(int)(p.getX() - 1)][(int)(p.getY())][oceanLevel] == BlockConstants.AIR) { toFlood.add(new Point((int)(p.getX() - 1), (int)(p.getY()))); } if (p.getX() < m_width -1 && m_blocks[(int)(p.getX() + 1)][(int)(p.getY())][oceanLevel] == BlockConstants.AIR) { toFlood.add(new Point((int)(p.getX() + 1), (int)(p.getY()))); } if (p.getY() > 0 && m_blocks[(int)(p.getX())][(int)(p.getY() - 1)][oceanLevel] == BlockConstants.AIR) { toFlood.add(new Point((int)(p.getX()), (int)(p.getY() - 1))); } if (p.getY() < m_height -1 && m_blocks[(int)(p.getX())][(int)(p.getY() + 1)][oceanLevel] == BlockConstants.AIR) { toFlood.add(new Point((int)(p.getX()), (int)(p.getY() + 1))); } } } } private void floodBlock(int x, int y, int oceanLevel) { for (int z = oceanLevel; true; z if (z < 0) { break; } if (m_blocks[x][y][z] == BlockConstants.AIR) { m_blocks[x][y][z] = BlockConstants.WATER; } else if (m_blocks[x][y][z + 1] == BlockConstants.WATER && (m_blocks[x][y][z] == BlockConstants.DIRT || m_blocks[x][y][z] == BlockConstants.GRASS)) { m_blocks[x][y][z] = BlockConstants.SAND; break; } } } }
package org.ow2.proactive_grid_cloud_portal; import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicLong; import org.apache.log4j.Logger; import org.objectweb.proactive.api.PAActiveObject; import org.objectweb.proactive.api.PAFuture; import org.objectweb.proactive.core.util.log.ProActiveLogger; import org.objectweb.proactive.utils.Sleeper; import org.ow2.proactive.authentication.crypto.Credentials; import org.ow2.proactive.scheduler.common.SchedulerState; import org.ow2.proactive.scheduler.common.util.CachingSchedulerProxyUserInterface; import org.ow2.proactive.scheduler.common.util.SchedulerLoggers; import org.ow2.proactive.scheduler.core.SchedulerStateImpl; /** * This class keeps a cache of the scheduler state and periodically refresh it. * This prevents to directly call the active object CachingSchedulerProxyUserInterface and thus * to have the scheduler state being copied each time. * the refresh rate can be configured using @see {org.ow2.proactive_grid_cloud_portal.PortalConfiguration.scheduler_cache_refreshrate} * * */ public class SchedulerStateCaching { private static Logger logger = ProActiveLogger.getLogger(SchedulerLoggers.PREFIX + ".rest.caching"); private static CachingSchedulerProxyUserInterface scheduler; private static SchedulerState localState; private static long schedulerRevision; private static int refreshInterval; private static volatile boolean kill = false; private static Thread cachedSchedulerStateThreadUpdater; private static Thread leaseRenewerThreadUpdater; protected static Map<AtomicLong, SchedulerState> revisionAndSchedulerState ; private static int leaseRenewRate; public static CachingSchedulerProxyUserInterface getScheduler() { return scheduler; } public static void setScheduler(CachingSchedulerProxyUserInterface scheduler) { SchedulerStateCaching.scheduler = scheduler; } public synchronized static void init() { // here we need a thread to free the calling thread // i.e. not locking it when the scheduler is unavailable new Thread(new Runnable() { public void run() { revisionAndSchedulerState = new HashMap<AtomicLong, SchedulerState>(); revisionAndSchedulerState.put(new AtomicLong(-1),new SchedulerStateImpl()); init_(); start_(); } }).start(); } private synchronized static void init_() { leaseRenewRate = Integer.parseInt(PortalConfiguration.getProperties().getProperty(PortalConfiguration.lease_renew_rate)); refreshInterval = Integer.parseInt(PortalConfiguration.getProperties().getProperty(PortalConfiguration.scheduler_cache_refreshrate)); String url = PortalConfiguration.getProperties().getProperty(PortalConfiguration.scheduler_url); String cred_path = PortalConfiguration.getProperties().getProperty(PortalConfiguration.scheduler_cache_credential); while (scheduler == null ) { try { if (scheduler == null) { scheduler = PAActiveObject.newActive( CachingSchedulerProxyUserInterface.class, new Object[] {}); // check is we use a credential file File f = new File(cred_path); if (f.exists()) { Credentials credential = Credentials.getCredentials(cred_path); scheduler.init(url, credential); } else { String login = PortalConfiguration.getProperties().getProperty(PortalConfiguration.scheduler_cache_login); String password = PortalConfiguration.getProperties().getProperty(PortalConfiguration.scheduler_cache_password); scheduler.init(url, login, password); } } } catch (Exception e) { logger.warn("no scheduler found on " + url + "retrying in 8 seconds", e); scheduler = null; new Sleeper(8 * 1000).sleep(); continue; } } } private static void start_() { cachedSchedulerStateThreadUpdater = new Thread(new Runnable() { public void run() { while (!kill) { long currentSchedulerStateRevision = scheduler.getSchedulerStateRevision(); if (currentSchedulerStateRevision != schedulerRevision) { Map<AtomicLong, SchedulerState> schedStateTmp = scheduler.getRevisionVersionAndSchedulerState(); PAFuture.waitFor(schedStateTmp); revisionAndSchedulerState = schedStateTmp; Entry<AtomicLong, SchedulerState> tmp = revisionAndSchedulerState.entrySet().iterator().next(); localState = tmp.getValue(); schedulerRevision = tmp.getKey().longValue(); logger.debug("updated scheduler state revision at " + schedulerRevision); } new Sleeper(refreshInterval).sleep(); } } },"State Updater Thread"); cachedSchedulerStateThreadUpdater.setDaemon(true); cachedSchedulerStateThreadUpdater.start(); leaseRenewerThreadUpdater = new Thread(new Runnable() { public void run() { if (( scheduler != null) && (! kill)) { try { scheduler.getStatus(); } catch (Exception e) { logger.info("leaseRenewerThread was not able to call the getStatus method, exception message is " + e.getMessage()); init_(); } } new Sleeper(leaseRenewRate).sleep(); } }, "Lease Renewer Thread"); leaseRenewerThreadUpdater.setDaemon(true); leaseRenewerThreadUpdater.start(); } public static SchedulerState getLocalState() { return localState; } public static void setLocalState(SchedulerState localState) { SchedulerStateCaching.localState = localState; } public static long getSchedulerRevision() { return schedulerRevision; } public static void setSchedulerRevision(long schedulerRevision) { SchedulerStateCaching.schedulerRevision = schedulerRevision; } public static int getRefreshInterval() { return refreshInterval; } public static void setRefreshInterval(int refreshInterval) { SchedulerStateCaching.refreshInterval = refreshInterval; } public static boolean isKill() { return kill; } public static void setKill(boolean kill) { SchedulerStateCaching.kill = kill; } public static Map<AtomicLong, SchedulerState> getRevisionAndSchedulerState() { return revisionAndSchedulerState; } }
package org.usfirst.frc.team4342.robot.vision; import java.io.File; import java.io.FileWriter; import java.io.IOException; import org.opencv.core.*; import org.opencv.features2d.FeatureDetector; import org.opencv.imgproc.*; import edu.wpi.first.wpilibj.vision.VisionPipeline; /** * DemonVisionPipeline class. * * <p>An OpenCV pipeline generated by GRIP. * * @author GRIP */ public class DemonVisionPipeline implements VisionPipeline { //Outputs private Mat cvResizeOutput = new Mat(); private Mat hsvThresholdOutput = new Mat(); private Mat cvErodeOutput = new Mat(); private Mat maskOutput = new Mat(); private MatOfKeyPoint findBlobsOutput = new MatOfKeyPoint(); static { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); } /** * This is the primary method that runs the entire pipeline and updates the outputs. */ public void process(Mat source0) { // Step CV_resize0: Mat cvResizeSrc = source0; Size cvResizeDsize = new Size(0, 0); double cvResizeFx = 0.25; double cvResizeFy = 0.25; int cvResizeInterpolation = Imgproc.INTER_LINEAR; cvResize(cvResizeSrc, cvResizeDsize, cvResizeFx, cvResizeFy, cvResizeInterpolation, cvResizeOutput); // Step HSV_Threshold0: Mat hsvThresholdInput = cvResizeOutput; double[] hsvThresholdHue = {99.98788670888683, 129.77071433461606}; double[] hsvThresholdSaturation = {50.44964028776978, 255.0}; double[] hsvThresholdValue = {50.44964028776978, 255.0}; hsvThreshold(hsvThresholdInput, hsvThresholdHue, hsvThresholdSaturation, hsvThresholdValue, hsvThresholdOutput); // Step CV_erode0: Mat cvErodeSrc = hsvThresholdOutput; Mat cvErodeKernel = new Mat(); Point cvErodeAnchor = new Point(-1, -1); double cvErodeIterations = 1.0; int cvErodeBordertype = Core.BORDER_CONSTANT; Scalar cvErodeBordervalue = new Scalar(-1); cvErode(cvErodeSrc, cvErodeKernel, cvErodeAnchor, cvErodeIterations, cvErodeBordertype, cvErodeBordervalue, cvErodeOutput); // Step Mask0: Mat maskInput = cvResizeOutput; Mat maskMask = cvErodeOutput; mask(maskInput, maskMask, maskOutput); // Step Find_Blobs0: Mat findBlobsInput = maskOutput; double findBlobsMinArea = 180.0; double[] findBlobsCircularity = {0.0, 1.0}; boolean findBlobsDarkBlobs = false; findBlobs(findBlobsInput, findBlobsMinArea, findBlobsCircularity, findBlobsDarkBlobs, findBlobsOutput); } /** * This method is a generated getter for the output of a CV_resize. * @return Mat output from CV_resize. */ public Mat cvResizeOutput() { return cvResizeOutput; } /** * This method is a generated getter for the output of a HSV_Threshold. * @return Mat output from HSV_Threshold. */ public Mat hsvThresholdOutput() { return hsvThresholdOutput; } /** * This method is a generated getter for the output of a CV_erode. * @return Mat output from CV_erode. */ public Mat cvErodeOutput() { return cvErodeOutput; } /** * This method is a generated getter for the output of a Mask. * @return Mat output from Mask. */ public Mat maskOutput() { return maskOutput; } /** * This method is a generated getter for the output of a Find_Blobs. * @return MatOfKeyPoint output from Find_Blobs. */ public MatOfKeyPoint findBlobsOutput() { return findBlobsOutput; } /** * Resizes an image. * @param src The image to resize. * @param dSize size to set the image. * @param fx scale factor along X axis. * @param fy scale factor along Y axis. * @param interpolation type of interpolation to use. * @param dst output image. */ private void cvResize(Mat src, Size dSize, double fx, double fy, int interpolation, Mat dst) { if (dSize==null) { dSize = new Size(0,0); } Imgproc.resize(src, dst, dSize, fx, fy, interpolation); } /** * Segment an image based on hue, saturation, and value ranges. * * @param input The image on which to perform the HSL threshold. * @param hue The min and max hue * @param sat The min and max saturation * @param val The min and max value * @param output The image in which to store the output. */ private void hsvThreshold(Mat input, double[] hue, double[] sat, double[] val, Mat out) { Imgproc.cvtColor(input, out, Imgproc.COLOR_BGR2HSV); Core.inRange(out, new Scalar(hue[0], sat[0], val[0]), new Scalar(hue[1], sat[1], val[1]), out); } /** * Expands area of lower value in an image. * @param src the Image to erode. * @param kernel the kernel for erosion. * @param anchor the center of the kernel. * @param iterations the number of times to perform the erosion. * @param borderType pixel extrapolation method. * @param borderValue value to be used for a constant border. * @param dst Output Image. */ private void cvErode(Mat src, Mat kernel, Point anchor, double iterations, int borderType, Scalar borderValue, Mat dst) { if (kernel == null) { kernel = new Mat(); } if (anchor == null) { anchor = new Point(-1,-1); } if (borderValue == null) { borderValue = new Scalar(-1); } Imgproc.erode(src, dst, kernel, anchor, (int)iterations, borderType, borderValue); } /** * Filter out an area of an image using a binary mask. * @param input The image on which the mask filters. * @param mask The binary image that is used to filter. * @param output The image in which to store the output. */ private void mask(Mat input, Mat mask, Mat output) { mask.convertTo(mask, CvType.CV_8UC1); Core.bitwise_xor(output, output, output); input.copyTo(output, mask); } /** * Detects groups of pixels in an image. * @param input The image on which to perform the find blobs. * @param minArea The minimum size of a blob that will be found * @param circularity The minimum and maximum circularity of blobs that will be found * @param darkBlobs The boolean that determines if light or dark blobs are found. * @param blobList The output where the MatOfKeyPoint is stored. */ private void findBlobs(Mat input, double minArea, double[] circularity, Boolean darkBlobs, MatOfKeyPoint blobList) { FeatureDetector blobDet = FeatureDetector.create(FeatureDetector.SIMPLEBLOB); try { File tempFile = File.createTempFile("config", ".xml"); StringBuilder config = new StringBuilder(); config.append("<?xml version=\"1.0\"?>\n"); config.append("<opencv_storage>\n"); config.append("<thresholdStep>10.</thresholdStep>\n"); config.append("<minThreshold>50.</minThreshold>\n"); config.append("<maxThreshold>220.</maxThreshold>\n"); config.append("<minRepeatability>2</minRepeatability>\n"); config.append("<minDistBetweenBlobs>10.</minDistBetweenBlobs>\n"); config.append("<filterByColor>1</filterByColor>\n"); config.append("<blobColor>"); config.append((darkBlobs ? 0 : 255)); config.append("</blobColor>\n"); config.append("<filterByArea>1</filterByArea>\n"); config.append("<minArea>"); config.append(minArea); config.append("</minArea>\n"); config.append("<maxArea>"); config.append(Integer.MAX_VALUE); config.append("</maxArea>\n"); config.append("<filterByCircularity>1</filterByCircularity>\n"); config.append("<minCircularity>"); config.append(circularity[0]); config.append("</minCircularity>\n"); config.append("<maxCircularity>"); config.append(circularity[1]); config.append("</maxCircularity>\n"); config.append("<filterByInertia>1</filterByInertia>\n"); config.append("<minInertiaRatio>0.1</minInertiaRatio>\n"); config.append("<maxInertiaRatio>" + Integer.MAX_VALUE + "</maxInertiaRatio>\n"); config.append("<filterByConvexity>1</filterByConvexity>\n"); config.append("<minConvexity>0.95</minConvexity>\n"); config.append("<maxConvexity>" + Integer.MAX_VALUE + "</maxConvexity>\n"); config.append("</opencv_storage>\n"); FileWriter writer; writer = new FileWriter(tempFile, false); writer.write(config.toString()); writer.close(); blobDet.read(tempFile.getPath()); } catch (IOException e) { e.printStackTrace(); } blobDet.detect(input, blobList); } }
package RetirementCalculator; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; /** * FXML Controller class * * @author derekbarrera */ public class RetirementCalculatorLayoutController { @FXML private TextArea calculationWindow; @FXML private final String string = "This"; @FXML private final String new_string = " is working!"; @FXML private TextField ageField; @FXML private TextField incomeTaxRateField; @FXML private TextField retirementAgeField; @FXML private TextField capGainsTxRateField; @FXML private TextField preTaxBalanceField; @FXML private TextField postTaxBalanceField; @FXML private TextField preTaxContField; @FXML private TextField postTaxContField; @FXML private TextField rateOfReturnField; @FXML protected void ageFieldGetter(ActionEvent event) { calculationWindow.setText(string); calculationWindow.appendText(new_string); calculationWindow.appendText(ageField.getText()); } }
package com.github.dozedoff.commonj.file; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.hasItems; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.Matchers.empty; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.github.dozedoff.commonj.filefilter.FileFilter; public class FileWalkerTest { File rootFolder; Path rootPath; List<File> files; List<File> folders; FileWalker fw; @Before public void setUp() throws Exception { files = new ArrayList<>(); folders = new ArrayList<>(); rootPath = Files.createTempDirectory("FileWalkerTest"); rootFolder = rootPath.toFile(); folders.add(new File(rootFolder, "subFolderOne")); folders.add(new File(rootFolder, "subFoldertwo")); folders.add(new File(folders.get(1), "subSubFolderOne")); for (File f : folders) { f.mkdirs(); } files.add(new File(rootFolder, "one.txt")); files.add(new File(folders.get(0), "two.txt")); files.add(new File(folders.get(1), "three.jpg")); files.add(new File(folders.get(2), "four.txt")); for (File f : files) { f.createNewFile(); } fw = new FileWalker(); } @After public void tearDown() throws Exception { rootFolder.delete(); fw = null; } @Test /** * Test if all files and folders have been created. */ public void testCorrectSetup() { assertTrue(folders.get(0).exists()); assertTrue(folders.get(1).exists()); assertTrue(folders.get(2).exists()); for (File f : files) assertTrue(f.exists()); } @Test public void testGetAllDirectories() throws IOException { assertThat(FileWalker.getAllDirectories(rootPath), hasItems(convertFileToPath(folders))); } @Test public void testGetCurrentDirectorySubdirectories() { List<Path> result = FileWalker.getCurrentDirectorySubdirectories(rootPath); assertThat(result, hasItems(folders.get(0).toPath(), folders.get(1).toPath())); assertThat(result, not(hasItem(folders.get(2).toPath()))); } @Test public void testGetCurrentDirectorySubdirectoriesNotDirectory() { assertThat(FileWalker.getCurrentDirectorySubdirectories(files.get(0).toPath()), is(empty())); } @Test public void testGetAllImages() throws IOException { assertThat(FileWalker.getAllImages(rootPath), hasItem(files.get(2).toPath())); } @Test public void testGetCurrentFolderImages() throws IOException { assertThat(FileWalker.getCurrentFolderImages(rootPath).size(), is(0)); } @Test public void testWalkFileTreeWithFilter() throws IOException { assertThat(FileWalker.walkFileTreeWithFilter(rootPath, new FileFilter()), hasItems(convertFileToPath(files))); } @Test public void testWalkFileTreePathArray() throws IOException { assertThat(FileWalker.walkFileTree(convertFileToPath(folders.get(0), folders.get(1))), hasItems(convertFileToPath(files.get(1), files.get(2), files.get(3)))); } @Test public void testWalkFileTreePathList() throws IOException { LinkedList<Path> sourceList = new LinkedList<>(); sourceList.add(folders.get(0).toPath()); sourceList.add(folders.get(1).toPath()); assertThat(FileWalker.walkFileTreePathList(sourceList), hasItems(convertFileToPath(files.get(1), files.get(2), files.get(3)))); } @Test public void testWalkFileTreeFileArray() throws IOException { assertThat(FileWalker.walkFileTree(folders.get(0), folders.get(1)), hasItems(convertFileToPath(files.get(1), files.get(2), files.get(3)))); } @Test public void testWalkFileTreeStringList() throws IOException { LinkedList<String> sourceList = new LinkedList<>(); sourceList.add(folders.get(0).toString()); sourceList.add(folders.get(1).toString()); assertThat(FileWalker.walkFileTreeStringList(sourceList), hasItems(convertFileToPath(files.get(1), files.get(2), files.get(3)))); } @Test public void testWalkFileTreeStringArray() throws IOException { assertThat(FileWalker.walkFileTree(folders.get(0).toString(), folders.get(1).toString()), hasItems(convertFileToPath(files.get(1), files.get(2), files.get(3)))); } @Test public void testWalkFileTreeFileList() throws IOException { LinkedList<File> sourceList = new LinkedList<>(); sourceList.add(folders.get(0)); sourceList.add(folders.get(1)); assertThat(FileWalker.walkFileTreeFileList(sourceList), hasItems(convertFileToPath(files.get(1), files.get(2), files.get(3)))); } @Test public void testCheckDuplicateElimination() throws IOException { LinkedList<Path> results = FileWalker.walkFileTree(rootPath, rootPath); assertThat(results, hasItems(convertFileToPath(files))); assertThat(results.size(), is(4)); } @Test public void testFindImageInFolder() throws IOException { LinkedList<Path> results = FileWalker.getCurrentFolderImages(folders.get(1).toPath()); assertThat(results, hasItem(files.get(2).toPath())); assertThat(results.size(), is(1)); } private Path[] convertFileToPath(Collection<File> files) { List<Path> paths = new ArrayList<>(files.size()); for (File f : files) { paths.add(f.toPath()); } return paths.toArray(new Path[0]); } private Path[] convertFileToPath(File... files) { return convertFileToPath(Arrays.asList(files)); } }
package com.infodesire.tablestream.util; import static org.junit.Assert.*; import com.infodesire.commons.FILE; import com.infodesire.commons.NUMBER; import com.infodesire.tablestream.Cell; import com.infodesire.tablestream.FileWriter; import com.infodesire.tablestream.Row; import com.infodesire.tablestream.TS; import com.infodesire.tablestream.tsfile.TSReader; import com.infodesire.tablestream.tsfile.TSWriter; import java.io.File; import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Test; public class SplitWriterTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void test() throws IOException { File dir = FILE.createTempDir( "SplitWriterTest-" ); try { FileWriter fileWriter = new TSWriter(); SplitWriter sw = new SplitWriter( 5, fileWriter, dir, "split.${num}.ts", null ); for( int i = 0; i < 43; i++ ) { Row row = new Row(); row.add( new Cell( i ) ); sw.write( row ); } sw.close(); int fileCounter = 0; int rowIndex = 0; TS ts = new TS(); for( File file : dir.listFiles() ) { if( file.isFile() ) { assertEquals( fileCounter < 8 ? 5 : 3, ts.count( file ).getRows() ); File expected = new File( dir, "split." + NUMBER.digits( 5, fileCounter ) + ".ts" ); assertEquals( "Expected: " + expected + " was " + file, expected, file ); fileCounter++; TSReader reader = new TSReader( file ); for( Row row = reader.next(); row != null; row = reader.next() ) { assertEquals( new Integer( rowIndex++ ), row.getCell( 0 ).getInt() ); } } } assertEquals( 9, fileCounter ); } finally { FILE.rmdir( dir ); } } }
package com.microsoft.sqlserver.jdbc.unit.lobs; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.Reader; import java.sql.Blob; import java.sql.Clob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.logging.Logger; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestFactory; import org.junit.jupiter.api.function.Executable; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBCoercion; import com.microsoft.sqlserver.testframework.DBColumn; import com.microsoft.sqlserver.testframework.DBConnection; import com.microsoft.sqlserver.testframework.DBInvalidUtil; import com.microsoft.sqlserver.testframework.DBResultSet; import com.microsoft.sqlserver.testframework.DBStatement; import com.microsoft.sqlserver.testframework.DBTable; import com.microsoft.sqlserver.testframework.Utils; import com.microsoft.sqlserver.testframework.Utils.DBBinaryStream; import com.microsoft.sqlserver.testframework.Utils.DBCharacterStream; import com.microsoft.sqlserver.testframework.sqlType.SqlType; import com.microsoft.sqlserver.testframework.util.RandomUtil; /** * This class tests lobs (Blob, Clob and NClob) and their APIs * */ @RunWith(JUnitPlatform.class) public class lobsTest extends AbstractTest { static Connection conn = null; static Statement stmt = null; static String tableName; static String escapedTableName; int datasize; int packetSize = 1000; int precision = 2000; long streamLength = -1; // Used to verify exceptions public static final Logger log = Logger.getLogger("lobs"); Class lobClass = null; boolean isResultSet = false; DBTable table = null; private static final int clobType = 0; private static final int nClobType = 1; private static final int blobType = 2; @BeforeAll public static void init() throws SQLException { conn = DriverManager.getConnection(connectionString); stmt = conn.createStatement(); tableName = RandomUtil.getIdentifier("LOBS"); escapedTableName = AbstractSQLGenerator.escapeIdentifier(tableName); } @AfterAll public static void terminate() throws SQLException { if (null != conn) conn.close(); if (null != stmt) stmt.close(); } @TestFactory public Collection<DynamicTest> executeDynamicTests() { List<Class> classes = new ArrayList<Class>(Arrays.asList(Blob.class, Clob.class, DBBinaryStream.class, DBCharacterStream.class)); List<Boolean> isResultSetTypes = new ArrayList<>(Arrays.asList(true, false)); Collection<DynamicTest> dynamicTests = new ArrayList<>(); for (int i = 0; i < classes.size(); i++) { for (int j = 0; j < isResultSetTypes.size(); j++) { final Class lobClass = classes.get(i); final boolean isResultSet = isResultSetTypes.get(j); Executable exec = new Executable() { @Override public void execute() throws Throwable { testInvalidLobs(lobClass, isResultSet); } }; // create a test display name String testName = " Test: " + lobClass + (isResultSet ? " isResultSet" : " isPreparedStatement"); // create dynamic test DynamicTest dTest = DynamicTest.dynamicTest(testName, exec); // add the dynamic test to collection dynamicTests.add(dTest); } } return dynamicTests; } /** * Tests invalid lobs * * @param lobClass * @param isResultSet * @throws SQLException */ private void testInvalidLobs(Class lobClass, boolean isResultSet) throws SQLException { String clobTypes[] = {"varchar(max)", "nvarchar(max)"}; String blobTypes[] = {"varbinary(max)"}; int choose = ThreadLocalRandom.current().nextInt(3); switch (choose) { case 0: datasize = packetSize; break; case 1: datasize = packetSize + ThreadLocalRandom.current().nextInt(packetSize) + 1; break; default: datasize = packetSize - ThreadLocalRandom.current().nextInt(packetSize); } int coercionType = isResultSet ? DBCoercion.UPDATE : DBCoercion.SET; try { if (clobType == classType(lobClass) || nClobType == classType(lobClass)) { table = this.createTable(table, clobTypes, true); } else { table = this.createTable(table, blobTypes, true); } Object updater; for (int i = 0; i < table.getColumns().size(); i++) { DBColumn col = table.getColumns().get(i); if (!col.getSqlType().canconvert(lobClass, coercionType, new DBConnection(connectionString))) continue; // re-create LOB since it might get closed Object lob = this.createLob(lobClass); if (isResultSet) { Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); updater = stmt.executeQuery( "Select " + table.getEscapedTableName() + ".[" + col.getColumnName() + "]" + " from " + table.getEscapedTableName()); ((ResultSet) updater).next(); } else updater = conn.prepareStatement("update " + table.getEscapedTableName() + " set " + ".[" + col.getColumnName() + "]" + "=?"); try { this.updateLob(lob, updater, 1); } catch (SQLException e) { boolean verified = false; if (lobClass == Clob.class) streamLength = ((DBInvalidUtil.InvalidClob) lob).length; else if (lobClass == Blob.class) streamLength = ((DBInvalidUtil.InvalidBlob) lob).length; // Case 1: Invalid length value is passed as LOB length if (streamLength < 0 || streamLength == Long.MAX_VALUE) { // Applies to all LOB types ("The length {0} is not valid} assertTrue(e.getMessage().startsWith("The length"), "Unexpected message thrown : " + e.getMessage()); assertTrue(e.getMessage().endsWith("is not valid."), "Unexpected message thrown : " + e.getMessage()); verified = true; } // Case 2: CharacterStream or Clob.getCharacterStream threw IOException if (lobClass == DBCharacterStream.class || (lobClass == Clob.class && ((DBInvalidUtil.InvalidClob) lob).stream != null)) { DBInvalidUtil.InvalidCharacterStream stream = lobClass == DBCharacterStream.class ? ((DBInvalidUtil.InvalidCharacterStream) lob) : ((DBInvalidUtil.InvalidClob) lob).stream; if (stream.threwException) { // CharacterStream threw IOException String[] args = {"java.io.IOException: " + DBInvalidUtil.InvalidCharacterStream.IOExceptionMsg}; assertTrue(e.getMessage().contains(args[0])); verified = true; } } if (!verified) { // Odd CharacterStream length will throw this exception if (!e.getMessage().contains("The stream value is not the specified length. The specified length was")) { if (lobClass == DBCharacterStream.class || lobClass == DBBinaryStream.class) assertTrue(e.getSQLState() != null, "SQLState should not be null"); assertTrue(e.getMessage().contains("An error occurred while reading the value from the stream object. Error:")); } } } } } catch (Exception e) { this.dropTables(table); e.printStackTrace(); } } @Test @DisplayName("testMultipleCloseCharacterStream") public void testMultipleCloseCharacterStream() throws Exception { testMultipleClose(DBCharacterStream.class); } @Test @DisplayName("MultipleCloseBinaryStream") public void MultipleCloseBinaryStream() throws Exception { testMultipleClose(DBBinaryStream.class); } /** * Tests stream closures * * @param streamClass * @throws Exception */ private void testMultipleClose(Class streamClass) throws Exception { DBConnection conn = new DBConnection(connectionString); String[] types = {"varchar(max)", "nvarchar(max)", "varbinary(max)"}; try { table = this.createTable(table, types, true); DBStatement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); String query = "select * from " + table.getEscapedTableName(); DBResultSet rs = stmt.executeQuery(query); while (rs.next()) { for (int i = 0; i < 3; i++) { DBColumn col = table.getColumns().get(i); if (!col.getSqlType().canconvert(streamClass, DBCoercion.GET, new DBConnection(connectionString))) continue; Object stream = rs.getXXX(i + 1, streamClass); if (stream == null) { assertEquals(stream, rs.getObject(i + 1), "Stream is null when data is not"); } else { // close the stream twice if (streamClass == DBCharacterStream.class) { ((Reader) stream).close(); ((Reader) stream).close(); } else { ((InputStream) stream).close(); ((InputStream) stream).close(); } } } } } finally { if (null != table) this.dropTables(table); if (null != null) conn.close(); } } /** * Tests Insert Retrive on nclob * * @throws Exception */ @Test @DisplayName("testlLobs_InsertRetrive") public void testNClob() throws Exception { String types[] = {"nvarchar(max)"}; testlLobs_InsertRetrive(types, NClob.class); } /** * Tests Insert Retrive on blob * * @throws Exception */ @Test @DisplayName("testlLobs_InsertRetrive") public void testBlob() throws Exception { String types[] = {"varbinary(max)"}; testlLobs_InsertRetrive(types, Blob.class); } /** * Tests Insert Retrive on clob * * @throws Exception */ @Test @DisplayName("testlLobs_InsertRetrive") public void testClob() throws Exception { String types[] = {"varchar(max)"}; testlLobs_InsertRetrive(types, Clob.class); } private void testlLobs_InsertRetrive(String types[], Class lobClass) throws Exception { table = createTable(table, types, false); // create empty table int size = 10000; byte[] data = new byte[size]; ThreadLocalRandom.current().nextBytes(data); Clob clob = null; Blob blob = null; NClob nclob = null; InputStream stream = null; PreparedStatement ps = conn.prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?)"); if (clobType == classType(lobClass)) { String stringData = new String(data); size = stringData.length(); clob = conn.createClob(); clob.setString(1, stringData); ps.setClob(1, clob); } else if (nClobType == classType(lobClass)) { String stringData = new String(data); size = stringData.length(); nclob = conn.createNClob(); nclob.setString(1, stringData); ps.setNClob(1, nclob); } else { blob = conn.createBlob(); blob.setBytes(1, data); ps.setBlob(1, blob); } ps.executeUpdate(); byte[] chunk = new byte[size]; ResultSet rs = stmt.executeQuery("select * from " + table.getEscapedTableName()); while (rs.next()) { if (clobType == classType(lobClass)) { String stringData = new String(data); size = stringData.length(); clob = conn.createClob(); clob.setString(1, stringData); rs.getClob(1); stream = clob.getAsciiStream(); assertEquals(clob.length(), size); } else if (nClobType == classType(lobClass)) { nclob = rs.getNClob(1); stream = nclob.getAsciiStream(); assertEquals(nclob.length(), size); BufferedInputStream is = new BufferedInputStream(stream); is.read(chunk); assertEquals(chunk.length, size); } else { blob = rs.getBlob(1); stream = blob.getBinaryStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int read = 0; while ((read = stream.read(chunk)) > 0) buffer.write(chunk, 0, read); assertEquals(chunk.length, size); } } if (null != clob) clob.free(); if (null != blob) blob.free(); if (null != nclob) nclob.free(); dropTables(table); } @Test @DisplayName("testUpdatorNClob") public void testUpdatorNClob() throws Exception { String types[] = {"nvarchar(max)"}; testUpdateLobs(types, NClob.class); } @Test @DisplayName("testUpdatorBlob") public void testUpdatorBlob() throws Exception { String types[] = {"varbinary(max)"}; testUpdateLobs(types, Blob.class); } @Test @DisplayName("testUpdatorClob") public void testUpdatorClob() throws Exception { String types[] = {"varchar(max)"}; testUpdateLobs(types, Clob.class); } private void testUpdateLobs(String types[], Class lobClass) throws Exception { table = createTable(table, types, false); // create empty table int size = 10000; byte[] data = new byte[size]; ThreadLocalRandom.current().nextBytes(data); Clob clob = null; Blob blob = null; NClob nclob = null; InputStream stream = null; PreparedStatement ps = conn.prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?)"); if (clobType == classType(lobClass)) { String stringData = new String(data); size = stringData.length(); clob = conn.createClob(); clob.setString(1, stringData); ps.setClob(1, clob); } else if (nClobType == classType(lobClass)) { String stringData = new String(data); size = stringData.length(); nclob = conn.createNClob(); nclob.setString(1, stringData); ps.setNClob(1, nclob); } else { blob = conn.createBlob(); blob.setBytes(1, data); ps.setBlob(1, blob); } ps.executeUpdate(); Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = stmt.executeQuery("select * from " + table.getEscapedTableName()); while (rs.next()) { if (clobType == classType(lobClass)) { String stringData = new String(data); size = stringData.length(); clob = conn.createClob(); clob.setString(1, stringData); rs.updateClob(1, clob); } else if (nClobType == classType(lobClass)) { String stringData = new String(data); size = stringData.length(); nclob = conn.createNClob(); nclob.setString(1, stringData); rs.updateClob(1, nclob); } else { blob = conn.createBlob(); rs.updateBlob(1, blob); } rs.updateRow(); } if (null != clob) clob.free(); if (null != blob) blob.free(); if (null != nclob) nclob.free(); dropTables(table); } private int classType(Class type) { if (Clob.class == type) return clobType; else if (NClob.class == type) return nClobType; else return blobType; } private void updateLob(Object lob, Object updater, int index) throws Exception { if (updater instanceof PreparedStatement) this.updatePreparedStatement((PreparedStatement) updater, lob, index, (int) streamLength); else this.updateResultSet((ResultSet) updater, lob, index, (int) streamLength); } private void updatePreparedStatement(PreparedStatement ps, Object lob, int index, int length) throws Exception { if (lob instanceof DBCharacterStream) ps.setCharacterStream(index, (DBCharacterStream) lob, length); else if (lob instanceof DBBinaryStream) ps.setBinaryStream(index, (InputStream) lob, length); else if (lob instanceof Clob) ps.setClob(index, (Clob) lob); else ps.setBlob(index, (Blob) lob); assertEquals(ps.executeUpdate(), 1, "ExecuteUpdate did not return the correct updateCount"); } private void updateResultSet(ResultSet rs, Object lob, int index, int length) throws Exception { if (lob instanceof DBCharacterStream) { rs.updateCharacterStream(index, (DBCharacterStream) lob, length); } else if (lob instanceof DBBinaryStream) { rs.updateBinaryStream(index, (InputStream) lob, length); } else if (lob instanceof Clob) { rs.updateClob(index, (Clob) lob); } else { rs.updateBlob(index, (Blob) lob); } rs.updateRow(); } private Object createLob(Class lobClass) { // Randomly indicate negative length streamLength = ThreadLocalRandom.current().nextInt(3) < 2 ? datasize : -1 - ThreadLocalRandom.current().nextInt(datasize); // For streams -1 means any length, avoid to ensure that an exception is always thrown if (streamLength == -1 && (lobClass == DBCharacterStream.class || lobClass == DBBinaryStream.class)) streamLength = datasize; log.fine("Length passed into update : " + streamLength); byte[] data = new byte[datasize]; ThreadLocalRandom.current().nextBytes(data); if (lobClass == DBCharacterStream.class) return new DBInvalidUtil().new InvalidCharacterStream(new String(data), streamLength < -1); else if (lobClass == DBBinaryStream.class) return new DBInvalidUtil().new InvalidBinaryStream(data, streamLength < -1); if (lobClass == Clob.class) { ArrayList<SqlType> types = Utils.types(); SqlType type = Utils.find(String.class); Object expected = type.createdata(String.class, data); return new DBInvalidUtil().new InvalidClob(expected, false); } else { ArrayList<SqlType> types = Utils.types(); SqlType type = Utils.find(byte[].class); Object expected = type.createdata(type.getClass(), data); return new DBInvalidUtil().new InvalidBlob(expected, false); } } private static DBTable createTable(DBTable table, String[] types, boolean populateTable) throws Exception { DBStatement stmt = new DBConnection(connectionString).createStatement(); table = new DBTable(false); for (int i = 0; i < types.length; i++) { SqlType type = Utils.find(types[i]); table.addColumn(type); } stmt.createTable(table); if (populateTable) { stmt.populateTable(table); } stmt.close(); return table; } private static void dropTables(DBTable table) throws SQLException { stmt.executeUpdate("if object_id('" + table.getEscapedTableName() + "','U') is not null" + " drop table " + table.getEscapedTableName()); } }
package de.vorb.platon.security; import de.vorb.platon.util.TimeProvider; import com.google.common.truth.Truth; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.test.annotation.Repeat; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import java.time.Instant; @RunWith(MockitoJUnitRunner.class) public class HmacRequestVerifierTest { @Mock private SecretKeyProvider secretKeyProvider; @Mock private TimeProvider timeProvider; private HmacRequestVerifier requestVerifier; @Before public void setUp() throws Exception { // generate a secret key once and always return that secret key final SecretKey secretKey = KeyGenerator.getInstance( HmacRequestVerifier.HMAC_ALGORITHM.toString()).generateKey(); Mockito.when(secretKeyProvider.getSecretKey()).thenReturn(secretKey); requestVerifier = new HmacRequestVerifier(secretKeyProvider, timeProvider); } @Test @Repeat(10) public void testGetSignatureTokenIsRepeatable() throws Exception { final String identifier = "comment/1"; final Instant expirationDate = Instant.now(); final byte[] firstSignatureToken = requestVerifier.getSignatureToken(identifier, expirationDate); final byte[] secondSignatureToken = requestVerifier.getSignatureToken(identifier, expirationDate); Truth.assertThat(firstSignatureToken).isEqualTo(secondSignatureToken); } @Test public void testTokenExpiration() throws Exception { final String identifier = "comment/1"; final Instant currentTime = Instant.now(); Mockito.when(timeProvider.getCurrentTime()).thenReturn(currentTime); final Instant expirationDate = currentTime.minusMillis(1); // token expired 1ms ago final byte[] signatureToken = requestVerifier.getSignatureToken(identifier, expirationDate); final boolean validity = requestVerifier.isRequestValid(identifier, expirationDate, signatureToken); Truth.assertThat(validity).isFalse(); } @Test public void testCannotFakeExpirationDate() throws Exception { final String identifier = "comment/1"; final Instant currentTime = Instant.now(); Mockito.when(timeProvider.getCurrentTime()).thenReturn(currentTime); final Instant expirationDate = currentTime.minusMillis(1); final byte[] signatureToken = requestVerifier.getSignatureToken(identifier, expirationDate); // a user attempts to set the expiration date manually (without changing the token) final Instant fakedExpirationDate = currentTime; final boolean validity = requestVerifier.isRequestValid(identifier, fakedExpirationDate, signatureToken); Truth.assertThat(validity).isFalse(); } }
package info.u_team.u_team_test.screen; import org.apache.logging.log4j.*; import com.mojang.blaze3d.matrix.MatrixStack; import info.u_team.u_team_core.gui.elements.*; import info.u_team.u_team_core.gui.renderer.*; import info.u_team.u_team_test.TestMod; import net.minecraft.client.gui.screen.Screen; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.*; public class ButtonTestScreen extends Screen { private static final Logger LOGGER = LogManager.getLogger(); private static final ResourceLocation TEXTURE1 = new ResourceLocation(TestMod.MODID, "textures/item/better_enderpearl.png"); private static final ResourceLocation TEXTURE2 = new ResourceLocation(TestMod.MODID, "textures/item/basicitem.png"); public ButtonTestScreen() { super(new StringTextComponent("test")); } private ScalingTextRenderer scalingRenderer; private ScrollingTextRenderer scrollingRenderer; @Override protected void init() { // U Button Test final UButton uButton = addButton(new UButton(10, 10, 200, 15, ITextComponent.getTextComponentOrEmpty("U Button"))); uButton.setPressable(() -> LOGGER.info("Pressed UButton")); uButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("U Button Tooltip"), mouseX, mouseY); } }); // Scalable Button Test final ScalableButton scalableButton = addButton(new ScalableButton(10, 30, 200, 15, ITextComponent.getTextComponentOrEmpty("Better button"), 0.75F)); scalableButton.setPressable(button -> LOGGER.info("Pressed ScalableButton")); scalableButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("ScalableButton Tooltip"), mouseX, mouseY); } }); final ActiveButton activeButton = addButton(new ActiveButton(10, 50, 200, 15, ITextComponent.getTextComponentOrEmpty("Basic Test button"), 0x006442FF)); activeButton.setPressable(() -> { System.out.println("Pressed ActiveButton"); activeButton.setActive(!activeButton.isActive()); }); addButton(new ImageButton(10, 70, 16, 16, TEXTURE1, button -> System.out.println("Pressed ImageButton"))); final ActiveImageButton activeImageButton = addButton(new ActiveImageButton(10, 90, 20, 20, TEXTURE1, 0x006442FF)); activeImageButton.setPressable(() -> { System.out.println("Pressed ActiveImageButton"); activeImageButton.setActive(!activeImageButton.isActive()); }); final ToggleImageButton toggleImageButton = addButton(new ToggleImageButton(10, 115, 20, 20, TEXTURE1, TEXTURE2)); toggleImageButton.setPressable(() -> { System.out.println("Pressed ToggleImageButton"); }); addButton(new BetterFontSlider(300, 10, 200, 15, ITextComponent.getTextComponentOrEmpty("Test: "), ITextComponent.getTextComponentOrEmpty("%"), 0, 100, 20, false, true, 0.75F, slider -> { System.out.println("Updated slider value: " + slider.getValueInt() + " --> draging: " + slider.dragging); })); addButton(new BetterFontSlider(300, 30, 200, 40, ITextComponent.getTextComponentOrEmpty("Test: "), ITextComponent.getTextComponentOrEmpty("%"), 0, 100, 20, false, true, 2, slider -> { System.out.println("Updated slider value: " + slider.getValueInt() + " --> draging: " + slider.dragging); })); scalingRenderer = new ScalingTextRenderer(() -> font, () -> "This is a test for the scaling text renderer"); scalingRenderer.setColor(0xFFFFFF); scalingRenderer.setScale(2); scrollingRenderer = new ScrollingTextRenderer(() -> font, () -> "This is a test for the scrolling text renderer that should be really long to test the scrolling"); scrollingRenderer.setColor(0xFFFFFF); scrollingRenderer.setWidth(200); scrollingRenderer.setScale(0.75F); } @Override public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) { renderBackground(matrixStack); super.render(matrixStack, mouseX, mouseY, partialTicks); scalingRenderer.render(matrixStack, 10, 145); scrollingRenderer.render(matrixStack, 10, 170); buttons.forEach(widget -> widget.renderToolTip(matrixStack, mouseX, mouseY)); } }
package info.u_team.u_team_test.screen; import org.apache.logging.log4j.*; import com.mojang.blaze3d.matrix.MatrixStack; import info.u_team.u_team_core.gui.elements.*; import info.u_team.u_team_core.gui.renderer.*; import info.u_team.u_team_core.util.*; import info.u_team.u_team_test.TestMod; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.widget.TextFieldWidget; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.*; public class ButtonTestScreen extends Screen { private static final Logger LOGGER = LogManager.getLogger(); private static final ResourceLocation TEXTURE1 = new ResourceLocation(TestMod.MODID, "textures/item/better_enderpearl.png"); private static final ResourceLocation TEXTURE2 = new ResourceLocation(TestMod.MODID, "textures/item/basicitem.png"); private TextFieldWidget textFieldWidget; private ScalingTextRenderer scalingRenderer; private ScrollingTextRenderer scrollingRenderer; public ButtonTestScreen() { super(new StringTextComponent("test")); } @Override protected void init() { // U Button Test final UButton uButton = addButton(new UButton(10, 10, 200, 15, ITextComponent.getTextComponentOrEmpty("U Button"))); uButton.setPressable(() -> LOGGER.info("Pressed U Button")); uButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (WidgetUtil.isHovered(button)) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("U Button Tooltip"), mouseX, mouseY); } }); // Scalable Button Test final ScalableButton scalableButton = addButton(new ScalableButton(10, 30, 200, 15, ITextComponent.getTextComponentOrEmpty("Scalable Button"), 0.75F)); scalableButton.setTextColor(new RGBA(0x00FFFF80)); scalableButton.setPressable(button -> LOGGER.info("Pressed Scalable Button")); scalableButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (WidgetUtil.isHovered(button)) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Scalable Button Tooltip"), mouseX, mouseY); } }); // Scalable Activatable Button Test final ScalableActivatableButton scalableActivatableButton = addButton(new ScalableActivatableButton(10, 50, 200, 15, ITextComponent.getTextComponentOrEmpty("Scalable Activatable Button"), 0.75F, false, new RGBA(0x006442FF))); scalableActivatableButton.setPressable(() -> { LOGGER.info("Pressed Scalable Activatable Button"); scalableActivatableButton.setActivated(!scalableActivatableButton.isActivated()); }); scalableActivatableButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (WidgetUtil.isHovered(button)) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Scalable Activatable Button Tooltip"), mouseX, mouseY); } }); // Image Button Test final ImageButton imageButton = addButton(new ImageButton(10, 70, 15, 15, TEXTURE1)); imageButton.setPressable(() -> { LOGGER.info("Pressed Image Button"); }); imageButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (WidgetUtil.isHovered(button)) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Image Button Tooltip"), mouseX, mouseY); } }); final ImageButton imageButton2 = addButton(new ImageButton(30, 70, 15, 15, TEXTURE1)); imageButton2.setButtonColor(new RGBA(0xFFFF2080)); imageButton2.setImageColor(new RGBA(0x00FFFF80)); imageButton2.setPressable(() -> { LOGGER.info("Pressed Image Button 2"); }); imageButton2.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (WidgetUtil.isHovered(button)) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Image Button 2 Tooltip"), mouseX, mouseY); } }); // Image Activatable Button Test final ImageActivatableButton imageActivatableButton = addButton(new ImageActivatableButton(10, 90, 15, 15, TEXTURE1, false, new RGBA(0x006442FF))); imageActivatableButton.setPressable(() -> { LOGGER.info("Pressed Image Activatable Button"); imageActivatableButton.setActivated(!imageActivatableButton.isActivated()); }); imageActivatableButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (WidgetUtil.isHovered(button)) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Image Activatable Button Tooltip"), mouseX, mouseY); } }); // Image Toggle Button Test final ImageToggleButton imageToggleButton = addButton(new ImageToggleButton(10, 110, 15, 15, TEXTURE1, TEXTURE2, false)); imageToggleButton.setPressable(() -> { LOGGER.info("Pressed Image Toggle Button"); }); imageToggleButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (WidgetUtil.isHovered(button)) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Image Toggle Button Tooltip"), mouseX, mouseY); } }); final ImageToggleButton imageToggleButton2 = addButton(new ImageToggleButton(30, 110, 15, 15, TEXTURE1, TEXTURE1, false)); imageToggleButton2.setImageColor(new RGBA(0x00FF00FF)); imageToggleButton2.setToggleImageColor(new RGBA(0xFF0000FF)); imageToggleButton2.setPressable(() -> { LOGGER.info("Pressed Image Toggle Button 2"); }); imageToggleButton2.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (WidgetUtil.isHovered(button)) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Image Toggle Button 2 Tooltip"), mouseX, mouseY); } }); // U Slider Test final USlider uSlider = addButton(new USlider(10, 130, 200, 20, ITextComponent.getTextComponentOrEmpty("U Slider: "), ITextComponent.getTextComponentOrEmpty("%"), 0, 100, 20, false, true, false)); uSlider.setSlider(() -> { LOGGER.info("Updated U Slider: " + uSlider.getValueInt()); }); uSlider.setTooltip((slider, matrixStack, mouseX, mouseY) -> { if (slider.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("U Slider Tooltip"), mouseX, mouseY); } }); // Scalable Slider Test final ScalableSlider scalableSlider = addButton(new ScalableSlider(10, 155, 200, 15, ITextComponent.getTextComponentOrEmpty("Scalable Slider: "), ITextComponent.getTextComponentOrEmpty("%"), 0, 100, 20, false, true, false, 0.5F)); scalableSlider.setSlider(() -> { LOGGER.info("Updated Scalable Slider: " + scalableSlider.getValueInt()); }); scalableSlider.setTooltip((slider, matrixStack, mouseX, mouseY) -> { if (slider.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Scalable Slider Tooltip"), mouseX, mouseY); } }); final ScalableSlider scalableSlider2 = addButton(new ScalableSlider(10, 175, 200, 30, ITextComponent.getTextComponentOrEmpty("Scalable Slider 2: "), ITextComponent.getTextComponentOrEmpty("%"), 0, 100, 20, false, true, false, 1.5F)); scalableSlider2.setSliderBackgroundColor(new RGBA(0x0000FFFF)); scalableSlider2.setSliderColor(new RGBA(0x00FF00FF)); scalableSlider2.setTextColor(new RGBA(0xFF0000FF)); scalableSlider2.setDisabledTextColor(new RGBA(0xFFFF0080)); scalableSlider2.setSlider(() -> { LOGGER.info("Updated Scalable Slider 2: " + scalableSlider2.getValueInt()); if (scalableSlider2.getValueInt() == 100) { scalableSlider2.active = false; } }); scalableSlider2.setTooltip((slider, matrixStack, mouseX, mouseY) -> { if (slider.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Scalable Slider 2 Tooltip"), mouseX, mouseY); scalableSlider2.active = true; } }); // Checkbox Button Test final CheckboxButton checkboxButton = addButton(new CheckboxButton(10, 210, 15, 15, ITextComponent.getTextComponentOrEmpty("Checkbox Button"), false, true)); checkboxButton.setPressable(() -> { LOGGER.info("Pressed Checkbox Button"); }); checkboxButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (WidgetUtil.isHovered(button)) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Checkbox Button Tooltip"), mouseX, mouseY); } }); final CheckboxButton checkboxButton2 = addButton(new CheckboxButton(110, 230, 15, 15, ITextComponent.getTextComponentOrEmpty("Checkbox Button 2"), false, true)); checkboxButton2.setLeftSideText(true); checkboxButton2.setPressable(() -> { LOGGER.info("Pressed Checkbox Button 2"); }); checkboxButton2.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (WidgetUtil.isHovered(button)) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Checkbox Button 2 Tooltip"), mouseX, mouseY); } }); // Scalable Checkbox Button Test final ScalableCheckboxButton scalableCheckboxButton = addButton(new ScalableCheckboxButton(10, 250, 15, 15, ITextComponent.getTextComponentOrEmpty("Scalable Checkbox Button"), false, true, 0.75F)); scalableCheckboxButton.setPressable(() -> { LOGGER.info("Pressed Scalable Checkbox Button"); }); scalableCheckboxButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (WidgetUtil.isHovered(button)) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Scalable Checkbox Button Tooltip"), mouseX, mouseY); } }); final ScalableCheckboxButton scalableCheckboxButton2 = addButton(new ScalableCheckboxButton(110, 270, 15, 15, ITextComponent.getTextComponentOrEmpty("Scalable Checkbox Button 2"), false, true, 0.65F)); scalableCheckboxButton2.setLeftSideText(true); scalableCheckboxButton2.setButtonColor(new RGBA(0x0000F0FF)); scalableCheckboxButton2.setTextColor(new RGBA(0xA0A0A0FF)); scalableCheckboxButton2.setPressable(() -> { LOGGER.info("Pressed Scalable Checkbox Button 2"); }); scalableCheckboxButton2.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (WidgetUtil.isHovered(button)) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Scalable Checkbox Button 2 Tooltip"), mouseX, mouseY); } }); // TEST TEST this.minecraft.keyboardListener.enableRepeatEvents(true); textFieldWidget = addButton(new TextFieldWidget(font, 10, 290, 200, 20, null, new TranslationTextComponent("mco.configure.world.invite.profile.name"))); textFieldWidget.setCanLoseFocus(false); setFocusedDefault(textFieldWidget); scalingRenderer = new ScalingTextRenderer(() -> font, () -> "This is a test for the scaling text renderer", 220, 10); scalingRenderer.setColor(new RGBA(0xFF00FF40)); scalingRenderer.setScale(1.5F); scrollingRenderer = new ScrollingTextRenderer(() -> font, () -> "This is a test for the scrolling text renderer that should be really long to test the scrolling", 220, 25); scrollingRenderer.setColor(new RGBA(0x00FFFFFF)); scrollingRenderer.setWidth(200); scrollingRenderer.setScale(2F); } @Override public void onClose() { this.minecraft.keyboardListener.enableRepeatEvents(false); } @Override public void tick() { textFieldWidget.tick(); } @Override public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) { renderBackground(matrixStack); super.render(matrixStack, mouseX, mouseY, partialTicks); scalingRenderer.render(matrixStack, mouseX, mouseY, partialTicks); scrollingRenderer.render(matrixStack, mouseX, mouseY, partialTicks); buttons.forEach(widget -> widget.renderToolTip(matrixStack, mouseX, mouseY)); } }
package javax.jmdns.test; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import javax.jmdns.impl.DNSStatefulObjectSemaphore; import org.junit.After; import org.junit.Before; import org.junit.Test; public class DNSStatefulObjectSemaphoreTest { public static final class WaitingThread extends Thread { private final DNSStatefulObjectSemaphore _semaphore; private final long _timeout; private boolean _hasFinished; public WaitingThread(DNSStatefulObjectSemaphore semaphore, long timeout) { super("Waiting thread"); _semaphore = semaphore; _timeout = timeout; _hasFinished = false; } @Override public void run() { _semaphore.waitForEvent(_timeout); _hasFinished = true; } /** * @return the hasFinished */ public boolean hasFinished() { return _hasFinished; } } DNSStatefulObjectSemaphore _semaphore; @Before public void setup() { _semaphore = new DNSStatefulObjectSemaphore("test"); } @After public void teardown() { _semaphore = null; } @Test public void testWaitAndSignal() throws InterruptedException { WaitingThread thread = new WaitingThread(_semaphore, 0); thread.start(); Thread.sleep(1); assertFalse("The thread should be waiting.", thread.hasFinished()); _semaphore.signalEvent(); Thread.sleep(1); assertTrue("The thread should have finished.", thread.hasFinished()); } @Test public void testWaitAndTimeout() throws InterruptedException { WaitingThread thread = new WaitingThread(_semaphore, 100); thread.start(); Thread.sleep(1); assertFalse("The thread should be waiting.", thread.hasFinished()); Thread.sleep(150); assertTrue("The thread should have finished.", thread.hasFinished()); } }
package nl.brusque.iou.minimocha; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.*; class MiniMochaSpecification extends MiniMochaNode implements IMiniMochaDoneListener { private MiniMochaSpecificationRunnable _test; private Date _start; private Date _stop; private final ExecutorService _executor = Executors.newSingleThreadExecutor(); private final List<AssertionError> _assertionErrors = new ArrayList<>(); MiniMochaSpecification(String description, MiniMochaSpecificationRunnable test) { setName(description); _test = test; } private Thread.UncaughtExceptionHandler createUncaughtExceptionHandler() { return new Thread.UncaughtExceptionHandler() {; @Override public void uncaughtException(Thread thread, Throwable throwable) { if (throwable instanceof AssertionError) { _assertionErrors.add((AssertionError) throwable); return; } throwable.printStackTrace(); throw new Error("Unexpected uncaughtException", throwable); } }; } boolean _isDoneCalled = false; public synchronized final void done() { _stop = new Date(); _isDoneCalled = true; if (!_executor.isTerminated()) { _executor.shutdownNow(); } notify(); } private void testDone() throws TimeoutException { if (!_isDoneCalled) { throw new TimeoutException("Test timed-out."); } } public synchronized final void run() throws InterruptedException, ExecutionException, TimeoutException { Thread.UncaughtExceptionHandler oldUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(createUncaughtExceptionHandler()); _executor.submit(new Runnable() { @Override public void run() { _start = new Date(); _test.addDoneListener(MiniMochaSpecification.this); _test.run(); } }).get(2000, TimeUnit.MILLISECONDS); wait(2500); testDone(); Thread.setDefaultUncaughtExceptionHandler(oldUncaughtExceptionHandler); if (_assertionErrors.size()>0) { throw _assertionErrors.get(0); } } }
package org.amc.myservlet.test.spc; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.util.HashMap; import java.util.Map; import org.amc.Constants; import org.amc.DAOException; import org.amc.dao.DAO; import org.amc.dao.SPCMeasurementDAO; import org.amc.model.Part; import org.amc.model.spc.SPCMeasurement; import org.amc.model.spc.SPCPartsList; import org.amc.servlet.APLSpcController; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.test.web.ModelAndViewAssert; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.servlet.ModelAndView; public class TestAPLSpcController { private DAO<SPCPartsList> partsListDao; private DAO<Part> partsDAO; private APLSpcController controller; private MockHttpServletRequest request; private BindingResult result; private SPCMeasurementDAO spcMeasurementDAO; private int spcPartid=1; @SuppressWarnings("unchecked") @Before public void setUp() { request=new MockHttpServletRequest(); //request.addUserRole(Constants.roles.QC.toString()); result=mock(BindingResult.class); //when(result.hasErrors()).thenReturn(false); spcMeasurementDAO=mock(SPCMeasurementDAO.class); partsDAO=mock(DAO.class); partsListDao=mock(DAO.class); //when(spcListPartDAO.getEntity(anyString())).thenReturn(spcPartsList); controller=new APLSpcController(); controller.setSPCDimensionDAO(spcMeasurementDAO); controller.setPartDAO(partsDAO); controller.setSPCListPartDAO(partsListDao); } /** * Preconditions:The User is not in the correct role * Preconditions:No PersistenceException thrown */ @Test public void testGetDimensionListNotInRole() { ModelAndView mav=new ModelAndView(); //The user is not in the required role QC request.addUserRole(Constants.roles.GUEST.toString()); SPCMeasurement spcMeasurement=getSPCMeasurement(); //Call APLSpcController method mav=controller.addDimension(request,mav,spcPartid,spcMeasurement,result); //Check Error message set ModelAndViewAssert.assertModelAttributeAvailable(mav,"message"); //Check the user is directed the Main.jsp ModelAndViewAssert.assertViewName(mav,"Main"); //Check there were no calls on the SPCMeasurement DAO verifyZeroInteractions(spcMeasurementDAO); } /** * * Preconditions:The User is in the correct role * Preconditions:No PersistenceException thrown */ @Test public void testGetDimensionList() throws DAOException { ModelAndView mav=new ModelAndView(); //The user is in the correct role request.addUserRole(Constants.roles.QC.toString()); when(this.partsListDao.getEntity(anyString())).thenReturn(this.getSPCPartsList()); SPCMeasurement spcMeasurement=getSPCMeasurement(); //Call APLSpcController method mav=controller.addDimension(request,mav,spcPartid,spcMeasurement,result); //Check that the required attributes were set ModelAndViewAssert.assertModelAttributeAvailable(mav,"spcPart"); ModelAndViewAssert.assertModelAttributeAvailable(mav,"dimensions"); ModelAndViewAssert.assertModelAttributeAvailable(mav,"part"); //Check the user is sent to the correct view ModelAndViewAssert.assertViewName(mav,"spc/SPCMeasurement"); } /** * Precondition:User in Role QC * Precondition:Binding Result returns error * Precondition:No PersistenceException thrown */ @Test public void testAddDimensionBindingError() throws DAOException { ModelAndView mav=new ModelAndView(); request.addUserRole(Constants.roles.QC.toString()); when(this.partsListDao.getEntity(anyString())).thenReturn(this.getSPCPartsList()); //Binding Results returns true. Errors mapping the form values to the Model attribute found when(result.hasErrors()).thenReturn(true); FieldError fieldError=mock(FieldError.class); when(fieldError.getField()).thenReturn("Input Field"); when(fieldError.getCode()).thenReturn("Input Code"); when(result.getFieldError()).thenReturn(fieldError); SPCMeasurement spcMeasurement=getSPCMeasurement(); mav=controller.addDimension(request,mav,spcPartid,spcMeasurement,result); //verifyZeroInteractions(spcMeasurementDAO); //Check the user is sent to the correct view ModelAndViewAssert.assertViewName(mav,"spc/SPCMeasurement"); //Check Error message set Object errors=mav.getModelMap().get("errors"); //Check errors is a list assertTrue(errors instanceof Map); } /** * Precondition:User not in Role QC * Precondition:Binding Result no error * Precondition:No PersistenceException thrown */ @Test public void testAddDimensionNotInRole() { ModelAndView mav=new ModelAndView(); //User is not in the required role request.addUserRole(Constants.roles.GUEST.toString()); //No binding errors when(result.hasErrors()).thenReturn(false); SPCMeasurement spcMeasurement=getSPCMeasurement(); mav=controller.addDimension(request,mav,spcPartid,spcMeasurement,result); //Check there were no calls on the SPCMeasurement DAO verifyZeroInteractions(spcMeasurementDAO); //Check the user is sent to the correct view ModelAndViewAssert.assertViewName(mav,"Main"); //Check Error message set ModelAndViewAssert.assertModelAttributeAvailable(mav, "message"); } /** * Precondition:User in Role QC * Precondition:Binding Result no error * Precondition:No PersistenceException thrown */ @Test public void testAddDimension() throws DAOException { ModelAndView mav=new ModelAndView(); request.addUserRole(Constants.roles.QC.toString()); when(result.hasErrors()).thenReturn(false); SPCMeasurement spcMeasurement=getSPCMeasurement(); when(this.partsListDao.getEntity(anyString())).thenReturn(this.getSPCPartsList()); mav=controller.addDimension(request,mav,spcPartid,spcMeasurement,result); //Check that entity SPCMeasurement is passed to the DAO for persistence verify(spcMeasurementDAO).addEntity(spcMeasurement); //Check the user is sent to the correct view ModelAndViewAssert.assertViewName(mav,"spc/SPCMeasurement"); //Check that the required attribute was set ModelAndViewAssert.assertModelAttributeAvailable(mav, "part"); } /** * Precondition:User in Role QC * Precondition:Binding Result no error * Precondition:PersistenceException thrown */ @Test public void testAddDimensionExceptionThrown() throws DAOException { ModelAndView mav=new ModelAndView(); //User is not in the required role request.addUserRole(Constants.roles.QC.toString()); Map<String, Object> params=new HashMap<String, Object>(); request.setParameters(params); //No binding errors when(result.hasErrors()).thenReturn(false); SPCMeasurement spcMeasurement=getSPCMeasurement(); when(this.partsListDao.getEntity(anyString())).thenReturn(this.getSPCPartsList()); doThrow(new DAOException()).when(spcMeasurementDAO).addEntity(any(SPCMeasurement.class)); mav=controller.addDimension(request,mav,spcPartid,spcMeasurement,result); //Check the user is sent to the correct view ModelAndViewAssert.assertViewName(mav,"spc/SPCMeasurement"); //Check that the required attribute was set /* @Todo */ //ModelAndViewAssert.assertModelAttributeAvailable(mav, "message"); assertNotNull(mav.getModelMap().get("message")); } /** * * @return typical SPCMeasurement Object */ private SPCMeasurement getSPCMeasurement() { SPCMeasurement spcMeasurement=new SPCMeasurement(); spcMeasurement.setDimension("Length of Side"); spcMeasurement.setActive(true); spcMeasurement.setLowerLimit(3); spcMeasurement.setUpperLimit(3); spcMeasurement.setNoOfMeasurements(5); spcMeasurement.setNominal(123.3f); return spcMeasurement; } /** * * @return typical SPCPartsList Object */ private SPCPartsList getSPCPartsList() { SPCPartsList spcPartsList=new SPCPartsList(); spcPartsList.setId(1); spcPartsList.setPart(new Part()); return spcPartsList; } }
package org.animotron.games.web; import org.animotron.ATest; import org.animotron.expression.Expression; import org.animotron.expression.JExpression; import org.animotron.statement.compare.WITH; import org.animotron.statement.query.ANY; import org.animotron.statement.query.GET; import org.junit.Test; import java.io.IOException; import static org.animotron.expression.AnimoExpression.__; import static org.animotron.expression.JExpression._; import static org.animotron.expression.JExpression.value; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a> * */ public class CurrentWebFrameworkTest extends ATest { private Expression query(String site, String service) { return new JExpression( _(ANY._, service, _(WITH._, "server-name", value(site)) ) ); } private Expression mime(Expression query) { return new JExpression(_(GET._, "type", _(GET._, "mime-type", _(query)))); } private void assertQuery(String site, String service, String mime, String html) throws IOException, InterruptedException { Expression e = query(site, service); assertStringResult(mime(e), mime); assertHtmlResult(e, html); } @Test public void test() throws Throwable { __( "the foo-site (site) (server-name \"foo.com\") (weak-use foo)", "the bar-site (site) (server-name \"bar.com\") (weak-use bar)", "the text-html (mime-type) (type \"text/html\") (extension \"htm\" \"html\")", "the html-page (mime-tipe text-html) (\\html (\\head \\title get title) (\\body any layout))", "the hello-foo (html-page) (foo-site, root) (use root) (title \"hello foo\") (content \"foo foo foo\")", "the hello-bar (html-page) (bar-site, root) (use root) (title \"hello bar\") (content \"bar bar bar\")", "the xxx-service (html-page) (foo-site, bar-site, xxx) (use xxx) (title \"hello yyy\") (content \"yyy yyy yyy\")", "the zzz-service (html-page) (foo-site, zzz) (use qLayout) (title \"hello zzz\") (content \"zzz zzz zzz\")", "the yyy-service (html-page) (bar-site, yyy) (use qLayout) (title \"hello yyy\") (content \"yyy yyy yyy\")", "the foo-root-layout (layout, foo, root) (\\h1 get title) (\\p get content)", "the bar-root-layout (layout, bar, root) (\\h2 get title) (\\div get content)", "the foo-xxx-layout (layout, foo, xxx) (\\h3 get title) (\\p get content)", "the bar-xxx-layout (layout, bar, xxx) (\\h4 get title) (\\div get content)", "the qLayout (layout) (\\h3 get title) (\\span get content)" ); assertQuery("foo.com", "root", "text/html", "<html><head><title>hello foo</title></head><body><h1>hello foo</h1><p>foo foo foo</p></body></html>"); assertQuery("foo.com", "xxx", "", ""); assertQuery("foo.com", "yyy", "", ""); assertQuery("foo.com", "zzz", "text/html", "<html><head><title>hello zzz</title></head><body><h3>hello zzz</h3><span>zzz zzz zzz</span></body></html>"); assertQuery("bar.com", "root", "text/html", "<html><head><title>hello bar</title></head><body><h2>hello bar</h2><div>bar bar bar</div></body></html>"); assertQuery("bar.com", "xxx", "", ""); assertQuery("bar.com", "yyy", "text/html", "<html><head><title>hello yyy</title></head><body><h3>hello yyy</h3><span>yyy yyy yyy</span></body></html>"); assertQuery("bar.com", "zzz", "", ""); } }
package org.animotron.games.web; import org.animotron.ATest; import org.animotron.expression.AbstractExpression; import org.animotron.expression.Expression; import org.animotron.statement.compare.WITH; import org.animotron.statement.operator.AN; import org.animotron.statement.operator.REF; import org.animotron.statement.query.ANY; import org.animotron.statement.query.GET; import org.junit.Ignore; import org.junit.Test; import java.io.IOException; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a> * */ public class CurrentWebFrameworkTest extends ATest { private Expression query(final String site, final String service) { return new AbstractExpression() { @Override public void build() throws Throwable { builder.start(AN._); builder.start(GET._); builder._(REF._, service); builder.start(ANY._); builder._(REF._, "site"); builder.start(WITH._); builder._(REF._, "server-name"); builder._(site); builder.end(); builder.end(); builder.end(); builder.end(); } }; } private Expression error(final String site, final int code, String trace) { return new AbstractExpression() { @Override public void build() throws Throwable { builder.start(AN._); builder.start(GET._); builder.start(ANY._); builder._(REF._, "error"); builder.start(WITH._); builder._(REF._, "code"); builder._(code); builder.end(); builder.end(); builder.start(ANY._); builder._(REF._, "site"); builder.start(WITH._); builder._(REF._, "server-name"); builder._(site); builder.end(); builder.end(); builder.end(); builder.end(); } }; } private Expression mime(final Expression query) { return new AbstractExpression() { @Override public void build() throws Throwable { builder.start(GET._); builder._(REF._, "type"); builder.start(GET._); builder._(REF._, "mime-type"); builder.bind(query); builder.end(); builder.end(); } }; } private void assertQuery(String site, String service, String mime, String html) throws IOException, InterruptedException { Expression e = query(site, service); assertStringResult(mime(e), mime); assertStringResult(e, html); } private void assertError(String site, int code, String trace, String mime, String html) throws IOException, InterruptedException { Expression e = error(site, code, trace); assertStringResult(mime(e), mime); assertStringResult(e, html); } @Test @Ignore public void test() throws Throwable { __( "def site (not-found-error default-not-found) (xxx xxx-service).", "def not-found-error (error) (code 404)." ); assertAnimoResult("get not-found-error site", "default-not-found."); } @Test @Ignore public void test_00() throws Throwable { __( "def site (icon any logo) (not-found-error default-not-found) (xxx xxx-service).", "def foo-site (^site) (server-name \"foo.com\") (weak-use foo) (root hello-foo) (zzz zzz-service).", "def bar-site (^site) (server-name \"bar.com\") (weak-use bar) (root hello-bar) (yyy yyy-service) (not-found-error bar-not-found).", "def text-html (mime-type) (type \"text/html\") (extension \"htm\" \"html\").", "def html-page (^text-html) (\\html (\\head (each (get icon) (\\link @href get uri)) (\\title get title)) (\\body any layout)).", "def hello-foo (^html-page) (use root) (title \"hello foo\") (content \"foo foo foo\").", "def hello-bar (^html-page) (use root) (title \"hello bar\") (content \"bar bar bar\").", "def xxx-service (^html-page) (use xxx) (title \"hello xxx\") (content \"xxx xxx xxx\").", "def zzz-service (^html-page) (use qLayout) (title \"hello zzz\") (content \"zzz zzz zzz\").", "def yyy-service (^html-page) (use qLayout) (title \"hello yyy\") (content \"yyy yyy yyy\").", "def foo-root-layout (layout, foo, root) (\\h1 get title) (\\p get content).", "def bar-root-layout (layout, bar, root) (\\h2 get title) (\\div get content).", "def foo-xxx-layout (layout, foo, xxx) (\\h3 get title) (\\p get content) (\\p get server-name).", "def bar-xxx-layout (layout, bar, xxx) (\\h4 get title) (\\div get content) (\\p get server-name).", "def qLayout (layout) (\\h3 get title) (\\span get content).", "def not-found-error (error) (code 404).", "def default-not-found (^html-page) (use default-error-layout) (title \"Not found\") (message \"Not found anything\").", "def bar-not-found (^html-page) (use error) (title \"Error. Not found\") (message \"Sorry, not found anything\").", "def default-error-layout (layout) (\\h1 get code) (\\h2 get title) (\\p get message) (\\p get stack-trace).", "def bar-errogr-layout (layout, bar, error) (\\h1 get code) (\\h2 get title) (\\div get message) (\\div get stack-trace).", "def foo-logo (logo, foo) (uri \"foo.png\").", "def bar-logo (logo, bar) (uri \"bar.png\")." ); assertAnimoResult("any error with code 404", "not-found-error (error) (code)."); assertAnimoResult( "get not-found-error site.", "default-not-found (html-page (text-html (mime-type) (type) (extension)) (\\html (\\head (\\link @href \"foo.png\") (\\title \"Not found\")) (\\body default-error-layout (layout) (\\h1 404) (\\h2 \"Not found\") (\\p \"Not found anything\") (\\p)))) (use default-error-layout) (title) (message)." ); assertAnimoResult( "get (any error with code 404) (site).", "default-not-found (html-page (text-html (mime-type) (type) (extension)) (\\html (\\head (\\link @href \"foo.png\") (\\title \"Not found\")) (\\body default-error-layout (layout) (\\h1 404) (\\h2 \"Not found\") (\\p \"Not found anything\") (\\p)))) (use default-error-layout) (title) (message)." ); assertError("foo.com", 404, "stack trace would be here", "text/html", "<html><head><link href=\"foo.png\"><title>Not found</title></head><body><h1>404</h1><h2>Not found</h2><p>Not found anything</p><p>stack trace would be here</p></body></html>" ); assertError("foo.com", 500, "", "", ""); assertError("bar.com", 404, "stack trace", "text/html", "<html><head><link href=\"bar.png\"><title>Error. Not found</title></head><body><h1>404</h1><h2>Error. Not found</h2><div>Sorry, not found anything</div><div>stack trace</div></body></html>" ); assertError("bar.com", 500, "", "", ""); assertQuery("foo.com", "root", "text/html", "<html><head><link href=\"foo.png\"><title>hello foo</title></head><body><h1>hello foo</h1><p>foo foo foo</p></body></html>"); assertQuery("foo.com", "xxx", "text/html", "<html><head><link href=\"foo.png\"><title>hello xxx</title></head><body><h3>hello xxx</h3><p>xxx xxx xxx</p><p>foo.com</p></body></html>"); assertQuery("foo.com", "yyy", "", ""); assertQuery("foo.com", "zzz", "text/html", "<html><head><link href=\"foo.png\"><title>hello zzz</title></head><body><h3>hello zzz</h3><span>zzz zzz zzz</span></body></html>"); assertQuery("bar.com", "root", "text/html", "<html><head><link href=\"bar.png\"><title>hello bar</title></head><body><h2>hello bar</h2><div>bar bar bar</div></body></html>"); assertQuery("bar.com", "xxx", "text/html", "<html><head><link href=\"bar.png\"><title>hello xxx</title></head><body><h4>hello xxx</h4><div>xxx xxx xxx</div><p>bar.com</p></body></html>"); assertQuery("bar.com", "yyy", "text/html", "<html><head><link href=\"bar.png\"><title>hello yyy</title></head><body><h3>hello yyy</h3><span>yyy yyy yyy</span></body></html>"); assertQuery("bar.com", "zzz", "", ""); } @Test @Ignore public void test_01() throws Throwable { __( "def site.", "def not-found-error.", "def default-not-found.", "def xxx.", "def xxx-service.", "def foo-site.", "def site.", "def server-name.", "def foo.", "def root.", "def hello-foo.", "def zzz.", "def zzz-service.", "def bar-site.", "def bar.", "def hello-bar.", "def yyy.", "def yyy-service.", "def bar-not-found.", "def text-html.", "def mime-type.", "def type.", "def extension.", "def html-page.", "def title.", "def layout.", "def content.", "def qLayout.", "def foo-root-layout.", "def bar-root-layout.", "def foo-xxx-layout.", "def bar-xxx-layout.", "def default-error-layout.", "def bar-error-layout.", "def code.", "def error.", "def message.", "def stack-trace.", "def logo.", "def foo-logo.", "def bar-logo.", "def icon.", "def site (icon any logo) (not-found-error default-not-found) (xxx xxx-service).", "def foo-site (^site) (server-name \"foo.com\") (weak-use foo) (root hello-foo) (zzz zzz-service).", "def bar-site (^site) (server-name \"bar.com\") (weak-use bar) (root hello-bar) (yyy yyy-service) (not-found-error bar-not-found).", "def text-html (mime-type) (type \"text/html\") (extension \"htm\" \"html\").", "def html-page (^text-html) (\\html (\\head (each (get icon) (\\link @href get uri)) (\\title get title)) (\\body any layout)).", "def hello-foo (^html-page) (use root) (title \"hello foo\") (content \"foo foo foo\").", "def hello-bar (^html-page) (use root) (title \"hello bar\") (content \"bar bar bar\").", "def xxx-service (^html-page) (use xxx) (title \"hello xxx\") (content \"xxx xxx xxx\").", "def zzz-service (^html-page) (use qLayout) (title \"hello zzz\") (content \"zzz zzz zzz\").", "def yyy-service (^html-page) (use qLayout) (title \"hello yyy\") (content \"yyy yyy yyy\").", "def foo-root-layout (layout, foo, root) (\\h1 get title) (\\p get content).", "def bar-root-layout (layout, bar, root) (\\h2 get title) (\\div get content).", "def foo-xxx-layout (layout, foo, xxx) (\\h3 get title) (\\p get content) (\\p get server-name).", "def bar-xxx-layout (layout, bar, xxx) (\\h4 get title) (\\div get content) (\\p get server-name).", "def qLayout (layout) (\\h3 get title) (\\span get content).", "def not-found-error (error) (code 404).", "def default-not-found (^html-page) (use default-error-layout) (title \"Not found\") (message \"Not found anything\").", "def bar-not-found (^html-page) (use error) (title \"Error. Not found\") (message \"Sorry, not found anything\").", "def default-error-layout (layout) (\\h1 get code) (\\h2 get title) (\\p get message) (\\p get stack-trace).", "def bar-errogr-layout (layout, bar, error) (\\h1 get code) (\\h2 get title) (\\div get message) (\\div get stack-trace).", "def foo-logo (logo, foo) (uri \"foo.png\").", "def bar-logo (logo, bar) (uri \"bar.png\")." ); assertAnimoResult("any error with code 404", "not-found-error (error) (code)."); assertAnimoResult( "get not-found-error site.", "default-not-found (html-page (text-html (mime-type) (type) (extension)) (\\html (\\head (\\link @href \"foo.png\") (\\title \"Not found\")) (\\body default-error-layout (layout) (\\h1 404) (\\h2 \"Not found\") (\\p \"Not found anything\") (\\p)))) (use default-error-layout) (title) (message)." ); assertAnimoResult( "get (any error with code 404) (site).", "default-not-found (html-page (text-html (mime-type) (type) (extension)) (\\html (\\head (\\link @href \"foo.png\") (\\title \"Not found\")) (\\body default-error-layout (layout) (\\h1 404) (\\h2 \"Not found\") (\\p \"Not found anything\") (\\p)))) (use default-error-layout) (title) (message)." ); assertError("foo.com", 404, "stack trace would be here", "text/html", "<html><head><link href=\"foo.png\"><title>Not found</title></head><body><h1>404</h1><h2>Not found</h2><p>Not found anything</p><p>stack trace would be here</p></body></html>" ); assertError("foo.com", 500, "", "", ""); assertError("bar.com", 404, "stack trace", "text/html", "<html><head><link href=\"bar.png\"><title>Error. Not found</title></head><body><h1>404</h1><h2>Error. Not found</h2><div>Sorry, not found anything</div><div>stack trace</div></body></html>" ); assertError("bar.com", 500, "", "", ""); assertQuery("foo.com", "root", "text/html", "<html><head><link href=\"foo.png\"><title>hello foo</title></head><body><h1>hello foo</h1><p>foo foo foo</p></body></html>"); assertQuery("foo.com", "xxx", "text/html", "<html><head><link href=\"foo.png\"><title>hello xxx</title></head><body><h3>hello xxx</h3><p>xxx xxx xxx</p><p>foo.com</p></body></html>"); assertQuery("foo.com", "yyy", "", ""); assertQuery("foo.com", "zzz", "text/html", "<html><head><link href=\"foo.png\"><title>hello zzz</title></head><body><h3>hello zzz</h3><span>zzz zzz zzz</span></body></html>"); assertQuery("bar.com", "root", "text/html", "<html><head><link href=\"bar.png\"><title>hello bar</title></head><body><h2>hello bar</h2><div>bar bar bar</div></body></html>"); assertQuery("bar.com", "xxx", "text/html", "<html><head><link href=\"bar.png\"><title>hello xxx</title></head><body><h4>hello xxx</h4><div>xxx xxx xxx</div><p>bar.com</p></body></html>"); assertQuery("bar.com", "yyy", "text/html", "<html><head><link href=\"bar.png\"><title>hello yyy</title></head><body><h3>hello yyy</h3><span>yyy yyy yyy</span></body></html>"); assertQuery("bar.com", "zzz", "", ""); } @Test @Ignore public void test_02() throws Throwable { __( "def site (not-found-error default-not-found) (xxx xxx-service).", "def foo-site (^site) (server-name \"foo.com\") (weak-use foo) (root hello-foo) (zzz zzz-service).", "def bar-site (^site) (server-name \"bar.com\") (weak-use bar) (root hello-bar) (yyy yyy-service) (not-found-error bar-not-found).", "def text-html (mime-type) (type \"text/html\") (extension \"htm\" \"html\").", "def html-page (mime-type text-html) (\\html (\\head \\title get title) (\\body any layout)).", "def hello-foo (^html-page) (use root) (title \"hello foo\") (content \"foo foo foo\").", "def hello-bar (^html-page) (use root) (title \"hello bar\") (content \"bar bar bar\").", "def xxx-service (^html-page) (use xxx) (title \"hello xxx\") (content \"xxx xxx xxx\").", "def zzz-service (^html-page) (use qLayout) (title \"hello zzz\") (content \"zzz zzz zzz\").", "def yyy-service (^html-page) (use qLayout) (title \"hello yyy\") (content \"yyy yyy yyy\").", "def foo-root-layout (layout, foo, root) (\\h1 get title) (\\p get content).", "def bar-root-layout (layout, bar, root) (\\h2 get title) (\\div get content).", "def foo-xxx-layout (layout, foo, xxx) (\\h3 get title) (\\p get content) (\\p get server-name).", "def bar-xxx-layout (layout, bar, xxx) (\\h4 get title) (\\div get content) (\\p get server-name).", "def qLayout (layout) (\\h3 get title) (\\span get content).", "def not-found-error (error) (code 404).", "def default-not-found (^html-page) (use default-error-layout) (title \"Not found\") (message \"Not found anything\").", "def bar-not-found (^html-page) (use error) (title \"Error. Not found\") (message \"Sorry, not found anything\").", "def default-error-layout (layout) (\\h1 get code) (\\h2 get title) (\\p get message) (\\p get stack-trace).", "def bar-error-layout (layout, bar, error) (\\h1 get code) (\\h2 get title) (\\div get message) (\\div get stack-trace)." ); assertError("foo.com", 404, "stack trace would be here", "text/html", "<html><head><title>Not found</title></head><body><h1>404</h1><h2>Not found</h2><p>Not found anything</p><p>stack trace would be here</p></body></html>" ); assertError("foo.com", 500, "", "", ""); assertError("bar.com", 404, "stack trace", "text/html", "<html><head><title>Error. Not found</title></head><body><h1>404</h1><h2>Error. Not found</h2><div>Sorry, not found anything</div><div>stack trace</div></body></html>" ); assertError("bar.com", 500, "", "", ""); assertQuery("foo.com", "root", "text/html", "<html><head><title>hello foo</title></head><body><h1>hello foo</h1><p>foo foo foo</p></body></html>"); assertQuery("foo.com", "xxx", "text/html", "<html><head><title>hello xxx</title></head><body><h3>hello xxx</h3><p>xxx xxx xxx</p><p>foo.com</p></body></html>"); assertQuery("foo.com", "yyy", "", ""); assertQuery("foo.com", "zzz", "text/html", "<html><head><title>hello zzz</title></head><body><h3>hello zzz</h3><span>zzz zzz zzz</span></body></html>"); assertQuery("bar.com", "root", "text/html", "<html><head><title>hello bar</title></head><body><h2>hello bar</h2><div>bar bar bar</div></body></html>"); assertQuery("bar.com", "xxx", "text/html", "<html><head><title>hello xxx</title></head><body><h4>hello xxx</h4><div>xxx xxx xxx</div><p>bar.com</p></body></html>"); assertQuery("bar.com", "yyy", "text/html", "<html><head><title>hello yyy</title></head><body><h3>hello yyy</h3><span>yyy yyy yyy</span></body></html>"); assertQuery("bar.com", "zzz", "", ""); } @Test @Ignore public void test_03() throws Throwable { __( "def foo-site (^site) (server-name \"foo.com\") (weak-use foo) (root hello-foo) (xxx xxx-service) (zzz zzz-service).", "def bar-site (^site) (server-name \"bar.com\") (weak-use bar) (root hello-bar) (xxx xxx-service) (yyy yyy-service).", "def text-html (mime-type) (type \"text/html\") (extension \"htm\" \"html\").", "def html-page (mime-type text-html) (\\html (\\head \\title get title) (\\body any layout)).", "def hello-foo (^html-page) (use root) (title \"hello foo\") (content \"foo foo foo\").", "def hello-bar (^html-page) (use root) (title \"hello bar\") (content \"bar bar bar\").", "def xxx-service (^html-page) (use xxx) (title \"hello xxx\") (content \"xxx xxx xxx\").", "def zzz-service (^html-page) (use qLayout) (title \"hello zzz\") (content \"zzz zzz zzz\").", "def yyy-service (^html-page) (use qLayout) (title \"hello yyy\") (content \"yyy yyy yyy\").", "def foo-root-layout (layout, foo, root) (\\h1 get title) (\\p get content).", "def bar-root-layout (layout, bar, root) (\\h2 get title) (\\div get content).", "def foo-xxx-layout (layout, foo, xxx) (\\h3 get title) (\\p get content) (\\p get server-name).", "def bar-xxx-layout (layout, bar, xxx) (\\h4 get title) (\\div get content) (\\p get server-name).", "def qLayout (layout) (\\h3 get title) (\\span get content)." ); assertQuery("foo.com", "root", "text/html", "<html><head><title>hello foo</title></head><body><h1>hello foo</h1><p>foo foo foo</p></body></html>"); assertQuery("foo.com", "xxx", "text/html", "<html><head><title>hello xxx</title></head><body><h3>hello xxx</h3><p>xxx xxx xxx</p><p>foo.com</p></body></html>"); assertQuery("foo.com", "yyy", "", ""); assertQuery("foo.com", "zzz", "text/html", "<html><head><title>hello zzz</title></head><body><h3>hello zzz</h3><span>zzz zzz zzz</span></body></html>"); assertQuery("bar.com", "root", "text/html", "<html><head><title>hello bar</title></head><body><h2>hello bar</h2><div>bar bar bar</div></body></html>"); assertQuery("bar.com", "xxx", "text/html", "<html><head><title>hello xxx</title></head><body><h4>hello xxx</h4><div>xxx xxx xxx</div><p>bar.com</p></body></html>"); assertQuery("bar.com", "yyy", "text/html", "<html><head><title>hello yyy</title></head><body><h3>hello yyy</h3><span>yyy yyy yyy</span></body></html>"); assertQuery("bar.com", "zzz", "", ""); } @Test @Ignore public void test_04() throws Throwable { __( "def site not-found-error default-not-found.", "def foo-site (^site) (server-name \"foo.com\") (weak-use foo) (root hello-foo).", "def text-html (mime-type) (type \"text/html\") (extension \"htm\" \"html\").", "def html-page (^text-html) (\\html (\\head \\title get title) (\\body any layout)).", "def hello-foo (^html-page) (use root) (title \"hello foo\") (content \"foo foo foo\").", "def foo-root-layout (layout, foo, root) (\\h1 get title) (\\p get content).", "def not-found-error (error) (code 404).", "def default-not-found (^html-page) (use default-error-layout) (title \"Not found\") (message \"Not found anything\").", "def default-error-layout (layout) (\\h1 get code) (\\h2 get title) (\\p get message) (\\p get stack-trace)." ); assertError("foo.com", 404, "stack trace would be here", "text/html", "<html><head><title>Not found</title></head><body><h1>404</h1><h2>Not found</h2><p>Not found anything</p><p>stack trace would be here</p></body></html>" ); assertQuery("foo.com", "root", "text/html", "<html><head><title>hello foo</title></head><body><h1>hello foo</h1><p>foo foo foo</p></body></html>"); } @Test @Ignore public void test_05() throws Throwable { __( "def site not-found-error default-not-found.", "def foo-site (^site) (server-name \"foo.com\") (weak-use foo) (root hello-foo).", "def text-html (mime-type) (type \"text/html\") (extension \"htm\" \"html\").", "def html-page (mime-type text-html) (\\html (\\head \\title get title) (\\body any layout)).", "def hello-foo (^html-page) (use root) (title \"hello foo\") (content \"foo foo foo\").", "def foo-root-layout (layout, foo, root) (\\h1 get title) (\\p get content).", "def not-found-error (error) (code 404).", "def default-not-found (^html-page) (use default-error-layout) (title \"Not found\") (message \"Not found anything\").", "def default-error-layout (layout) (\\h1 get code) (\\h2 get title) (\\p get message) (\\p get stack-trace)." ); assertError("foo.com", 404, "stack trace would be here", "text/html", "<html><head><title>Not found</title></head><body><h1>404</h1><h2>Not found</h2><p>Not found anything</p><p>stack trace would be here</p></body></html>" ); assertQuery("foo.com", "root", "text/html", "<html><head><title>hello foo</title></head><body><h1>hello foo</h1><p>foo foo foo</p></body></html>"); } @Test @Ignore public void test_06() throws Throwable { __( "def foo-site (^site) (server-name \"foo.com\") (weak-use foo) (root hello-foo).", "def text-html (mime-type) (type \"text/html\") (extension \"htm\" \"html\").", "def html-page (^text-html) (\\html (\\head \\title get title) (\\body any layout)).", "def hello-foo (^html-page) (use root) (title \"hello foo\") (content \"foo foo foo\").", "def foo-root-layout (layout, foo, root) (\\h1 get title) (\\p get content)." ); assertQuery("foo.com", "root", "text/html", "<html><head><title>hello foo</title></head><body><h1>hello foo</h1><p>foo foo foo</p></body></html>"); } @Test @Ignore public void test_07() throws Throwable { __( "def foo-site (^site) (server-name \"foo.com\") (weak-use foo) (root hello-foo).", "def text-html (mime-type) (type \"text/html\") (extension \"htm\" \"html\").", "def html-page (mime-type text-html) (\\html (\\head \\title get title) (\\body any layout)).", "def hello-foo (^html-page) (use root) (title \"hello foo\") (content \"foo foo foo\").", "def foo-root-layout (layout, foo, root) (\\h1 get title) (\\p get content)." ); assertQuery("foo.com", "root", "text/html", "<html><head><title>hello foo</title></head><body><h1>hello foo</h1><p>foo foo foo</p></body></html>"); } @Test @Ignore public void test_08() throws Throwable { __( "def site not-found-error default-not-found.", "def foo-site (^site) (server-name \"foo.com\") (weak-use foo).", "def text-html (mime-type) (type \"text/html\") (extension \"htm\" \"html\").", "def html-page (^text-html) (\\html (\\head \\title get title) (\\body any layout)).", "def not-found-error (error) (code 404).", "def default-not-found (^html-page) (use default-error-layout) (title \"Not found\") (message \"Not found anything\").", "def default-error-layout (layout) (\\h1 get code) (\\h2 get title) (\\p get message) (\\p get stack-trace)." ); assertError("foo.com", 404, "stack trace would be here", "text/html", "<html><head><title>Not found</title></head><body><h1>404</h1><h2>Not found</h2><p>Not found anything</p><p>stack trace would be here</p></body></html>" ); } @Test @Ignore public void test_09() throws Throwable { __( "def site not-found-error default-not-found.", "def foo-site (^site) (server-name \"foo.com\") (weak-use foo).", "def text-html (mime-type) (type \"text/html\") (extension \"htm\" \"html\").", "def html-page (mime-type text-html) (\\html (\\head \\title get title) (\\body any layout)).", "def not-found-error (error) (code 404).", "def default-not-found (^html-page) (use default-error-layout) (title \"Not found\") (message \"Not found anything\").", "def default-error-layout (layout) (\\h1 get code) (\\h2 get title) (\\p get message) (\\p get stack-trace)." ); assertError("foo.com", 404, "stack trace would be here", "text/html", "<html><head><title>Not found</title></head><body><h1>404</h1><h2>Not found</h2><p>Not found anything</p><p>stack trace would be here</p></body></html>" ); } @Test @Ignore public void test_10() throws Throwable { __( "def foo-root-layout.", "def foo-site (site) (server-name \"foo.com\") (root hello-foo).", "def text-html (mime-type) (type \"text/html\") (extension \"htm\" \"html\").", "def html-page (mime-type text-html) (\\html (\\head \\title get title) (\\body any layout)).", "def hello-foo (^html-page) (use root) (title \"hello foo\") (content \"foo foo foo\").", "def foo-root-layout (layout, root) (\\h1 get title) (\\p get content)." ); assertQuery("foo.com", "root", "text/html", "<html><head><title>hello foo</title></head><body><h1>hello foo</h1><p>foo foo foo</p></body></html>"); } @Test @Ignore public void test_11() throws Throwable { __( "def foo-root-layout.", "def foo-site (site) (server-name \"foo.com\") (root hello-foo).", "def text-html (mime-type) (type \"text/html\") (extension \"htm\" \"html\").", "def html-page (^text-html) (\\html (\\head \\title get title) (\\body any layout)).", "def hello-foo (^html-page) (use root) (title \"hello foo\") (content \"foo foo foo\").", "def foo-root-layout (layout, root) (\\h1 get title) (\\p get content)." ); assertQuery("foo.com", "root", "text/html", "<html><head><title>hello foo</title></head><body><h1>hello foo</h1><p>foo foo foo</p></body></html>"); } @Test @Ignore public void test_12() throws Throwable { __( "def site icon any logo.", "def foo-site (^site) (root hello-foo).", "def html-page each (get icon) (\\link get uri).", "def hello-foo html-page.", "def foo-logo (logo) (uri \"foo.png\")." ); assertAnimoResult("an get root any site", "hello-foo html-page \\link \"foo.png\"."); } @Test @Ignore public void test_13() throws Throwable { __( "def site any logo.", "def foo-site (^site) (root hello-foo).", "def html-page each (get logo) (\\link get uri).", "def hello-foo html-page.", "def foo-logo (logo) (uri \"foo.png\")." ); assertAnimoResult("an get root any site", "hello-foo html-page \\link \"foo.png\"."); } @Test @Ignore public void test_14() throws Throwable { __( "def foo-site (site) (root hello-foo) (weak-use foo).", "def html-page each (prefer logo) (\\link get uri).", "def hello-foo html-page.", "def foo-logo (logo, foo) (uri \"foo.png\")." ); assertAnimoResult("an get root any site", "hello-foo html-page \\link \"foo.png\"."); } @Test @Ignore public void test_15() throws Throwable { __( "def foo-site (site) (root hello-foo css hello-css) (xxx xxx-foo css xxx-css).", "def html-page each (get css) (\\link get uri).", "def hello-foo html-page.", "def xxx-foo html-page.", "def hello-css uri \"hello.css\".", "def xxx-css uri \"xxx.css\"." ); assertAnimoResult("an get root any site", "hello-foo html-page \\link \"hello.css\"."); assertAnimoResult("an get xxx any site", "xxx-foo html-page \\link \"xxx.css\"."); } @Test @Ignore public void test_16() throws Throwable { __( "def foo-site (site) (root hello-foo ^hello-css).", "def html-page each (get css) (\\link get uri).", "def hello-foo html-page.", "def hello-css (css) (uri \"hello.css\")." ); assertAnimoResult("an get root any site", "hello-foo html-page \\link \"hello.css\"."); } @Test @Ignore public void test_17() throws Throwable { __( "def foo-site (site) (root hello any css, root) (xxx hello any css, xxx).", "def html-page each (get css) (\\link get uri).", "def hello html-page.", "def hello-css (css, root) (uri \"hello.css\").", "def xxx-css (css, xxx) (uri \"xxx.css\")." ); assertAnimoResult("an get root any site", "hello html-page \\link \"hello.css\"."); assertAnimoResult("an get xxx any site", "hello html-page \\link \"xxx.css\"."); } @Test @Ignore public void test_18() throws Throwable { __( "def html-page each (get less) (\\link get uri).", "def hello (html-page) (any ^bootstrap.less).", "def xxx (bootstrap.less) (uri \"uri-bootstrap.less\").", "def bootstrap.less less." ); assertAnimoResult("hello", "hello (html-page \\link \"uri-bootstrap.less\") (xxx (bootstrap.less less) (uri))."); } @Test @Ignore public void test_19() throws Throwable { __( "def html-page any layout.", "def app (html-page) (each (get script) (\\script this script)).", "def root (app) (script \"alert('Hello world!')\")." ); assertStringResult("root", "<script>alert('Hello world!')</script>"); } @Test @Ignore public void test_20() throws Throwable { __( "def foo-site not-found-error default-not-found.", "def html-page \\html (\\head get title) (\\body get code).", "def not-found-error code 404.", "def default-not-found (html-page) (title \"Not found\")." ); assertStringResult("an get not-found-error foo-site", "<html><head>Not found</head><body>404</body></html>"); } @Test @Ignore public void test_21() throws Throwable { __( "def foo-site (site) (root foo).", "def html-page \\html any layout.", "def foo-layout (layout) (get code).", "def foo html-page." ); assertStringResult("an (get root any site) (code 500)", "<html>500</html>"); } }
package org.animotron.games.web; import org.animotron.ATest; import org.animotron.Expression; import org.animotron.exception.AnimoException; import org.animotron.operator.AN; import org.animotron.operator.THE; import org.animotron.operator.compare.WITH; import org.animotron.operator.query.ANY; import org.animotron.operator.query.GET; import org.animotron.operator.relation.HAVE; import org.animotron.operator.relation.IS; import org.animotron.operator.relation.USE; import org.junit.Test; import java.io.IOException; import static org.animotron.Expression.*; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a> * */ public class CurrentWebFrameworkTest extends ATest { @Test public void test() throws AnimoException, IOException, InterruptedException { new Expression( _(THE._, "service", _(IS._, "resource") ) ); new Expression ( _(THE._, "html", _(HAVE._, "mime-type", text("text/html")), _(HAVE._, "content", element("html", element("head", element("title", _(GET._, "title")) ), element("body", _(ANY._, "layout") ) ) ) ) ); new Expression ( _(THE._, "resource-not-found", _(IS._, "not-found-content"), _(HAVE._, "title", text("Not found")), _(HAVE._, "content", text("Can't find resource \""), _(GET._, "uri"), text("\"")) ) ); new Expression ( _(THE._, "it-working", _(IS._, "root-content"), _(HAVE._, "title", text("Welcome to Animo")), _(HAVE._, "content", text("It is working!")) ) ); new Expression ( _(THE._, "current-site", _(ANY._, "site", _(WITH._, "server-name", _(GET._, "host")) ) ) ); new Expression ( _(THE._, "localhost-site", _(IS._, "site"), _(HAVE._, "server-name", text("localhost")), _(USE._, "theme-concrete-root-layout"), _(USE._, "it-working") ) ); new Expression ( _(THE._, "not-found-service", _(IS._, "service"), _(IS._, "not-found"), _(AN._, "html", _(ANY._, "not-found-content"), _(USE._, "not-found-layout") ) ) ); new Expression ( _(THE._, "root-service", _(IS._, "service"), _(IS._, "root"), _(AN._, "html", _(ANY._, "root-content"), _(USE._, "root-layout") ) ) ); new Expression ( _(THE._, "not-found-layout", _(IS._, "layout"), element("p", _(GET._, "content")) ) ); new Expression ( _(THE._, "root-layout", _(IS._, "layout"), element("p", text("The default root layout!")) ) ); new Expression ( _(THE._, "theme-concrete-root-layout", _(IS._, "root-layout"), element("h1", _(GET._, "title")), element("p", _(GET._, "content")), element("ul", element("li", text("host: \""), element("strong" ,_(GET._, "host")), text("\"")), element("li", text("uri: \""), element("strong", _(GET._, "uri")), text("\"")) ) ) ); new Expression( _(THE._, "rest", _(ANY._, "resource", _(AN._, "current-site") ) ) ); Expression s = new Expression( _(GET._, "content", _(AN._, "rest", _(USE._, "root"), _(HAVE._, "uri", text("/")), _(HAVE._, "host", text("localhost")) ) ) ); assertAnimo(s, "<the:5ba40e69742be366f1cdcf7a2cfb107bce112789e9b056737ce87231e7386fd0>" + "<have:content>" + "<html>" + "<head>" + "<title><have:title>Welcome to Animo</have:title></title>" + "</head>" + "<body>" + "<the:theme-concrete-root-layout>" + "<is:root-layout/>" + "<h1><have:title>Welcome to Animo</have:title></h1>" + "<p><have:content>It is working!</have:content></p>" + "<ul>" + "<li>host: \"<strong><have:host>localhost</have:host></strong>\"</li>" + "<li>uri: \"<strong><have:uri>/</have:uri></strong>\"</li>" + "</ul>" + "</the:theme-concrete-root-layout>" + "</body>" + "</html>" + "</have:content>" + "</the:5ba40e69742be366f1cdcf7a2cfb107bce112789e9b056737ce87231e7386fd0>"); assertResult(s, "<html>" + "<head>" + "<title>Welcome to Animo</title>" + "</head>" + "<body>" + "<h1>Welcome to Animo</h1>" + "<p>It is working!</p>" + "<ul>" + "<li>host: \"<strong>localhost</strong>\"</li>" + "<li>uri: \"<strong>/</strong>\"</li>" + "</ul>" + "</body>" + "</html>"); } }
package org.scenarioo.pizza.pageObjects; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import static org.junit.jupiter.api.Assertions.*; public class SelectPizzaPage extends BasePage { public static void assertPageIsShown() { assertTrue(getStepElement().isDisplayed(), "Expected page to be displayed"); } public static void selectPizzaVerdura() { getWebDriver().findElement(By.id("pizza-verdura")).click(); } public static void clickNextButton() { getStepElement().findElement(By.className("next")).click(); } private static WebElement getStepElement() { return getWebDriver().findElement(By.id("step-selectPizza")); } }
package uk.gov.verifiablelog.merkletree; import org.junit.Before; import org.junit.Test; import javax.xml.bind.DatatypeConverter; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static java.util.stream.Collectors.toList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.quicktheories.quicktheories.QuickTheory.qt; import static org.quicktheories.quicktheories.generators.SourceDSL.*; class MerkleTreeTestUnit { public MerkleTree merkleTree; public List<byte[]> leaves; public MemoizationStore memoizationStore; public MerkleTreeTestUnit(MerkleTree merkleTree, List<byte[]> leaves, MemoizationStore memoizationStore) { this.merkleTree = merkleTree; this.leaves = leaves; this.memoizationStore = memoizationStore; } } public class MerkleTreeTests { public static final List<byte[]> TEST_INPUTS = Arrays.asList( new byte[]{}, new byte[]{0x00}, new byte[]{0x10}, new byte[]{0x20, 0x21}, new byte[]{0x30, 0x31}, new byte[]{0x40, 0x41, 0x42, 0x43}, new byte[]{0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57}, new byte[]{0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f}); private ArrayList<MerkleTreeTestUnit> merkleTreeTestUnits; @Before public void beforeEach() throws NoSuchAlgorithmException { MemoizationStore inMemory = new InMemory(); MemoizationStore inMemoryPowOfTwo = new InMemoryPowOfTwo(); merkleTreeTestUnits = new ArrayList<>(Arrays.asList( makeMerkleTreeTestUnit(null), makeMerkleTreeTestUnit(inMemory), makeMerkleTreeTestUnit(inMemory), makeMerkleTreeTestUnit(inMemoryPowOfTwo), makeMerkleTreeTestUnit(inMemoryPowOfTwo) )); } private MerkleTreeTestUnit makeMerkleTreeTestUnit(MemoizationStore memoizationStore) throws NoSuchAlgorithmException { List<byte[]> leafValues = new ArrayList<>(); MerkleTree merkleTree = new MerkleTree(MessageDigest.getInstance("SHA-256"), leafValues::get, leafValues::size); return new MerkleTreeTestUnit(merkleTree, leafValues, memoizationStore); } @Test public void expectedRootFromEmptyMerkleTree() { String emptyRootHash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; merkleTreeTestUnits.forEach(testUnit -> assertThat(bytesToString(testUnit.merkleTree.currentRoot()), is(emptyRootHash))); } @Test public void expectedRootFromMerkleTreeWithLeavesForTree() { merkleTreeTestUnits.forEach(testUnit -> { MerkleTree merkleTree = testUnit.merkleTree; List<byte[]> leafValues = testUnit.leaves; leafValues.add(TEST_INPUTS.get(0)); assertThat(bytesToString(merkleTree.currentRoot()), is("6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d")); leafValues.add(TEST_INPUTS.get(1)); assertThat(bytesToString(merkleTree.currentRoot()), is("fac54203e7cc696cf0dfcb42c92a1d9dbaf70ad9e621f4bd8d98662f00e3c125")); leafValues.add(TEST_INPUTS.get(2)); assertThat(bytesToString(merkleTree.currentRoot()), is("aeb6bcfe274b70a14fb067a5e5578264db0fa9b51af5e0ba159158f329e06e77")); leafValues.add(TEST_INPUTS.get(3)); assertThat(bytesToString(merkleTree.currentRoot()), is("d37ee418976dd95753c1c73862b9398fa2a2cf9b4ff0fdfe8b30cd95209614b7")); leafValues.add(TEST_INPUTS.get(4)); assertThat(bytesToString(merkleTree.currentRoot()), is("4e3bbb1f7b478dcfe71fb631631519a3bca12c9aefca1612bfce4c13a86264d4")); leafValues.add(TEST_INPUTS.get(5)); assertThat(bytesToString(merkleTree.currentRoot()), is("76e67dadbcdf1e10e1b74ddc608abd2f98dfb16fbce75277b5232a127f2087ef")); leafValues.add(TEST_INPUTS.get(6)); assertThat(bytesToString(merkleTree.currentRoot()), is("ddb89be403809e325750d3d263cd78929c2942b7942a34b77e122c9594a74c8c")); leafValues.add(TEST_INPUTS.get(7)); assertThat(bytesToString(merkleTree.currentRoot()), is("5dc9da79a70659a9ad559cb701ded9a2ab9d823aad2f4960cfe370eff4604328")); }); } @Test public void expectedAuditPathForSnapshotSize() { merkleTreeTestUnits.forEach(testUnit -> { List<byte[]> leafValues = testUnit.leaves; MerkleTree merkleTree = testUnit.merkleTree; for (byte[] testInput : TEST_INPUTS) { leafValues.add(testInput); } List<byte[]> auditPath1 = merkleTree.pathToRootAtSnapshot(0, 0); assertThat(auditPath1.size(), is(0)); List<byte[]> auditPath2 = merkleTree.pathToRootAtSnapshot(0, 1); assertThat(auditPath2.size(), is(0)); List<byte[]> auditPath3 = merkleTree.pathToRootAtSnapshot(0, 8); assertThat(bytesToString(auditPath3), is(Arrays.asList( "96a296d224f285c67bee93c30f8a309157f0daa35dc5b87e410b78630a09cfc7", "5f083f0a1a33ca076a95279832580db3e0ef4584bdff1f54c8a360f50de3031e", "6b47aaf29ee3c2af9af889bc1fb9254dabd31177f16232dd6aab035ca39bf6e4"))); List<byte[]> auditPath4 = merkleTree.pathToRootAtSnapshot(5, 8); assertThat(bytesToString(auditPath4), is(Arrays.asList( "bc1a0643b12e4d2d7c77918f44e0f4f79a838b6cf9ec5b5c283e1f4d88599e6b", "ca854ea128ed050b41b35ffc1b87b8eb2bde461e9e3b5596ece6b9d5975a0ae0", "d37ee418976dd95753c1c73862b9398fa2a2cf9b4ff0fdfe8b30cd95209614b7"))); List<byte[]> auditPath5 = merkleTree.pathToRootAtSnapshot(2, 3); assertThat(bytesToString(auditPath5), is(Arrays.asList( "fac54203e7cc696cf0dfcb42c92a1d9dbaf70ad9e621f4bd8d98662f00e3c125"))); List<byte[]> auditPath6 = merkleTree.pathToRootAtSnapshot(1, 5); assertThat(bytesToString(auditPath6), is(Arrays.asList( "6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d", "5f083f0a1a33ca076a95279832580db3e0ef4584bdff1f54c8a360f50de3031e", "bc1a0643b12e4d2d7c77918f44e0f4f79a838b6cf9ec5b5c283e1f4d88599e6b"))); }); } @Test public void expectedConsistencySetForSnapshots() { merkleTreeTestUnits.forEach(testUnit -> { List<byte[]> leafValues = testUnit.leaves; MerkleTree merkleTree = testUnit.merkleTree; for (byte[] testInput : TEST_INPUTS) { leafValues.add(testInput); } List<byte[]> consistencySet1 = merkleTree.snapshotConsistency(1, 1); assertThat(consistencySet1.size(), is(0)); List<byte[]> consistencySet2 = merkleTree.snapshotConsistency(1, 8); assertThat(bytesToString(consistencySet2), is(Arrays.asList( "96a296d224f285c67bee93c30f8a309157f0daa35dc5b87e410b78630a09cfc7", "5f083f0a1a33ca076a95279832580db3e0ef4584bdff1f54c8a360f50de3031e", "6b47aaf29ee3c2af9af889bc1fb9254dabd31177f16232dd6aab035ca39bf6e4"))); List<byte[]> consistencySet3 = merkleTree.snapshotConsistency(6, 8); assertThat(bytesToString(consistencySet3), is(Arrays.asList( "0ebc5d3437fbe2db158b9f126a1d118e308181031d0a949f8dededebc558ef6a", "ca854ea128ed050b41b35ffc1b87b8eb2bde461e9e3b5596ece6b9d5975a0ae0", "d37ee418976dd95753c1c73862b9398fa2a2cf9b4ff0fdfe8b30cd95209614b7"))); List<byte[]> consistencySet4 = merkleTree.snapshotConsistency(2, 5); assertThat(bytesToString(consistencySet4), is(Arrays.asList( "5f083f0a1a33ca076a95279832580db3e0ef4584bdff1f54c8a360f50de3031e", "bc1a0643b12e4d2d7c77918f44e0f4f79a838b6cf9ec5b5c283e1f4d88599e6b"))); }); } @Test public void property_rootHashFromMemoizedTreeIsSameAsRootHashFromNonMemoizedTree() { qt().forAll(lists().allListsOf(strings().numeric()).ofSizeBetween(1, 1000)) .checkAssert(entryStrings -> { List<byte[]> entries = entryStrings.stream().map(String::getBytes).collect(toList()); MemoizationStore inMemoryMs = new InMemory(); MerkleTree memoizedTree = new MerkleTree(Util.sha256Instance(), entries::get, entries::size, inMemoryMs); memoizedTree.currentRoot(); MemoizationStore inMemoryPowOfTwoMs = new InMemoryPowOfTwo(); MerkleTree memoizedPowOfTwoTree = new MerkleTree(Util.sha256Instance(), entries::get, entries::size, inMemoryPowOfTwoMs); memoizedPowOfTwoTree.currentRoot(); MerkleTree nonMemoizedTree = new MerkleTree(Util.sha256Instance(), entries::get, entries::size); assertThat(bytesToString(memoizedTree.currentRoot()), is(bytesToString(nonMemoizedTree.currentRoot()))); assertThat(bytesToString(memoizedPowOfTwoTree.currentRoot()), is(bytesToString(nonMemoizedTree.currentRoot()))); }); } @Test public void property_canConstructRootHashFromLeafAndAuditPath() throws Exception { qt().forAll(lists().allListsOf(strings().numeric()).ofSizeBetween(1, 1000), integers().between(0, 999)) .assuming((entries, leafIndex) -> leafIndex < entries.size()) .checkAssert((entryStrings, leafIndex) -> { List<byte[]> entries = entryStrings.stream().map(String::getBytes).collect(toList()); MerkleTree merkleTree = makeMerkleTree(entries); List<byte[]> auditPath = merkleTree.pathToRootAtSnapshot(leafIndex, entries.size()); assertThat(MerkleTreeVerification.isValidAuditProof(merkleTree.currentRoot(), entries.size(), leafIndex, auditPath, entries.get(leafIndex)), is(true)); }); } @Test public void property_auditPathFromMemoizedTreeIsSameAsAuditPathFromNonMemoizedTree() throws Exception { qt().forAll(lists().allListsOf(strings().numeric()).ofSizeBetween(1, 1000), integers().between(0, 999)) .assuming((entries, leafIndex) -> leafIndex < entries.size()) .checkAssert((entryStrings, leafIndex) -> { List<byte[]> entries = entryStrings.stream().map(String::getBytes).collect(toList()); MemoizationStore inMemoryMs = new InMemory(); MerkleTree memoizedTree = new MerkleTree(Util.sha256Instance(), entries::get, entries::size, inMemoryMs); memoizedTree.currentRoot(); MemoizationStore inMemoryPowOfTwoMs = new InMemoryPowOfTwo(); MerkleTree memoizedPowOfTwoTree = new MerkleTree(Util.sha256Instance(), entries::get, entries::size, inMemoryPowOfTwoMs); memoizedPowOfTwoTree.currentRoot(); MerkleTree nonMemoizedTree = new MerkleTree(Util.sha256Instance(), entries::get, entries::size); List<byte[]> auditPathNonMemoized = nonMemoizedTree.pathToRootAtSnapshot(leafIndex, entries.size()); List<byte[]> auditPathInMemory = memoizedTree.pathToRootAtSnapshot(leafIndex, entries.size()); List<byte[]> auditPathInMemoryPowOfTwo = memoizedPowOfTwoTree.pathToRootAtSnapshot(leafIndex, entries.size()); assertThat(bytesToString(auditPathInMemory), is(bytesToString(auditPathNonMemoized))); assertThat(bytesToString(auditPathInMemoryPowOfTwo), is(bytesToString(auditPathNonMemoized))); }); } @Test public void property_canVerifyConsistencyProof() { qt().forAll(lists().allListsOf(strings().numeric()).ofSizeBetween(2, 1000), integers().between(1, 1000), integers().between(1, 1000)) .assuming((entries, low, high) -> low <= high && high <= entries.size()) .check((entryStrings, low, high) -> { List<byte[]> entries = entryStrings.stream().map(String::getBytes).collect(toList()); MerkleTree merkleTree = makeMerkleTree(entries); byte[] lowRoot = makeMerkleTree(entries.subList(0, low)).currentRoot(); byte[] highRoot = makeMerkleTree(entries.subList(0, high)).currentRoot(); List<byte[]> consistencyProof = merkleTree.snapshotConsistency(low, high); return MerkleTreeVerification.isValidConsistencyProof(low, lowRoot, high, highRoot, consistencyProof); }); } @Test public void property_consistencyProofForMemoizedTreeIsSameAsConsistencyProofForNonMemoizedTree() { qt().forAll(lists().allListsOf(strings().numeric()).ofSizeBetween(2, 1000), integers().between(1, 1000), integers().between(1, 1000)) .assuming((entries, low, high) -> low <= high && high <= entries.size()) .checkAssert((entryStrings, low, high) -> { List<byte[]> entries = entryStrings.stream().map(String::getBytes).collect(toList()); MemoizationStore inMemoryMs = new InMemory(); MerkleTree memoizedTree = new MerkleTree(Util.sha256Instance(), entries::get, entries::size, inMemoryMs); memoizedTree.currentRoot(); MemoizationStore inMemoryPowOfTwoMs = new InMemoryPowOfTwo(); MerkleTree memoizedPowOfTwoTree = new MerkleTree(Util.sha256Instance(), entries::get, entries::size, inMemoryPowOfTwoMs); memoizedPowOfTwoTree.currentRoot(); MerkleTree nonMemoizedTree = new MerkleTree(Util.sha256Instance(), entries::get, entries::size); List<byte[]> consistencyProofForNonMemoized = nonMemoizedTree.snapshotConsistency(low, high); List<byte[]> consistencyProofForInMemory = memoizedTree.snapshotConsistency(low, high); List<byte[]> consistencyProofForInMemoryPowOfTwo = memoizedPowOfTwoTree.snapshotConsistency(low, high); assertThat(bytesToString(consistencyProofForInMemory), is(bytesToString(consistencyProofForNonMemoized))); assertThat(bytesToString(consistencyProofForInMemoryPowOfTwo), is(bytesToString(consistencyProofForNonMemoized))); }); } private MerkleTree makeMerkleTree(List<byte[]> entries) { return new MerkleTree(Util.sha256Instance(), entries::get, entries::size); } private List<String> bytesToString(List<byte[]> listOfByteArrays) { return listOfByteArrays.stream().map(this::bytesToString).collect(toList()); } private String bytesToString(byte[] bytes) { return DatatypeConverter.printHexBinary(bytes).toLowerCase(); } }
// Test case file for checkstyle. // Created: 2001 package com.puppycrawl.tools.checkstyle; /** * Test case for correct use of braces. * @author Oliver Burn **/ class InputLeftCurlyOther { /** @see test method **/ void foo() throws InterruptedException { int x = 1; int a = 2; while (true) { try { if (x > 0) { break; } else if (x < 0) { ; } else { break; } switch (a) { case 0: break; default: break; } } catch (Exception e) { break; } finally { break; } } synchronized (this) { do { x = 2; } while (x == 2); } this.wait(666 ); } }
package uk.org.cinquin.mutinack.tests; import org.junit.Ignore; import org.junit.Test; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import uk.org.cinquin.mutinack.DuplexRead; import uk.org.cinquin.mutinack.MutinackGroup; import uk.org.cinquin.mutinack.Parameters; import uk.org.cinquin.mutinack.SequenceLocation; import uk.org.cinquin.mutinack.distributed.Job; //TODO Some classes are missing because ExtendedSAMRecord is recursive and //is not easy to instantiate from scratch @SuppressWarnings("static-method") public class TestEqualsHashcodeContracts { @Test @Ignore//Fails because hashCode does not rely on referenceGenome, which is by design public void seqLocEqualsContract1() { EqualsVerifier.forClass(SequenceLocation.class).withCachedHashCode( "hash", "computeHash", new SequenceLocation(0, "", 0)).suppress(Warning.NULL_FIELDS).verify(); } @Test public void duplexReadEqualsContract1() { EqualsVerifier.forClass(DuplexRead.class). suppress(Warning.NONFINAL_FIELDS). suppress(Warning.NULL_FIELDS). withPrefabValues(Thread.class, new Thread(), new Thread()). verify(); } @SuppressWarnings({ "resource" }) @Test public void parametersJobEquals() { EqualsVerifier.forClass(Parameters.class).withPrefabValues( MutinackGroup.class, new MutinackGroup(false), new MutinackGroup(false)). suppress(Warning.NONFINAL_FIELDS).suppress(Warning.NULL_FIELDS).verify(); EqualsVerifier.forClass(Job.class).withPrefabValues( MutinackGroup.class, new MutinackGroup(false), new MutinackGroup(false)). suppress(Warning.NONFINAL_FIELDS).suppress(Warning.NULL_FIELDS).verify(); } }
package us.kbase.narrativejobservice.sdkjobs; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.dockerjava.api.model.AccessMode; import com.github.dockerjava.api.model.Bind; import com.github.dockerjava.api.model.Volume; import com.google.common.html.HtmlEscapers; import com.sun.jna.Library; import com.sun.jna.Native; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import us.kbase.auth.AuthConfig; import us.kbase.auth.AuthToken; import us.kbase.auth.ConfigurableAuthService; import us.kbase.catalog.*; import us.kbase.common.executionengine.*; import us.kbase.common.executionengine.CallbackServerConfigBuilder.CallbackServerConfig; import us.kbase.common.service.*; import us.kbase.common.utils.NetUtils; import us.kbase.narrativejobservice.*; import us.kbase.narrativejobservice.JobState; import us.kbase.narrativejobservice.MethodCall; import us.kbase.narrativejobservice.RpcContext; import us.kbase.narrativejobservice.subjobs.NJSCallbackServer; import us.kbase.narrativejobservice.NarrativeJobServiceServer; import java.io.*; import java.net.*; import java.nio.file.Paths; import java.time.Instant; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SDKLocalMethodRunner { private final static DateTimeFormatter DATE_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ").withZoneUTC(); public static final String DEV = JobRunnerConstants.DEV; public static final String BETA = JobRunnerConstants.BETA; public static final String RELEASE = JobRunnerConstants.RELEASE; public static final Set<String> RELEASE_TAGS = JobRunnerConstants.RELEASE_TAGS; private static final long MAX_OUTPUT_SIZE = JobRunnerConstants.MAX_IO_BYTE_SIZE; public static final String JOB_CONFIG_FILE = JobRunnerConstants.JOB_CONFIG_FILE; public static final String CFG_PROP_EE_SERVER_VERSION = JobRunnerConstants.CFG_PROP_EE_SERVER_VERSION; public static final String CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS = JobRunnerConstants.CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS; /** * Get time for job to live based on token expiry date * * @param token User Token * @param config Configuration Vars * @return time to live in milliseconds * @throws Exception */ public static long milliSecondsToLive(String token, Map<String, String> config) throws Exception { String authUrl = config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL_V2); if (authUrl == null) { throw new IllegalStateException("Deployment configuration parameter is not defined: " + NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL_V2); } //Check to see if http links are allowed String authAllowInsecure = config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_ALLOW_INSECURE_URL_PARAM); if (!"true".equals(authAllowInsecure) && !authUrl.startsWith("https: throw new Exception("Only https links are allowed: " + authUrl); } CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet request = new HttpGet(authUrl); request.setHeader(HttpHeaders.AUTHORIZATION, token); InputStream response = httpclient.execute(request).getEntity().getContent(); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> jsonMap = mapper.readValue(response, Map.class); Object expire = jsonMap.getOrDefault("expires", null); //Calculate ms till expiration if (expire == null) throw new Exception("Unable to get expiry date of token, we should cancel it now" + jsonMap.toString()); long ms = ((long) expire - Instant.now().toEpochMilli()); //Time of token expiration - N time String time_before_expiration = config.get(NarrativeJobServiceServer.CFG_PROP_TIME_BEFORE_EXPIRATION); //10 Minute Default if (time_before_expiration == null) return ms - (10 * 60 * 1000); //Number of minutes / 60 * 1000 return ms - (Long.parseLong(time_before_expiration) / 60) * 1000; } /** * Submit a cancel job request to the NJS Client * * @param jobSrvClient * @param jobId * @throws Exception */ public static void canceljob(NarrativeJobServiceClient jobSrvClient, String jobId) throws Exception { jobSrvClient.cancelJob(new CancelJobParams().withJobId(jobId)); } /** * Used for getting PID */ private interface CLibrary extends Library { CLibrary INSTANCE = (CLibrary) Native.loadLibrary("c", CLibrary.class); int getpid (); } public static void main(String[] args) throws Exception { System.out.println("Starting docker runner with args " + StringUtils.join(args, ", ")); if (args.length != 2) { System.err.println("Usage: <program> <job_id> <job_service_url>"); for (int i = 0; i < args.length; i++) System.err.println("\tArgument[" + i + "]: " + args[i]); System.exit(1); } int pid = CLibrary.INSTANCE.getpid(); System.out.println("Looking up cgroup for " + pid); String parentCgroup = new SDKJobsUtils().lookupParentCgroup(pid); System.out.println(parentCgroup); String[] hostnameAndIP = getHostnameAndIP(); final String jobId = args[0]; String jobSrvUrl = args[1]; String tokenStr = System.getenv("KB_AUTH_TOKEN"); if (tokenStr == null || tokenStr.isEmpty()) tokenStr = System.getProperty("KB_AUTH_TOKEN"); // For tests if (tokenStr == null || tokenStr.isEmpty()) throw new IllegalStateException("Token is not defined"); // We should skip token validation now because we don't have auth service URL yet. final AuthToken tempToken = new AuthToken(tokenStr, "<unknown>"); final NarrativeJobServiceClient jobSrvClient = getJobClient( jobSrvUrl, tempToken); Thread logFlusher = null; Thread tokenExpiration = null; Thread timedJobShutdown = null; Thread shutdownHook = null; final List<LogLine> logLines = new ArrayList<LogLine>(); final LineLogger log = new LineLogger() { @Override public void logNextLine(String line, boolean isError) { addLogLine(jobSrvClient, jobId, logLines, new LogLine().withLine(line) .withIsError(isError ? 1L : 0L)); } }; Server callbackServer = null; try { JobState jobState = jobSrvClient.checkJob(jobId); if (jobState.getFinished() != null && jobState.getFinished() == 1L) { if (jobState.getCanceled() != null && jobState.getCanceled() == 1L) { log.logNextLine("Job was canceled", false); } else { log.logNextLine("Job was already done before", true); } flushLog(jobSrvClient, jobId, logLines); return; } Tuple2<RunJobParams, Map<String, String>> jobInput = jobSrvClient.getJobParams(jobId); Map<String, String> config = jobInput.getE2(); if (System.getenv("CALLBACK_INTERFACE") != null) config.put(CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS, System.getenv("CALLBACK_INTERFACE")); if (System.getenv("REFDATA_DIR") != null) config.put(NarrativeJobServiceServer.CFG_PROP_REF_DATA_BASE, System.getenv("REFDATA_DIR")); ConfigurableAuthService auth = getAuth(config); // We couldn't validate token earlier because we didn't have auth service URL. AuthToken token = auth.validateToken(tokenStr); final URL catalogURL = getURL(config, NarrativeJobServiceServer.CFG_PROP_CATALOG_SRV_URL); final URI dockerURI = getURI(config, NarrativeJobServiceServer.CFG_PROP_AWE_CLIENT_DOCKER_URI, true); RunJobParams job = jobInput.getE1(); for (String msg : jobSrvClient.updateJob(new UpdateJobParams().withJobId(jobId) .withIsStarted(1L)).getMessages()) { log.logNextLine(msg, false); } File jobDir = getJobDir(jobInput.getE2(), jobId); if (!mountExists()) { log.logNextLine("Cannot find mount point as defined in condor-submit-workdir", true); throw new IOException("Cannot find mount point condor-submit-workdir"); } final ModuleMethod modMeth = new ModuleMethod(job.getMethod()); RpcContext context = job.getRpcContext(); if (context == null) context = new RpcContext().withRunId(""); if (context.getCallStack() == null) context.setCallStack(new ArrayList<MethodCall>()); context.getCallStack().add(new MethodCall().withJobId(jobId).withMethod(job.getMethod()) .withTime(DATE_FORMATTER.print(new DateTime()))); Map<String, Object> rpc = new LinkedHashMap<String, Object>(); rpc.put("version", "1.1"); rpc.put("method", job.getMethod()); rpc.put("params", job.getParams()); rpc.put("context", context); File workDir = new File(jobDir, "workdir"); if (!workDir.exists()) workDir.mkdir(); File scratchDir = new File(workDir, "tmp"); if (!scratchDir.exists()) scratchDir.mkdir(); File inputFile = new File(workDir, "input.json"); UObject.getMapper().writeValue(inputFile, rpc); File outputFile = new File(workDir, "output.json"); File configFile = new File(workDir, JOB_CONFIG_FILE); String kbaseEndpoint = config.get(NarrativeJobServiceServer.CFG_PROP_KBASE_ENDPOINT); String clientDetails = hostnameAndIP[1]; String clientName = System.getenv("AWE_CLIENTNAME"); if (clientName != null && !clientName.isEmpty()) { clientDetails += ", client-name=" + clientName; } log.logNextLine("Running on " + hostnameAndIP[0] + " (" + clientDetails + "), in " + new File(".").getCanonicalPath(), false); String clientGroup = System.getenv("AWE_CLIENTGROUP"); if (clientGroup == null) clientGroup = "<unknown>"; log.logNextLine("Client group: " + clientGroup, false); String codeEeVer = NarrativeJobServiceServer.VERSION; String runtimeEeVersion = config.get(CFG_PROP_EE_SERVER_VERSION); if (runtimeEeVersion == null) runtimeEeVersion = "<unknown>"; if (codeEeVer.equals(runtimeEeVersion)) { log.logNextLine("Server version of Execution Engine: " + runtimeEeVersion + " (matches to version of runner script)", false); } else { log.logNextLine("WARNING: Server version of Execution Engine (" + runtimeEeVersion + ") doesn't match to version of runner script " + "(" + codeEeVer + ")", true); } CatalogClient catClient = new CatalogClient(catalogURL, token); catClient.setIsInsecureHttpConnectionAllowed(true); catClient.setAllSSLCertificatesTrusted(true); // the NJSW always passes the githash in service ver final String imageVersion = job.getServiceVer(); final String requestedRelease = (String) job .getAdditionalProperties().get(SDKMethodRunner.REQ_REL); final ModuleVersion mv; try { mv = catClient.getModuleVersion(new SelectModuleVersion() .withModuleName(modMeth.getModule()) .withVersion(imageVersion)); } catch (ServerException se) { throw new IllegalArgumentException(String.format( "Error looking up module %s with version %s: %s", modMeth.getModule(), imageVersion, se.getLocalizedMessage())); } String imageName = mv.getDockerImgName(); File refDataDir = null; String refDataBase = config.get(NarrativeJobServiceServer.CFG_PROP_REF_DATA_BASE); if (mv.getDataFolder() != null && mv.getDataVersion() != null) { if (refDataBase == null) throw new IllegalStateException("Reference data parameters are defined for image but " + NarrativeJobServiceServer.CFG_PROP_REF_DATA_BASE + " property isn't set in configuration"); refDataDir = new File(new File(refDataBase, mv.getDataFolder()), mv.getDataVersion()); if (!refDataDir.exists()) throw new IllegalStateException("Reference data directory doesn't exist: " + refDataDir); } if (imageName == null) { throw new IllegalStateException("Image is not stored in catalog"); } else { log.logNextLine("Image name received from catalog: " + imageName, false); } logFlusher = new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException ex) { break; } flushLog(jobSrvClient, jobId, logLines); if (Thread.currentThread().isInterrupted()) break; } } }); logFlusher.setDaemon(true); logFlusher.start(); // Let's check if there are some volume mount rules or secure configuration parameters // set up for this module List<Bind> additionalBinds = null; Map<String, String> envVars = null; List<SecureConfigParameter> secureCfgParams = null; String adminTokenStr = System.getenv("KB_ADMIN_AUTH_TOKEN"); if (adminTokenStr == null || adminTokenStr.isEmpty()) adminTokenStr = System.getProperty("KB_ADMIN_AUTH_TOKEN"); // For tests String miniKB = System.getenv("MINI_KB"); boolean useVolumeMounts = true; if (miniKB != null && !miniKB.isEmpty() && miniKB.equals("true")) { useVolumeMounts = false; } if (adminTokenStr != null && !adminTokenStr.isEmpty() && useVolumeMounts) { final AuthToken adminToken = auth.validateToken(adminTokenStr); final CatalogClient adminCatClient = new CatalogClient(catalogURL, adminToken); adminCatClient.setIsInsecureHttpConnectionAllowed(true); adminCatClient.setAllSSLCertificatesTrusted(true); List<VolumeMountConfig> vmc = null; try { vmc = adminCatClient.listVolumeMounts(new VolumeMountFilter().withModuleName( modMeth.getModule()).withClientGroup(clientGroup) .withFunctionName(modMeth.getMethod())); } catch (Exception ex) { log.logNextLine("Error requesing volume mounts from Catalog: " + ex.getMessage(), true); } if (vmc != null && vmc.size() > 0) { if (vmc.size() > 1) throw new IllegalStateException("More than one rule for Docker volume mounts was found"); additionalBinds = new ArrayList<Bind>(); for (VolumeMount vm : vmc.get(0).getVolumeMounts()) { boolean isReadOnly = vm.getReadOnly() != null && vm.getReadOnly() != 0L; File hostDir = new File(processHostPathForVolumeMount(vm.getHostDir(), token.getUserName())); if (!hostDir.exists()) { if (isReadOnly) { throw new IllegalStateException("Volume mount directory doesn't exist: " + hostDir); } else { hostDir.mkdirs(); } } String contDir = vm.getContainerDir(); AccessMode am = isReadOnly ? AccessMode.ro : AccessMode.rw; additionalBinds.add(new Bind(hostDir.getCanonicalPath(), new Volume(contDir), am)); } } secureCfgParams = adminCatClient.getSecureConfigParams( new GetSecureConfigParamsInput().withModuleName(modMeth.getModule()) .withVersion(mv.getGitCommitHash()).withLoadAllVersions(0L)); envVars = new TreeMap<String, String>(); for (SecureConfigParameter param : secureCfgParams) { envVars.put("KBASE_SECURE_CONFIG_PARAM_" + param.getParamName(), param.getParamValue()); } } PrintWriter pw = new PrintWriter(configFile); pw.println("[global]"); if (kbaseEndpoint != null) pw.println("kbase_endpoint = " + kbaseEndpoint); pw.println("job_service_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_JOBSTATUS_SRV_URL)); pw.println("workspace_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_WORKSPACE_SRV_URL)); pw.println("shock_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_SHOCK_URL)); pw.println("handle_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_HANDLE_SRV_URL)); pw.println("srv_wiz_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_SRV_WIZ_URL)); pw.println("njsw_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_SELF_EXTERNAL_URL)); pw.println("auth_service_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL)); pw.println("auth_service_url_allow_insecure = " + config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_ALLOW_INSECURE_URL_PARAM)); if (secureCfgParams != null) { for (SecureConfigParameter param : secureCfgParams) { pw.println(param.getParamName() + " = " + param.getParamValue()); } } pw.close(); // Cancellation checker CancellationChecker cancellationChecker = new CancellationChecker() { Boolean canceled = null; @Override public boolean isJobCanceled() { if (canceled != null) return canceled; try { final CheckJobCanceledResult jobState = jobSrvClient.checkJobCanceled( new CancelJobParams().withJobId(jobId)); if (jobState.getFinished() != null && jobState.getFinished() == 1L) { canceled = true; if (jobState.getCanceled() != null && jobState.getCanceled() == 1L) { // Print cancellation message after DockerRunner is done } else { log.logNextLine("Job was registered as finished by another worker", true); } flushLog(jobSrvClient, jobId, logLines); return true; } } catch (Exception ex) { log.logNextLine("Non-critical error checking for job cancelation - " + String.format("Will check again in %s seconds. ", DockerRunner.CANCELLATION_CHECK_PERIOD_SEC) + "Error reported by execution engine was: " + HtmlEscapers.htmlEscaper().escape(ex.getMessage()), true); } return false; } }; // Starting up callback server String[] callbackNetworks = null; String callbackNetworksText = config.get(CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS); if (callbackNetworksText != null) { callbackNetworks = callbackNetworksText.trim().split("\\s*,\\s*"); } final int callbackPort = NetUtils.findFreePort(); final URL callbackUrl = CallbackServer. getCallbackUrl(callbackPort, callbackNetworks); if (callbackUrl != null) { log.logNextLine("Job runner recieved callback URL: " + callbackUrl, false); final ModuleRunVersion runver = new ModuleRunVersion( new URL(mv.getGitUrl()), modMeth, mv.getGitCommitHash(), mv.getVersion(), requestedRelease); final CallbackServerConfig cbcfg = new CallbackServerConfigBuilder(config, callbackUrl, jobDir.toPath(), Paths.get(refDataBase), log).build(); final JsonServerServlet callback = new NJSCallbackServer( token, cbcfg, runver, job.getParams(), job.getSourceWsObjects(), additionalBinds, cancellationChecker); callbackServer = new Server(callbackPort); final ServletContextHandler srvContext = new ServletContextHandler( ServletContextHandler.SESSIONS); srvContext.setContextPath("/"); callbackServer.setHandler(srvContext); /** * Check to see if the basedir exists, which is in * a format similar to /mnt/condor/<username> * * @return */ private static boolean mountExists() { File mountPath = new File(System.getenv("BASE_DIR")); return mountPath.exists() && mountPath.canWrite(); } public static NarrativeJobServiceClient getJobClient(String jobSrvUrl, AuthToken token) throws UnauthorizedException, IOException, MalformedURLException { final NarrativeJobServiceClient jobSrvClient = new NarrativeJobServiceClient(new URL(jobSrvUrl), token); jobSrvClient.setIsInsecureHttpConnectionAllowed(true); return jobSrvClient; } private static ConfigurableAuthService getAuth(final Map<String, String> config) throws Exception { String authUrl = config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL); if (authUrl == null) { throw new IllegalStateException("Deployment configuration parameter is not defined: " + NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL); } String authAllowInsecure = config.get( NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_ALLOW_INSECURE_URL_PARAM); final AuthConfig c = new AuthConfig().withKBaseAuthServerURL(new URL(authUrl)); if ("true".equals(authAllowInsecure)) { c.withAllowInsecureURLs(true); } return new ConfigurableAuthService(c); } private static URL getURL(final Map<String, String> config, final String param) { final String urlStr = config.get(param); if (urlStr == null || urlStr.isEmpty()) { throw new IllegalStateException("Parameter '" + param + "' is not defined in configuration"); } try { return new URL(urlStr); } catch (MalformedURLException mal) { throw new IllegalStateException("The configuration parameter '" + param + " = " + urlStr + "' is not a valid URL"); } } private static URI getURI(final Map<String, String> config, final String param, boolean allowAbsent) { final String urlStr = config.get(param); if (urlStr == null || urlStr.isEmpty()) { if (allowAbsent) { return null; } throw new IllegalStateException("Parameter '" + param + "' is not defined in configuration"); } try { return new URI(urlStr); } catch (URISyntaxException use) { throw new IllegalStateException("The configuration parameter '" + param + " = " + urlStr + "' is not a valid URI"); } } public static String[] getHostnameAndIP() { String hostname = null; String ip = null; try { InetAddress ia = InetAddress.getLocalHost(); ip = ia.getHostAddress(); hostname = ia.getHostName(); } catch (Throwable ignore) { } if (hostname == null) { try { hostname = System.getenv("HOSTNAME"); if (hostname != null && hostname.isEmpty()) hostname = null; } catch (Throwable ignore) { } } if (ip == null && hostname != null) { try { ip = InetAddress.getByName(hostname).getHostAddress(); } catch (Throwable ignore) { } } return new String[]{hostname == null ? "unknown" : hostname, ip == null ? "unknown" : ip}; } }
package de.tuberlin.dima.schubotz.wiki; import java.io.IOException; import java.util.regex.Pattern; import de.tuberlin.dima.schubotz.common.utils.CSVHelper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.google.common.collect.HashMultiset; import de.tuberlin.dima.schubotz.common.mappers.OutputSimple; import de.tuberlin.dima.schubotz.common.types.OutputSimpleTuple; import de.tuberlin.dima.schubotz.fse.types.ResultTuple; import de.tuberlin.dima.schubotz.wiki.mappers.QueryWikiMatcher; import de.tuberlin.dima.schubotz.wiki.mappers.WikiCleaner; import de.tuberlin.dima.schubotz.wiki.mappers.WikiQueryCleaner; import de.tuberlin.dima.schubotz.wiki.mappers.WikiQueryMapper; import de.tuberlin.dima.schubotz.wiki.types.WikiQueryTuple; import de.tuberlin.dima.schubotz.wiki.types.WikiTuple; import eu.stratosphere.api.common.operators.Order; import eu.stratosphere.api.java.DataSet; import eu.stratosphere.api.java.ExecutionEnvironment; import eu.stratosphere.api.java.io.TextInputFormat; import eu.stratosphere.api.java.operators.DataSource; import eu.stratosphere.api.java.typeutils.BasicTypeInfo; import eu.stratosphere.core.fs.FileSystem.WriteMode; import eu.stratosphere.core.fs.Path; /** * Returns search results for NTCIR-11 2014 Wikipedia Subtask * */ public class WikiProgram { /** * Main execution environment for Stratosphere */ static ExecutionEnvironment env; /** * Root logger class. Leave all logging implementation up to * Stratosphere and its config files. */ private static final Log LOG = LogFactory.getLog(WikiProgram.class); /** * Splitter for tokens */ public static final String STR_SPLIT = "<S>"; /** * Generates matches for words separated by whitespace */ public static final Pattern WORD_SPLIT = Pattern.compile("\\W+", Pattern.UNICODE_CHARACTER_CLASS); /** * Used to split input into stratosphere for wikis */ public static final String WIKI_SEPARATOR = "</page>"; /** * Used to split input into stratosphere for queries */ public static final String QUERY_SEPARATOR = "</topic>"; /** * Used for line splitting so that CsvReader is not looking for "\n" in XML */ public static final String CSV_LINE_SEPARATOR = "\u001E"; /** * Used for field splitting so that CsvReader doesn't get messed up on comma latex tokens */ public static final String CSV_FIELD_SEPARATOR = "\u001F"; //public static final String CSV_FIELD_SEPARATOR = "\u01DF"; /** * HashMultiset for storing preprocessed data of latex token : count * of documents containing token */ public static HashMultiset<String> latexWikiMultiset; //SETTINGS /** * The overall maximal results that can be returned per query. */ public final static int MaxResultsPerQuery = 1000; /** * Runtag in output */ public static final String RUNTAG = "wiki_latex"; //ARGUMENTS /** * Stratosphere parallelism */ static int noSubTasks; /** * Output path and filename */ static String output; /** * Input path and filename for wikipedia files */ static String wikiInput; /** * Input path and filename for wikiquery file */ static String wikiQueryInput; /** * Input path and filename for preprocessed csv */ static String latexWikiMapInput; /** * Input path and filename for preprocessed tuples */ static String tupleWikiInput; /** * Total number of wikipedia files */ public static int numWiki; /** * Enable or disable low level debugging TODO clean this up (make it based on logger level?) */ static boolean debug; protected static void parseArgs(String[] args) throws Exception { noSubTasks = (args.length > 0 ? Integer.parseInt( args[0] ) : 16); output = (args.length > 1 ? args[1] : "file://mnt/ntcir-math/test-output/WikiProgramOUT-" + System.currentTimeMillis() + ".csv"); wikiInput = (args.length > 2 ? args[2] : "file:///mnt/ntcir-math/testdata/augmentedWikiDump.xml"); wikiQueryInput = (args.length > 3 ? args[3] : "file:///mnt/ntcir-math/queries/wikiQuery.xml"); latexWikiMapInput = (args.length > 4 ? args[4] : "file:///mnt/ntcir-math/queries/latexWikiMap.csv"); tupleWikiInput = (args.length > 5 ? args[5] : "file:///mnt/ntcir-math/queries/tupleWikiMap.csv"); try { numWiki = Integer.valueOf(args[6]); } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn("numWiki not given as parameter or is not a number, defaulting to 30040"); } numWiki = 30040; } debug = (args.length > 7 ? (args[7].equals("debug") ? true : false) : false); } public static void main(String[] args) { try { parseArgs(args); ConfigurePlan(); env.setDegreeOfParallelism(noSubTasks); env.execute("MathoWikiSphere"); } catch (Exception e) { LOG.fatal("Env WikiProgram execution exception", e); e.printStackTrace(); System.exit(0); } System.exit(1); } public static ExecutionEnvironment getExecutionEnvironment() { return env; } @SuppressWarnings("serial") public static void ConfigurePlan() throws IOException { env = ExecutionEnvironment.getExecutionEnvironment(); TextInputFormat formatWiki = new TextInputFormat(new Path(wikiInput)); //Generate latexWikiMap from preprocessed files latexWikiMultiset = CSVHelper.csvToMultiset(latexWikiMapInput); DataSet<WikiTuple> wikiSet = CSVHelper.csvToWikiTuple(env, tupleWikiInput); TextInputFormat formatQuery = new TextInputFormat(new Path(wikiQueryInput)); formatQuery.setDelimiter(QUERY_SEPARATOR); //this will leave a System.getProperty("line.separator")</topics> at the end as well as header info at the begin DataSet<String> rawWikiQueryText = new DataSource<>(env, formatQuery, BasicTypeInfo.STRING_TYPE_INFO); //Clean up and format queries DataSet<String> cleanWikiQueryText = rawWikiQueryText.flatMap(new WikiQueryCleaner()); DataSet<WikiQueryTuple> wikiQuerySet = cleanWikiQueryText.flatMap(new WikiQueryMapper(STR_SPLIT)); DataSet<ResultTuple> matches = wikiSet.flatMap(new QueryWikiMatcher(STR_SPLIT, latexWikiMultiset, numWiki, debug)) .withBroadcastSet(wikiQuerySet, "Queries"); DataSet<OutputSimpleTuple> outputTuples = matches//Group by queryid .groupBy(0) //Sort by score <queryid, docid, score> .sortGroup(2, Order.DESCENDING) .reduceGroup(new OutputSimple(MaxResultsPerQuery,RUNTAG)); outputTuples.writeAsCsv(output,"\n"," ",WriteMode.OVERWRITE); } }
package mb.statix.random; import java.util.Deque; import java.util.Iterator; import java.util.LinkedList; import java.util.Optional; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; import org.metaborg.core.MetaborgException; import org.metaborg.util.functions.Function1; import org.metaborg.util.log.ILogger; import org.metaborg.util.log.Level; import org.metaborg.util.log.LoggerUtils; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import mb.nabl2.terms.ITerm; import mb.nabl2.terms.unification.IUnifier; import mb.statix.constraints.CAstId; import mb.statix.constraints.CAstProperty; import mb.statix.constraints.CInequal; import mb.statix.constraints.CResolveQuery; import mb.statix.constraints.CUser; import mb.statix.constraints.Constraints; import mb.statix.random.predicate.Any; import mb.statix.random.predicate.IsGen; import mb.statix.random.predicate.IsType; import mb.statix.random.predicate.Not; import mb.statix.random.strategy.Either2; import mb.statix.random.strategy.SearchStrategies; import mb.statix.solver.IConstraint; import mb.statix.solver.persistent.State; import mb.statix.spec.Spec; public class RandomTermGenerator { private static final ILogger log = LoggerUtils.logger(RandomTermGenerator.class); private static final boolean DEBUG = false; private static final int LINE_WIDTH = 100; private static final int MAX_DEPTH = 1024; private final long seed = System.currentTimeMillis(); private final Random rnd = new Random(seed); private final Deque<Iterator<SearchNode<SearchState>>> stack = new LinkedList<>(); private final SearchStrategy<SearchState, SearchState> strategy = N.seq(enumerateComb(), infer()); private final Function1<ITerm, String> pp; public RandomTermGenerator(Spec spec, IConstraint constraint, Function1<ITerm, String> pp) { initStack(spec, constraint); this.pp = pp; log.info("random seed: {}", seed); log.info("strategy: {}", strategy); log.info("constraint: {}", constraint); log.info("max depth: {}", MAX_DEPTH); } private void initStack(Spec spec, IConstraint constraint) { final SearchState initState = SearchState.of(State.of(spec), ImmutableList.of(constraint)); // It is necessary to start with inference, otherwise we get stuck directly, // on, e.g., top-level existentials final Stream<SearchNode<SearchState>> initNodes = infer().apply(new NullSearchContext(rnd), initState, null); stack.push(initNodes.iterator()); } final AtomicInteger nodeId = new AtomicInteger(); private int work = 0; private int backtracks = 0; private int deadEnds = 0; private int hits = 0; public Optional<SearchState> next() throws MetaborgException, InterruptedException { final SearchContext ctx = new SearchContext() { @Override public Random rnd() { return rnd; } @Override public int nextNodeId() { return nodeId.incrementAndGet(); } @Override public void addFailed(SearchNode<SearchState> node) { printResult('.', "FAILURE", node, Level.Debug, Level.Debug); } }; while(!stack.isEmpty()) { final Iterator<SearchNode<SearchState>> nodes = stack.peek(); if(!nodes.hasNext()) { backtracks++; stack.pop(); continue; } final SearchNode<SearchState> node = nodes.next(); work++; if(done(node.output())) { printResult('+', "SUCCESS", node, Level.Info, Level.Debug); hits++; return Optional.of(node.output()); } else if(stack.size() >= MAX_DEPTH) { ctx.addFailed(node); deadEnds++; continue; } final Iterator<SearchNode<SearchState>> nextNodes = strategy.apply(ctx, node.output(), node).iterator(); if(!nextNodes.hasNext()) { ctx.addFailed(node); deadEnds++; continue; } stack.push(nextNodes); } if(!DEBUG) { System.out.println(); } log.info("hits {}", hits); log.info("work {}", work); log.info("dead ends {}", deadEnds); log.info("backtracks {}", backtracks); return Optional.empty(); } private static boolean done(SearchState state) { return state.constraints().stream() .allMatch(c -> c instanceof CInequal || (c instanceof CUser && ((CUser) c).name().startsWith("gen_"))); } private static final SearchStrategies N = new SearchStrategies(); private static SearchStrategy<SearchState, SearchState> infer() { return N.seq(N.infer(), dropAst()); } private static SearchStrategy<SearchState, SearchState> dropAst() { return N.drop(CAstId.class, CAstProperty.class); } // enumerate all possible combinations of solving constraints private static SearchStrategy<SearchState, SearchState> enumerateComb() { // @formatter:off return N.seq(selectConstraint(1), N.match( expandExpComb(), N.resolve() )); // @formatter:on } private static SearchStrategy<SearchState, Either2<FocusedSearchState<CUser>, FocusedSearchState<CResolveQuery>>> selectConstraint(int limit) { // @formatter:off return N.limit(limit, N.alt( N.select(CUser.class, new Not<>(new IsGen())), N.seq(N.select(CResolveQuery.class, new Any<>()), N.canResolve()) )); // @formatter:on } private static SearchStrategy<FocusedSearchState<CUser>, SearchState> expandExpComb() { // @formatter:off return N.expand(ImmutableMap.of( "T-Unit", 1, "T-Fun", 1, "T-Var", 1, "T-App", 1, "T-Let", 1 )); // @formatter:on } private static SearchStrategy<SearchState, SearchState> search(int ruleLimit) { // @formatter:off return N.seq(selectConstraint(1), N.match( expandExpSearch(ruleLimit), N.resolve() )); // @formatter:on } private static SearchStrategy<FocusedSearchState<CUser>, SearchState> expandExpSearch(int ruleLimit) { // @formatter:off return N.limit(ruleLimit, N.expand(ImmutableMap.of( "T-Unit", 1, "T-Fun", 1, "T-Var", 1, "T-App", 1, "T-Let", 0 ))); // @formatter:on } private static SearchStrategy<SearchState, SearchState> fillTypes() { // @formatter:off return N.seq( N.select(CUser.class, new IsType()), N.limit(5, N.expand(ImmutableMap.of("T-Unit", 2, "T-Fun", 1))) ); // @formatter:on } private int summaries = 0; private void printResult(char summary, String header, SearchNode<SearchState> node, Level level1, Level level2) { if(!DEBUG) { if((summaries++ % LINE_WIDTH) == 0) { System.out.println(); } System.out.print(summary); } else { log.log(level1, "+ node.output().print(s -> log.log(level1, s), (t, u) -> pp.apply(u.findRecursive(t))); log.log(level1, "+~~~ Trace ~~~+."); boolean first = true; SearchNode<?> traceNode = node; do { log.log(first ? level1 : level2, "+ * {}", traceNode); first = false; if(traceNode.output() instanceof SearchState) { SearchState state = (SearchState) traceNode.output(); IUnifier u = state.state().unifier(); log.log(level2, "+ constraints: {}", Constraints.toString(state.constraints(), t -> pp.apply(u.findRecursive(t)))); } } while((traceNode = traceNode.parent()) != null); log.log(level1, "+ } } }
package uk.ac.shef.dcs.kbproxy.model; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Entity extends Resource { private static final long serialVersionUID = -1208425814000405913L; protected List<Clazz> types=new ArrayList<>(); protected Set<String> typeIds=new HashSet<>(); protected Set<String> typeNames =new HashSet<>(); public Entity(String id, String label){ this.id=id; this.label=label; } public void addType(Clazz c){ types.add(c); typeIds.add(c.getId()); typeNames.add(c.getLabel()); } public Set<String> getTypeIds() { return typeIds; } public Set<String> getTypeNames() { return typeNames; } public boolean hasType(String typeId) { return typeIds.contains(typeId); } public List<Clazz> getTypes() { return types; } public void clearTypes(){ types.clear(); typeIds.clear(); typeNames.clear(); } }
package fr.obeo.tools.stuart.gerrit; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import fr.obeo.tools.stuart.Post; import fr.obeo.tools.stuart.gerrit.model.PatchSet; import fr.obeo.tools.stuart.git.GitLogger; public class GerritLogger { private static final String GERRIT_ICON = "http://static1.squarespace.com/static/525e9a22e4b0fe5f668a8903/t/557afd6de4b05d594de11f63/1434123630015/checklist?format=300w"; private String serverURL; private Gson gson; private int nbDays; private boolean groupReviews = true; public GerritLogger(String serverURL, int daysAgo) { this.serverURL = serverURL; gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").setPrettyPrinting().create(); this.nbDays = daysAgo; } public Collection<Post> getPatchsets(Collection<String> projects) { List<Post> posts = new ArrayList<Post>(); String prjString = Joiner.on(" OR ").join(Iterables.transform(projects, new Function<String, String>() { public String apply(String projectName) { return "project:" + projectName; } })); String query = "status:open AND label:Verified=1 AND -age:" + nbDays + "d AND (" + prjString + ")"; String url = serverURL + "/changes/?q=" + query + "&o=DETAILED_ACCOUNTS&o=CURRENT_REVISION"; Request request = new Request.Builder().url(url).get().build(); OkHttpClient client = new OkHttpClient(); Response response = null; try { response = client.newCall(request).execute(); String returnedJson = response.body().string(); PatchSet[] recentReviews = gson.fromJson(returnedJson, PatchSet[].class); List<PatchSet> reviewsToSend = Lists.newArrayList(); for (PatchSet review : recentReviews) { if (!review.getSubject().contains("DRAFT")) { reviewsToSend.add(review); } } Collections.sort(reviewsToSend, new Comparator<PatchSet>() { public int compare(PatchSet m1, PatchSet m2) { return m1.getUpdated().compareTo(m2.getUpdated()); } }); if (reviewsToSend.size() == 1 || !groupReviews) { for (PatchSet review : reviewsToSend) { Post newPost = Post.createPostWithSubject(serverURL + "/" + review.getId(), GitLogger.detectBugzillaLink(review.getSubject()), "ready for review (Validated)\n\n" + "|additions| deletions|\n" + "| + "|" + review.getInsertions() + " | " + review.getDeletions() + "|", review.getOwner().getName(), GERRIT_ICON, review.getUpdated()); newPost.addURLs(serverURL + "/#/c/" + review.get_number()); newPost.setQuote(false); newPost.mightBeTruncated(false); posts.add(newPost); } } else if (reviewsToSend.size() > 1) { List<List<PatchSet>> partitions = Lists.partition(reviewsToSend, 14); for (List<PatchSet> reviews : partitions) { String body = "\n" + "|subject|author|changes| merge ?| |\n" + "| Set<String> authors = Sets.newLinkedHashSet(); Set<String> urls = Sets.newLinkedHashSet(); for (PatchSet review : reviews) { String reviewKey = serverURL + "/" + review.getId(); String mergeable = ":boom:"; if (review.isMergeable()) { mergeable = ":star:"; } body += "| " + GitLogger.detectBugzillaLink(review.getSubject()) + " | " + review.getOwner().getName() + " | *+" + review.getInsertions() + "/-" + review.getDeletions() + "*|"+ mergeable + "| [link](" + serverURL + "/#/c/" + review.get_number() + ")|\n"; authors.add(review.getOwner().getName()); urls.add(reviewKey); } String authorName = Joiner.on(',').join(authors); String postKey = Joiner.on('_').join(urls); Post newPost = Post.createPostWithSubject(postKey, "Ready for reviews (" + reviews.size() + ")", body, authorName, GERRIT_ICON, reviews.iterator().next().getUpdated()); newPost.setQuote(false); newPost.mightBeTruncated(false); posts.add(newPost); } } response.body().close(); } catch (IOException e) { throw new RuntimeException(e); } return posts; } }
package com.maxifier.mxcache.legacy.layered; import com.magenta.dataserializator.MxObjectInput; import com.magenta.dataserializator.MxObjectOutput; import com.maxifier.mxcache.MxCacheException; import com.maxifier.mxcache.impl.resource.DependencyNode; import com.maxifier.mxcache.impl.resource.DependencyTracker; import com.maxifier.mxcache.impl.resource.ResourceOccupied; import com.maxifier.mxcache.proxy.Resolvable; import com.maxifier.mxcache.proxy.MxProxy; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.lang.ref.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SuppressWarnings({"SynchronizeOnNonFinalField", "SynchronizationOnLocalVariableOrMethodParameter"}) public final class MxLayeredStrategy<T> extends MxList.Element<MxLayeredStrategy<T>> implements Externalizable, Comparable<MxLayeredStrategy<T>>, Resolvable<T> { private static final Logger logger = LoggerFactory.getLogger(MxLayeredStrategy.class); private static final long serialVersionUID = -5171623695018264162L; private static final float MIN_REUSAGE_TO_PRESERVE = 5.0f; private MxLayeredCache<T> manager; /** * : * ( weak-) */ private Reference<MxLayeredStrategy<T>> selfReference; private Object[] data; private int queries; private int lastQueryTime; private int count; private T shorttimeValue; private MxReusageForecastManager<T> reusageForecastManager; private float reusageForecast; void updateReusageForecast() { reusageForecast = reusageForecastManager.getReusageForecast(this); } Reference<MxLayeredStrategy<T>> getSelfReference() { return selfReference; } void setSelfReference(Reference<MxLayeredStrategy<T>> selfReference) { this.selfReference = selfReference; } /** * should be called with synchronization on manager. * * @return true if this strategy should be preserved */ boolean isConfident() { if (reusageForecast >= MIN_REUSAGE_TO_PRESERVE || shorttimeValue != null) { return true; } for (int i = 0; i < count - 1; i++) { if (data[i] != null) { return true; } } return false; } @Override public void writeExternal(ObjectOutput out) throws IOException { MxObjectOutput output = (MxObjectOutput) out; output.serialize(manager); output.serialize(getValue()); output.writeObject(reusageForecastManager); } @Override @SuppressWarnings({"unchecked"}) public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { MxObjectInput input = (MxObjectInput) in; MxLayeredCache<T> manager = input.deserialize(); T stv = (T) input.deserialize(); reusageForecastManager = (MxReusageForecastManager) input.readObject(); init(manager, stv); } private void init(MxLayeredCache<T> manager, T stv) { this.manager = manager; count = manager.getLayerCount(); data = new Object[count]; synchronized (manager) { this.manager.registerStrategy(this); this.manager.addAndUpdate(this); shorttimeValue = stv; } } /** * @deprecated externalizable use only */ @Deprecated public MxLayeredStrategy() { } public MxLayeredStrategy(MxLayeredCache<T> manager, T value, MxReusageForecastManager<T> reusageForecastManager) { this.reusageForecastManager = reusageForecastManager; init(manager, value); } /** * , , MxLayeredStrategy * (, -). * , . */ void removeFromAllCaches() { if (shorttimeValue != null) { shorttimeValue = null; manager.removeFromShorttime(this); } for (int i = 0; i < count - 1; i++) { if (data[i] != null) { manager.getLayer(i).removeFromCache(this); data[i] = null; } } data[count - 1] = null; } void clearShorttime() { boolean canRemove = false; if (data[0] == null) { if (shorttimeValue instanceof MxProxy) { logger.warn("MxProxy passed to convertDown(int,Object)"); } if (count == 1 || manager.getLayer(0).tryToCache(this)) { data[0] = shorttimeValue; canRemove = true; } else if (!convertDown(0, shorttimeValue)) { for (int i = 1; i<count; i++) { if (data[i] != null) { canRemove = true; break; } } } } else { canRemove = true; } if (canRemove) { shorttimeValue = null; } } @Override public T getValue() { DependencyNode callerNode = DependencyTracker.track(DependencyTracker.DUMMY_NODE); try { while (true) { try { return getValue0(); } catch (ResourceOccupied e) { if (callerNode != null) { throw e; } else { e.getResource().waitForEndOfModification(); } } } } finally { DependencyTracker.exit(callerNode); } } @SuppressWarnings({"unchecked"}) private T getValue0() { synchronized (manager) { queries++; lastQueryTime = manager.getTime(); if (shorttimeValue == null) { if (data[0] == null) { long start = System.nanoTime(); shorttimeValue = getInternalValue(); manager.addAndUpdate(this); long end = System.nanoTime(); manager.miss(end - start); } else { shorttimeValue = (T) data[0]; manager.addAndUpdate(this); manager.hit(); } } else { manager.moveToEnd(this); manager.hit(); } return shorttimeValue; } } void exitPool(int layer) { if (convertDown(layer, data[layer])) { data[layer] = null; } else { for (int i = 0; i < count; i++) { if (data[i] != null && i != layer) { data[layer] = null; break; } } } } /** * , , , * , . * * @param layerId * @param value * @return true if corresponding layer was found and previous representation can be removed */ private boolean convertDown(int layerId, Object value) { if (value instanceof MxProxy) { logger.warn("MxProxy passed to convertDown(int,Object)"); } float minCost = Float.POSITIVE_INFINITY; int minLayer = -1; for (int i = layerId + 1; i < count; i++) { MxCacheLayer layer = manager.getLayer(i); if (data[i] != null || (manager.getConverter().canConvert(layerId, i) && (i == count - 1 || layer.canCache(this)))) { float cost = reusageForecast * manager.getConverter().getConvertCost(i, 0, 0); if (data[i] == null) { cost += manager.getConverter().getConvertCost(layerId, i, 0); } cost /= layer.getPreferenceFactor(); if (minCost > cost) { minCost = cost; minLayer = i; } } } if (minLayer == -1) { logger.error("Cannot collapse: no layer found to move from " + layerId); return false; } if (data[minLayer] == null) { if (minLayer != count - 1) { if (!manager.getLayer(minLayer).tryToCache(this)) { logger.error("Cannot add to longtime cache from " + layerId); return false; } } try { data[minLayer] = manager.getConverter().convert(layerId, minLayer, 0, value); } catch (Throwable e) { logger.error("Cannot convert from " + layerId + " to " + minLayer, e); return false; } } return true; } private T getInternalValue() { // data[0] is checked in getValue0(), so we don't check it again assert data[0] == null; int min = 0; float minCost = Float.POSITIVE_INFINITY; for (int i = 1; i < count; i++) { float cost = manager.getConverter().getConvertCost(i, 0, 0) / manager.getLayer(i).getPreferenceFactor(); if (data[i] != null && cost < minCost) { min = i; minCost = cost; } } if (min == 0) { throw new MxCacheException("Cannot deconvert " + this + ": all layers are empty"); } return convertAndSave(min); } @SuppressWarnings ({ "unchecked" }) private T convertAndSave(int min) { T v = (T) manager.getConverter().convert(min, 0, 0, data[min]); if (manager.getLayer(0).tryToCache(this)) { data[0] = v; } return v; } public int getQueries() { return queries; } public int getLastQueryTime() { return lastQueryTime; } @Override public int compareTo(MxLayeredStrategy<T> o) { return Float.compare(reusageForecast, o.reusageForecast); } String getKey() { StringBuilder builder = new StringBuilder(); if (shorttimeValue != null) { builder.append("SHORTTIME "); } for (int i = 0; i < count; i++) { if (data[i] != null) { builder.append(manager.getLayer(i).getName()).append(' '); } } return builder.toString(); } MxLayeredCache<T> getManager() { return manager; } @Override public String toString() { return getKey(); } }
package org.ovirt.engine.api.restapi.resource; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URI; import java.util.HashMap; import java.util.List; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import org.ovirt.engine.api.common.util.QueryHelper; import org.ovirt.engine.api.common.util.StatusUtils; import org.ovirt.engine.api.model.BaseResource; import org.ovirt.engine.core.common.action.VdcActionParametersBase; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.action.VdcReturnValueBase; import org.ovirt.engine.core.common.interfaces.SearchType; import org.ovirt.engine.core.common.queries.SearchParameters; import org.ovirt.engine.core.common.queries.VdcQueryParametersBase; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.utils.log.Log; import org.ovirt.engine.core.utils.log.LogFactory; public abstract class AbstractBackendCollectionResource<R extends BaseResource, Q /* extends IVdcQueryable */> extends AbstractBackendResource<R, Q> { private static final String EXPECT_HEADER = "Expect"; private static final String BLOCKING_EXPECTATION = "201-created"; private static final String CREATION_STATUS_REL = "creation_status"; public static final String FROM_CONSTRAINT_PARAMETER = "from"; public static final String CASE_SENSITIVE_CONSTRAINT_PARAMETER = "case_sensitive"; protected static final Log LOG = LogFactory.getLog(AbstractBackendCollectionResource.class); protected AbstractBackendCollectionResource(Class<R> modelType, Class<Q> entityType, String... subCollections) { super(modelType, entityType, subCollections); } public Response remove(String id) { getEntity(id); //will throw 404 if entity not found. return performRemove(id); } protected abstract Response performRemove(String id); protected List<Q> getBackendCollection(SearchType searchType) { return getBackendCollection(searchType, QueryHelper.getConstraint(getUriInfo(), "", modelType)); } protected List<Q> getBackendCollection(SearchType searchType, String constraint) { return getBackendCollection(entityType, VdcQueryType.Search, getSearchParameters(searchType, constraint)); } private SearchParameters getSearchParameters(SearchType searchType, String constraint) { SearchParameters searchParams = new SearchParameters(constraint, searchType); HashMap<String, String> matrixConstraints = QueryHelper.getMatrixConstraints(getUriInfo(), CASE_SENSITIVE_CONSTRAINT_PARAMETER, FROM_CONSTRAINT_PARAMETER); //preserved in sake if backward compatibility till 4.0 HashMap<String, String> queryConstraints = QueryHelper.getQueryConstraints(getUriInfo(), FROM_CONSTRAINT_PARAMETER); if (matrixConstraints.containsKey(FROM_CONSTRAINT_PARAMETER)) { try { searchParams.setSearchFrom(Long.parseLong(matrixConstraints.get(FROM_CONSTRAINT_PARAMETER))); } catch (Exception ex) { LOG.error("Unwrapping of '"+FROM_CONSTRAINT_PARAMETER+"' matrix search parameter failed.", ex); } } else if (queryConstraints.containsKey(FROM_CONSTRAINT_PARAMETER)) { //preserved in sake if backward compatibility till 4.0 try { searchParams.setSearchFrom(Long.parseLong(queryConstraints.get(FROM_CONSTRAINT_PARAMETER))); } catch (Exception ex) { LOG.error("Unwrapping of '"+FROM_CONSTRAINT_PARAMETER+"' query search parameter failed.", ex); } } if (matrixConstraints.containsKey(CASE_SENSITIVE_CONSTRAINT_PARAMETER)) { try { searchParams.setCaseSensitive(Boolean.parseBoolean(matrixConstraints.get(CASE_SENSITIVE_CONSTRAINT_PARAMETER))); } catch (Exception ex) { LOG.error("Unwrapping of '"+CASE_SENSITIVE_CONSTRAINT_PARAMETER+"' search parameter failed.", ex); } } if (QueryHelper.hasMatrixParam(getUriInfo(), MAX) && getMaxResults()!=NO_LIMIT) { searchParams.setMaxCount(getMaxResults()); } return searchParams; } protected List<Q> getBackendCollection(VdcQueryType query, VdcQueryParametersBase queryParams) { return getBackendCollection(entityType, query, queryParams); } protected Response performCreation(VdcActionType task, VdcActionParametersBase taskParams, EntityIdResolver entityResolver, boolean block) { VdcReturnValueBase createResult; try { createResult = runAction(task, taskParams); } catch (Exception e) { return handleError(e, false); } R model = resolveCreated(createResult, entityResolver); Response response = null; if (createResult.getHasAsyncTasks()) { if (block) { awaitCompletion(createResult); // refresh model state model = resolveCreated(createResult, entityResolver); response = Response.created(URI.create(model.getHref())).entity(model).build(); } else { if (model==null) { response = Response.status(ACCEPTED_STATUS).build(); } else { handleAsynchrony(createResult, model); response = Response.status(ACCEPTED_STATUS).entity(model).build(); } } } else { if (model==null) { response = Response.status(ACCEPTED_STATUS).build(); } else { response = Response.created(URI.create(model.getHref())).entity(model).build(); } } return response; } protected VdcReturnValueBase runAction(VdcActionType task, VdcActionParametersBase taskParams) throws BackendFailureException { VdcReturnValueBase createResult = backend.RunAction(task, sessionize(taskParams)); if (!createResult.getCanDoAction()) { throw new BackendFailureException(localize(createResult.getCanDoActionMessages())); } else if (!createResult.getSucceeded()) { throw new BackendFailureException(localize(createResult.getExecuteFailedMessages())); } return createResult; } protected Response performCreation(VdcActionType task, VdcActionParametersBase taskParams, EntityIdResolver entityResolver) { return performCreation(task, taskParams, entityResolver, expectBlocking()); } protected boolean expectBlocking() { boolean expectBlocking = false; List<String> expect = httpHeaders.getRequestHeader(EXPECT_HEADER); if (expect != null && expect.size() > 0) { expectBlocking = expect.get(0).equalsIgnoreCase(BLOCKING_EXPECTATION); } return expectBlocking; } protected void handleAsynchrony(VdcReturnValueBase result, R model) { model.setCreationStatus(StatusUtils.create(getAsynchronousStatus(result))); linkSubResource(model, CREATION_STATUS_REL, asString(result.getTaskIdList())); } protected R resolveCreated(VdcReturnValueBase result, EntityIdResolver entityResolver) { try { Q created = entityResolver.resolve((Guid)result.getActionReturnValue()); return addLinks(populate(map(created), created)); } catch (Exception e) { // we tolerate a failure in the entity resolution // as the substantive action (entity creation) has // already succeeded e.printStackTrace(); return null; } } protected String asString(VdcReturnValueBase result) { Guid guid = (Guid)result.getActionReturnValue(); return guid != null ? guid.toString() : null; } protected void getEntity(String id) { try { Method method = getMethod(this.getClass(), SingleEntityResource.class); if (method==null) { LOG.error("Could not find sub-resource in the collection resource"); } else { Object entityResource = method.invoke(this, id); method = entityResource.getClass().getMethod("get"); if (method==null) { LOG.warn("Could not find GET method in " + entityResource.getClass().getName()); } else { method.invoke(entityResource); } } } catch (IllegalAccessException e) { LOG.error("Reflection Error", e); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof WebApplicationException) { throw((WebApplicationException)e.getTargetException()); } else { LOG.error("Reflection Error", e); } } catch (SecurityException e) { LOG.error("Reflection Error", e); } catch (NoSuchMethodException e) { LOG.error("Reflection Error", e); } } @SuppressWarnings("unchecked") private Method getMethod(Class<?> clazz, @SuppressWarnings("rawtypes") Class annotation) { for (Method m : clazz.getMethods()) { if (m.getAnnotation(annotation)!=null) { return m; } } return null; } }
package jkind.interval; import java.math.BigInteger; import java.util.ArrayDeque; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import java.util.Set; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.NamedType; import jkind.lustre.SubrangeIntType; import jkind.lustre.Type; import jkind.lustre.values.IntegerValue; import jkind.lustre.values.RealValue; import jkind.lustre.values.Value; import jkind.results.Counterexample; import jkind.results.Signal; import jkind.solvers.BoolValue; import jkind.solvers.Model; import jkind.translation.Specification; import jkind.util.Util; public class ModelGeneralizer { private final Specification spec; private final String property; private final Model basisModel; private final int k; private final Map<IdIndexPair, Interval> cache = new HashMap<>(); private final Map<String, Expr> equations = new HashMap<>(); private final Queue<IdIndexPair> toGeneralize = new ArrayDeque<>(); private final Map<IdIndexPair, Interval> generalized = new HashMap<>(); private final ReverseDependencyMap dependsOn; private final IntIntervalGeneralizer intIntervalGeneralizer; private final RealIntervalGeneralizer realIntervalGeneralizer; public ModelGeneralizer(Specification spec, String property, Model model, int k) { this.spec = spec; this.property = property; this.basisModel = model; this.k = k; for (Equation eq : spec.node.equations) { equations.put(eq.lhs.get(0).id, eq.expr); } dependsOn = new ReverseDependencyMap(spec.node, spec.dependencyMap.get(property)); intIntervalGeneralizer = new IntIntervalGeneralizer(this); realIntervalGeneralizer = new RealIntervalGeneralizer(this); } public Counterexample generalize() { // This fills the initial toGeneralize queue as a side-effect if (!modelConsistent()) { throw new IllegalStateException("Internal JKind error during interval generalization"); } // More items may be added to the toGeneralize queue as prior // generalizations make them relevant while (!toGeneralize.isEmpty()) { IdIndexPair pair = toGeneralize.remove(); Interval interval = generalizeInterval(pair.id, pair.i); generalized.put(pair, interval); } return extractCounterexample(); } private Interval generalizeInterval(String id, int i) { Type type = spec.typeMap.get(id); if (type == NamedType.BOOL) { return generalizeBoolInterval(id, i); } else if (type == NamedType.INT) { NumericInterval initial = (NumericInterval) originalInterval(id, i); return intIntervalGeneralizer.generalize(id, i, initial); } else if (type == NamedType.REAL) { NumericInterval initial = (NumericInterval) originalInterval(id, i); return realIntervalGeneralizer.generalize(id, i, initial); } else if (type instanceof SubrangeIntType) { return generalizeSubrangeIntInterval(id, i); } else { throw new IllegalArgumentException("Unknown type in generalization: " + type); } } private Interval generalizeBoolInterval(String id, int i) { if (modelConsistent(id, i, BoolInterval.ARBITRARY)) { return BoolInterval.ARBITRARY; } else { return originalInterval(id, i); } } private Interval generalizeSubrangeIntInterval(String id, int i) { NumericInterval next = new NumericInterval(IntEndpoint.NEGATIVE_INFINITY, IntEndpoint.POSITIVE_INFINITY); if (modelConsistent(id, i, next)) { return next; } else { return originalInterval(id, i); } } private Counterexample extractCounterexample() { // This fills the cache as a side-effect if (!modelConsistent()) { throw new IllegalStateException("Internal JKind error during interval generalization"); } Counterexample cex = new Counterexample(k); for (Entry<IdIndexPair, Interval> entry : cache.entrySet()) { IdIndexPair pair = entry.getKey(); Interval value = entry.getValue(); if (!value.isArbitrary()) { Signal<Value> signal = cex.getSignal(pair.id); if (signal == null) { signal = new Signal<>(pair.id); cex.addSignal(signal); } signal.putValue(pair.i, value); } } return cex; } private Interval originalInterval(String id, int i) { return eval(id, i); } private boolean modelConsistent() { BoolInterval interval = (BoolInterval) eval(property, k - 1); if (!interval.isFalse()) { return false; } for (Expr as : spec.node.assertions) { for (int i = 0; i < k; i++) { interval = (BoolInterval) eval(as, i); if (!interval.isTrue()) { return false; } } } return true; } public boolean modelConsistent(String id, int i, Interval proposedValue) { clearCacheFrom(id, i); cache.put(new IdIndexPair(id, i), proposedValue); boolean result = modelConsistent(); clearCacheFrom(id, i); return result; } private void clearCacheFrom(String id, int step) { for (String recompute : dependsOn.get(id)) { for (int i = step; i < k; i++) { cache.remove(new IdIndexPair(recompute, i)); } } } public static class AlgebraicLoopException extends RuntimeException { private static final long serialVersionUID = 1L; } private final Set<IdIndexPair> working = new HashSet<>(); private Interval eval(Expr expr, int i) { return expr.accept(new IntervalEvaluator(i, this)); } private Interval eval(String id, int i) { return eval(new IdExpr(id), i); } /* * The IntervalEvaluator will call back in to this class to look up ids. */ public Interval evalId(String id, int i) { IdIndexPair pair = new IdIndexPair(id, i); if (cache.containsKey(pair)) { return cache.get(pair); } Interval result; if (equations.containsKey(id) && i >= 0) { pair = new IdIndexPair(id, i); if (working.contains(pair)) { throw new AlgebraicLoopException(); } working.add(pair); result = eval(equations.get(id), i); working.remove(pair); } else if (generalized.containsKey(pair)) { result = generalized.get(pair); } else { result = getFromBasisModel(pair); // Due to checking all assertions, we may hit variables that our // property doesn't depend on. We detect and ignore these variables. if (i >= 0 && dependsOn.get(id) != null) { toGeneralize.add(pair); } } cache.put(pair, result); return result; } private Interval getFromBasisModel(IdIndexPair pair) { jkind.solvers.Value raw = basisModel.getFunctionValue("$" + pair.id, BigInteger.valueOf(pair.i)); if (raw instanceof BoolValue) { BoolValue bv = (BoolValue) raw; return bv.getBool() ? BoolInterval.TRUE : BoolInterval.FALSE; } else { Value parsed = Util.parseValue(Util.getName(spec.typeMap.get(pair.id)), raw.toString()); if (parsed instanceof IntegerValue) { IntegerValue iv = (IntegerValue) parsed; IntEndpoint endpoint = new IntEndpoint(iv.value); return new NumericInterval(endpoint, endpoint); } else { RealValue rv = (RealValue) parsed; RealEndpoint endpoint = new RealEndpoint(rv.value); return new NumericInterval(endpoint, endpoint); } } } }
package com.x.program.center.schedule; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.stream.Collectors; import javax.persistence.EntityManager; import javax.persistence.Tuple; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.script.Bindings; import javax.script.CompiledScript; import javax.script.ScriptContext; import javax.script.SimpleScriptContext; import com.google.gson.JsonElement; import com.x.base.core.project.config.CenterServer; import com.x.base.core.project.config.Config; import com.x.base.core.project.connection.ActionResponse; import com.x.base.core.project.connection.CipherConnectionAction; import com.x.base.core.project.exception.RunningException; import com.x.base.core.project.jaxrs.WrapBoolean; import com.x.base.core.project.tools.ListTools; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import com.x.base.core.container.EntityManagerContainer; import com.x.base.core.container.factory.EntityManagerContainerFactory; import com.x.base.core.project.cache.Cache.CacheCategory; import com.x.base.core.project.cache.Cache.CacheKey; import com.x.base.core.project.cache.CacheManager; import com.x.base.core.project.logger.Logger; import com.x.base.core.project.logger.LoggerFactory; import com.x.base.core.project.script.AbstractResources; import com.x.base.core.project.script.ScriptFactory; import com.x.base.core.project.tools.CronTools; import com.x.base.core.project.tools.DateTools; import com.x.base.core.project.webservices.WebservicesClient; import com.x.organization.core.express.Organization; import com.x.program.center.Business; import com.x.program.center.ThisApplication; import com.x.program.center.core.entity.Agent; import com.x.program.center.core.entity.Agent_; /** * * @author sword */ public class TriggerAgent extends BaseAction { private static Logger logger = LoggerFactory.getLogger(TriggerAgent.class); private static final CopyOnWriteArrayList<String> LOCK = new CopyOnWriteArrayList<>(); private static final ExecutorService executorService = new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), new BasicThreadFactory.Builder().namingPattern("triggerAgent-pool-%d").daemon(true).build()); @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { try { if (pirmaryCenter()) { List<Pair> list; try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) { Business business = new Business(emc); list = this.list(business); } if(list!=null) { list.stream().forEach(p -> { this.trigger(p); }); } } } catch (Exception e) { logger.error(e); throw new JobExecutionException(e); } } private void trigger(Pair pair) { try { if (StringUtils.isEmpty(pair.getCron())) { return; } Date date = CronTools.next(pair.getCron(), pair.getLastStartTime()); if (date.before(new Date())) { if (LOCK.contains(pair.getId())) { throw new ExceptionAgentLastNotEnd(pair); } Agent agent = null; try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) { agent = emc.find(pair.getId(), Agent.class); if (null != agent) { emc.beginTransaction(Agent.class); agent.setLastStartTime(new Date()); emc.commit(); } } if (null != agent && agent.getEnable()) { logger.info("trigger agent : {}, name :{}, cron: {}, last start time: {}.", pair.getId(), pair.getName(), pair.getCron(), (pair.getLastStartTime() == null ? "" : DateTools.format(pair.getLastStartTime()))); ExecuteThread thread = new ExecuteThread(agent); executorService.execute(thread); } } } catch (Exception e) { logger.error(e); } } private List<Pair> list(Business business) throws Exception { EntityManagerContainer emc = business.entityManagerContainer(); EntityManager em = emc.get(Agent.class); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class); Root<Agent> root = cq.from(Agent.class); Path<String> path_id = root.get(Agent_.id); Path<String> path_name = root.get(Agent_.name); Path<String> path_cron = root.get(Agent_.cron); Path<Date> path_lastEndTime = root.get(Agent_.lastEndTime); Path<Date> path_lastStartTime = root.get(Agent_.lastStartTime); Predicate p = cb.equal(root.get(Agent_.enable), true); List<Tuple> list = em .createQuery( cq.multiselect(path_id, path_name, path_cron, path_lastEndTime, path_lastStartTime).where(p)) .getResultList(); List<Pair> pairs = list.stream().map(o -> { return new Pair(o.get(path_id), o.get(path_name), o.get(path_cron), o.get(path_lastStartTime)); }).distinct().collect(Collectors.toList()); return pairs; } class Pair { Pair(String id, String name, String cron, Date lastStartTime) { this.id = id; this.name = name; this.cron = cron; this.lastStartTime = lastStartTime; } private String id; private String name; private String cron; private Date lastStartTime; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCron() { return cron; } public void setCron(String cron) { this.cron = cron; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getLastStartTime() { return lastStartTime; } public void setLastStartTime(Date lastStartTime) { this.lastStartTime = lastStartTime; } } public class ExecuteThread implements Runnable { private Agent agent; public ExecuteThread(Agent agent) { this.agent = agent; } @Override public void run() { if (StringUtils.isNotEmpty(agent.getText())) { try { LOCK.add(agent.getId()); Map.Entry<String, CenterServer> centerServer = getCenterServer(); if(centerServer==null){ try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) { CacheCategory cacheCategory = new CacheCategory(Agent.class); CacheKey cacheKey = new CacheKey(TriggerAgent.class, agent.getId()); CompiledScript compiledScript = null; Optional<?> optional = CacheManager.get(cacheCategory, cacheKey); if (optional.isPresent()) { compiledScript = (CompiledScript) optional.get(); } else { compiledScript = ScriptFactory.compile(ScriptFactory.functionalization(agent.getText())); CacheManager.put(cacheCategory, cacheKey, compiledScript); } ScriptContext scriptContext = new SimpleScriptContext(); Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE); Resources resources = new Resources(); resources.setEntityManagerContainer(emc); resources.setContext(ThisApplication.context()); resources.setOrganization(new Organization(ThisApplication.context())); resources.setApplications(ThisApplication.context().applications()); resources.setWebservicesClient(new WebservicesClient()); bindings.put(ScriptFactory.BINDING_NAME_RESOURCES, resources); try { ScriptFactory.initialServiceScriptText().eval(scriptContext); compiledScript.eval(scriptContext); } catch (Exception e) { throw new ExceptionAgentEval(e, e.getMessage(), agent.getId(), agent.getName(), agent.getAlias(), agent.getText()); } } catch (Exception e) { logger.error(e); } try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) { Agent o = emc.find(agent.getId(), Agent.class); if (null != o) { emc.beginTransaction(Agent.class); o.setLastEndTime(new Date()); emc.commit(); } } catch (Exception e) { logger.error(e); } }else{ try { CipherConnectionAction.get(false, Config.url_x_program_center_jaxrs(centerServer, "agent", agent.getId(), "execute") + "?tt=" + System.currentTimeMillis()); } catch (Exception e) { logger.warn("trigger agent {} on center {} error:{}", agent.getName(), centerServer.getKey(), e.getMessage()); } } } finally { LOCK.remove(agent.getId()); } } } private Map.Entry<String, CenterServer> getCenterServer(){ Map.Entry<String, CenterServer> centerServer = null; try { Map.Entry<String, CenterServer> entry; List<Map.Entry<String, CenterServer>> list = Config.nodes().centerServers().orderedEntry(); if (ListTools.isNotEmpty(list)) { Collections.shuffle(list); entry = list.get(0); ActionResponse response = CipherConnectionAction.get(false, 2000, 4000, Config.url_x_program_center_jaxrs(entry, "echo")); JsonElement jsonElement = response.getData(JsonElement.class); if (null != jsonElement && (!jsonElement.isJsonNull())) { centerServer = entry; } } } catch (Exception e) { logger.debug(e.getMessage()); } return centerServer; } } public static class Resources extends AbstractResources { private Organization organization; public Organization getOrganization() { return organization; } public void setOrganization(Organization organization) { this.organization = organization; } } }
package jnode.ftn.tosser; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.zip.CRC32; import java.util.zip.ZipFile; import jnode.dto.Dupe; import jnode.dto.Echoarea; import jnode.dto.Echomail; import jnode.dto.EchomailAwaiting; import jnode.dto.FileSubscription; import jnode.dto.Filearea; import jnode.dto.Filemail; import jnode.dto.FilemailAwaiting; import jnode.dto.FileForLink; import jnode.dto.Link; import jnode.dto.LinkOption; import jnode.dto.Netmail; import jnode.dto.Subscription; import jnode.event.NewEchomailEvent; import jnode.event.NewFilemailEvent; import jnode.event.NewNetmailEvent; import jnode.event.Notifier; import jnode.ftn.types.Ftn2D; import jnode.ftn.types.FtnAddress; import jnode.ftn.types.FtnMessage; import jnode.ftn.types.FtnPkt; import jnode.ftn.types.FtnTIC; import jnode.logger.Logger; import jnode.main.MainHandler; import jnode.main.threads.PollQueue; import jnode.main.threads.TosserQueue; import jnode.orm.ORMManager; import jnode.protocol.io.Message; import static jnode.ftn.FtnTools.*; /** * * @author kreon * */ public class FtnTosser { private static final String FILEECHO_ENABLE = "fileecho.enable"; private static final String FILEECHO_PATH = "fileecho.path"; private static final Logger logger = Logger.getLogger(FtnTosser.class); private final Map<String, Integer> tossed = new HashMap<String, Integer>(); private final Map<String, Integer> bad = new HashMap<String, Integer>(); private final Set<Link> pollLinks = new HashSet<Link>(); private void tossNetmail(FtnMessage netmail, boolean secure) { if (secure) { if (checkRobot(netmail)) { return; } } boolean drop = validateNetmail(netmail); if (drop) { Integer n = bad.get("netmail"); bad.put("netmail", (n == null) ? 1 : n + 1); } else { if ((netmail.getAttribute() & FtnMessage.ATTR_ARQ) > 0) { writeReply(netmail, "ARQ reply", "Your message was successfully reached this system"); } processRewrite(netmail); Link routeVia = getRouting(netmail); Netmail dbnm = new Netmail(); dbnm.setRouteVia(routeVia); dbnm.setDate(netmail.getDate()); dbnm.setFromFTN(netmail.getFromAddr().toString()); dbnm.setToFTN(netmail.getToAddr().toString()); dbnm.setFromName(netmail.getFromName()); dbnm.setToName(netmail.getToName()); dbnm.setSubject(netmail.getSubject()); dbnm.setText(netmail.getText()); dbnm.setAttr(netmail.getAttribute()); ORMManager.INSTANSE.getNetmailDAO().save(dbnm); Notifier.INSTANSE.notify(new NewNetmailEvent(dbnm)); Integer n = tossed.get("netmail"); tossed.put("netmail", (n == null) ? 1 : n + 1); if (routeVia == null) { logger.l4(String .format("Netmail %s -> %s is not transferred ( routing not found )", netmail.getFromAddr().toString(), netmail .getToAddr().toString())); } else { routeVia = ORMManager.INSTANSE.getLinkDAO().getById( routeVia.getId()); logger.l4(String.format("Netmail %s -> %s transferred via %s", netmail.getFromAddr().toString(), netmail.getToAddr() .toString(), routeVia.getLinkAddress())); if (getOptionBooleanDefTrue(routeVia, LinkOption.BOOLEAN_CRASH_NETMAIL)) { PollQueue.INSTANSE.add(routeVia); } } } } private void tossEchomail(FtnMessage echomail, Link link, boolean secure) { if (!secure) { logger.l3("Echomail via unsecure is dropped"); return; } Echoarea area = getAreaByName(echomail.getArea(), link); if (area == null) { logger.l3("Echoarea " + echomail.getArea() + " is not avalible for " + link.getLinkAddress()); Integer n = bad.get(echomail.getArea()); bad.put(echomail.getArea(), (n == null) ? 1 : n + 1); return; } if (echomail.getMsgid() == null) { logger.l3("echomai " + echomail + " has null msgid"); } else { if (isADupe(area, echomail.getMsgid())) { logger.l3("Message " + echomail.getArea() + " " + echomail.getMsgid() + " is a dupe"); Integer n = bad.get(echomail.getArea()); bad.put(echomail.getArea(), (n == null) ? 1 : n + 1); return; } } processRewrite(echomail); Echomail mail = new Echomail(); mail.setArea(area); mail.setDate(echomail.getDate()); mail.setFromFTN(echomail.getFromAddr().toString()); mail.setFromName(echomail.getFromName()); mail.setToName(echomail.getToName()); mail.setSubject(echomail.getSubject()); mail.setText(echomail.getText()); mail.setSeenBy(write2D(echomail.getSeenby(), true)); mail.setPath(write2D(echomail.getPath(), false)); ORMManager.INSTANSE.getEchomailDAO().save(mail); for (Subscription sub : ORMManager.INSTANSE.getSubscriptionDAO() .getAnd("echoarea_id", "=", area)) { if (link == null || !sub.getLink().getId().equals(link.getId())) { ORMManager.INSTANSE.getEchomailAwaitingDAO().save( new EchomailAwaiting(sub.getLink(), mail)); pollLinks.add(sub.getLink()); } } Notifier.INSTANSE.notify(new NewEchomailEvent(mail)); { Dupe dupe = new Dupe(); dupe.setEchoarea(area); dupe.setMsgid(echomail.getMsgid()); ORMManager.INSTANSE.getDupeDAO().save(dupe); } Integer n = tossed.get(echomail.getArea()); tossed.put(echomail.getArea(), (n == null) ? 1 : n + 1); } public int tossIncoming(Message message) { if (message == null) { return 0; } try { unpack(message); TosserQueue.getInstanse().toss(); } catch (IOException e) { logger.l1( "Exception file tossing message " + message.getMessageName(), e); return 1; } return 0; } public synchronized void tossInboundDirectory() { logger.l4("Start tossInboundDirectory()"); Set<Link> poll = new HashSet<Link>(); File inbound = new File(getInbound()); for (File file : inbound.listFiles()) { String loname = file.getName().toLowerCase(); if (loname.matches("^[a-f0-9]{8}\\.pkt$")) { try { Message m = new Message(file); logger.l4("Tossing file " + file.getAbsolutePath()); FtnMessage ftnm; FtnPkt pkt = new FtnPkt(); pkt.unpack(m.getInputStream()); while ((ftnm = pkt.getNextMessage()) != null) { if (ftnm.isNetmail()) { tossNetmail(ftnm, true); } else { tossEchomail(ftnm, null, true); } } file.delete(); } catch (Exception e) { logger.l3("Tossing failed " + file.getAbsolutePath(), e); } } else if (loname.matches("(s|u)inb\\d*.pkt")) { try { Message m = new Message(file); logger.l4("Tossing file " + file.getAbsolutePath()); FtnPkt pkt = new FtnPkt(); pkt.unpack(m.getInputStream()); Link link = ORMManager.INSTANSE.getLinkDAO().getFirstAnd( "ftn_address", "=", pkt.getFromAddr().toString()); boolean secure = loname.charAt(0) == 's'; if (secure) { if (!getOptionBooleanDefTrue(link, LinkOption.BOOLEAN_IGNORE_PKTPWD)) { if (!link.getPaketPassword().equalsIgnoreCase( pkt.getPassword())) { logger.l2("Pkt password mismatch - package moved to inbound"); moveToBad(pkt); continue; } } } FtnMessage ftnm; while ((ftnm = pkt.getNextMessage()) != null) { if (ftnm.isNetmail()) { tossNetmail(ftnm, secure); } else { tossEchomail(ftnm, link, secure); } } file.delete(); } catch (Exception e) { logger.l3("Tossing failed " + file.getAbsolutePath(), e); } } else if (loname.matches("^[a-z0-9]{8}\\.tic$")) { if (!MainHandler.getCurrentInstance().getBooleanProperty( FILEECHO_ENABLE, true)) { continue; } logger.l3("Proccessing " + file.getName()); try { FileInputStream fis = new FileInputStream(file); FtnTIC tic = new FtnTIC(); tic.unpack(fis); fis.close(); String filename = tic.getFile().toLowerCase(); File attach = new File(getInbound() + File.separator + filename); boolean ninetoa = false; boolean ztonull = false; boolean underll = false; while (!attach.exists()) { if ((ninetoa && ztonull) || underll) { break; } else { char[] array = filename.toCharArray(); char c = array[array.length - 1]; if ((c >= '0' && c <= '8') || (c >= 'a' && c <= 'y')) { c++; } else if (c == '9') { c = 'a'; ninetoa = true; } else if (c == 'z') { c = '0'; ztonull = true; } else { c = '_'; underll = true; } array[array.length - 1] = c; filename = new String(array); attach = new File(getInbound() + File.separator + filename); } } if (attach.canRead()) { // processing logger.l3("File found as " + filename); if (!MainHandler.getCurrentInstance().getInfo() .getAddressList().contains(tic.getTo())) { file.delete(); logger.l3("Tic " + file.getName() + " is not for us"); continue; } Link source = ORMManager.INSTANSE.getLinkDAO() .getFirstAnd("ftn_address", "=", tic.getFrom().toString()); if (source == null) { logger.l3("Link " + tic.getFrom() + " not found"); file.renameTo(new File(getInbound() + File.separator + "bad_" + generateTic())); continue; } Filearea area = getFileareaByName(tic.getArea() .toLowerCase(), source); if (area == null) { logger.l3("Filearea " + tic.getArea() + " is not avalible for " + source.getLinkAddress()); file.renameTo(new File(getInbound() + File.separator + "bad_" + generateTic())); continue; } new File(getFileechoPath() + File.separator + area.getName()).mkdir(); Filemail mail = new Filemail(); if (attach.renameTo(new File(getFileechoPath() + File.separator + area.getName() + File.separator + tic.getFile()))) { mail.setFilepath(getFileechoPath() + File.separator + area.getName() + File.separator + tic.getFile()); } else { mail.setFilepath(attach.getAbsolutePath()); } mail.setFilearea(area); mail.setFilename(tic.getFile()); mail.setFiledesc(tic.getDesc()); mail.setOrigin(tic.getOrigin().toString()); mail.setPath(tic.getPath()); mail.setSeenby(write4D(tic.getSeenby())); mail.setCreated(new Date()); ORMManager.INSTANSE.getFilemailDAO().save(mail); for (FileSubscription sub : ORMManager.INSTANSE .getFileSubscriptionDAO().getAnd("filearea_id", "=", area, "link_id", "!=", source)) { ORMManager.INSTANSE.getFilemailAwaitingDAO().save( new FilemailAwaiting(sub.getLink(), mail)); if (getOptionBooleanDefFalse(sub.getLink(), LinkOption.BOOLEAN_CRASH_FILEMAIL)) { poll.add(sub.getLink()); } } Notifier.INSTANSE.notify(new NewFilemailEvent(mail)); } else { logger.l3("File " + tic.getFile() + " not found in inbound, waiting"); continue; } file.delete(); } catch (Exception e) { logger.l1("Error while processing tic " + file.getName(), e); } } else if (loname.matches("^[0-9a-f]{8}\\..?lo$")) { FtnAddress address = getPrimaryFtnAddress().clone(); address.setPoint(0); try { address.setNet(Integer.parseInt(loname.substring(0, 4), 16)); address.setNode(Integer.parseInt(loname.substring(4, 8), 16)); Link l = ORMManager.INSTANSE.getLinkDAO().getFirstAnd( "ftn_address", "=", address.toString()); if (l != null) { try { BufferedReader br = new BufferedReader( new FileReader(file)); while (br.ready()) { String name = br.readLine(); if (name != null) { File f = new File(name); if (f.exists() && f.canRead()) { FileForLink ffl = new FileForLink(); ffl.setLink(l); ffl.setFilename(name); ORMManager.INSTANSE.getFileForLinkDAO() .save(ffl); } else { logger.l2("File from ?lo not exists: " + name); } } } br.close(); } catch (Exception e) { logger.l2("Unable to read .?lo for files list", e); } poll.add(l); } } catch (NumberFormatException e) { logger.l3("?LO file " + loname + " is invalid"); } file.delete(); } } for (Link l : poll) { PollQueue.INSTANSE.add(ORMManager.INSTANSE.getLinkDAO().getById( l.getId())); } } public String getFileechoPath() { return MainHandler.getCurrentInstance().getProperty(FILEECHO_PATH, getInbound()); } public void end() { if (!tossed.isEmpty()) { logger.l3("Messages wrote:"); for (String area : tossed.keySet()) { logger.l3(String.format("\t%s - %d", area, tossed.get(area))); } } if (!bad.isEmpty()) { logger.l2("Messages dropped:"); for (String area : bad.keySet()) { logger.l2(String.format("\t%s - %d", area, bad.get(area))); } } for (Link l : pollLinks) { if (getOptionBooleanDefFalse(l, LinkOption.BOOLEAN_CRASH_ECHOMAIL)) { PollQueue.INSTANSE.add(ORMManager.INSTANSE.getLinkDAO() .getById(l.getId())); } } tossed.clear(); bad.clear(); pollLinks.clear(); } public synchronized static List<Message> getMessagesForLink(Link link) { FtnAddress link_address = new FtnAddress(link.getLinkAddress()); Ftn2D link2d = new Ftn2D(link_address.getNet(), link_address.getNode()); List<FtnMessage> messages = new ArrayList<FtnMessage>(); List<File> attachedFiles = new ArrayList<File>(); List<FtnTIC> tics = new ArrayList<FtnTIC>(); List<Message> ret = new ArrayList<Message>(); try { List<Netmail> netmails = ORMManager.INSTANSE.getNetmailDAO() .getAnd("send", "=", false, "route_via", "=", link); if (!netmails.isEmpty()) { for (Netmail netmail : netmails) { FtnMessage msg = netmailToFtnMessage(netmail); messages.add(msg); logger.l4(String.format( "Pack netmail #%d %s -> %s for %s flags %d", netmail.getId(), netmail.getFromFTN(), netmail.getToFTN(), link.getLinkAddress(), msg.getAttribute())); if ((netmail.getAttr() & FtnMessage.ATTR_FILEATT) > 0) { String filename = netmail.getSubject(); filename = filename.replaceAll("^[\\./\\\\]+", "_"); File file = new File(getInbound() + File.separator + filename); if (file.canRead()) { attachedFiles.add(file); logger.l5("Netmail with attached file " + filename); } } netmail.setSend(true); ORMManager.INSTANSE.getNetmailDAO().update(netmail); } } } catch (Exception e) { logger.l2("Netmail error " + link.getLinkAddress(), e); } // echomail { List<Echomail> toRemove = new ArrayList<Echomail>(); List<EchomailAwaiting> mailToSend = ORMManager.INSTANSE .getEchomailAwaitingDAO().getAnd("link_id", "=", link); for (EchomailAwaiting ema : mailToSend) { Echomail mail = ema.getMail(); if (mail == null) { logger.l2(MessageFormat.format( "Error: not found echomail for awaiting mail {0}", ema)); continue; } Echoarea area = mail.getArea(); toRemove.add(mail); Set<Ftn2D> seenby = new HashSet<Ftn2D>(read2D(mail.getSeenBy())); if (seenby.contains(link2d) && link_address.getPoint() == 0) { logger.l5(link2d + " is in seenby for " + link_address); continue; } List<Ftn2D> path = read2D(mail.getPath()); for (FtnAddress address : MainHandler.getCurrentInstance() .getInfo().getAddressList()) { Ftn2D me = new Ftn2D(address.getNet(), address.getNode()); seenby.add(me); if (!path.contains(me)) { path.add(me); } } seenby.add(link2d); List<Subscription> ssubs = ORMManager.INSTANSE .getSubscriptionDAO().getAnd("echoarea_id", "=", area); for (Subscription ssub : ssubs) { try { Link _sslink = ORMManager.INSTANSE.getLinkDAO() .getById(ssub.getLink().getId()); FtnAddress addr = new FtnAddress( _sslink.getLinkAddress()); Ftn2D d2 = new Ftn2D(addr.getNet(), addr.getNode()); seenby.add(d2); } catch (NullPointerException e) { logger.l1("Bad link for subscriprion " + ssub + " : ignored", e); } } FtnMessage message = new FtnMessage(); message.setNetmail(false); message.setArea(area.getName().toUpperCase()); message.setFromName(mail.getFromName()); message.setToName(mail.getToName()); message.setFromAddr(getPrimaryFtnAddress()); message.setToAddr(link_address); message.setDate(mail.getDate()); message.setSubject(mail.getSubject()); message.setText(mail.getText()); message.setSeenby(new ArrayList<Ftn2D>(seenby)); message.setPath(path); logger.l4("Echomail #" + mail.getId() + " (" + area.getName() + ") packed for " + link.getLinkAddress()); messages.add(message); } if (!toRemove.isEmpty()) { ORMManager.INSTANSE.getEchomailAwaitingDAO().delete("link_id", "=", link, "echomail_id", "in", toRemove); } } // fileechoes { List<Filemail> toRemove = new ArrayList<Filemail>(); List<FilemailAwaiting> filemail = ORMManager.INSTANSE .getFilemailAwaitingDAO().getAnd("link_id", "=", link); for (FilemailAwaiting awmail : filemail) { Filemail mail = awmail.getMail(); toRemove.add(mail); if (mail == null) { continue; } Filearea area = mail.getFilearea(); File f = new File(mail.getFilepath()); if (!f.canRead()) { logger.l3("File unavalible"); continue; } Set<FtnAddress> seenby = new HashSet<FtnAddress>( read4D(mail.getSeenby())); if (seenby.contains(link_address)) { logger.l3("This file have a seen-by for link"); continue; } FtnTIC tic = new FtnTIC(); try { CRC32 crc32 = new CRC32(); FileInputStream fis = new FileInputStream(f); int len; do { byte buf[]; len = fis.available(); if (len > 1024) { buf = new byte[1024]; } else { buf = new byte[len]; } fis.read(buf); crc32.update(buf); } while (len > 0); tic.setCrc32(crc32.getValue()); fis.close(); } catch (IOException e) { logger.l2("fail process tic", e); } tic.setArea(area.getName().toUpperCase()); tic.setAreaDesc(area.getDescription()); tic.setFile(mail.getFilename()); tic.setSize(f.length()); tic.setDesc(mail.getFiledesc()); tic.setPassword(link.getPaketPassword()); tic.setFrom(getPrimaryFtnAddress()); tic.setTo(link_address); tic.setOrigin(new FtnAddress(mail.getOrigin())); for (FtnAddress address : MainHandler.getCurrentInstance() .getInfo().getAddressList()) { seenby.add(address); } for (FileSubscription sub : ORMManager.INSTANSE .getFileSubscriptionDAO().getAnd("filearea_id", "=", area)) { try { Link l = ORMManager.INSTANSE.getLinkDAO().getById( sub.getLink().getId()); seenby.add(new FtnAddress(l.getLinkAddress())); } catch (NullPointerException e) { logger.l1("bad link for FileSubscription " + sub + " - ignored", e); } } List<FtnAddress> sb = new ArrayList<FtnAddress>(seenby); Collections.sort(sb, new Ftn4DComparator()); tic.setSeenby(sb); tic.setPath(mail.getPath() + "Path " + getPrimaryFtnAddress() + " " + System.currentTimeMillis() / 1000 + " " + FORMAT.format(new Date()) + " " + MainHandler.getVersion() + "\r\n"); tic.setRealpath(mail.getFilepath()); tics.add(tic); } if (!toRemove.isEmpty()) { ORMManager.INSTANSE.getFilemailAwaitingDAO().delete("link_id", "=", link, "filemail_id", "in", toRemove); } } // files for link { List<FileForLink> ffls = ORMManager.INSTANSE.getFileForLinkDAO() .getAnd("link_id", "eq", link); for (FileForLink ffl : ffls) { try { File file = new File(ffl.getFilename()); Message m = new Message(file); ORMManager.INSTANSE.getFileForLinkDAO().delete("link_id", "=", link, "filename", "=", ffl.getFilename()); ret.add(m); } catch (Exception ex) { logger.l1(MessageFormat.format( "Exception during get file {0} for link {1}", ffl, link), ex); } } } if (!messages.isEmpty()) { pack(messages, link); } // scan inbound synchronized (FtnTosser.class) { File inbound = new File(getInbound()); for (File file : inbound.listFiles()) { String loname = file.getName().toLowerCase(); if (loname.matches("^out_" + link.getId() + "\\..*$")) { boolean packed = true; try { new ZipFile(file).close(); } catch (Exception e) { packed = false; } try { Message m = new Message(file); if (packed) { m.setMessageName(generateEchoBundle()); } else { m.setMessageName(generate8d() + ".pkt"); } ret.add(m); } catch (Exception e) { // ignore } } } } for (FtnTIC tic : tics) { try { byte[] data = tic.pack(); Message message = new Message(generateTic(), data.length); message.setInputStream(new ByteArrayInputStream(data)); ret.add(message); message = new Message(tic.getFile(), tic.getSize()); message.setInputStream(new FileInputStream(tic.getRealpath())); ret.add(message); logger.l4("Packed tic " + message.getMessageName() + " for file " + tic.getFile()); } catch (Exception e) { logger.l3("Tic attach failed"); } } for (File f : attachedFiles) { try { ret.add(new Message(f)); f.delete(); } catch (Exception e) { logger.l3("File attach filed " + f.getAbsolutePath()); } } return ret; } }
package SimpleWithButtons; import Gui2D.WizardOfTreldan; import TWoT_A1.*; import static TWoT_A1.EquippableItem.EItem.*; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Stream; import javafx.application.Application; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.ProgressBar; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.effect.DropShadow; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Text; import javafx.stage.Stage; import static javafx.application.Application.launch; import javafx.scene.image.Image; import static javafx.application.Application.launch; /** * * @author Mathias */ public class GUIFX extends Application { private static TWoT twot; private TextArea textArea; private TextArea statsArea; private ProgressBar healthbar; private String help; private TextField nameArea; private VBox statsField = new VBox(20); private Label label1; private Group walkButtons = new Group(); private int pos = 120; private Label endScore; private Stage primaryStage; private Scene endMenu; private TableView<InventoryItems> invTable = new TableView(); private final ObservableList<InventoryItems> invData = FXCollections.observableArrayList(); private TableView<EquippedItems> equipTable = new TableView(); private final ObservableList<EquippedItems> equipData = FXCollections.observableArrayList(); private String printHelp() { HashMap<String, String> printHelpMSG = twot.getHelpMessages(); return printHelpMSG.get("helpMessage1") + printHelpMSG.get("helpMessage2") + printHelpMSG.get("helpMessage3"); } public GUIFX () { twot = new TWoT(); } public static void main(String[] args) { launch(args); } @Override public void start (Stage primaryStage) { primaryStage.getIcons().add(new Image("icon.png")); this.primaryStage = primaryStage; this.primaryStage.setTitle("The Wizard of Treldan"); textArea = new TextArea(); statsArea = new TextArea(); /** * Name scene visuals */ Label setName = new Label("ENTER YOUR NAME: "); nameArea = new TextField(); /** * Main menu buttons */ Button button_play = new Button("NEW GAME"); Button button_load = new Button("LOAD GAME"); Button button_how = new Button("HOW TO PLAY"); Button button_highscore = new Button("HIGHSCORES"); Button button_exitMenu = new Button("EXIT GAME"); button_play.setMinWidth(180); button_load.setMinWidth(180); button_how.setMinWidth(180); button_exitMenu.setMinWidth(180); button_highscore.setMinWidth(180); button_play.setMinHeight(30); button_load.setMinHeight(30); button_how.setMinHeight(30); button_exitMenu.setMinHeight(30); button_highscore.setMinHeight(30); /** * Loadscreen buttons and list of loads */ Button button_loadGame = new Button("Load Game"); Button button_exitToMenu = new Button("Exit To Menu"); button_loadGame.setMinWidth(180); button_exitToMenu.setMinWidth(180); button_loadGame.setMinHeight(40); button_exitToMenu.setMinHeight(40); Pane anchorpane = new Pane(); ListView<AnchorPane> list = new ListView(); ObservableList<AnchorPane> loads = FXCollections.observableArrayList (); List<String> loadList = getLoadList(); for(String i: loadList){ //add a new anchorpane with a Text component to the ObservableList AnchorPane t = new AnchorPane(); Text itemName = new Text(i); itemName.relocate(0, 3); t.getChildren().add(itemName); loads.add(t); } //add the ObservableList to the ListView list.setItems(loads); //add the ListView to the pane. list.setPrefWidth(250); list.setPrefHeight(288); anchorpane.getChildren().add(list); /** * scene1 buttons */ Button button_clear = new Button("Clear"); Button button_help = new Button("Help"); Button button_exit = new Button("Exit"); Button button_save = new Button("Save"); Button button_use = new Button("Use Item"); Button button_equip = new Button("Equip Item"); button_help.setMaxWidth(90); button_exit.setMaxWidth(90); button_clear.setMaxWidth(90); button_use.setMaxWidth(90); button_equip.setMaxWidth(90); button_save.setMaxWidth(90); healthbar = new ProgressBar(twot.getPlayerHealth()/100); label1 = new Label("Health "+ twot.getPlayerHealth()); /** * End menu */ Button button_endGameExitGame = new Button("Exit Game"); endScore = new Label(); button_endGameExitGame.setMinWidth(180); button_endGameExitGame.setMinHeight(40); endScore.setLayoutX(110); endScore.setLayoutY(80); button_endGameExitGame.setLayoutX(170); button_endGameExitGame.setLayoutY(150); /** * Inventory list */ invTable.setEditable(true); List<Item> l = twot.getInventoryItems(); for(Item i: l){ if(i instanceof UseableItem){ invData.add(new InventoryItems(i.getItemName(), "Usable Item", i.getItemDescription())); } else if (i instanceof QuestItem) { invData.add(new InventoryItems(i.getItemName(), "Quest Item", i.getItemDescription())); } else if(i instanceof EquippableItem) { invData.add(new InventoryItems(i.getItemName(), "Equippable Item", i.getItemDescription())); } } TableColumn itemName = new TableColumn("Item Name"); itemName.setMinWidth(100); itemName.setCellValueFactory( new PropertyValueFactory<InventoryItems, String>("itemName")); TableColumn itemType = new TableColumn("Item Type"); itemType.setMinWidth(100); itemType.setCellValueFactory( new PropertyValueFactory<InventoryItems, String>("itemType")); TableColumn itemDescription = new TableColumn("Description"); itemDescription.setMinWidth(200); itemDescription.setCellValueFactory( new PropertyValueFactory<InventoryItems, String>("itemDesc")); /** * Nodes */ /** * Layouts for game scene */ HBox invButtons = new HBox(20); invButtons.setLayoutX(770 + pos); invButtons.setLayoutY(420); invButtons.getChildren().addAll(button_use, button_equip); VBox loadMenuButtons = new VBox(20); loadMenuButtons.setLayoutX(295); loadMenuButtons.setLayoutY(70); loadMenuButtons.getChildren().addAll(button_loadGame, button_exitToMenu); VBox gameButtons = new VBox(20); gameButtons.setLayoutX(591 + pos); gameButtons.setLayoutY(10); gameButtons.getChildren().addAll(button_clear, button_help, button_save, button_exit); VBox menuButtons = new VBox(20); menuButtons.setLayoutX(166); menuButtons.setLayoutY(30); menuButtons.getChildren().addAll(button_play, button_load, button_how, button_highscore, button_exitMenu); invTable.setItems(invData); invTable.getColumns().addAll(itemName, itemType, itemDescription); invTable.setLayoutX(652 + pos); healthbar.setStyle("-fx-accent: red;"); healthbar.setPrefSize(256, 26); healthbar.relocate(0 + pos, 265); label1.setTextFill(Color.web("BLACK")); label1.relocate(10 + pos, 269); /** * Buttons for the main menu */ /** * Label * Name area field * Added to VBox */ VBox nameField = new VBox(); nameField.setMaxWidth(300); nameField.setMinWidth(300); nameField.setMaxHeight(50); nameField.setMinHeight(50); nameField.relocate(106, 119); nameField.getChildren().addAll(setName, nameArea); /** * Textarea for the playing scene */ VBox outputField = new VBox(20); textArea.setMaxWidth(572); outputField.setLayoutX(pos); textArea.setMinWidth(572); textArea.setMinHeight(258); textArea.setMaxHeight(258); textArea.setWrapText(true); textArea.setEditable(false); outputField.getChildren().addAll(textArea); /** * Equipped items list */ equipTable.setEditable(false); HashMap<EquippableItem.EItem, EquippableItem> k = twot.getEquippableItems(); for(Map.Entry<EquippableItem.EItem, EquippableItem> entry : k.entrySet()){ if(entry.getKey() == AMULET_SLOT) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Amulet Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (HEAD_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Head slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (WEAPON_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Weapon Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (CHEST_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Chest Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (LEG_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Leg Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (BOOT_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Boot Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (GLOVES_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Glove Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (RING_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Ring Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); } } TableColumn itemNames = new TableColumn("Item Name"); itemNames.setMinWidth(100); itemNames.setCellValueFactory( new PropertyValueFactory<EquippedItems, String>("itemNames")); TableColumn itemSlot = new TableColumn("Item Slot"); itemSlot.setMinWidth(90); itemSlot.setCellValueFactory( new PropertyValueFactory<EquippedItems, String>("itemSlots")); TableColumn itemAttack = new TableColumn("Attack"); itemAttack.setMaxWidth(90); itemAttack.setMinWidth(90); itemAttack.setCellValueFactory( new PropertyValueFactory<EquippedItems, String>("itemAttack")); TableColumn itemDefence = new TableColumn("Defence"); itemDefence.setMaxWidth(90); itemDefence.setMinWidth(90); itemDefence.setCellValueFactory( new PropertyValueFactory<EquippedItems, String>("itemDefence")); equipTable.setItems(equipData); equipTable.getColumns().addAll(itemNames, itemSlot, itemAttack, itemDefence); equipTable.setLayoutX(264 + pos); equipTable.setLayoutY(265); equipTable.setMinWidth(370); equipTable.setMaxWidth(370); equipTable.setMinHeight(235); equipTable.setMaxHeight(235); /** * Statsarea on the playing scene */ NumberFormat df = new DecimalFormat(" statsArea.appendText("****************************\n"); statsArea.appendText("** Player name: " + twot.getPlayerName() + "\n"); statsArea.appendText("** Attack value: " + df.format(twot.getPlayerAtt()) + "\n"); statsArea.appendText("** Defense value: " + df.format(twot.getPlayerDeff()) + "\n"); statsArea.appendText("** Gold: " + twot.getPlayerGold() + "\n"); statsArea.appendText("****************************"); statsField.setMaxWidth(256); statsField.setMaxHeight(110); statsField.relocate(0 + pos, 300); statsField.getChildren().addAll(statsArea); /** * adding buttons to panes */ healthbar = new ProgressBar(twot.getPlayerHealth()/100); healthbar.setStyle("-fx-accent: red;"); healthbar.setPrefSize(256, 26); healthbar.relocate(0 + pos, 265); label1 = new Label("Health "+ twot.getPlayerHealth()); label1.setTextFill(Color.web("BLACK")); label1.relocate(10 + pos, 269); Label setNamePls = new Label("ENTER YOUR NAME: "); //Highscore screen Button button_cancel = new Button("EXIT TO MENU"); ListView<AnchorPane> hList = new ListView(); button_cancel.relocate(0, 220); hList.relocate(0, 0); hList.setPrefWidth(300); hList.setPrefHeight(210); //adding observableList with type AnchorPane ObservableList<AnchorPane> hloads = FXCollections.observableArrayList(); //Getting an arraylist of load files, List<String> loadHList = getHighscoreList(); //Go through each String in the list for (String i : loadHList) { //add a new anchorpane with a Text component to the ObservableList AnchorPane t = new AnchorPane(); Text hItemName = new Text(i); hItemName.relocate(0, 3); t.getChildren().add(hItemName); hloads.add(t); } //add the ObservableList to the ListView hList.setItems(hloads); Pane root = new Pane(equipTable, invButtons, gameButtons, outputField, healthbar, invTable, label1, statsField, walkButtons); Pane root2 = new Pane(menuButtons); Pane root3 = new Pane(nameField); Pane root4 = new Pane(loadMenuButtons, anchorpane); Pane root5 = new Pane(endScore, button_endGameExitGame); Pane root6 = new Pane(hList, button_cancel); Scene game = new Scene(root, 1052 + pos, 512); Scene menu = new Scene(root2, 512, 288); Scene nameScene = new Scene(root3, 512, 288); Scene loadMenu = new Scene(root4, 512, 288); endMenu = new Scene(root5, 512, 288); Scene highscoreMenu = new Scene(root6, 512, 288); /** * Actions events */ DropShadow shade = new DropShadow(); root.addEventHandler(MouseEvent.MOUSE_ENTERED, (MouseEvent e) -> { root.setEffect(shade); }); root.addEventHandler(MouseEvent.MOUSE_EXITED, (MouseEvent e) -> { root.setEffect(null); }); button_equip.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ if(invTable.getSelectionModel().getSelectedItem() == null){ textArea.appendText("\n\nPlease select an item."); }else{ for(String s: twot.equipItem(new Command(CommandWord.USE, invTable.getSelectionModel().getSelectedItem().getItemName()))){ if(invTable.getSelectionModel().getSelectedItem().getItemType() == "Equippable Item"){ textArea.appendText("\n" + s); updateGUI(); } else { textArea.appendText("\nThis item cannot be equipped."); } } } }); /** * makes an instance of TWoT and equals it with the load, then sets it */ button_loadGame.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ TWoT loadedGame = getLoad((((Text)list.getSelectionModel().getSelectedItem().getChildren().get(0)).getText())); //set the game to the loaded instance setGame(loadedGame); primaryStage.setScene(game); primaryStage.centerOnScreen(); textArea.clear(); textArea.appendText(loadedGame.getCurrentRoomDescription()); updateGUI(); }); button_load.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ primaryStage.setScene(loadMenu); }); button_save.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ saveGame(); textArea.appendText("\n\nGame has been saved. It can be loaded from the start menu.\n\n"); }); /** * If a useable item is selected and the button is clicked, the action events takes the commandword USE and the item name */ button_use.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ if(invTable.getSelectionModel().getSelectedItem() == null){ textArea.appendText("\n\nPlease select an item."); }else{ for(String s: twot.useItem(new Command(CommandWord.USE, invTable.getSelectionModel().getSelectedItem().getItemName()))){ if(invTable.getSelectionModel().getSelectedItem().getItemType() == "Usable Item"){ textArea.appendText("\n" + s); updateGUI(); } else { textArea.appendText("\nThis item cannot be used."); } } } }); button_play.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ primaryStage.setScene(nameScene); }); button_cancel.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ primaryStage.setScene(menu); }); button_highscore.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ primaryStage.setScene(highscoreMenu); }); button_help.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ help=printHelp(); textArea.appendText(help); }); button_clear.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ textArea.clear(); }); /** * Takes the text in the inputfield and uses the setPlayerName() method in the twot class */ nameField.setOnKeyPressed(new EventHandler<KeyEvent>(){ @Override public void handle(KeyEvent k){ if(k.getCode().equals(KeyCode.ENTER)){ twot.setPlayerName(nameArea.getText()); primaryStage.setScene(game); primaryStage.centerOnScreen(); updateGUI(); } } }); /** * Calls on the other class 'PopUps' with the parameters given below */ button_how.setOnAction(new EventHandler<ActionEvent>(){ @Override public void handle(ActionEvent e){ PopUps.display("HOW TO PLAY", "Move around with the 'go [interactable object]' " + "command. \nYou automatically pick up items if the " + "interior have any available.\n" + "You lose score points when you die but you are free to continue the game as if nothing happened."); } }); button_exitToMenu.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ primaryStage.setScene(menu); }); /** * closes the platform */ button_exit.setOnAction(actionEvent -> Platform.exit()); button_exitMenu.setOnAction(actionEvent -> Platform.exit()); button_endGameExitGame.setOnAction(actionEvent -> Platform.exit()); /** * sets and shows the primarystage */ primaryStage.setScene(menu); primaryStage.centerOnScreen(); primaryStage.show(); String welcome = ""; for(HashMap.Entry<Integer, String> entry : twot.getWelcomeMessages().entrySet()){ welcome = welcome + entry.getValue(); } textArea.appendText(welcome); } public List<String> getHighscoreList() { //create empty arraylist. List<String> loadList = new ArrayList(); //try to get each file in the directory "loads" by using Files.walk List<Score> highscores = twot.readHighScore(); for(Score s : highscores){ loadList.add("Name: " + s.getName() + " | Score: " + s.getScore() + " | Time: " + s.getTime()); } //return the List return loadList; } /** * Method that runs methods to update the GUI, hardcoded to update everyting actionevents are called */ public void updateGUI(){ updatePlayer(); updateHealth(); updateInventory(); updateEquipInventory(); updateButtons(); } /** * Method that fetches player stats */ public void updatePlayer(){ statsArea.clear(); NumberFormat df = new DecimalFormat(" statsArea.appendText("****************************\n"); statsArea.appendText("** Player name: " + twot.getPlayerName() + "\n"); statsArea.appendText("** Attack value: " + df.format(twot.getPlayerAtt()) + "\n"); statsArea.appendText("** Defense value: " + df.format(twot.getPlayerDeff()) + "\n"); statsArea.appendText("** Gold: " + twot.getPlayerGold() + "\n"); statsArea.appendText("****************************"); } /** * updates health on the healthbar */ public void updateHealth(){ label1.setText("Health "+ twot.getPlayerHealth()); healthbar.setProgress(twot.getPlayerHealth()/100); if(twot.getPlayerHealth() <= 100 && twot.getPlayerHealth() > 66){ healthbar.setStyle("-fx-accent: green;"); } else if (twot.getPlayerHealth() <= 66 && twot.getPlayerHealth() > 33){ healthbar.setStyle("-fx-accent: yellow;"); } else if (twot.getPlayerHealth() <= 33 && twot.getPlayerHealth() > 0){ healthbar.setStyle("-fx-accent: red;"); } } /** * Removes all instances of items in the list, and adds the ones in the inventory */ public void updateInventory(){ List<Item> l = twot.getInventoryItems(); invData.removeAll(invData); for(Item i: l){ if(i instanceof UseableItem){ invData.add(new InventoryItems(i.getItemName(), "Usable Item", i.getItemDescription())); } else if (i instanceof QuestItem) { invData.add(new InventoryItems(i.getItemName(), "Quest Item", i.getItemDescription())); } else if(i instanceof EquippableItem) { invData.add(new InventoryItems(i.getItemName(), "Equippable Item", i.getItemDescription())); } } } /** * Removes all instances of items in the list, and adds the equippableItems from the inventory */ public void updateEquipInventory(){ HashMap<EquippableItem.EItem, EquippableItem> k = twot.getEquippableItems(); equipData.removeAll(equipData); for(Map.Entry<EquippableItem.EItem, EquippableItem> entry : k.entrySet()){ if(entry.getKey() == AMULET_SLOT) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Amulet Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (HEAD_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Head slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (WEAPON_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Weapon Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (CHEST_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Chest Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (LEG_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Leg Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (BOOT_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Boot Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (GLOVES_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Glove Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (RING_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Ring Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); } } } /** * Runs the switch to check the current room and adds the buttons defined with the methods bellow */ public void updateButtons() { switch (twot.getCurrentRoomId()) { case 1: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(cellarButtons()); break; case 2: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(villageButtons()); break; case 3: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(house1Buttons()); break; case 4: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(house2Buttons()); break; case 5: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(house3Buttons()); break; case 6: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(forestButtons()); break; case 7: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(wizardHouseButtons()); break; case 8: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(caveButtons()); break; case 9: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(lairButtons()); break; case 10: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(clearingButtons()); break; case 11: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(dungeonButtons()); break; case 12: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(libraryButtons()); break; case 13: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(evilWizardsButtons()); break; default: break; } } //WALK BUTTONS CommandWords commandword = new CommandWords(); private Group cellarButtons() { Button button_haystack = new Button("Haystack"); Button button_table = new Button("Table"); Button button_door = new Button("Door"); button_haystack.setPrefSize(110, 10); button_table.setPrefSize(110, 10); button_door.setPrefSize(110, 10); VBox cellarButtons = new VBox(20); cellarButtons.setLayoutX(5); cellarButtons.setLayoutY(10); cellarButtons.getChildren().addAll(button_door, button_table, button_haystack); walkButtons = new Group(cellarButtons); button_haystack.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "haystack"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_table.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "table"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_door.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "door"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return walkButtons; } private Group villageButtons() { Button button_reborn = new Button("House 1"); Button button_riches = new Button("House 2"); Button button_hOfGuard = new Button("House 3"); Button button_guard = new Button("The Guard"); Button button_axe = new Button("Axe"); Button button_forest = new Button("Forest"); button_reborn.setPrefSize(110, 10); button_riches.setPrefSize(110, 10); button_hOfGuard.setPrefSize(110, 10); button_guard.setPrefSize(110, 10); button_axe.setPrefSize(110, 10); button_forest.setPrefSize(110, 10); button_forest.setDisable(true); VBox villageButtons = new VBox(20); //if guard children not delivered. villageButtons.getChildren().addAll(button_reborn, button_riches, button_hOfGuard, button_guard, button_axe, button_forest); if(twot.checkExisting("forest")){ button_forest.setDisable(false); } if(!twot.checkExisting("axe")){ button_axe.setDisable(true); } walkButtons = new Group(villageButtons); button_reborn.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "house1"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_riches.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "house2"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_hOfGuard.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "house3"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_guard.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "guard"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_axe.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "axe"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_forest.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "forest"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return walkButtons; } private Group house1Buttons() { Button button_man = new Button("Man"); Button button_chest = new Button("Chest"); Button button_door = new Button("Door"); Button button_stranger = new Button("Stranger"); button_man.setPrefSize(110, 10); button_chest.setPrefSize(110, 10); button_door.setPrefSize(110, 10); button_stranger.setPrefSize(110, 10); VBox house1Buttons = new VBox(20); house1Buttons.getChildren().addAll(button_door, button_chest, button_man); Group root = new Group(house1Buttons); if(!twot.checkExisting("man")){ button_man.setDisable(true); } if(twot.checkExisting("stranger")){ house1Buttons.getChildren().add(button_stranger); } button_man.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "man"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_chest.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "chest"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_door.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "door"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_stranger.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "stranger"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return root; } private Group house2Buttons() { Button button_door = new Button("Door"); Button button_wardrobe = new Button("Wardrobe"); Button button_bed = new Button("Bed"); Button button_table = new Button("Table"); Button button_stranger = new Button("Stranger"); button_door.setPrefSize(110, 10); button_wardrobe.setPrefSize(110, 10); button_bed.setPrefSize(110, 10); button_table.setPrefSize(110, 10); button_stranger.setPrefSize(110, 10); VBox house2Buttons = new VBox(20); house2Buttons.getChildren().addAll(button_door, button_wardrobe, button_bed, button_table); Group root = new Group(house2Buttons); if(twot.checkExisting("stranger")){ house2Buttons.getChildren().add(button_stranger); } button_door.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "door"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_wardrobe.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "wardrobe"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_bed.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "bed"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_table.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "table"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_stranger.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "stranger"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return root; } private Group house3Buttons() { Button button_door = new Button("Door"); Button button_kitchen = new Button("Kitchen"); Button button_woman = new Button("Woman"); Button button_chest = new Button("Chest"); Button button_stranger = new Button("Stranger"); button_door.setPrefSize(110, 10); button_kitchen.setPrefSize(110, 10); button_woman.setPrefSize(110, 10); button_chest.setPrefSize(110, 10); button_stranger.setPrefSize(110, 10); VBox house3Buttons = new VBox(20); house3Buttons.getChildren().addAll(button_door, button_kitchen, button_woman, button_chest); Group root = new Group(house3Buttons); if(twot.checkExisting("stranger")){ house3Buttons.getChildren().add(button_stranger); } if(!twot.checkExisting("woman")){ button_woman.setDisable(true); } button_stranger.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "stranger"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_door.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "door"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_kitchen.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "kitchen"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_woman.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "woman"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_chest.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "chest"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return root; } private Group forestButtons() { Button button_mushroom = new Button("Mushroom"); Button button_goblin = new Button("Dead goblin"); Button button_house = new Button("Wiz House"); Button button_cave = new Button("Cave"); Button button_clearing = new Button("Clearing"); Button button_village = new Button("Village"); button_mushroom.setPrefSize(110, 10); button_goblin.setPrefSize(110, 10); button_house.setPrefSize(110, 10); button_cave.setPrefSize(110, 10); button_clearing.setPrefSize(110, 10); button_village.setPrefSize(110, 10); VBox forestButtons = new VBox(20); forestButtons.getChildren().addAll(button_village, button_goblin, button_house, button_mushroom, button_cave, button_clearing); Group root = new Group(forestButtons); button_mushroom.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "mushroom"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_goblin.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "goblin"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_house.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "house"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_cave.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "cave"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_clearing.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "clearing"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_village.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "village"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return root; } private Group wizardHouseButtons() { Button button_upstairs = new Button("Sacks"); Button button_box = new Button("Box"); Button button_lab = new Button("Alchemy Lab"); Button button_wizard = new Button("Wizard"); Button button_door = new Button("Door"); button_upstairs.setPrefSize(110, 10); button_box.setPrefSize(110, 10); button_lab.setPrefSize(110, 10); button_wizard.setPrefSize(110, 10); button_door.setPrefSize(110, 10); VBox wizardHouseButtons = new VBox(20); wizardHouseButtons.getChildren().addAll(button_door, button_box, button_lab, button_wizard, button_upstairs); Group root = new Group(wizardHouseButtons); button_upstairs.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "upstairs"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_box.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "box"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_lab.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "lab"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_wizard.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "wizard"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_door.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "door"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return root; } private Group caveButtons() { Button button_troll1 = new Button("Troll"); Button button_troll2 = new Button("Troll"); Button button_troll3 = new Button("Troll"); Button button_forest = new Button("Forest"); Button button_lair = new Button("Lair"); button_troll1.setPrefSize(110, 10); button_troll2.setPrefSize(110, 10); button_troll3.setPrefSize(110, 10); button_forest.setPrefSize(110, 10); button_lair.setPrefSize(110, 10); VBox caveButtons = new VBox(20); caveButtons.getChildren().addAll(button_forest, button_troll1, button_troll2, button_troll3, button_lair); Group root = new Group(caveButtons); if(!twot.checkExisting("troll1")){ button_troll1.setDisable(true); } if(!twot.checkExisting("troll2")){ button_troll2.setDisable(true); } if(!twot.checkExisting("troll3")){ button_troll3.setDisable(true); } button_troll1.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "troll1"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_troll2.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "troll2"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_troll3.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "troll3"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_forest.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "forest"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_lair.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "lair"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return root; } private Group lairButtons() { Button button_gruul = new Button("Gruul"); Button button_cave = new Button("Cave"); button_gruul.setPrefSize(110, 10); button_cave.setPrefSize(110, 10); VBox lairButtons = new VBox(20); lairButtons.getChildren().addAll(button_cave, button_gruul); Group root = new Group(lairButtons); if(!twot.checkExisting("gruul")){ button_gruul.setDisable(true); } button_gruul.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "gruul"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_cave.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "cave"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return root; } private Group clearingButtons() { Button button_forest = new Button("Forest"); Button button_unicorn = new Button("Unicorn"); Button button_tree = new Button("Tree"); button_forest.setPrefSize(110, 10); button_unicorn.setPrefSize(110, 10); button_tree.setPrefSize(110, 10); VBox clearingButtons = new VBox(20); clearingButtons.getChildren().addAll(button_forest, button_unicorn, button_tree); Group root = new Group(clearingButtons); if(!twot.checkExisting("unicorn")){ button_unicorn.setDisable(true); } button_forest.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "forest"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_unicorn.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "unicorn"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_tree.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "tree"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return root; } private Group dungeonButtons() { Button button_skeleton1 = new Button("Skeleton"); Button button_skeleton2 = new Button("Skeleton"); Button button_skeleton3 = new Button("Skeleton"); Button button_pathway = new Button("Pathway"); button_skeleton1.setPrefSize(110, 10); button_skeleton2.setPrefSize(110, 10); button_skeleton3.setPrefSize(110, 10); button_pathway.setPrefSize(110, 10); VBox dungeonButtons = new VBox(20); dungeonButtons.getChildren().addAll(button_pathway, button_skeleton1, button_skeleton2, button_skeleton3); Group root = new Group(dungeonButtons); if(!twot.checkExisting("skeleton1")){ button_skeleton1.setDisable(true); } if(!twot.checkExisting("skeleton2")){ button_skeleton2.setDisable(true); } if(!twot.checkExisting("skeleton3")){ button_skeleton3.setDisable(true); } button_skeleton1.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "skeleton1"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_skeleton2.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "skeleton2"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_skeleton3.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "skeleton3"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_pathway.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "pathway"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return root; } private Group libraryButtons() { Button button_librarian = new Button("Librarian"); Button button_door = new Button("Door"); Button button_chest = new Button("Chest"); button_librarian.setPrefSize(110, 10); button_door.setPrefSize(110, 10); button_chest.setPrefSize(110, 10); VBox libraryButtons = new VBox(20); libraryButtons.getChildren().addAll(button_door, button_librarian, button_chest); Group root = new Group(libraryButtons); if(!twot.checkExisting("librarian")){ button_librarian.setDisable(true); } button_librarian.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "librarian"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_door.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "door"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_chest.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "chest"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return root; } private Group evilWizardsButtons() { Button button_evilWizard = new Button("Evil Wizard"); Button button_minion1 = new Button("Minion1"); Button button_minion2 = new Button("Minion2"); button_evilWizard.setPrefSize(110, 10); button_minion1.setPrefSize(110, 10); button_minion2.setPrefSize(110, 10); VBox evilWizardsButtons = new VBox(20); evilWizardsButtons.getChildren().addAll(button_evilWizard, button_minion1, button_minion2); Group root = new Group(evilWizardsButtons); if(!twot.checkExisting("minion2")){ button_minion2.setDisable(true); } if(!twot.checkExisting("minion1")){ button_minion1.setDisable(true); } button_evilWizard.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "wizard"); if(!twot.checkExisting("minion1") && !twot.checkExisting("minion2")){ for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } }else{ textArea.appendText("\n\nFoolish mortal! You have to defeat my minions before you prove yourself worthy to fight me."); } if(twot.endGame() == true){ endScore.setText("Congratulations! You have beaten The Wizard of Treldan!\n" + " Your final score is: " + twot.getHighscore() + "\n It took you " + ((long)(System.currentTimeMillis() / 1000L) - twot.getStartTime()) + " seconds to finish the game."); twot.writeHighScore(); primaryStage.setScene(endMenu); } updateGUI(); }); button_minion1.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "minion1"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_minion2.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "minion2"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return root; } /** * Opens a FileOutputStream and an oObjectOutputStream and saves the game in a .data file with the date * and currentRoom as the name, and saves it in the projectfolder under a folder called "loads" */ public void saveGame(){ SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss"); Date date = new Date(); String strDate = sdf.format(date); try { FileOutputStream fos = new FileOutputStream("loads/" + twot.getCurrentRoomName() + "-" + strDate + ".data"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(twot); oos.close(); } catch(FileNotFoundException e){ e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } } /** * checks the folder "loads" for files, and adds them to a list<String> and then returns it * @return */ public List<String> getLoadList(){ //create empty arraylist. List<String> loadList = new ArrayList(); //try to get each file in the directory "loads" by using Files.walk try{ //Go through each Path in the Stream. Stream<Path> paths = Files.walk(Paths.get("loads/")); paths.forEach(filePath -> { //if the file is a FILE continue if (Files.isRegularFile(filePath)) { //add the filename with extenstion to the List. loadList.add(filePath.getFileName().toString()); } }); } catch (IOException ex) { System.out.println("FAIL"); } //return the List return loadList; } /** * uses the filename and checks if the file exists, then it takes TWoT and equals the inputStream to that. * @param filename * @return */ public TWoT getLoad(String filename){ //Try loading the file. try { //Read from the stored file in folder "loads" FileInputStream fileInputStream = new FileInputStream(new File("loads/" + filename)); //Create a ObjectInputStream object from the FileInputStream ObjectInputStream input = new ObjectInputStream(fileInputStream); //load the TWoT file into object TWoT twot = (TWoT) input.readObject(); //close the objects input.close(); fileInputStream.close(); //returns the gamefile return twot; } catch (FileNotFoundException e) { System.out.println("File not found"); } catch (IOException e) { System.out.println("Wrong version of game"); } catch (ClassNotFoundException e) { System.out.println("Game was not found."); } return null; } /** * method that sets twot to the loaded game * @param loaded */ public void setGame(TWoT loaded){ twot = loaded; } }
package org.ocelotds.processors; import org.ocelotds.annotations.JsCacheResult; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.ElementFilter; import javax.tools.Diagnostic; import org.ocelotds.KeyMaker; /** * Visitor of class annoted org.ocelotds.annotations.DataService<br> * Generate javascript classes * * @author hhfrancois */ public class DataServiceVisitorJsBuilder extends AbstractDataServiceVisitor { protected final Messager messager; protected final KeyMaker keyMaker; /** * * @param environment */ public DataServiceVisitorJsBuilder(ProcessingEnvironment environment) { super(environment); this.messager = environment.getMessager(); this.keyMaker = new KeyMaker(); } @Override public String visitType(TypeElement typeElement, Writer writer) { try { createClassComment(typeElement, writer); String jsclsname = getJsClassname(typeElement); writer.append("function ").append(jsclsname).append("() {\n"); String classname = typeElement.getQualifiedName().toString(); writer.append("\tthis.ds = \"").append(classname).append("\";\n"); writer.append("}\n"); writer.append(jsclsname).append(".prototype = {\n"); List<ExecutableElement> methodElements = ElementFilter.methodsIn(typeElement.getEnclosedElements()); Iterator<ExecutableElement> iterator = methodElements.iterator(); Collection<String> methodProceeds = new ArrayList<>(); boolean first = true; while (iterator.hasNext()) { ExecutableElement methodElement = iterator.next(); if (isConsiderateMethod(methodProceeds, methodElement)) { visitMethodElement(first, methodProceeds, classname, jsclsname, methodElement, writer); first = false; } } writer.append("\n};\n"); writer.append("console.info('create OcelotDataService<"+jsclsname.substring(0, 1).toLowerCase()+jsclsname.substring(1)+":"+jsclsname+">');\n"); writer.append("var "+jsclsname.substring(0, 1).toLowerCase()+jsclsname.substring(1)+" = new "+jsclsname+"();\n"); } catch (IOException ex) { } return null; } /** * * @param first * @param methodProceeds * @param classname * @param jsclsname * @param methodElement * @param writer * @throws IOException */ void visitMethodElement(boolean first, Collection<String> methodProceeds, String classname, String jsclsname, ExecutableElement methodElement, Writer writer) throws IOException { if (!first) { // previous method exist writer.append(",\n"); } String methodName = methodElement.getSimpleName().toString(); List<String> argumentsType = getArgumentsType(methodElement); List<String> arguments = getArguments(methodElement); TypeMirror returnType = methodElement.getReturnType(); createMethodComment(methodElement, arguments, argumentsType, returnType, writer); writer.append("\t").append(methodName).append(" : function ("); if (arguments.size() != argumentsType.size()) { messager.printMessage(Diagnostic.Kind.ERROR, (new StringBuilder()) .append("Cannot Create service : ").append(jsclsname).append(" cause method ") .append(methodName).append(" arguments inconsistent - argNames : ") .append(arguments.size()).append(" / args : ").append(argumentsType.size()).toString()); return; } int i = 0; while (i < argumentsType.size()) { writer.append((String) arguments.get(i)); if ((++i) < arguments.size()) { writer.append(", "); } } writer.append(") {\n"); createMethodBody(classname, methodElement, arguments.iterator(), writer); writer.append("\t}"); } /** * Create comment of the class * * @param typeElement * @param writer * @throws IOException */ void createClassComment(TypeElement typeElement, Writer writer) throws IOException { String comment = environment.getElementUtils().getDocComment(typeElement); if (comment == null) { List<? extends TypeMirror> interfaces = typeElement.getInterfaces(); for (TypeMirror typeMirror : interfaces) { TypeElement element = (TypeElement) environment.getTypeUtils().asElement(typeMirror); comment = environment.getElementUtils().getDocComment(element); if (comment != null) { /** * Create javascript comment from Method comment * * @param methodElement * @param argumentsName * @param argumentsType * @param returnType * @param writer * @throws IOException */ void createMethodComment(ExecutableElement methodElement, List<String> argumentsName, List<String> argumentsType, TypeMirror returnType, Writer writer) throws IOException { String methodComment = environment.getElementUtils().getDocComment(methodElement); writer.append("\t/**\n"); // The javadoc comment if (methodComment != null) { methodComment = methodComment.split("@")[0]; int lastIndexOf = methodComment.lastIndexOf('\n'); if (lastIndexOf >= 0) { methodComment = methodComment.substring(0, lastIndexOf); // include the \n } writer.append("\t *").append(computeComment(methodComment, "\t ")).append("\n"); } // La liste des arguments de la javadoc Iterator<String> typeIterator = argumentsType.iterator(); for (String argumentName : argumentsName) { String type = typeIterator.next(); writer.append("\t * @param {").append(type).append("} ").append(argumentName).append("\n"); } // Si la methode retourne ou non quelque chose if (!returnType.toString().equals("void")) { writer.append("\t * @return {").append(returnType.toString()).append("}\n"); } writer.append("\t */\n"); } /** * Create javascript method body * * @param classname * @param methodElement * @param arguments * @param writer * @throws IOException */ void createMethodBody(String classname, ExecutableElement methodElement, Iterator<String> arguments, Writer writer) throws IOException { String methodName = methodElement.getSimpleName().toString(); writer.append("\t\tvar op = \"").append(methodName).append("\";\n"); StringBuilder args = new StringBuilder(""); StringBuilder paramNames = new StringBuilder(""); StringBuilder keys = new StringBuilder(""); if (arguments != null && arguments.hasNext()) { JsCacheResult jcr = methodElement.getAnnotation(JsCacheResult.class); boolean allArgs = true; // if there is a jcr annotation with value diferrent of *, so we dont use all arguments if (null != jcr && null != jcr.keys() && (jcr.keys().length == 0 || (jcr.keys().length > 0 && !"*".equals(jcr.keys()[0])))) { allArgs = false; for (int i = 0; i < jcr.keys().length; i++) { String arg = jcr.keys()[i]; keys.append(getKeyFromArg(arg)); if (i < jcr.keys().length - 1) { keys.append(","); } } } while (arguments.hasNext()) { String arg = arguments.next(); if (allArgs) { keys.append(arg); } args.append(arg); paramNames.append("\"").append(arg).append("\""); if (arguments.hasNext()) { args.append(","); paramNames.append(","); if (allArgs) { keys.append(","); } } } } String md5 = "\"" + keyMaker.getMd5(classname + "." + methodName); writer.append("\t\tvar id = " + md5 + "_\" + JSON.stringify([").append(keys.toString()).append("]).md5();\n"); writer.append("\t\treturn OcelotPromiseFactory.createPromise(this.ds, id, op, [").append(paramNames.toString()).append("], [").append(args.toString()).append("]").append(");\n"); } String getKeyFromArg(String arg) { String[] objs = arg.split("\\."); StringBuilder result = new StringBuilder(); if(objs.length>1) { StringBuilder obj = new StringBuilder(objs[0]); result.append("(").append(obj); for (int i = 1; i < objs.length-1; i++) { result.append("&&"); obj.append(".").append(objs[i]); result.append(obj); } result.append(")?").append(arg).append(":null"); } else { result.append(arg); } return result.toString(); } }
package org.hisp.dhis.analytics.table; import static org.hisp.dhis.commons.util.TextUtils.removeLast; import static org.hisp.dhis.system.util.MathUtils.NUMERIC_LENIENT_REGEXP; import static org.hisp.dhis.program.ProgramIndicator.DB_SEPARATOR_ID; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; import org.hisp.dhis.analytics.AnalyticsTable; import org.hisp.dhis.analytics.AnalyticsTableColumn; import org.hisp.dhis.common.ValueType; import org.hisp.dhis.commons.collection.UniqueArrayList; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.organisationunit.OrganisationUnitGroupSet; import org.hisp.dhis.organisationunit.OrganisationUnitLevel; import org.hisp.dhis.period.PeriodType; import org.hisp.dhis.program.Program; import org.hisp.dhis.program.ProgramStage; import org.hisp.dhis.program.ProgramStageDataElement; import org.hisp.dhis.trackedentity.TrackedEntityAttribute; import org.springframework.transaction.annotation.Transactional; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; /** * @author Markus Bekken */ public class JdbcEnrollmentAnalyticsTableManager extends AbstractEventJdbcTableManager { private static final Set<ValueType> NO_INDEX_VAL_TYPES = ImmutableSet.of( ValueType.TEXT, ValueType.LONG_TEXT ); @Override public AnalyticsTableType getAnalyticsTableType() { return AnalyticsTableType.ENROLLMENT; } @Override @Transactional public List<AnalyticsTable> getTables( Date earliest ) { return getTables(); } @Override public Set<String> getExistingDatabaseTables() { return null; } private List<AnalyticsTable> getTables() { List<AnalyticsTable> tables = new UniqueArrayList<>(); List<Program> programs = idObjectManager.getAllNoAcl( Program.class ); String baseName = getTableName(); for ( Program program : programs ) { AnalyticsTable table = new AnalyticsTable( baseName, null, null, program ); List<AnalyticsTableColumn> dimensionColumns = getDimensionColumns( table ); table.setDimensionColumns( dimensionColumns ); tables.add( table ); } return tables; } @Override protected void populateTable( AnalyticsTable table ) { final String tableName = table.getTempTableName(); final String piEnrollmentDate = statementBuilder.getCastToDate( "pi.enrollmentdate" ); String sql = "insert into " + table.getTempTableName() + " ("; List<AnalyticsTableColumn> columns = getDimensionColumns( table ); validateDimensionColumns( columns ); for ( AnalyticsTableColumn col : columns ) { sql += col.getName() + ","; } sql = removeLast( sql, 1 ) + ") select "; for ( AnalyticsTableColumn col : columns ) { sql += col.getAlias() + ","; } sql = removeLast( sql, 1 ) + " "; sql += "from programinstance pi " + "inner join program pr on pi.programid=pr.programid " + "left join trackedentityinstance tei on pi.trackedentityinstanceid=tei.trackedentityinstanceid " + "inner join organisationunit ou on pi.organisationunitid=ou.organisationunitid " + "left join _orgunitstructure ous on pi.organisationunitid=ous.organisationunitid " + "left join _organisationunitgroupsetstructure ougs on pi.organisationunitid=ougs.organisationunitid " + "left join _dateperiodstructure dps on " + piEnrollmentDate + "=dps.dateperiod " + "where pr.programid=" + table.getProgram().getId() + " " + "and pi.organisationunitid is not null " + "and pi.incidentdate is not null"; populateAndLog( sql, tableName ); } @Override public List<Integer> getDataYears( Date earliest ) { return null; } @Override protected List<AnalyticsTableColumn> getDimensionColumns( AnalyticsTable table ) { final String dbl = statementBuilder.getDoubleColumnType(); final String numericClause = " and value " + statementBuilder.getRegexpMatch() + " '" + NUMERIC_LENIENT_REGEXP + "'"; final String dateClause = " and value " + statementBuilder.getRegexpMatch() + " '" + DATE_REGEXP + "'"; List<AnalyticsTableColumn> columns = new ArrayList<>(); List<OrganisationUnitLevel> levels = organisationUnitService.getFilledOrganisationUnitLevels(); List<OrganisationUnitGroupSet> orgUnitGroupSets = idObjectManager.getDataDimensionsNoAcl( OrganisationUnitGroupSet.class ); for ( OrganisationUnitLevel level : levels ) { String column = quote( PREFIX_ORGUNITLEVEL + level.getLevel() ); columns.add( new AnalyticsTableColumn( column, "character(11)", "ous." + column, level.getCreated() ) ); } for ( OrganisationUnitGroupSet groupSet : orgUnitGroupSets ) { columns.add( new AnalyticsTableColumn( quote( groupSet.getUid() ), "character(11)", "ougs." + quote( groupSet.getUid() ), groupSet.getCreated() ) ); } for ( PeriodType periodType : PeriodType.getAvailablePeriodTypes() ) { String column = quote( periodType.getName().toLowerCase() ); columns.add( new AnalyticsTableColumn( column, "character varying(15)", "dps." + column ) ); } for ( ProgramStage programStage : table.getProgram().getProgramStages() ) { for( ProgramStageDataElement programStageDataElement : programStage.getProgramStageDataElements() ) { DataElement dataElement = programStageDataElement.getDataElement(); ValueType valueType = dataElement.getValueType(); String dataType = getColumnType( valueType ); String dataClause = dataElement.isNumericType() ? numericClause : dataElement.getValueType().isDate() ? dateClause : ""; String select = getSelectClause( valueType ); boolean skipIndex = NO_INDEX_VAL_TYPES.contains( dataElement.getValueType() ) && !dataElement.hasOptionSet(); String sql = "(select " + select + " from trackedentitydatavalue tedv " + "inner join programstageinstance psi on psi.programstageinstanceid = tedv.programstageinstanceid " + "where psi.executiondate is not null " + "and psi.deleted is false " + "and psi.programinstanceid=pi.programinstanceid " + dataClause + " " + "and tedv.dataelementid=" + dataElement.getId() + " " + "and psi.programstageid=" + programStage.getId() + " " + "order by psi.executiondate desc " + "limit 1) as " + quote( programStage.getUid() + DB_SEPARATOR_ID + dataElement.getUid() ); columns.add( new AnalyticsTableColumn( quote( programStage.getUid() + DB_SEPARATOR_ID + dataElement.getUid() ), dataType, sql, skipIndex ) ); } } for ( TrackedEntityAttribute attribute : table.getProgram().getNonConfidentialTrackedEntityAttributes() ) { String dataType = getColumnType( attribute.getValueType() ); String dataClause = attribute.isNumericType() ? numericClause : attribute.isDateType() ? dateClause : ""; String select = getSelectClause( attribute.getValueType() ); boolean skipIndex = NO_INDEX_VAL_TYPES.contains( attribute.getValueType() ) && !attribute.hasOptionSet(); String sql = "(select " + select + " from trackedentityattributevalue " + "where trackedentityinstanceid=pi.trackedentityinstanceid " + "and trackedentityattributeid=" + attribute.getId() + dataClause + ") as " + quote( attribute.getUid() ); columns.add( new AnalyticsTableColumn( quote( attribute.getUid() ), dataType, sql, skipIndex ) ); } AnalyticsTableColumn pi = new AnalyticsTableColumn( quote( "pi" ), "character(11) not null", "pi.uid" ); AnalyticsTableColumn erd = new AnalyticsTableColumn( quote( "enrollmentdate" ), "timestamp", "pi.enrollmentdate" ); AnalyticsTableColumn id = new AnalyticsTableColumn( quote( "incidentdate" ), "timestamp", "pi.incidentdate" ); final String executionDateSql = "(select psi.executionDate from programstageinstance psi " + "where psi.programinstanceid=pi.programinstanceid " + "and psi.executiondate is not null " + "and psi.deleted is false " + "order by psi.executiondate desc " + "limit 1) as " + quote( "executiondate" ); AnalyticsTableColumn ed = new AnalyticsTableColumn( quote( "executiondate" ), "timestamp", executionDateSql ); final String dueDateSql = "(select psi.duedate from programstageinstance psi " + "where psi.programinstanceid = pi.programinstanceid " + "and psi.duedate is not null " + "and psi.deleted is false " + "order by psi.duedate desc " + "limit 1) as " + quote( "duedate" ); AnalyticsTableColumn dd = new AnalyticsTableColumn( quote( "duedate" ), "timestamp", dueDateSql ); AnalyticsTableColumn cd = new AnalyticsTableColumn( quote( "completeddate" ), "timestamp", "case status when 'COMPLETED' then enddate end" ); AnalyticsTableColumn es = new AnalyticsTableColumn( quote( "enrollmentstatus" ), "character(50)", "pi.status" ); AnalyticsTableColumn longitude = new AnalyticsTableColumn( quote( "longitude" ), dbl, "pi.longitude" ); AnalyticsTableColumn latitude = new AnalyticsTableColumn( quote( "latitude" ), dbl, "pi.latitude" ); AnalyticsTableColumn ou = new AnalyticsTableColumn( quote( "ou" ), "character(11) not null", "ou.uid" ); AnalyticsTableColumn oun = new AnalyticsTableColumn( quote( "ouname" ), "character varying(230) not null", "ou.name" ); AnalyticsTableColumn ouc = new AnalyticsTableColumn( quote( "oucode" ), "character varying(50)", "ou.code" ); columns.addAll( Lists.newArrayList( pi, erd, id, ed, es, dd, cd, longitude, latitude, ou, oun, ouc ) ); if ( databaseInfo.isSpatialSupport() ) { String alias = "(select ST_SetSRID(ST_MakePoint(pi.longitude, pi.latitude), 4326)) as geom"; columns.add( new AnalyticsTableColumn( quote( "geom" ), "geometry(Point, 4326)", alias, false, "gist" ) ); } if ( table.hasProgram() && table.getProgram().isRegistration() ) { columns.add( new AnalyticsTableColumn( quote( "tei" ), "character(11)", "tei.uid" ) ); } return filterDimensionColumns( columns ); } }
package pl.edu.icm.coansys.classification.documents.pig.extractors; import com.google.common.base.Joiner; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.DefaultDataBag; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.apache.zookeeper.KeeperException.UnimplementedException; import pl.edu.icm.coansys.classification.documents.auxil.StackTraceExtractor; import pl.edu.icm.coansys.disambiguation.auxil.Pair; import pl.edu.icm.coansys.importers.models.DocumentProtos.ClassifCode; import pl.edu.icm.coansys.importers.models.DocumentProtos.DocumentMetadata; import pl.edu.icm.coansys.importers.models.DocumentProtos.TextWithLanguage; /** * * @author pdendek */ @SuppressWarnings("rawtypes") public class EXTRACT_MAP_WHEN_CATEG_LIM extends EvalFunc<Map> { private String language = null; public EXTRACT_MAP_WHEN_CATEG_LIM(String language){ this.language = language; } public EXTRACT_MAP_WHEN_CATEG_LIM(){ } @Override public Schema outputSchema(Schema p_input) { try { return Schema.generateNestedSchema(DataType.MAP); } catch (FrontendException e) { throw new IllegalStateException(e); } } @Override public Map exec(Tuple input) throws IOException { try { DataByteArray protoMetadata = (DataByteArray) input.get(0); int lim = (Integer) input.get(1); DocumentMetadata metadata = DocumentMetadata.parseFrom(protoMetadata.get()); if(language!=null){ return generateConcreteLanguageMap(metadata,lim); }else{ return generateAllLanguageMap(metadata,lim); } } catch (Exception e) { // Throwing an exception will cause the task to fail. throw new IOException("Caught exception processing input row:\n" + StackTraceExtractor.getStackTrace(e)); } } protected Map generateConcreteLanguageMap(DocumentMetadata dm, int lim){ String docTitle; String docAbstract; if((docTitle = extractLangTitle(dm))==null) return null; docAbstract = extractLangAbstract(dm); Pair<String, DataBag> kwCc = extractLangKeywords(dm); if (kwCc.getY().size() > lim) { Map<String, Object> map = new HashMap<String, Object>(); map.put("key", dm.getKey()); map.put("title", docTitle); map.put("keywords", kwCc.getX()); map.put("abstract", docAbstract); map.put("categories", kwCc.getY()); return map; } return null; } private Pair<String, DataBag> extractLangKeywords(DocumentMetadata dm) { List<String> kws = new ArrayList<String>(); Set<String> ctgs = new HashSet<String>(); for(TextWithLanguage twl : dm.getKeywordList()){ if(language.equalsIgnoreCase(twl.getLanguage())){ String str = twl.getText(); if(!isClassifCode(str)) kws.add(str); else ctgs.add(str); } } for(ClassifCode cc : dm.getBasicMetadata().getClassifCodeList()){ for(String s : cc.getValueList()) ctgs.add(s); } DataBag db = new DefaultDataBag(); for(String s : ctgs){ db.add(TupleFactory.getInstance().newTuple(s)); } return new Pair<String,DataBag>(Joiner.on(" ").join(kws),db); } private boolean isClassifCode(String str) { if(isMSc(str)) return true; else return false; } private boolean isMSc(String str) { return str.toUpperCase().matches("[0-9][0-9][A-Z][0-9][0-9]"); } private String extractLangAbstract(DocumentMetadata dm) { String docAbstract; List<String> abstractsList = new ArrayList<String>(); //getDocumentAbstractList() for (TextWithLanguage documentAbstract : dm.getDocumentAbstractList()) { if(language.equalsIgnoreCase(documentAbstract.getLanguage())); abstractsList.add(documentAbstract.getText()); } docAbstract = Joiner.on(" ").join(abstractsList); return docAbstract; } private String extractLangTitle(DocumentMetadata dm) { List<String> titleList = new ArrayList<String>(); //getTitleList() for (TextWithLanguage title : dm.getBasicMetadata().getTitleList()) { if(language.equalsIgnoreCase(title.getLanguage())); titleList.add(title.getText()); } String docTitle; switch(titleList.size()){ case 0: System.out.println("No title IN GIVEN LANG ("+language+") out of "+dm.getBasicMetadata().getTitleCount() +" titles. Ignoring record!"); return null; case 1: docTitle = titleList.get(0); break; default: System.out.println("Number of titles IN GIVEN LANGUAGE ("+language+") is more then one. " + "Titles will be concatenated"); docTitle = Joiner.on(" ").join(titleList); break; } if(docTitle.trim().isEmpty()) return null; return docTitle; } protected Map generateAllLanguageMap(DocumentMetadata dm, int lim) throws UnimplementedException{ throw new UnimplementedException(); } private DataBag getCategories(List<ClassifCode> classifCodeList) { DataBag db = new DefaultDataBag(); for (ClassifCode code : classifCodeList) { for (String co_str : code.getValueList()) { // System.out.print(" "+co_str); db.add(TupleFactory.getInstance().newTuple(co_str)); } } return db; } private String getConcatenated(List<TextWithLanguage> list) { if (list == null || list.isEmpty()) {return null;} return Joiner.on(" ").join(list); } }
package edu.cuny.citytech.defaultrefactoring.core.utils; import static org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTester.getTopLevelType; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.refactoring.Checks; import org.eclipse.jdt.internal.corext.util.JdtFlags; import edu.cuny.citytech.defaultrefactoring.core.refactorings.MigrateSkeletalImplementationToInterfaceRefactoringProcessor; /** * @author <a href="mailto:rkhatchadourian@citytech.cuny.edu">Raffi * Khatchadourian</a> * @see org.eclipse.jdt.internal.corext.refactoring. * RefactoringAvailabilityTester */ @SuppressWarnings("restriction") public final class RefactoringAvailabilityTester { private RefactoringAvailabilityTester() { } public static boolean isInterfaceMigrationAvailable(IMethod method, Optional<IProgressMonitor> monitor) throws JavaModelException { return isInterfaceMigrationAvailable(method, true, monitor); } public static boolean isInterfaceMigrationAvailable(IMethod method, boolean allowConcreteClasses, Optional<IProgressMonitor> monitor) throws JavaModelException { if (!Checks.isAvailable(method)) return false; if (method.isConstructor()) return false; if (JdtFlags.isNative(method)) return false; final IType declaring = method.getDeclaringType(); if (declaring != null) { if (declaring.isInterface()) return false; // Method is already in an interface else if (!allowConcreteClasses && !Flags.isAbstract(declaring.getFlags())) return false; // no concrete types allowed. } // ensure that there is a target method. IMethod targetMethod = MigrateSkeletalImplementationToInterfaceRefactoringProcessor.getTargetMethod(method, monitor); if (targetMethod == null) // no possible target. return false; return true; } public static boolean isInterfaceMigrationAvailable(IMethod[] methods, Optional<IProgressMonitor> monitor) throws JavaModelException { if (methods != null && methods.length != 0) { // FIXME: This seems wrong. There should be a look up here and use // getDeclaringType() on each method. final IType type = getTopLevelType(methods); if (type != null && getMigratableSkeletalImplementations(type, monitor).length != 0) return true; for (int index = 0; index < methods.length; index++) if (!isInterfaceMigrationAvailable(methods[index], monitor)) return false; // return isCommonDeclaringType(methods); } return false; } public static IMethod[] getMigratableSkeletalImplementations(final IType type, Optional<IProgressMonitor> monitor) throws JavaModelException { List<IMethod> ret = new ArrayList<>(); if (type.exists()) { IMethod[] methodsOfType = type.getMethods(); for (int i = 0; i < methodsOfType.length; i++) { IMethod method = methodsOfType[i]; if (RefactoringAvailabilityTester.isInterfaceMigrationAvailable(method, monitor)) ret.add(method); } } return ret.toArray(new IMethod[ret.size()]); } }
package org.estatio.capex.dom.invoice.approval; import java.util.Collections; import java.util.List; import java.util.Optional; import javax.inject.Inject; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.NatureOfService; import org.apache.isis.applib.services.registry.ServiceRegistry2; import org.apache.isis.applib.util.Enums; import org.incode.module.document.dom.impl.docs.Document; import org.incode.module.document.dom.impl.paperclips.PaperclipRepository; import org.estatio.capex.dom.bankaccount.verification.BankAccountVerificationState; import org.estatio.capex.dom.bankaccount.verification.BankAccountVerificationStateTransition; import org.estatio.capex.dom.bankaccount.verification.BankAccountVerificationStateTransitionType; import org.estatio.capex.dom.documents.LookupAttachedPdfService; import org.estatio.capex.dom.invoice.IncomingInvoice; import org.estatio.capex.dom.invoice.IncomingInvoiceType; import org.estatio.capex.dom.project.ProjectRoleTypeEnum; import org.estatio.capex.dom.state.AdvancePolicy; import org.estatio.capex.dom.state.NextTransitionSearchStrategy; import org.estatio.capex.dom.state.StateTransitionEvent; import org.estatio.capex.dom.state.StateTransitionRepository; import org.estatio.capex.dom.state.StateTransitionService; import org.estatio.capex.dom.state.StateTransitionServiceSupportAbstract; import org.estatio.capex.dom.state.StateTransitionType; import org.estatio.capex.dom.state.TaskAssignmentStrategy; import org.estatio.dom.asset.role.FixedAssetRoleTypeEnum; import org.estatio.dom.financial.bankaccount.BankAccount; import org.estatio.dom.invoice.PaymentMethod; import org.estatio.dom.party.PartyRoleTypeEnum; import org.estatio.dom.party.Person; import org.estatio.dom.party.role.IPartyRoleType; import lombok.Getter; @Getter public enum IncomingInvoiceApprovalStateTransitionType implements StateTransitionType< IncomingInvoice, IncomingInvoiceApprovalStateTransition, IncomingInvoiceApprovalStateTransitionType, IncomingInvoiceApprovalState> { // a "pseudo" transition type; won't ever see this persisted as a state transition INSTANTIATE( (IncomingInvoiceApprovalState)null, IncomingInvoiceApprovalState.NEW, NextTransitionSearchStrategy.firstMatching(), TaskAssignmentStrategy.none(), AdvancePolicy.MANUAL), COMPLETE( IncomingInvoiceApprovalState.NEW, IncomingInvoiceApprovalState.COMPLETED, NextTransitionSearchStrategy.firstMatching(), null, // task assignment strategy overridden below AdvancePolicy.MANUAL) { @Override public TaskAssignmentStrategy getTaskAssignmentStrategy() { return (TaskAssignmentStrategy< IncomingInvoice, IncomingInvoiceApprovalStateTransition, IncomingInvoiceApprovalStateTransitionType, IncomingInvoiceApprovalState>) (incomingInvoice, serviceRegistry2) -> { final boolean hasProperty = incomingInvoice.getProperty() != null; if (hasProperty) { return FixedAssetRoleTypeEnum.PROPERTY_MANAGER; } switch (incomingInvoice.getType()) { case CAPEX: case PROPERTY_EXPENSES: case SERVICE_CHARGES: // this case should not be hit, because the upstream document categorisation process // should have also set a property in this case, so the previous check would have been satisfied // just adding this case in the switch stmt "for completeness" return FixedAssetRoleTypeEnum.PROPERTY_MANAGER; case LOCAL_EXPENSES: return PartyRoleTypeEnum.OFFICE_ADMINISTRATOR; case CORPORATE_EXPENSES: return PartyRoleTypeEnum.CORPORATE_ADMINISTRATOR; } // REVIEW: for other types, we haven't yet established a business process, so no task will be created return null; }; } @Override public boolean isMatch( final IncomingInvoice domainObject, final ServiceRegistry2 serviceRegistry2) { return getTaskAssignmentStrategy().getAssignTo(domainObject, serviceRegistry2) != null; } @Override public String reasonGuardNotSatisified( final IncomingInvoice incomingInvoice, final ServiceRegistry2 serviceRegistry2) { return incomingInvoice.reasonIncomplete(); } }, APPROVE( IncomingInvoiceApprovalState.COMPLETED, IncomingInvoiceApprovalState.APPROVED, NextTransitionSearchStrategy.firstMatching(), null, // task assignment strategy overridden below AdvancePolicy.MANUAL) { @Override public TaskAssignmentStrategy getTaskAssignmentStrategy() { return (TaskAssignmentStrategy< IncomingInvoice, IncomingInvoiceApprovalStateTransition, IncomingInvoiceApprovalStateTransitionType, IncomingInvoiceApprovalState>) (incomingInvoice, serviceRegistry2) -> { switch (incomingInvoice.getType()) { case CAPEX: return ProjectRoleTypeEnum.PROJECT_MANAGER; case PROPERTY_EXPENSES: case SERVICE_CHARGES: return FixedAssetRoleTypeEnum.ASSET_MANAGER; } return null; }; } @Override public boolean isMatch( final IncomingInvoice domainObject, final ServiceRegistry2 serviceRegistry2) { return getTaskAssignmentStrategy().getAssignTo(domainObject, serviceRegistry2) != null; } }, APPROVE_LOCAL_AS_COUNTRY_DIRECTOR( IncomingInvoiceApprovalState.COMPLETED, IncomingInvoiceApprovalState.APPROVED_BY_COUNTRY_DIRECTOR, NextTransitionSearchStrategy.firstMatching(), TaskAssignmentStrategy.to(PartyRoleTypeEnum.COUNTRY_DIRECTOR), AdvancePolicy.MANUAL) { @Override public boolean isMatch( final IncomingInvoice incomingInvoice, final ServiceRegistry2 serviceRegistry2) { return incomingInvoice.getType() == IncomingInvoiceType.LOCAL_EXPENSES; } }, CHECK_BANK_ACCOUNT_FOR_CORPORATE( IncomingInvoiceApprovalState.COMPLETED, IncomingInvoiceApprovalState.PENDING_BANK_ACCOUNT_CHECK, NextTransitionSearchStrategy.firstMatching(), TaskAssignmentStrategy.none(), AdvancePolicy.AUTOMATIC) { @Override public boolean isMatch( final IncomingInvoice incomingInvoice, final ServiceRegistry2 serviceRegistry2) { return incomingInvoice.getType() == IncomingInvoiceType.CORPORATE_EXPENSES; } @Override public void applyTo( final IncomingInvoice incomingInvoice, final Class<IncomingInvoiceApprovalStateTransition> stateTransitionClass, final ServiceRegistry2 serviceRegistry2) { CHECK_BANK_ACCOUNT.applyTo(incomingInvoice, stateTransitionClass, serviceRegistry2); } }, APPROVE_AS_COUNTRY_DIRECTOR( IncomingInvoiceApprovalState.APPROVED, IncomingInvoiceApprovalState.APPROVED_BY_COUNTRY_DIRECTOR, NextTransitionSearchStrategy.firstMatching(), TaskAssignmentStrategy.to(PartyRoleTypeEnum.COUNTRY_DIRECTOR), AdvancePolicy.MANUAL), CHECK_BANK_ACCOUNT( IncomingInvoiceApprovalState.APPROVED_BY_COUNTRY_DIRECTOR, IncomingInvoiceApprovalState.PENDING_BANK_ACCOUNT_CHECK, NextTransitionSearchStrategy.firstMatching(), TaskAssignmentStrategy.none(), AdvancePolicy.AUTOMATIC) { @Override public void applyTo( final IncomingInvoice incomingInvoice, final Class<IncomingInvoiceApprovalStateTransition> stateTransitionClass, final ServiceRegistry2 serviceRegistry2) { super.applyTo(incomingInvoice, stateTransitionClass, serviceRegistry2); if(CONFIRM_BANK_ACCOUNT_VERIFIED.isGuardSatisified(incomingInvoice, serviceRegistry2)) { return; } final BankAccount bankAccount = triggerBankVerificationState(incomingInvoice, serviceRegistry2); attachDocumentAsPossibleIbanProof(incomingInvoice, bankAccount, serviceRegistry2); } private BankAccount triggerBankVerificationState( final IncomingInvoice incomingInvoice, final ServiceRegistry2 serviceRegistry2) { final StateTransitionService stateTransitionService = serviceRegistry2.lookupService(StateTransitionService.class); final BankAccount bankAccount = incomingInvoice.getBankAccount(); if (bankAccount != null) { if(stateTransitionService.currentStateOf(bankAccount, BankAccountVerificationStateTransition.class) == null) { stateTransitionService .trigger(bankAccount, BankAccountVerificationStateTransitionType.INSTANTIATE, null); } // re-evaluate the state machine. stateTransitionService .trigger(bankAccount, BankAccountVerificationStateTransition.class, null, null); } return bankAccount; } private void attachDocumentAsPossibleIbanProof( final IncomingInvoice incomingInvoice, final BankAccount bankAccount, final ServiceRegistry2 serviceRegistry2) { final LookupAttachedPdfService lookupAttachedPdfService = serviceRegistry2.lookupService(LookupAttachedPdfService.class); final PaperclipRepository paperclipRepository = serviceRegistry2 .lookupService(PaperclipRepository.class); final Optional<Document> documentIfAny = lookupAttachedPdfService.lookupIncomingInvoicePdfFrom(incomingInvoice); if (documentIfAny.isPresent()) { final Document document = documentIfAny.get(); paperclipRepository.attach(document, "iban-proof", bankAccount); } } }, CONFIRM_BANK_ACCOUNT_VERIFIED( IncomingInvoiceApprovalState.PENDING_BANK_ACCOUNT_CHECK, IncomingInvoiceApprovalState.PAYABLE, NextTransitionSearchStrategy.firstMatching(), TaskAssignmentStrategy.none(), AdvancePolicy.AUTOMATIC) { @Override public boolean isGuardSatisified( final IncomingInvoice incomingInvoice, final ServiceRegistry2 serviceRegistry2) { return isBankAccountVerified(incomingInvoice, serviceRegistry2) || incomingInvoice.getPaymentMethod() == PaymentMethod.DIRECT_DEBIT; } private boolean isBankAccountVerified( final IncomingInvoice incomingInvoice, final ServiceRegistry2 serviceRegistry2) { final StateTransitionService stateTransitionService = serviceRegistry2.lookupService(StateTransitionService.class); final BankAccount bankAccount = incomingInvoice.getBankAccount(); BankAccountVerificationState state = stateTransitionService .currentStateOf(bankAccount, BankAccountVerificationStateTransition.class); return state == BankAccountVerificationState.VERIFIED; } }, PAY_BY_IBP( IncomingInvoiceApprovalState.PAYABLE, IncomingInvoiceApprovalState.PAID, NextTransitionSearchStrategy.firstMatching(), TaskAssignmentStrategy.none(), AdvancePolicy.MANUAL), PAY_BY_DD( IncomingInvoiceApprovalState.PAYABLE, IncomingInvoiceApprovalState.PAID, NextTransitionSearchStrategy.firstMatching(), TaskAssignmentStrategy.none(), AdvancePolicy.MANUAL), DISCARD( IncomingInvoiceApprovalState.NEW, IncomingInvoiceApprovalState.DISCARDED, NextTransitionSearchStrategy.none(), TaskAssignmentStrategy.none(), AdvancePolicy.MANUAL), ; private final List<IncomingInvoiceApprovalState> fromStates; private final IncomingInvoiceApprovalState toState; private final NextTransitionSearchStrategy nextTransitionSearchStrategy; private final TaskAssignmentStrategy taskAssignmentStrategy; private final AdvancePolicy advancePolicy; IncomingInvoiceApprovalStateTransitionType( final List<IncomingInvoiceApprovalState> fromState, final IncomingInvoiceApprovalState toState, final NextTransitionSearchStrategy nextTransitionSearchStrategy, final TaskAssignmentStrategy taskAssignmentStrategy, final AdvancePolicy advancePolicy) { this.fromStates = fromState; this.toState = toState; this.nextTransitionSearchStrategy = nextTransitionSearchStrategy; this.taskAssignmentStrategy = taskAssignmentStrategy; this.advancePolicy = advancePolicy; } IncomingInvoiceApprovalStateTransitionType( final IncomingInvoiceApprovalState fromState, final IncomingInvoiceApprovalState toState, final NextTransitionSearchStrategy nextTransitionSearchStrategy, final TaskAssignmentStrategy taskAssignmentStrategy, final AdvancePolicy advancePolicy) { this(fromState != null ? Collections.singletonList(fromState) : null, toState, nextTransitionSearchStrategy, taskAssignmentStrategy, advancePolicy); } public static class TransitionEvent extends StateTransitionEvent< IncomingInvoice, IncomingInvoiceApprovalStateTransition, IncomingInvoiceApprovalStateTransitionType, IncomingInvoiceApprovalState> { public TransitionEvent( final IncomingInvoice domainObject, final IncomingInvoiceApprovalStateTransition stateTransitionIfAny, final IncomingInvoiceApprovalStateTransitionType transitionType) { super(domainObject, stateTransitionIfAny, transitionType); } } @Override public NextTransitionSearchStrategy getNextTransitionSearchStrategy() { return nextTransitionSearchStrategy; } @Override public TransitionEvent newStateTransitionEvent( final IncomingInvoice domainObject, final IncomingInvoiceApprovalStateTransition transitionIfAny) { return new TransitionEvent(domainObject, transitionIfAny, this); } @Override public AdvancePolicy advancePolicyFor( final IncomingInvoice domainObject, final ServiceRegistry2 serviceRegistry2) { return advancePolicy; } @Override public IncomingInvoiceApprovalStateTransition createTransition( final IncomingInvoice domainObject, final IncomingInvoiceApprovalState fromState, final IPartyRoleType assignToIfAny, final Person personToAssignToIfAny, final ServiceRegistry2 serviceRegistry2) { final IncomingInvoiceApprovalStateTransition.Repository repository = serviceRegistry2.lookupService(IncomingInvoiceApprovalStateTransition.Repository.class); final String taskDescription = Enums.getFriendlyNameOf(this); return repository.create(domainObject, this, fromState, assignToIfAny, personToAssignToIfAny, taskDescription); } @DomainService(nature = NatureOfService.DOMAIN) public static class SupportService extends StateTransitionServiceSupportAbstract< IncomingInvoice, IncomingInvoiceApprovalStateTransition, IncomingInvoiceApprovalStateTransitionType, IncomingInvoiceApprovalState> { public SupportService() { super(IncomingInvoiceApprovalStateTransitionType.class, IncomingInvoiceApprovalStateTransition.class ); } @Override protected StateTransitionRepository< IncomingInvoice, IncomingInvoiceApprovalStateTransition, IncomingInvoiceApprovalStateTransitionType, IncomingInvoiceApprovalState > getRepository() { return repository; } @Inject IncomingInvoiceApprovalStateTransition.Repository repository; } }
package i2am.benchmark.storm.bloom; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.storm.redis.common.config.JedisClusterConfig; import org.apache.storm.redis.common.container.JedisCommandsContainerBuilder; import org.apache.storm.redis.common.container.JedisCommandsInstanceContainer; import org.apache.storm.task.OutputCollector; import org.apache.storm.task.TopologyContext; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.topology.base.BaseRichBolt; import org.apache.storm.tuple.Fields; import org.apache.storm.tuple.Tuple; import org.apache.storm.tuple.Values; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.jpountz.xxhash.XXHash32; import net.jpountz.xxhash.XXHashFactory; import redis.clients.jedis.JedisCommands; public class BloomFilteringBolt extends BaseRichBolt { /* Parameters */ int bucketSize = 0; String redisKey = null; String bucketSizeKey = "BucketSize"; List<String> dataArray; private Map<String, String> parameters; BloomFilter bloomFilter; private final static Logger logger = LoggerFactory.getLogger(BloomFilteringBolt.class); private OutputCollector outputCollector = null; /* Jedis */ private transient JedisCommandsInstanceContainer jedisContainer; private JedisClusterConfig jedisClusterConfig; private JedisCommands jedisCommands = null; /* Constructor */ public BloomFilteringBolt(List<String> dataArray, String redisKey, JedisClusterConfig jedisClusterConfig){ this.dataArray = dataArray; this.redisKey = redisKey; this.jedisClusterConfig = jedisClusterConfig; } @Override public void prepare(Map stormConf, TopologyContext context, OutputCollector outputCollector) { // TODO Auto-generated method stub this.outputCollector = outputCollector; /* Connect Redis*/ if (jedisClusterConfig != null) { this.jedisContainer = JedisCommandsContainerBuilder.build(jedisClusterConfig); jedisCommands = jedisContainer.getInstance(); } else { throw new IllegalArgumentException("Jedis configuration not found"); } /* Get parameters */ parameters = jedisCommands.hgetAll(redisKey); bucketSize = Integer.parseInt(parameters.get(bucketSizeKey)); bloomFilter = new BloomFilter(bucketSize); for(String data: dataArray){ try { bloomFilter.registData(data); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Override public void execute(Tuple tuple) { // TODO Auto-generated method stub int production = tuple.getIntegerByField("production"); String sentence = tuple.getStringByField("sentence"); String createdTime = tuple.getStringByField("created_time"); long inputTime = tuple.getLongByField("input_time"); boolean flag = false; System.out.println("tuple"); String[] words = sentence.split(" "); for(String data : words){ try { flag = bloomFilter.filtering(data); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(flag){ outputCollector.emit(new Values(new String(sentence + "," + production + "," + createdTime + "," + inputTime + "," + System.currentTimeMillis()))); } } } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { // TODO Auto-generated method stub declarer.declare(new Fields("message")); } } class BloomFilter{ int bucketSize; List<Boolean> buckets; HashFunction hashFunction = new HashFunction(); BloomFilter(int bucketSize){ this.bucketSize = bucketSize; buckets = new ArrayList<Boolean>(); for(int i = 0; i < bucketSize; i++){ buckets.add(false); } } void registData(String data) throws UnsupportedEncodingException{ int hashCode = 0; hashCode = hashFunction.javaHashFunction(data); buckets.set(hashCode%bucketSize, true); hashCode = hashFunction.xxHash32(data); buckets.set(hashCode%bucketSize, true); hashCode = hashFunction.JSHash(data); buckets.set(hashCode%bucketSize, true); } boolean filtering(String data) throws UnsupportedEncodingException{ boolean flag = false; int hashCode1 = 0; int hashCode2 = 0; int hashCode3 = 0; hashCode1 = hashFunction.javaHashFunction(data); hashCode2 = hashFunction.xxHash32(data); hashCode3 = hashFunction.JSHash(data); if(buckets.get(hashCode1%bucketSize) && buckets.get(hashCode2%bucketSize) && buckets.get(hashCode3%bucketSize)){ flag = true; } return flag; } } class HashFunction{ HashFunction(){} int javaHashFunction(String data){ int hashCode = data.hashCode(); hashCode = Math.abs(hashCode); return hashCode; } int xxHash32(String data) throws UnsupportedEncodingException{ byte[] byteData = data.getBytes("euc-kr"); XXHashFactory factory = XXHashFactory.fastestInstance(); XXHash32 hash32 = factory.hash32(); int seed = 0x9747b28c; int hashCode = hash32.hash(byteData, 0, byteData.length, seed); hashCode = Math.abs(hashCode); return hashCode; } int JSHash(String data){ int hashCode = 1315423911; for(int i = 0; i < data.length(); i++){ hashCode ^= ((hashCode << 5) + data.charAt(i) + (hashCode >> 2)); } hashCode = Math.abs(hashCode); return hashCode; } }
package org.eclipse.birt.report.model.adapter.oda.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import org.eclipse.birt.core.data.ExpressionUtil; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.report.model.adapter.oda.IODADesignFactory; import org.eclipse.birt.report.model.adapter.oda.ODADesignFactory; import org.eclipse.birt.report.model.api.DynamicFilterParameterHandle; import org.eclipse.birt.report.model.api.FilterConditionHandle; import org.eclipse.birt.report.model.api.OdaDataSetHandle; import org.eclipse.birt.report.model.api.ParameterHandle; import org.eclipse.birt.report.model.api.PropertyHandle; import org.eclipse.birt.report.model.api.SortHintHandle; import org.eclipse.birt.report.model.api.StructureFactory; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.birt.report.model.api.elements.structures.FilterCondition; import org.eclipse.birt.report.model.api.elements.structures.SortHint; import org.eclipse.birt.report.model.api.util.StringUtil; import org.eclipse.birt.report.model.elements.interfaces.IDataSetModel; import org.eclipse.birt.report.model.elements.interfaces.IDynamicFilterParameterModel; import org.eclipse.datatools.connectivity.oda.design.AndExpression; import org.eclipse.datatools.connectivity.oda.design.CompositeFilterExpression; import org.eclipse.datatools.connectivity.oda.design.CustomFilterExpression; import org.eclipse.datatools.connectivity.oda.design.DataSetDesign; import org.eclipse.datatools.connectivity.oda.design.DynamicFilterExpression; import org.eclipse.datatools.connectivity.oda.design.ExpressionArguments; import org.eclipse.datatools.connectivity.oda.design.ExpressionParameterDefinition; import org.eclipse.datatools.connectivity.oda.design.ExpressionVariable; import org.eclipse.datatools.connectivity.oda.design.FilterExpression; import org.eclipse.datatools.connectivity.oda.design.FilterExpressionType; import org.eclipse.datatools.connectivity.oda.design.NullOrderingType; import org.eclipse.datatools.connectivity.oda.design.ParameterDefinition; import org.eclipse.datatools.connectivity.oda.design.ResultSetCriteria; import org.eclipse.datatools.connectivity.oda.design.ResultSetDefinition; import org.eclipse.datatools.connectivity.oda.design.SortDirectionType; import org.eclipse.datatools.connectivity.oda.design.SortKey; import org.eclipse.datatools.connectivity.oda.design.SortSpecification; import org.eclipse.emf.common.util.EList; /** * The utility class that converts between ROM filter conditions and ODA filter * expression * * @see FilterConditionHandle * @see FilterExpression */ public class ResultSetCriteriaAdapter { /** * The data set handle. */ private final OdaDataSetHandle setHandle; /** * The data set design. */ private final DataSetDesign setDesign; /** * Parameter convert utility */ private final DynamicFilterParameterAdapter paramAdapter; /** * Prefix constant for custom expression. */ private final static String CUSTOM_PREFIX = "#"; //$NON-NLS-1$ /** * Prefix constant for dynamic expression. */ private final static String DYNAMIC_PREFIX = "!"; //$NON-NLS-1$ /** * Constant for invalid dynamic expression. */ private final static String INVALID_FILTER = "^"; //$NON-NLS-1$ /** * Design factory */ protected final IODADesignFactory designFactory; /** * The constructor. * * @param setHandle * the data set handle * @param setDesign * the data set design * */ public ResultSetCriteriaAdapter( OdaDataSetHandle setHandle, DataSetDesign setDesign ) { this.setHandle = setHandle; this.setDesign = setDesign; this.paramAdapter = new DynamicFilterParameterAdapter( setHandle, setDesign ); designFactory = ODADesignFactory.getFactory( ); } /** * Updates rom filter and sort hints. * * @throws SemanticException */ public void updateROMSortAndFilter( ) throws SemanticException { ResultSetDefinition resultSet = setDesign.getPrimaryResultSet( ); if ( resultSet == null ) return; ResultSetCriteria criteria = resultSet.getCriteria( ); if ( criteria == null ) return; updateROMSortHint( criteria ); updateROMFilterCondition( criteria ); } /** * Updates oda result set criteria. * */ public void updateODAResultSetCriteria( ) { ResultSetDefinition resultSet = setDesign.getPrimaryResultSet( ); if ( resultSet == null ) return; // if criteria is null, a new criteria will be created. ResultSetCriteria criteria = resultSet.getCriteria( ); if ( criteria == null ) { criteria = designFactory.createResultSetCriteria( ); resultSet.setCriteria( criteria ); } updateODASortKey( criteria ); updateOdaFilterExpression( criteria ); } /** * Updates oda filter expression by ROM filter condition. * * @param criteria * the result set criteria. */ private void updateOdaFilterExpression( ResultSetCriteria criteria ) { int count = 0; FilterExpression filterExpr = null; for ( Iterator<FilterConditionHandle> iter = setHandle .filtersIterator( ); iter.hasNext( ); ) { FilterConditionHandle filterHandle = iter.next( ); FilterExpression filter = createOdaFilterExpression( filterHandle ); if ( filter == null ) { continue; } count++; switch ( count ) { case 1 : filterExpr = filter; break; case 2 : AndExpression compositeFilterExp = designFactory .createAndExpression( ); compositeFilterExp.add( filterExpr ); filterExpr = compositeFilterExp; default : if ( filterExpr instanceof CompositeFilterExpression ) ( (CompositeFilterExpression) filterExpr ).add( filter ); } } criteria.setFilterSpecification( filterExpr ); } /** * Updates oda sort key. * */ private void updateODASortKey( ResultSetCriteria criteria ) { SortSpecification sortSpec = criteria.getRowOrdering( ); // if an Oda data set has no BIRT sort hints, the Adapter should create // an empty SortSpecification. if ( sortSpec == null ) { sortSpec = designFactory.createSortSpecification( ); criteria.setRowOrdering( sortSpec ); } EList<SortKey> list = sortSpec.getSortKeys( ); // clear the original value. list.clear( ); Iterator<SortHintHandle> iter = setHandle.sortHintsIterator( ); while ( iter.hasNext( ) ) { SortHintHandle handle = iter.next( ); SortKey key = designFactory.createSortKey( ); key.setColumnName( handle.getColumnName( ) ); key.setColumnPosition( handle.getPosition( ) ); String ordering = handle.getNullValueOrdering( ); setODANullValueOrdering( key, ordering ); key.setOptional( handle.isOptional( ) ); // default value if ( DesignChoiceConstants.SORT_DIRECTION_ASC.equals( handle .getDirection( ) ) ) { key.setSortDirection( SortDirectionType.ASCENDING ); } else if ( DesignChoiceConstants.SORT_DIRECTION_DESC.equals( handle .getDirection( ) ) ) { key.setSortDirection( SortDirectionType.DESCENDING ); } list.add( key ); } } /** * Updates null value ordering value in oda. * * @param key * the sort key. * @param ordering * the ordering. */ private void setODANullValueOrdering( SortKey key, String ordering ) { if ( DesignChoiceConstants.NULL_VALUE_ORDERING_TYPE_NULLISFIRST .equals( ordering ) ) { key.setNullValueOrdering( NullOrderingType.NULLS_FIRST ); } else if ( DesignChoiceConstants.NULL_VALUE_ORDERING_TYPE_NULLISLAST .equals( ordering ) ) { key.setNullValueOrdering( NullOrderingType.NULLS_LAST ); } else if ( DesignChoiceConstants.NULL_VALUE_ORDERING_TYPE_UNKNOWN .equals( ordering ) ) { key.setNullValueOrdering( NullOrderingType.UNKNOWN ); } } /** * Updates rom sort hint. * * @throws SemanticException */ private void updateROMSortHint( ResultSetCriteria criteria ) throws SemanticException { SortSpecification sortSpec = criteria.getRowOrdering( ); if ( sortSpec == null ) return; PropertyHandle propHandle = setHandle .getPropertyHandle( IDataSetModel.SORT_HINTS_PROP ); // clear the original value. propHandle.clearValue( ); EList<SortKey> list = sortSpec.getSortKeys( ); for ( int i = 0; i < list.size( ); i++ ) { SortKey key = list.get( i ); SortHint sortHint = StructureFactory.createSortHint( ); sortHint.setProperty( SortHint.COLUMN_NAME_MEMBER, key.getColumnName( ) ); sortHint.setProperty( SortHint.POSITION_MEMBER, key.getColumnPosition( ) ); sortHint.setProperty( SortHint.IS_OPTIONAL_MEMBER, key.isOptional( ) ); SortDirectionType sortType = key.getSortDirection( ); if ( SortDirectionType.ASCENDING.equals( sortType ) ) { sortHint.setProperty( SortHint.DIRECTION_MEMBER, DesignChoiceConstants.SORT_DIRECTION_ASC ); } else if ( SortDirectionType.DESCENDING.equals( sortType ) ) { sortHint.setProperty( SortHint.DIRECTION_MEMBER, DesignChoiceConstants.SORT_DIRECTION_DESC ); } NullOrderingType type = key.getNullValueOrdering( ); setROMNullValueOrdering( sortHint, type ); propHandle.addItem( sortHint ); } } /** * Updates null value ordering value in rom. * * @param hint * sort hint. * @param type * the null ordering type. */ private void setROMNullValueOrdering( SortHint hint, NullOrderingType type ) { if ( NullOrderingType.NULLS_FIRST.equals( type ) ) { hint.setProperty( SortHint.NULL_VALUE_ORDERING_MEMBER, DesignChoiceConstants.NULL_VALUE_ORDERING_TYPE_NULLISFIRST ); } else if ( NullOrderingType.NULLS_LAST.equals( type ) ) { hint.setProperty( SortHint.NULL_VALUE_ORDERING_MEMBER, DesignChoiceConstants.NULL_VALUE_ORDERING_TYPE_NULLISLAST ); } else if ( NullOrderingType.UNKNOWN.equals( type ) ) { hint.setProperty( SortHint.NULL_VALUE_ORDERING_MEMBER, DesignChoiceConstants.NULL_VALUE_ORDERING_TYPE_UNKNOWN ); } } /** * Updates rom filter condition by ODA filter expression. * * @param criteria * result set criteria. * @throws SemanticException */ private void updateROMFilterCondition( ResultSetCriteria criteria ) throws SemanticException { FilterExpression filterExpression = null; filterExpression = criteria.getFilterSpecification( ); Map<String, Filter> filterExprMap = buildFilterExpressionMap( filterExpression ); // clears up old filter conditions and finds parameters to refresh cleanUpROMFilterCondition( filterExprMap ); if ( filterExpression != null ) { // update exists filter conditions updateExistingROMFilterConditions( filterExprMap ); // sets new filter conditions createROMFilterConditions( filterExprMap ); filterExprMap.clear( ); } filterExprMap = null; } /** * Builds the filter expression map to convert * * @param filterExpr * the filter expression * @return the map containing filter expression to convert */ private Map<String, Filter> buildFilterExpressionMap( FilterExpression filterExpr ) { HashMap<String, Filter> filterExpressions = new LinkedHashMap<String, Filter>( ); if ( filterExpr != null ) { if ( filterExpr instanceof CompositeFilterExpression ) { CompositeFilterExpression compositeFilterExp = (CompositeFilterExpression) filterExpr; if ( compositeFilterExp instanceof AndExpression ) { // Convert and expression only now. for ( FilterExpression child : compositeFilterExp .getChildren( ) ) { filterExpressions .putAll( buildFilterExpressionMap( child ) ); } } } else if ( filterExpr instanceof CustomFilterExpression ) { Filter customFilter = new CustomFilter( (CustomFilterExpression) filterExpr ); String key = getMapKey( customFilter ); if ( key != null ) { filterExpressions.put( key, customFilter ); } } else if ( filterExpr instanceof DynamicFilterExpression ) { DynamicFilterExpression dynamicFilterExpr = (DynamicFilterExpression) filterExpr; boolean isOptional = dynamicFilterExpr.isOptional( ); ExpressionArguments arguments = dynamicFilterExpr .getContextArguments( ); if ( arguments != null && arguments.getExpressionParameterDefinitions( ) != null ) { for ( ExpressionParameterDefinition paramDefn : arguments .getExpressionParameterDefinitions( ) ) { Filter dynamicFilter = new DynamicFilter( paramDefn, dynamicFilterExpr.getDefaultType( ), isOptional ); String key = getMapKey( dynamicFilter ); if ( key != null ) { filterExpressions.put( key, dynamicFilter ); } } } } } return filterExpressions; } /** * Returns the map key for the given filter. * * @param filter * the filter * @return the key for the given filter */ private String getMapKey( Filter filter ) { String key = null; if ( filter instanceof CustomFilter ) { CustomFilter customFilter = (CustomFilter) filter; if ( !StringUtil.isBlank( customFilter.getColumnExpr( ) ) ) key = CUSTOM_PREFIX + customFilter.customFilterExpr.toString( ); } else if ( filter instanceof DynamicFilter ) { String columnExpr = ( (DynamicFilter) filter ).getColumnExpr( ); if ( !StringUtil.isBlank( columnExpr ) ) key = DYNAMIC_PREFIX + columnExpr; } else assert false; return key; } /** * Returns the map key for the given filter condition * * @param filterConditionHandle * the handle of the filter condition * @return the key for the given filter handle,or null if the filter * condition is not dynamic. */ private String getMapKey( FilterConditionHandle filterConditionHandle ) { String key = null; String dynamicFilterParameter = filterConditionHandle .getDynamicFilterParameter( ); if ( !StringUtil.isBlank( dynamicFilterParameter ) ) { ParameterHandle parameterHandle = setHandle.getModuleHandle( ) .findParameter( dynamicFilterParameter ); if ( parameterHandle instanceof DynamicFilterParameterHandle ) { key = DYNAMIC_PREFIX + ExpressionUtil .createDataSetRowExpression( ( (DynamicFilterParameterHandle) parameterHandle ) .getColumn( ) ); } else { // Cannot find the parameter key = INVALID_FILTER; } } return key; } /** * Updates existing filter conditions with the given filters * * @param filterMap * the map containing the filters to update * @throws SemanticException */ private void updateExistingROMFilterConditions( Map<String, Filter> filterMap ) throws SemanticException { for ( Iterator iter = setHandle.filtersIterator( ); iter.hasNext( ); ) { FilterConditionHandle filterConditionHandle = (FilterConditionHandle) iter .next( ); String key = getMapKey( filterConditionHandle ); if ( key != null && filterMap.containsKey( key ) ) { DynamicFilterParameterHandle dynamicFilterParamHandle = (DynamicFilterParameterHandle) setHandle .getModuleHandle( ).findParameter( filterConditionHandle .getDynamicFilterParameter( ) ); updateDynamicFilterCondition( filterConditionHandle, (DynamicFilter) filterMap.get( key ), dynamicFilterParamHandle ); // Removes the filter from the map after updated filterMap.remove( key ); } else {// not expected assert false; } } } /** * Creates new filter conditions by the given filters * * @param filterMap * the map containing filters * @throws SemanticException */ private void createROMFilterConditions( Map<String, Filter> filterMap ) throws SemanticException { for ( Filter filter : filterMap.values( ) ) { FilterCondition filterCondition = StructureFactory .createFilterCond( ); filterCondition.setExpr( filter.getColumnExpr( ) ); // in default, to make sure the pushdown is true. filterCondition.setPushDown( true ); FilterConditionHandle filterConditionHandle = (FilterConditionHandle) setHandle .getPropertyHandle( IDataSetModel.FILTER_PROP ).addItem( filterCondition ); if ( filter instanceof CustomFilter ) { CustomFilterExpression customFilterExp = ( (CustomFilter) filter ).customFilterExpr; updateCustomFilterCondition( filterConditionHandle, customFilterExp ); } else if ( filter instanceof DynamicFilter ) { DynamicFilter dynamicFilter = (DynamicFilter) filter; // if ( dynamicFilter.defaultType != null ) // filterConditionHandle // .setExtensionName( dynamicFilter.defaultType // .getDeclaringExtensionId( ) ); // filterConditionHandle // .setExtensionExprId( dynamicFilter.defaultType // .getId( ) ); // creates new dynamic filter parameter DynamicFilterParameterHandle dynamicFilterParamHandle = setHandle .getModuleHandle( ).getElementFactory( ) .newDynamicFilterParameter( null ); dynamicFilterParamHandle.setColumn( dynamicFilter .getColumnName( ) ); Integer nativeDataType = dynamicFilter.getNativeDataType( ); if ( nativeDataType != null ) { dynamicFilterParamHandle.setNativeDataType( nativeDataType ); try { dynamicFilterParamHandle .setDataType( NativeDataTypeUtil.getUpdatedDataType( setDesign.getOdaExtensionDataSourceId( ), setDesign.getOdaExtensionDataSetId( ), nativeDataType, null, DesignChoiceConstants.CHOICE_PARAM_TYPE ) ); } catch ( BirtException e ) { // Do nothing } } setHandle.getModuleHandle( ).getParameters( ) .add( dynamicFilterParamHandle ); // sets the reference filterConditionHandle .setDynamicFilterParameter( dynamicFilterParamHandle .getName( ) ); // updates the dynamic filter parameter updateDynamicFilterCondition( filterConditionHandle, dynamicFilter, dynamicFilterParamHandle ); } } } /** * Updates the filter condition by the given custom filter expression * * @param filterConditionHandle * the handle of the filter condition to update * @param customFilterExpr * the custom filter expression * @throws SemanticException */ private void updateCustomFilterCondition( FilterConditionHandle filterConditionHandle, CustomFilterExpression customFilterExpr ) throws SemanticException { FilterExpressionType tmpType = customFilterExpr.getType( ); if ( tmpType != null ) { filterConditionHandle.setExtensionName( tmpType .getDeclaringExtensionId( ) ); filterConditionHandle.setExtensionExprId( tmpType.getId( ) ); } filterConditionHandle.setPushDown( true ); filterConditionHandle.setOptional( customFilterExpr.isOptional( ) ); } /** * Updates the filter condition by the given dynamic filter * * @param filterConditionHandle * the handle of the filter condition to update * @param dynamicFilterExpr * the dynamic filter * @throws SemanticException */ private void updateDynamicFilterCondition( FilterConditionHandle filterConditionHandle, DynamicFilter dynamicFilter, DynamicFilterParameterHandle dynamicFilterParamHandle ) throws SemanticException { filterConditionHandle.setOptional( dynamicFilter.isOptional ); paramAdapter.updateROMDynamicFilterParameter( dynamicFilter, dynamicFilterParamHandle ); } /** * Clears up all unnecessary dynamic filter parameter and filter conditions * * @param filterMap * the map contains filters * @throws SemanticException * */ private void cleanUpROMFilterCondition( Map<String, Filter> filterMap ) throws SemanticException { ArrayList<FilterCondition> dropList = new ArrayList<FilterCondition>( ); for ( Iterator iter = setHandle.filtersIterator( ); iter.hasNext( ); ) { FilterConditionHandle filterHandle = (FilterConditionHandle) iter .next( ); String dynamicParameterName = filterHandle .getDynamicFilterParameter( ); String key = getMapKey( filterHandle ); // Check if contains such filter. if ( key != null && !filterMap.containsKey( key ) ) { // Remove the filter condition which is not contained. if ( !StringUtil.isBlank( dynamicParameterName ) ) { ParameterHandle parameterHandle = setHandle .getModuleHandle( ).findParameter( dynamicParameterName ); if ( parameterHandle != null ) parameterHandle.drop( ); } dropList.add( (FilterCondition) filterHandle.getStructure( ) ); } } for ( FilterCondition fc : dropList ) { setHandle.removeFilter( fc ); } } /** * Creates the oda filter expression by the given filter condition. * * @param filterHandle * the handle of the given filter condition * @return the filter expression created */ private FilterExpression createOdaFilterExpression( FilterConditionHandle filterHandle ) { FilterExpression filterExpr = null; if ( StringUtil.isBlank( filterHandle.getDynamicFilterParameter( ) ) ) { if ( filterHandle.getExtensionName( ) == null || filterHandle.getExtensionExprId( ) == null ) { // Both extension name and extension id should not be null return null; } CustomFilterExpression customFilterExpr = designFactory .createCustomFilterExpression( ); ExpressionVariable variable = designFactory .createExpressionVariable( ); variable.setIdentifier( filterHandle.getExpr( ) ); customFilterExpr.setContextVariable( variable ); FilterExpressionType tmpType = designFactory .createFilterExpressionType( ); tmpType.setDeclaringExtensionId( filterHandle.getExtensionName( ) ); tmpType.setId( filterHandle.getExtensionExprId( ) ); customFilterExpr.setType( tmpType ); customFilterExpr.setIsOptional( filterHandle.isOptional( ) ); filterExpr = customFilterExpr; } else { ParameterHandle paramHandle = setHandle.getModuleHandle( ) .findParameter( filterHandle.getDynamicFilterParameter( ) ); if ( paramHandle instanceof DynamicFilterParameterHandle ) { DynamicFilterParameterHandle dynamicParamHandle = (DynamicFilterParameterHandle) paramHandle; DynamicFilterExpression dynamicFilterExpr = designFactory .createDynamicFilterExpression( ); dynamicFilterExpr.setIsOptional( filterHandle.isOptional( ) ); ExpressionArguments arguments = designFactory .createExpressionArguments( ); ParameterDefinition paramDefn = designFactory .createParameterDefinition( ); // create the default type instance anyway to pass to // DynamicFilterParameterAdapter. FilterExpressionType defaultType = designFactory .createFilterExpressionType( ); paramAdapter.updateODADynamicFilter( paramDefn, defaultType, dynamicParamHandle ); if ( filterHandle.getExtensionName( ) != null && filterHandle.getExtensionExprId( ) != null ) { defaultType.setDeclaringExtensionId( filterHandle .getExtensionName( ) ); } if ( defaultType.getDeclaringExtensionId( ) == null ) { defaultType.setDeclaringExtensionId( setDesign .getOdaExtensionDataSetId( ) ); } paramDefn.getAttributes( ).setName( dynamicParamHandle.getColumn( ) ); if ( dynamicParamHandle .getProperty( IDynamicFilterParameterModel.NATIVE_DATA_TYPE_PROP ) != null ) { paramDefn.getAttributes( ).setNativeDataTypeCode( dynamicParamHandle.getNativeDataType( ) ); } arguments.addDynamicParameter( paramDefn ); dynamicFilterExpr.setContextArguments( arguments ); if ( defaultType.getDeclaringExtensionId( ) != null && defaultType.getId( ) != null ) dynamicFilterExpr.setDefaultType( defaultType ); filterExpr = dynamicFilterExpr; } } return filterExpr; } private static interface Filter { /** * Returns the column expression for the dynamic filter. * * @return the column expression for the dynamic filter. */ String getColumnExpr( ); } private static class CustomFilter implements Filter { public CustomFilterExpression customFilterExpr; public CustomFilter( CustomFilterExpression filterExpr ) { this.customFilterExpr = filterExpr; } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.adapter.oda.impl.ResultSetCriteriaAdapter * .Filter#getColumnExpr() */ public String getColumnExpr( ) { ExpressionVariable variable = customFilterExpr.getContextVariable( ); if ( variable != null ) { return variable.getIdentifier( ); } return null; } } static class DynamicFilter implements Filter { /** * Identifies if the filter is optional. */ boolean isOptional; ExpressionParameterDefinition exprParamDefn; FilterExpressionType defaultType; /** * The default constructor. * * @param exprParamDefn * @param defaultType * @param isOptional */ DynamicFilter( ExpressionParameterDefinition exprParamDefn, FilterExpressionType defaultType, boolean isOptional ) { this.isOptional = isOptional; this.exprParamDefn = exprParamDefn; this.defaultType = defaultType; } /** * Returns the column name for the dynamic filter. * * @return the column name for the dynamic filter. */ public String getColumnName( ) { ParameterDefinition paramDefn = exprParamDefn .getDynamicInputParameter( ); if ( paramDefn != null && paramDefn.getAttributes( ) != null ) { return paramDefn.getAttributes( ).getName( ); } return null; } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.adapter.oda.impl.ResultSetCriteriaAdapter * .Filter#getColumnExpr() */ public String getColumnExpr( ) { String columnName = getColumnName( ); if ( !StringUtil.isBlank( columnName ) ) { return ExpressionUtil.createDataSetRowExpression( columnName ); } return null; } /** * Returns the native data type code. * * @return the native data type code */ public Integer getNativeDataType( ) { ParameterDefinition paramDefn = exprParamDefn .getDynamicInputParameter( ); if ( paramDefn != null && paramDefn.getAttributes( ) != null ) { return paramDefn.getAttributes( ).getNativeDataTypeCode( ); } return null; } /** * @return the defaultType */ public FilterExpressionType getDefaultType( ) { return defaultType; } } }
package org.camunda.bpm.modeler.ui.property.tabs.util; /** * Help texts used by the application * * @author nico.rehwaldt */ public class HelpText { public static final String SUPPORTED_VERSION_NOTE = "This feature is supported for camunda BPM engine version %s and higher."; public static final String SUPPORTED_VERSION_NOTE_7_1 = String.format(SUPPORTED_VERSION_NOTE, "7.1"); public static final String SUPPORTED_VERSION_NOTE_7_2 = String.format(SUPPORTED_VERSION_NOTE, "7.2"); public static final String MANDATORY_VALUE = "This value is mandatory. Empty value will not be saved."; public static final String TABLE_HELP = "Add or remove table entry by right-click."; public static final String TABLE_ELEM_NOT_EDITABLE = "It is not possible to edit a nested Map, List or Script value."; public static final String TIME_DATE = "Date in ISO 8601 format (e.g. \"2011-03-11T12:13:14\")"; public static final String TIME_DURATION = "Duration in ISO 8601 format (e.g. \"P4DT12H30M5S\" as a duration of \"four days, 12 hours, 30 minutes, and five seconds\")"; public static final String TIME_CYCLE = "Retry interval in ISO 8601 format (e.g. \"R3/PT10M\" for \"3 cycles, every 10 minutes\")"; public static final String ELEMENT_DEF_TABLE = "%ss can be defined below"; private static final String ASYNC_LINK_TO_USER_GUIDE = "https://docs.camunda.org/manual/user-guide/process-engine/transactions-in-processes/#asynchronous-continuations"; private static final String CALL_ACTIVITY_VARIABLES_GUIDE = "https://docs.camunda.org/manual/reference/bpmn20/subprocesses/call-activity/#passing-variables"; private static final String CALL_ACTIVITY_BUSINESS_KEY_GUIDE = "https://docs.camunda.org/manual/reference/bpmn20/subprocesses/call-activity/#passing-business-key"; private static final String LINK_EVENT_DEFINITION_USER_GUIDE = "https://docs.camunda.org/manual/reference/bpmn20/events/link-events/"; private static final String COMPENSATION_THROWING_EVENT_USER_GUIDE = "https://docs.camunda.org/manual/reference/bpmn20/events/cancel-and-compensation-events/#compensation-events"; private static final String MULTI_INSTANCE_USER_GUIDE = "https://docs.camunda.org/manual/reference/bpmn20/tasks/task-markers/#multiple-instance"; private static final String IS_LOOP_USER_GUIDE = "https://docs.camunda.org/manual/reference/bpmn20/tasks/task-markers/#loops"; private static final String SIGNAL_THROW_EVENT_USER_GUIDE = "https://docs.camunda.org/manual/reference/bpmn20/events/signal-events/#throwing-signal-events"; private static final String FOLLOW_UP_DATE_USER_GUIDE = "https://docs.camunda.org/manual/reference/bpmn20/tasks/user-task/#follow-up-date"; private static final String DUE_DATE_USER_GUIDE = "https://docs.camunda.org/manual/reference/bpmn20/tasks/user-task/#due-date"; private static final String EXCLUSIVE_LINK_TO_USER_GUIDE = "https://docs.camunda.org/manual/user-guide/process-engine/the-job-executor/#exclusive-jobs"; private static final String FIELD_INJECTIONS_USER_GUIDE = "https://docs.camunda.org/manual/user-guide/process-engine/delegation-code/#field-injection"; public static final String ASYNC_FLAG = String.format( "More information on asynchronous continuation can be found in the <a href=\"%s\">user guide</a>.", ASYNC_LINK_TO_USER_GUIDE); public static final String CALL_ACTIVITY_CALLED_ELEMENT_VERSION = "Processdefinition version of called process (e.g. \"17\")"; public static final String CALL_ACTIVITY_ALL_VARIABLES_IN = String.format( "Pass all process variables from mainprocess to the subprocess. See for more information <a href=\"%s\">user guide</a>.", CALL_ACTIVITY_VARIABLES_GUIDE); public static final String CALL_ACTIVITY_ALL_VARIABLES_OUT = String.format( "Pass all process variables from subprocess to mainprocess. See for more information <a href=\"%s\">user guide</a>.", CALL_ACTIVITY_VARIABLES_GUIDE); public static final String CALL_ACTIVITY_BUSINESS_KEY = String.format( "Pass business key from mainprocess to subprocess. See for more information <a href=\"%s\">user guide</a>.", CALL_ACTIVITY_BUSINESS_KEY_GUIDE); public static final String LINK_EVENT_DEFINITION_NAME = String.format("More information on link event definition can be found in the <a href=\"%s\">user guide</a>.", LINK_EVENT_DEFINITION_USER_GUIDE); public static final String STANDARD_LOOP_CHARACTERISTICS_NOTE = String.format("Please note, the loop activity is not supported by the camunda BPM engine. See for more information <a href=\"%s\">user guide</a>.", IS_LOOP_USER_GUIDE); public static final String WAIT_FOR_COMPLETION_NOTE = "Please note, only the default value \"true\" is supported by the camunda BPM engine."; public static final String COMPENSATION_THROWING_EVENT = String.format("More information on compensation intermediate throwing event can be found in the <a href=\"%s\">user guide</a>.", COMPENSATION_THROWING_EVENT_USER_GUIDE); public static final String MULTI_INSTANCE_CHARACTERISTICS = String.format("Please refer to our <a href=\"%s\">documentation</a> for multi instance.", MULTI_INSTANCE_USER_GUIDE); public static final String SIGNAL_THROW_EVENT_ASYNC_FLAG = String.format("Asynchronous notification of event listener. For more information, refer to our <a href=\"%s\">user guide</a>.", SIGNAL_THROW_EVENT_USER_GUIDE); public static final String FOLLOW_UP_DATE = String.format("The follow up date as an EL expression (e.g. ${someDate}) or an ISO date (e.g. 2012-03-01T15:30:23). See for more information <a href=\"%s\">user guide</a>.", FOLLOW_UP_DATE_USER_GUIDE); public static final String DUE_DATE = String.format("The due date as an EL expression (e.g. ${someDate}) or an ISO date (e.g. 2012-03-01T15:30:23). See for more information <a href=\"%s\">user guide</a>.", DUE_DATE_USER_GUIDE); public static final String EXCLUSIVE_FLAG = String.format("More information on exclusive jobs can be found in the <a href=\"%s\">user guide</a>.", EXCLUSIVE_LINK_TO_USER_GUIDE); public static final String FIELD_INJECTIONS = String.format("Support only field injections with child-elements. For more information see <a href=\"%s\">user guide</a>.", FIELD_INJECTIONS_USER_GUIDE); }
package org.strategoxt.imp.runtime.stratego; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.console.ConsolePlugin; import org.eclipse.ui.console.IConsole; import org.eclipse.ui.console.IConsoleConstants; import org.eclipse.ui.console.IConsoleManager; import org.eclipse.ui.console.IConsoleView; import org.eclipse.ui.console.IOConsoleOutputStream; import org.eclipse.ui.console.MessageConsole; import org.eclipse.ui.progress.UIJob; import org.strategoxt.imp.runtime.Environment; import org.strategoxt.imp.runtime.dynamicloading.Descriptor; /** * The Stratego console. * * @author Lennart Kats <lennart add lclnet.nl> */ public class StrategoConsole { private static final String CONSOLE_NAME = "Spoofax/IMP console"; private static MessageConsole lastConsole; private static Writer lastConsoleOutputWriter; private static Writer lastConsoleErrorWriter; public static Writer getErrorWriter() { MessageConsole console = getConsole(); if (console == lastConsole && lastConsoleErrorWriter != null) { return lastConsoleErrorWriter; } else { IOConsoleOutputStream stream = console.newOutputStream(); // A red color doesn't seem to make sense for Stratego // stream.setColor(DebugUIPlugin.getPreferenceColor(IDebugPreferenceConstants.CONSOLE_SYS_ERR_COLOR)); lastConsoleErrorWriter = new AutoFlushOutputStreamWriter(stream); lastConsole = console; return lastConsoleErrorWriter; } } public static Writer getOutputWriter() { MessageConsole console = getConsole(); if (console == lastConsole && lastConsoleOutputWriter != null) { return lastConsoleOutputWriter; } else { lastConsoleOutputWriter = new AutoFlushOutputStreamWriter(console.newOutputStream()); lastConsole = console; return lastConsoleOutputWriter; } } /** * Gets or opens the Eclipse console for this plugin. */ private synchronized static MessageConsole getConsole() { IConsoleManager consoles = ConsolePlugin.getDefault().getConsoleManager(); for (IConsole console: consoles.getConsoles()) { if (StrategoConsole.CONSOLE_NAME.equals(console.getName())) return (MessageConsole) console; } // No console found, so create a new one MessageConsole result = new MessageConsole(StrategoConsole.CONSOLE_NAME, null); consoles.addConsoles(new IConsole[] { result }); return result; } /** * Activates the console for this plugin. * * Swallows and logs any PartInitException. * * @see Descriptor#isDynamicallyLoaded() Should typically be checked before opening a console. */ public static void activateConsole() { activateConsole(false); } /** * Activates the console for this plugin. * * Swallows and logs any PartInitException. * * @param consoleViewOnly * Only open the console within the console view; don't activate * the console view itself. * * @see Descriptor#isDynamicallyLoaded() Should typically be checked before * opening a console. */ public static void activateConsole(final boolean consoleViewOnly) { Job job = new UIJob("Open console") { @Override public IStatus runInUIThread(IProgressMonitor monitor) { final String ID = IConsoleConstants.ID_CONSOLE_VIEW; MessageConsole console = StrategoConsole.getConsole(); if (consoleViewOnly) { console.activate(); return Status.OK_STATUS; } IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); try { IConsoleView view = (IConsoleView) page.showView(ID, null, IWorkbenchPage.VIEW_VISIBLE); view.display(console); } catch (PartInitException e) { Environment.logException("Could not activate the console", e); } return Status.OK_STATUS; } }; job.setSystem(true); job.schedule(); } /** * An OutputStreamWriter that automatically flushes its buffer. * * @author Lennart Kats <lennart add lclnet.nl> */ private static class AutoFlushOutputStreamWriter extends OutputStreamWriter { public AutoFlushOutputStreamWriter(OutputStream out) { super(out); } @Override public void write(String str, int off, int len) throws IOException { super.write(str, off, len); super.flush(); } @Override public void write(char[] cbuf, int off, int len) throws IOException { super.write(cbuf, off, len); super.flush(); } @Override public void write(int c) throws IOException { super.write(c); super.flush(); } } }
package cs437.som.neighborhood; import cs437.som.NeighborhoodWidthFunction; import java.util.*; public class CompoundNeighborhood implements NeighborhoodWidthFunction { private int nextTransition = -1; private NeighborhoodWidthFunction currentFunction; private final Map<Integer, NeighborhoodWidthFunction> widthFunctions = new HashMap<Integer, NeighborhoodWidthFunction>(2); public CompoundNeighborhood(NeighborhoodWidthFunction initialWidthFuncton) { widthFunctions.put(0, initialWidthFuncton); currentFunction = initialWidthFuncton; } public void setExpectedIterations(int expectedIterations) { if (nextTransition == -1) { nextTransition = expectedIterations; } } public double neighborhoodWidth(int iteration) { if (iteration == nextTransition) { shiftFunctions(); } return currentFunction.neighborhoodWidth(iteration); } /** * Add a neighborhood function to be used after a specific number of * iterations. * * @param neighborhood The neighborhood function object to add. * @param startAt The iteration at which to use {@code neighborhood}. */ public void addNeighborhood(NeighborhoodWidthFunction neighborhood, int startAt) { widthFunctions.put(startAt, neighborhood); } /** * Find the next neighborhood width function shift it into the current * slot. */ private void shiftFunctions() { // Don't try to shift if there's nothing left to use. if (widthFunctions.isEmpty()) { return; } // Find the next lowest transition point int low = nextTransition; for (Integer i : widthFunctions.keySet()) { if (i < low) { low = i; } } // Move the next function into place. currentFunction = widthFunctions.remove(low); nextTransition = low; } @Override public String toString() { return "CompoundNeighborhood"; } public CompoundNeighborhood(String parameters) { // todo IMPLEMENT!!! throw new UnsupportedOperationException( "CompoundNeighborhood cannot be loaded from a file yet."); } }
package SW9.model_canvas.locations; import SW9.Keybind; import SW9.KeyboardTracker; import SW9.MouseTracker; import SW9.model_canvas.edges.Edge; import SW9.model_canvas.IParent; import SW9.model_canvas.ModelCanvas; import SW9.model_canvas.Parent; import SW9.utility.BindingHelper; import SW9.utility.DragHelper; import SW9.utility.DropShadowHelper; import javafx.animation.Animation; import javafx.animation.Transition; import javafx.beans.binding.StringBinding; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.value.ObservableDoubleValue; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.shape.Circle; import javafx.util.Duration; public class Location extends Parent implements MouseTracker.hasMouseTracker { // Used to create the Location public final static double RADIUS = 25.0f; // Used to update the interaction with the mouse private BooleanProperty isOnMouse = new SimpleBooleanProperty(false); public final MouseTracker localMouseTracker; public Circle circle; public Label locationLabel; public BooleanProperty isUrgent = new SimpleBooleanProperty(false); public BooleanProperty isCommitted = new SimpleBooleanProperty(false); public enum Type { NORMAL, INITIAL, FINAL } public Type type; public Location(MouseTracker canvasMouseTracker) { this(canvasMouseTracker.getXProperty(), canvasMouseTracker.getYProperty(), canvasMouseTracker, Type.NORMAL); isOnMouse.set(true); } public Location(final ObservableDoubleValue centerX, final ObservableDoubleValue centerY, final MouseTracker canvasMouseTracker, Type type) { // Initialize the type property this.type = type; // Bind the mouse transparency to the boolean telling if the location is on the mouse this.mouseTransparentProperty().bind(isOnMouse); // Add the circle and add it at a child circle = new Circle(centerX.doubleValue(), centerY.doubleValue(), RADIUS); addChild(circle); // If the location is not a normal locations draw the visual cues if(type == Type.INITIAL) { addChild(new InitialLocationCircle(this)); } else if(type == Type.FINAL) { addChild(new FinalLocationCross(this)); } // Add a text which we will use as a label for urgent and committed locations locationLabel = new Label(); locationLabel.textProperty().bind(new StringBinding() { { super.bind(isUrgent, isCommitted); } @Override protected String computeValue() { if (isUrgent.get()) { return "U"; } else if (isCommitted.get()) { return "C"; } else { return ""; } } }); locationLabel.setMinWidth(2 * RADIUS); locationLabel.setMaxWidth(2 * RADIUS); locationLabel.setMinHeight(2 * RADIUS); locationLabel.setMaxHeight(2 * RADIUS); addChild(locationLabel); // Bind the label to the circle BindingHelper.bind(locationLabel, this); // Add style for the circle and label circle.getStyleClass().add("location"); locationLabel.getStyleClass().add("location-label"); locationLabel.getStyleClass().add("headline"); locationLabel.getStyleClass().add("white-text"); // Bind the Location to the property circle.centerXProperty().bind(centerX); circle.centerYProperty().bind(centerY); // Initialize the local mouse tracker this.localMouseTracker = new MouseTracker(this); // Register the handler for entering the location localMouseTracker.registerOnMouseEnteredEventHandler(event -> { ModelCanvas.setHoveredLocation(this); }); // Register the handler for existing the locations localMouseTracker.registerOnMouseExitedEventHandler(event -> { if (ModelCanvas.mouseIsHoveringLocation() && ModelCanvas.getHoveredLocation().equals(this)) { ModelCanvas.setHoveredLocation(null); } }); // Place the new location when the mouse is pressed (i.e. stop moving it) canvasMouseTracker.registerOnMousePressedEventHandler(mouseClickedEvent -> { if (isOnMouse.get()) { circle.centerXProperty().unbind(); circle.centerYProperty().unbind(); // Tell the canvas that the mouse is no longer occupied ModelCanvas.setLocationOnMouse(null); // Disable discarding functionality for a location when it is placed on the canvas KeyboardTracker.unregisterKeybind(KeyboardTracker.DISCARD_NEW_LOCATION); // Animate the way the location is placed on the canvas Animation locationPlaceAnimation = new Transition() { { setCycleDuration(Duration.millis(50)); } protected void interpolate(double frac) { Location.this.setEffect(DropShadowHelper.generateElevationShadow(12 - 12 * frac)); } }; // When the animation is done ensure that we note that we are no longer on the mouse locationPlaceAnimation.setOnFinished(event -> { isOnMouse.set(false); }); locationPlaceAnimation.play(); } }); // Make the location draggable (if shift is not pressed, and there is no edge currently being drawn) DragHelper.makeDraggable(this, (event) -> !event.isShiftDown() && !ModelCanvas.edgeIsBeingDrawn() && !this.equals(ModelCanvas.getLocationOnMouse()) && type.equals(Type.NORMAL)); // Draw a new edge from the location localMouseTracker.registerOnMousePressedEventHandler(event -> { if (event.isShiftDown() && !ModelCanvas.edgeIsBeingDrawn()) { final Edge edge = new Edge(this, canvasMouseTracker); addChildToParent(edge); } }); // Add keybind to discard the location if ESC is pressed KeyboardTracker.registerKeybind(KeyboardTracker.DISCARD_NEW_LOCATION, removeOnEscape); // Register toggle urgent and committed keybinds when the locations is hovered, and unregister them when we are not localMouseTracker.registerOnMouseEnteredEventHandler(event -> { KeyboardTracker.registerKeybind(KeyboardTracker.MAKE_LOCATION_URGENT, makeLocationUrgent); KeyboardTracker.registerKeybind(KeyboardTracker.MAKE_LOCATION_COMMITTED, makeLocationCommitted); }); localMouseTracker.registerOnMouseExitedEventHandler(event -> { KeyboardTracker.unregisterKeybind(KeyboardTracker.MAKE_LOCATION_URGENT); KeyboardTracker.unregisterKeybind(KeyboardTracker.MAKE_LOCATION_COMMITTED); }); } private final Keybind removeOnEscape = new Keybind(new KeyCodeCombination(KeyCode.ESCAPE), () -> { // Get the parent and detach this Location IParent parent = (IParent) this.getParent(); if (parent == null) return; parent.removeChild(this); // Notify the canvas that we are no longer placing a location ModelCanvas.setLocationOnMouse(null); }); private final Keybind makeLocationUrgent = new Keybind(new KeyCodeCombination(KeyCode.U), () -> { // The location cannot be committed isCommitted.set(false); // Toggle the urgent boolean isUrgent.set(!isUrgent.get()); }); private final Keybind makeLocationCommitted = new Keybind(new KeyCodeCombination(KeyCode.C), () -> { // The location cannot be committed isUrgent.set(false); // Toggle the urgent boolean isCommitted.set(!isCommitted.get()); }); private void addChildToParent(final Node child) { // Get the parent from the source location IParent parent = (IParent) this.getParent(); if (parent == null) return; parent.addChild(child); } @Override public MouseTracker getMouseTracker() { return this.localMouseTracker; } @Override public DoubleProperty xProperty() { return circle.centerXProperty(); } @Override public DoubleProperty yProperty() { return circle.centerYProperty(); } }
import java.util.*; public class MovementLogic { public static final int ROUTINE_A = 0; public static final int ROUTINE_B = 1; public static final int ROUTINE_C = 2; public static final int ROUTINE_D = 3; public static final int MAX_CHARACTERS = 20; private static final int MOVED_OK = 0; private static final int MOVE_FINISHED = 1; private static final int DIRECTION_BLOCKED = 2; private static final int MOVE_ERROR = 3; private static final int LOCATION_VISITED = 4; public MovementLogic (Map theMap, boolean debug) { _theMap = theMap; _robotTrack = new Trail(_theMap); _path = new Stack<String>(); _routeTaken = ""; _robotFacing = CellId.ROBOT_FACING_UP; _currentMoveDirection = ""; _currentPosition = new Coordinate(_theMap.findStartingPoint()); _debug = debug; } public void createMovementFunctions () { createPath(); /* * Now convert the path into a series of commands * such as L,4 or R,8. */ Vector<String> commands = getCommands(); /* * Now turn the series of commands into functions * A, B and C based on repeated commands. * * There are only 3 possible functions. * This means one function always starts at the beginning. * One function always ends at the ending (!) assuming it's not a repeat * of the first. * Then using both the first and the last fragment to find the third * and split the entire sequence into functions. */ } public void createMovementRoutine () { } private Vector<String> getCommands () { Vector<String> commands = new Vector<String>(_path.size()); String pathElement = null; /* * Pop the track to reverse it and get commands from the * starting position. */ do { try { pathElement = _path.pop(); String str = pathElement.charAt(0)+","+pathElement.length(); commands.add(str); } catch (Exception ex) { pathElement = null; } } while (pathElement != null); //if (_debug) { for (int i = commands.size() -1; i >= 0; i { System.out.println("Commands: "+commands.elementAt(i)); } } return commands; } /* * Create path using only L and R. */ private int createPath () { System.out.println("createPath from: "+_currentPosition); if (_currentPosition != null) { /* * Try L then R. * * Robot always starts facing up. Change facing when we * start to move but remember initial facing so we can * refer movement directions as L or R. */ if (tryToMove(CellId.MOVE_LEFT, leftCoordinate(_currentPosition)) != MOVE_FINISHED) { return tryToMove(CellId.MOVE_RIGHT, rightCoordinate(_currentPosition)); } else return MOVE_FINISHED; } else { System.out.println("Robot not found!"); return MOVE_ERROR; } } private int tryToMove (String direction, Coordinate coord) { System.out.println("tryMove: "+coord+" with direction: "+direction); System.out.println("and current position: "+_currentPosition); /* * Already visited? Might be sufficient to just check .path */ if (_robotTrack.visited(coord) && !_robotTrack.path(coord)) { System.out.println("Robot already visited this location."); return LOCATION_VISITED; } System.out.println("Location not visited ... yet."); if (_theMap.isScaffold(coord)) { System.out.println("Is scaffolding!"); _currentMoveDirection = direction; _routeTaken += _currentMoveDirection; _robotTrack.changeElement(coord, _currentMoveDirection); _currentPosition = coord; System.out.println("\n"+_robotTrack); } else { System.out.println("Not scaffolding!"); System.out.println("Robot was facing "+_robotFacing+" and moving "+direction); if (_theMap.theEnd(_currentPosition)) return MOVE_FINISHED; changeFacing(); System.out.println("Robot now facing "+_robotFacing); String nextDirection = getNextDirection(); System.out.println("Next direction to try with new facing: "+nextDirection); direction = nextDirection; } if (CellId.MOVE_LEFT.equals(direction)) coord = leftCoordinate(_currentPosition); else coord = rightCoordinate(_currentPosition); return tryToMove(direction, coord); } private String getNextDirection () { System.out.println("Getting next direction to move from: "+_currentPosition); Coordinate coord = leftCoordinate(_currentPosition); System.out.println("Left coordinate would be: "+coord); if (_robotTrack.visited(coord) || !_robotTrack.isScaffold(coord)) { System.out.println("Visited so try right ..."); coord = rightCoordinate(_currentPosition); System.out.println("Right coordinate would be: "+coord); if (_robotTrack.visited(coord)) return null; else return CellId.MOVE_RIGHT; } else { System.out.println("Not visited."); return CellId.MOVE_LEFT; } } private void changeFacing () { _path.push(_routeTaken); System.out.println("Pushing: "+_routeTaken); _routeTaken = ""; switch (_robotFacing) { case CellId.ROBOT_FACING_UP: { if (_currentMoveDirection.equals(CellId.MOVE_LEFT)) _robotFacing = CellId.ROBOT_FACING_LEFT; else _robotFacing = CellId.ROBOT_FACING_RIGHT; } break; case CellId.ROBOT_FACING_DOWN: { if (_currentMoveDirection.equals(CellId.MOVE_LEFT)) _robotFacing = CellId.ROBOT_FACING_RIGHT; else _robotFacing = CellId.ROBOT_FACING_LEFT; } break; case CellId.ROBOT_FACING_LEFT: { if (_currentMoveDirection.equals(CellId.MOVE_LEFT)) _robotFacing = CellId.ROBOT_FACING_DOWN; else _robotFacing = CellId.ROBOT_FACING_UP; } break; case CellId.ROBOT_FACING_RIGHT: default: { if (_currentMoveDirection.equals(CellId.MOVE_LEFT)) _robotFacing = CellId.ROBOT_FACING_UP; else _robotFacing = CellId.ROBOT_FACING_DOWN; } break; } } /* * Map/Trail can deal with invalid Coordinates. */ private final Coordinate rightCoordinate (Coordinate coord) { int x = coord.getX(); int y = coord.getY(); if (_debug) System.out.println("rightCoordinate facing: "+_robotFacing+" and position: "+coord); switch (_robotFacing) { case CellId.ROBOT_FACING_DOWN: { x } break; case CellId.ROBOT_FACING_UP: { x++; } break; case CellId.ROBOT_FACING_LEFT: { y } break; case CellId.ROBOT_FACING_RIGHT: default: { y++; } break; } return new Coordinate(x, y); } private final Coordinate leftCoordinate (Coordinate coord) { int x = coord.getX(); int y = coord.getY(); if (_debug) System.out.println("leftCoordinate facing: "+_robotFacing+" and position: "+coord); switch (_robotFacing) { case CellId.ROBOT_FACING_DOWN: { x++; } break; case CellId.ROBOT_FACING_UP: { x } break; case CellId.ROBOT_FACING_LEFT: { y++; } break; case CellId.ROBOT_FACING_RIGHT: default: { y } break; } return new Coordinate(x, y); } private Map _theMap; private Trail _robotTrack; private Stack<String> _path; private String _routeTaken; private String _robotFacing; private String _currentMoveDirection; private Coordinate _currentPosition; private boolean _debug; }
package org.orienteer.core.loader.util.metadata; import com.google.common.base.Optional; import com.google.common.collect.Lists; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.artifact.DefaultArtifact; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.XMLEvent; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.util.Iterator; import java.util.List; import static org.orienteer.core.loader.util.metadata.MetadataUtil.*; /** * @author Vitaliy Gonchar */ class OModuleReader { private final Path pathToMetadataXml; private final XMLEventReader xmlReader; private final boolean trusted; private final boolean load; private final boolean allModules; private static final Logger LOG = LoggerFactory.getLogger(OModuleReader.class); private OModuleReader(OModuleReaderBuilder builder) { this.pathToMetadataXml = builder.pathToMetadataXml; this.xmlReader = builder.xmlReader; this.trusted = builder.trusted; this.load = builder.load; this.allModules = builder.allModules; } public static class OModuleReaderBuilder { private final Path pathToMetadataXml; private XMLEventReader xmlReader = null; private boolean trusted = true; private boolean load = true; private boolean allModules = false; public OModuleReaderBuilder(Path pathToMetadataXml) { this.pathToMetadataXml = pathToMetadataXml; } public OModuleReader build() { try { xmlReader = getReader(); return new OModuleReader(this); } catch (NoSuchFileException ex) { LOG.warn("Cannot open file. File does not exists! File: " + pathToMetadataXml.toAbsolutePath()); } catch (XMLStreamException | IOException e) { LOG.error("Cannot open file to read: " + pathToMetadataXml); if (LOG.isDebugEnabled()) e.printStackTrace(); } return null; } public OModuleReaderBuilder setTrusted(boolean trusted) { this.trusted = trusted; return this; } public OModuleReaderBuilder setLoad(boolean load) { this.load = load; return this; } public OModuleReaderBuilder setAllModules(boolean allModules) { this.allModules = allModules; return this; } private XMLEventReader getReader() throws XMLStreamException, IOException { XMLInputFactory factory = XMLInputFactory.newFactory(); InputStream in = Files.newInputStream(pathToMetadataXml); XMLEventReader reader = factory.createXMLEventReader(in); return reader; } } public List<OModuleMetadata> read() { List<OModuleMetadata> metadata = Lists.newArrayList(); try { if (allModules) { metadata = readAllModules(); } else metadata = readLoadedModules(load); // if (allModules && trusted) { // metadata = readTrustedModules(); // } else if (allModules && load) { // metadata = readLoadedModules(); // } else if (allModules) { // metadata = readAllModules(); // else if (load && trusted) { // } else if (load && !trusted) { // } else if (!load && trusted) { // } else if (!load && !trusted) { } catch (XMLStreamException ex) { LOG.error("Cannot read file: " + pathToMetadataXml.toAbsolutePath()); if (LOG.isDebugEnabled()) ex.printStackTrace(); } return metadata; } private List<OModuleMetadata> readAllModules() throws XMLStreamException { List<OModuleMetadata> metadata = Lists.newArrayList(); while (xmlReader.hasNext()) { XMLEvent xmlEvent = xmlReader.nextEvent(); if (xmlEvent.isStartElement()) { String tag = xmlEvent.asStartElement().getName().toString(); if (tag.equals(MODULE)) { metadata.add(getModuleMetadata()); } } } return metadata; } private List<OModuleMetadata> readTrustedModules() throws XMLStreamException { List<OModuleMetadata> metadata = readAllModules(); Iterator<OModuleMetadata> iterator = metadata.iterator(); while (iterator.hasNext()) { OModuleMetadata module = iterator.next(); if (!module.isTrusted()) { iterator.remove(); } } return metadata; } private List<OModuleMetadata> readLoadedModules(boolean load) throws XMLStreamException { List<OModuleMetadata> metadata = readAllModules(); Iterator<OModuleMetadata> iterator = metadata.iterator(); while (iterator.hasNext()) { OModuleMetadata module = iterator.next(); if (module.isLoad() != load) { iterator.remove(); } } return metadata; } public Optional<OModuleMetadata> getModule(int id) throws XMLStreamException { List<OModuleMetadata> metadata = readAllModules(); for (OModuleMetadata module : metadata) { if (module.getId() == id) { return Optional.of(module); } } return Optional.absent(); } public Optional<OModuleMetadata> getModule(String initializer) throws XMLStreamException { if (initializer == null) return null; List<OModuleMetadata> metadata = readAllModules(); for (OModuleMetadata module : metadata) { if (module.getInitializerName().equals(initializer)) { return Optional.of(module); } } return Optional.absent(); } public Optional<OModuleMetadata> getModule(String groupId, String artifactId, String versionId) throws XMLStreamException { List<OModuleMetadata> metadata = readAllModules(); for (OModuleMetadata module : metadata) { Artifact artifact = module.getMainArtifact(); if (artifact.getGroupId().equals(groupId) && artifact.getArtifactId().equals(artifactId) && artifact.getVersion().equals(versionId)) { return Optional.of(module); } } return Optional.absent(); } private OModuleMetadata getModuleMetadata() throws XMLStreamException { OModuleMetadata moduleMetadata = new OModuleMetadata(); String groupId = null; String artifactId = null; String version = null; String file = null; while (xmlReader.hasNext()) { XMLEvent xmlEvent = xmlReader.nextEvent(); if (xmlEvent.isStartElement()) { String tag = xmlEvent.asStartElement().getName().toString(); switch (tag) { case ID: moduleMetadata.setId(Integer.parseInt(xmlReader.getElementText())); break; case INITIALIZER: moduleMetadata.setInitializerName(xmlReader.getElementText()); break; case TRUSTED: String trusted = xmlReader.getElementText(); moduleMetadata.setTrusted(Boolean.parseBoolean(trusted)); break; case LOAD: String load = xmlReader.getElementText(); moduleMetadata.setLoad(Boolean.parseBoolean(load)); break; case GROUP_ID: groupId = xmlReader.getElementText(); break; case ARTIFACT_ID: artifactId = xmlReader.getElementText(); break; case VERSION: version = xmlReader.getElementText(); break; case JAR: file = xmlReader.getElementText(); break; case DEPENDENCIES: moduleMetadata.setDependencies(getDependencies()); break; } } else if (xmlEvent.isEndElement() && xmlEvent.asEndElement().getName().toString().equals(MODULE)) { break; } } moduleMetadata.setMainArtifact(getArtifact(groupId, artifactId, version, file)); return moduleMetadata; } private List<Artifact> getDependencies() throws XMLStreamException { List<Artifact> dependencies = Lists.newArrayList(); String file = null; String groupId = null; String artifactId = null; String versionId = null; boolean depStart = false; boolean run = true; while (xmlReader.hasNext() && run) { XMLEvent xmlEvent = xmlReader.nextEvent(); if (xmlEvent.isStartElement()) { String tag = xmlEvent.asStartElement().getName().toString(); switch (tag) { case GROUP_ID: groupId = xmlReader.getElementText(); break; case ARTIFACT_ID: artifactId = xmlReader.getElementText(); break; case VERSION: versionId = xmlReader.getElementText(); break; case JAR: file = xmlReader.getElementText(); break; case DEPENDENCY: depStart = true; break; } } else if (xmlEvent.isEndElement()) { String tag = xmlEvent.asEndElement().getName().toString(); switch (tag) { case DEPENDENCY: depStart = false; break; case DEPENDENCIES: run = false; break; } } if (!depStart && groupId != null && artifactId != null && versionId != null) { dependencies.add(getArtifact(groupId, artifactId, versionId, file)); groupId = null; artifactId = null; versionId = null; file = null; } } return dependencies; } private Artifact getArtifact(String groupId, String artifactId, String version, String file) { Artifact artifact = new DefaultArtifact( String.format("%s:%s:%s", groupId, artifactId, version)); if (file != null) artifact = artifact.setFile(new File(file)); return artifact; } }
package org.sourcepit.osgify.core.bundle; import java.util.List; public class PackageResolutionResult { private String requiredPackage; private PackageExportDescription selectedExporter; private AccessRestriction accessRestriction; private List<PackageExportDescription> exporters; public PackageResolutionResult(String requiredPackage, PackageExportDescription selectedExporter, AccessRestriction accessRestriction, List<PackageExportDescription> exporters) { this.requiredPackage = requiredPackage; this.selectedExporter = selectedExporter; this.accessRestriction = accessRestriction; this.exporters = exporters; } public String getRequiredPackage() { return requiredPackage; } public PackageExportDescription getSelectedExporter() { return selectedExporter; } public AccessRestriction getAccessRestriction() { return accessRestriction; } public List<PackageExportDescription> getExporters() { return exporters; } }
package com.qpark.maven.plugin.flowmapper; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.slf4j.impl.StaticLoggerBinder; import com.qpark.maven.Util; import com.qpark.maven.xmlbeans.ComplexType; import com.qpark.maven.xmlbeans.ComplexTypeChild; import com.qpark.maven.xmlbeans.ServiceIdRegistry; import com.qpark.maven.xmlbeans.XsdsUtil; /** * This goal generates Flow and mapping interfaces as well as implementations of * direct mappers. * * @author bhausen */ @Mojo(name = "generate-flow-mapper", defaultPhase = LifecyclePhase.PROCESS_SOURCES) public class GeneratorMapperMojo extends AbstractMojo { public static List<ComplexTypeChild> getValidChildren( final ComplexType complexType) { List<ComplexTypeChild> list = new ArrayList<ComplexTypeChild>( complexType.getChildren().size()); for (ComplexTypeChild child : complexType.getChildren()) { if (!child.getComplexType().isSimpleType() // && !child.getComplexType().isAbstractType() ) { if (child.getComplexType().getType().getName().getLocalPart() .equals("NoMappingType")) { /* not to add. */ } else if (child.getChildName().equals("return")) { /* not to add. */ } else if (child.getComplexType().getType().getName() .getLocalPart().equals("anyType")) { /* not to add. */ } else { list.add(child); } } } return list; } /** The base directory where to start the scan of xsd files. */ @Parameter(property = "baseDirectory", defaultValue = "${project.build.directory}/model") private File baseDirectory; /** The base package name where to place the mappings factories. */ @Parameter(property = "basePackageName", defaultValue = "") private String basePackageName; /** The name of the interface id to generate. If empty use all. */ @Parameter(property = "interfaceId", defaultValue = "") private String interfaceId; /** * The package names of the mappings should end with - separation by space. * Default is <code>mapping</code>. */ @Parameter(property = "mappingPackageNameSuffixes", defaultValue = "map svc flow") protected String mappingPackageNameSuffixes; /** * The service request name need to end with this suffix (Default * <code>Request</code>). */ @Parameter(property = "mappingRequestSuffix", defaultValue = "Request") private String mappingRequestSuffix; /** * The service response name need to end with this suffix (Default * <code>Response</code>). */ @Parameter(property = "mappingResponseSuffix", defaultValue = "Response") private String mappingResponseSuffix; /** * The directory where to put the prepared implementation source of the * classes. */ @Parameter(property = "outputClassesDirectory", defaultValue = "${project.build.directory}/prepared-sources") private File outputClassesDirectory; /** The directory where to put the generated interfaces. */ @Parameter(property = "outputInterfacesDirectory", defaultValue = "${project.build.directory}/generated-sources") private File outputInterfacesDirectory; @Component protected MavenProject project; /** * @see org.apache.maven.plugin.Mojo#execute() */ @Override public void execute() throws MojoExecutionException, MojoFailureException { StaticLoggerBinder.getSingleton().setLog(this.getLog()); this.getLog().debug("+execute"); this.getLog().debug("get xsds"); XsdsUtil config = new XsdsUtil(this.baseDirectory, this.basePackageName, this.mappingPackageNameSuffixes, null, this.mappingRequestSuffix, this.mappingResponseSuffix); String eipVersion = null; if (this.project.getArtifact() != null) { eipVersion = this.project.getArtifact().getVersion(); } ComplexContentList complexContentList = new ComplexContentList(); complexContentList.setupComplexContentLists(config); Collection<String> interfaceIds = this.getInterfaceIds(config); String basicPackageName = null; for (ComplexType ct : config.getComplexTypes()) { if (ct.getPackageName().contains(".inf.")) { basicPackageName = ct.getPackageName().substring(0, ct.getPackageName().indexOf(".inf.") + 4); break; } } int flows = 0; int directMappers = 0; int defaultMappers = 0; int complexUUIDMappers = 0; int complexMappers = 0; int tabularMappers = 0; int interfaceMappers = 0; int mappingOperations = 0; if (basicPackageName != null) { this.generateBasicFlowInterface(basicPackageName); for (ComplexType ct : config.getComplexTypes()) { if (ct.isFlowInputType()) { FlowInterfaceGenerator fig = new FlowInterfaceGenerator( config, ct, this.getLog()); fig.generateInterface(this.outputInterfacesDirectory, basicPackageName); flows++; } } this.generateReferenceDataTypeProvider(config, basicPackageName); List<String> errorMessages = new ArrayList<String>(); List<AbstractGenerator> generators = new ArrayList<AbstractGenerator>(); for (ComplexContent cc : complexContentList.getDirectMappings()) { try { DirectMappingTypeGenerator mtg = new DirectMappingTypeGenerator( config, basicPackageName, cc, complexContentList, eipVersion, this.outputInterfacesDirectory, this.outputClassesDirectory, this.getLog()); mtg.generateInterface(); if (!cc.ct.toQNameString().startsWith( "{http: generators.add(mtg); directMappers++; } } catch (Exception e) { errorMessages.add(e.getMessage()); } } for (ComplexContent cc : complexContentList.getDefaultMappings()) { try { DefaultMappingTypeGenerator mtg = new DefaultMappingTypeGenerator( config, basicPackageName, cc, complexContentList, eipVersion, this.outputInterfacesDirectory, this.outputClassesDirectory, this.getLog()); mtg.generateInterface(); generators.add(mtg); defaultMappers++; } catch (IllegalStateException e) { errorMessages.add(e.getMessage()); } } for (ComplexContent cc : complexContentList .getComplexUUIDMappings()) { try { ComplexUUIDReferenceDataMappingTypeGenerator mtg = new ComplexUUIDReferenceDataMappingTypeGenerator( config, basicPackageName, cc, complexContentList, eipVersion, this.outputInterfacesDirectory, this.outputClassesDirectory, this.getLog()); mtg.generateInterface(); generators.add(mtg); complexUUIDMappers++; } catch (Exception e) { errorMessages.add(e.getMessage()); } } for (ComplexContent cc : complexContentList.getComplexMappings()) { try { ComplexMappingTypeGenerator mtg = new ComplexMappingTypeGenerator( config, basicPackageName, cc, complexContentList, eipVersion, this.outputInterfacesDirectory, this.outputClassesDirectory, this.getLog()); mtg.generateInterface(); generators.add(mtg); complexMappers++; } catch (Exception e) { errorMessages.add(e.getMessage()); } } for (ComplexContent cc : complexContentList.getTabularMappings()) { try { TabularMappingTypeGenerator mtg = new TabularMappingTypeGenerator( config, basicPackageName, cc, complexContentList, eipVersion, this.outputInterfacesDirectory, this.outputClassesDirectory, this.getLog()); mtg.generateInterface(); generators.add(mtg); tabularMappers++; } catch (Exception e) { errorMessages.add(e.getMessage()); } } for (ComplexContent cc : complexContentList.getInterfaceTypes()) { InterfaceMappingTypeGenerator mtg = new InterfaceMappingTypeGenerator( config, basicPackageName, cc, complexContentList, eipVersion, this.outputInterfacesDirectory, this.outputClassesDirectory, this.getLog()); mtg.generateInterface(); generators.add(mtg); interfaceMappers++; } for (ComplexRequestResponse crr : complexContentList .getRequestResponses()) { MappingOperationGenerator mog = new MappingOperationGenerator( config, basicPackageName, crr, complexContentList, eipVersion, this.outputInterfacesDirectory, this.outputClassesDirectory, this.getLog()); mog.generateInterface(); generators.add(mog); mappingOperations++; } for (AbstractGenerator gen : generators) { try { gen.generateImpl(); } catch (Exception e) { errorMessages.add(e.getMessage()); } } for (String errorMessage : errorMessages) { this.getLog().error(errorMessage); } } this.getLog().info(String.format("%-40s:%4i", "Namespaces", config.getXsdContainerMap().size())); this.getLog().info(String.format("%-40s:%4i", "ComplexTypes", config.getComplexTypes().size())); this.getLog().info(String.format("%-40s:%4i", "ElementTypes", config.getElementTypes().size())); this.getLog() .info(String.format("%-40s:%4i", "Generated flows", flows)); this.getLog().info(String.format("%-40s:%4i", "Generated direct mappers", directMappers)); this.getLog().info(String.format("%-40s:%4i", "Generated default mappers", defaultMappers)); this.getLog().info(String.format("%-40s:%4i", "Generated complex UUID mappers", complexUUIDMappers)); this.getLog().info(String.format("%-40s:%4i", "Generated complex mappers", complexMappers)); this.getLog().info(String.format("%-40s:%4i", "Generated tabular mappers", tabularMappers)); this.getLog().info(String.format("%-40s:%4i", "Generated interface mappers", interfaceMappers)); this.getLog().info(String.format("%-40s:%4i", "Generated mapping operations", mappingOperations)); this.getLog().debug("-execute"); } private void generateBasicFlowInterface(final String basicPackageName) { StringBuffer sb = new StringBuffer(); sb.append("package "); sb.append(basicPackageName); sb.append(";\n"); sb.append("\n"); sb.append("/**\n"); sb.append(" * Basic flow interface.\n"); sb.append(" * @author bhausen\n"); sb.append(" */\n"); sb.append("public interface Flow<Request, Response> {\n"); sb.append("\t/**\n"); sb.append( "\t * Invoke the flow. This calls executeRequest and processResponse.\n"); sb.append("\t * @param request the {@link Request}\n"); sb.append("\t * @param flowContext the {@link FlowContext}\n"); sb.append("\t * @return the {@link Response}\n"); sb.append("\t */\n"); sb.append( "\tResponse invokeFlow(Request request, FlowContext flowContext);\n"); sb.append("}\n"); sb.append("\n"); File f = Util.getFile(this.outputInterfacesDirectory, basicPackageName, "Flow.java"); this.getLog().info(new StringBuffer().append("Write ") .append(f.getAbsolutePath())); try { Util.writeToFile(f, sb.toString()); } catch (Exception e) { this.getLog().error(e.getMessage()); e.printStackTrace(); } sb.setLength(0); sb.append("package "); sb.append(basicPackageName); sb.append(";\n"); sb.append("\n"); sb.append("/**\n"); sb.append(" * Basic flow gateway interface.\n"); sb.append(" * @author bhausen\n"); sb.append(" */\n"); sb.append("public interface FlowGateway {\n"); sb.append("}\n"); sb.append("\n"); f = Util.getFile(this.outputInterfacesDirectory, basicPackageName, "FlowGateway.java"); this.getLog().info(new StringBuffer().append("Write ") .append(f.getAbsolutePath())); try { Util.writeToFile(f, sb.toString()); } catch (Exception e) { this.getLog().error(e.getMessage()); e.printStackTrace(); } sb.setLength(0); sb.append("package "); sb.append(basicPackageName); sb.append(";\n"); sb.append("\n"); sb.append("/**\n"); sb.append( " * The flow context containing the requester user name, service name and version\n"); sb.append(" * and the operation name.\n"); sb.append(" * \n"); sb.append(" * @author bhausen\n"); sb.append(" */\n"); sb.append("public interface FlowContext {\n"); sb.append("\t/**\n"); sb.append("\t * Get the operation name of the flow requester.\n"); sb.append("\t *\n"); sb.append("\t * @return the operation name of the flow requester.\n"); sb.append("\t */\n"); sb.append("\tString getRequesterOperationName();\n"); sb.append("\n"); sb.append("\t/**\n"); sb.append("\t * Get the service name of the flow requester.\n"); sb.append("\t *\n"); sb.append("\t * @return the service name of the flow requester.\n"); sb.append("\t */\n"); sb.append("\tString getRequesterServiceName();\n"); sb.append("\n"); sb.append("\t/**\n"); sb.append("\t * Get the service version of the flow requester.\n"); sb.append("\t *\n"); sb.append("\t * @return the service version of the flow requester.\n"); sb.append("\t */\n"); sb.append("\tString getRequesterServiceVersion();\n"); sb.append("\n"); sb.append("\t/**\n"); sb.append("\t * Get the user name of the flow requester.\n"); sb.append("\t *\n"); sb.append("\t * @return the user name of the flow requester.\n"); sb.append("\t */\n"); sb.append("\tString getRequesterUserName();\n"); sb.append("\n"); sb.append("\t/**\n"); sb.append("\t * Get the session id.\n"); sb.append("\t *\n"); sb.append("\t * @return the session id.\n"); sb.append("\t */\n"); sb.append("\tString getSessionId();\n"); sb.append("\n"); sb.append("\t/**\n"); sb.append("\t * Set the operation name of the flow requester.\n"); sb.append("\t *\n"); sb.append("\t * @param requesterOperationName\n"); sb.append( "\t * the operation name of the flow requester.\n"); sb.append("\t */\n"); sb.append( "\tvoid setRequesterOperationName(String requesterOperationName);\n"); sb.append("\n"); sb.append("\t/**\n"); sb.append("\t * Set the service name of the flow requester.\n"); sb.append("\t *\n"); sb.append("\t * @param requesterServiceName\n"); sb.append("\t * the service name of the flow requester.\n"); sb.append("\t */\n"); sb.append( "\tvoid setRequesterServiceName(String requesterServiceName);\n"); sb.append("\n"); sb.append("\t/**\n"); sb.append("\t * Set the service version of the flow requester.\n"); sb.append("\t *\n"); sb.append("\t * @param requesterServiceVersion\n"); sb.append( "\t * the service version of the flow requester.\n"); sb.append("\t */\n"); sb.append( "\tvoid setRequesterServiceVersion(String requesterServiceVersion);\n"); sb.append("\n"); sb.append("\t/**\n"); sb.append("\t * Set the user name of the flow requester.\n"); sb.append("\t *\n"); sb.append("\t * @param requesterUserName\n"); sb.append("\t * the user name of the flow requester.\n"); sb.append("\t */\n"); sb.append("\tvoid setRequesterUserName(String requesterUserName);\n"); sb.append("\n"); sb.append("\t/**\n"); sb.append("\t * Set the session id.\n"); sb.append("\t *\n"); sb.append("\t * @param sessionId\n"); sb.append("\t * the session id.\n"); sb.append("\t */\n"); sb.append("\tvoid setSessionId(String sessionId);\n"); sb.append("\n"); sb.append("}\n"); f = Util.getFile(this.outputInterfacesDirectory, basicPackageName, "FlowContext.java"); this.getLog().info(new StringBuffer().append("Write ") .append(f.getAbsolutePath())); try { Util.writeToFile(f, sb.toString()); } catch (Exception e) { this.getLog().error(e.getMessage()); e.printStackTrace(); } } private void generateReferenceDataTypeProvider(final XsdsUtil config, final String basicPackageName) { ComplexType referenceDataType = null; for (ComplexType ct : config.getComplexTypes()) { if (ct.getClassNameFullQualified().contains("ReferenceDataType") && ct.getClassNameFullQualified().contains("common")) { referenceDataType = ct; break; } } if (referenceDataType != null) { StringBuffer sb = new StringBuffer(256); sb.append("package "); sb.append(basicPackageName); sb.append(";\n"); sb.append("\n"); sb.append("import java.util.List;\n"); sb.append("\n"); sb.append("import "); sb.append(referenceDataType.getClassNameFullQualified()); sb.append(";\n"); sb.append("\n"); sb.append("/**\n"); sb.append(" * Provides {@link "); sb.append(referenceDataType.getClassName()); sb.append("}s to the flows.\n"); sb.append(" * @author bhausen\n"); sb.append(" */\n"); sb.append("public interface ReferenceDataProvider {\n"); sb.append("\t/**\n"); sb.append("\t * Get the list of all <i>active</i> {@link "); sb.append(referenceDataType.getClassName()); sb.append("}s.\n"); sb.append("\t * @param userName the user name.\n"); sb.append("\t * @return the list of all <i>active</i> {@link "); sb.append(referenceDataType.getClassName()); sb.append("}s.\n"); sb.append("\t */\n"); sb.append("\tList<"); sb.append(referenceDataType.getClassName()); sb.append("> getReferenceData(String userName);\n"); sb.append("\n"); sb.append("\t/**\n"); sb.append("\t * Get the list of <i>active</i> {@link "); sb.append(referenceDataType.getClassName()); sb.append("}s of a specific\n"); sb.append("\t * category.\n"); sb.append("\t * @param category the name of the category.\n"); sb.append("\t * @param userName the user name.\n"); sb.append("\t * @return the list of <i>active</i> {@link "); sb.append(referenceDataType.getClassName()); sb.append("}s.\n"); sb.append("\t */\n"); sb.append("\tList<"); sb.append(referenceDataType.getClassName()); sb.append("> getReferenceDataByCategory(final String category,\n"); sb.append("\t\t\tString userName);\n"); sb.append("\n"); sb.append("\t/**\n"); sb.append("\t * Get the <i>active</i> {@link "); sb.append(referenceDataType.getClassName()); sb.append("}s of a specific\n"); sb.append("\t * referenceData UUID.\n"); sb.append("\t * @param uuid the UUID of the {@link "); sb.append(referenceDataType.getClassName()); sb.append("}.\n"); sb.append("\t * @param userName the user name.\n"); sb.append("\t * @return the <i>active</i> {@link "); sb.append(referenceDataType.getClassName()); sb.append("} or <code>null</code>.\n"); sb.append("\t */\n"); sb.append("\t"); sb.append(referenceDataType.getClassName()); sb.append( " getReferenceDataById(final String uuid, String userName);\n"); sb.append("}\n"); sb.append("\n"); File f = Util.getFile(this.outputInterfacesDirectory, basicPackageName, "ReferenceDataProvider.java"); this.getLog().info(new StringBuffer().append("Write ") .append(f.getAbsolutePath())); try { Util.writeToFile(f, sb.toString()); } catch (Exception e) { this.getLog().error(e.getMessage()); e.printStackTrace(); } } } private Collection<String> getInterfaceIds(final XsdsUtil config) { Collection<String> interfaceIds = ServiceIdRegistry .splitServiceIds(this.interfaceId); if (interfaceIds.size() == 0) { interfaceIds.addAll(ServiceIdRegistry.getAllServiceIds()); } interfaceIds.add("core"); return interfaceIds; } }
package atg.tools.ant.types; import org.apache.tools.ant.types.resources.FileResource; import java.io.File; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author msicker * @version 2.0 */ public class AtgInstallation extends FileResource { private final Map<String, Module> modules = new ConcurrentHashMap<String, Module>(); /** * Sets the base ATG installation directory. For example, one might have ATG installed in * {@code $HOME/ATG/ATG11.0}, so you would use the following: * <pre> * {@code <atg:atg id="atg.installation" home="${user.home}/ATG/ATG11.0"/>} * </pre> * * @param home * directory where ATG is installed. */ public void setHome(final File home) { setFile(home); } public File getHome() { return getFile(); } protected Module getModule(final String name) { final Module cached = modules.get(name); if (cached != null) { return cached; } final Module module = new Module(); module.setAtg(this); module.setModule(name); modules.put(name, module); return module; } }
package com.chiralbehaviors.CoRE.phantasm.graphql; import static com.chiralbehaviors.CoRE.phantasm.model.PhantasmTraversal.toTypeName; import static graphql.Scalars.GraphQLBoolean; import static graphql.Scalars.GraphQLFloat; import static graphql.Scalars.GraphQLInt; import static graphql.Scalars.GraphQLString; import static graphql.schema.GraphQLArgument.newArgument; import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition; import static graphql.schema.GraphQLInputObjectField.newInputObjectField; import static graphql.schema.GraphQLInputObjectType.newInputObject; import static graphql.schema.GraphQLObjectType.newObject; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.chiralbehaviors.CoRE.ExistentialRuleform; import com.chiralbehaviors.CoRE.attribute.Attribute; import com.chiralbehaviors.CoRE.attribute.AttributeAuthorization; import com.chiralbehaviors.CoRE.attribute.ValueType; import com.chiralbehaviors.CoRE.kernel.phantasm.product.Constructor; import com.chiralbehaviors.CoRE.kernel.phantasm.product.InstanceMethod; import com.chiralbehaviors.CoRE.kernel.phantasm.product.Plugin; import com.chiralbehaviors.CoRE.meta.Model; import com.chiralbehaviors.CoRE.meta.NetworkedModel; import com.chiralbehaviors.CoRE.network.NetworkAuthorization; import com.chiralbehaviors.CoRE.network.NetworkRuleform; import com.chiralbehaviors.CoRE.network.XDomainNetworkAuthorization; import com.chiralbehaviors.CoRE.phantasm.Phantasm; import com.chiralbehaviors.CoRE.phantasm.model.PhantasmCRUD; import com.chiralbehaviors.CoRE.phantasm.model.PhantasmTraversal; import com.chiralbehaviors.CoRE.relationship.Relationship; import com.fasterxml.jackson.databind.ObjectMapper; import graphql.Scalars; import graphql.schema.DataFetchingEnvironment; import graphql.schema.GraphQLArgument; import graphql.schema.GraphQLFieldDefinition; import graphql.schema.GraphQLInputObjectField; import graphql.schema.GraphQLInputType; import graphql.schema.GraphQLList; import graphql.schema.GraphQLNonNull; import graphql.schema.GraphQLObjectType; import graphql.schema.GraphQLObjectType.Builder; import graphql.schema.GraphQLOutputType; import graphql.schema.GraphQLTypeReference; /** * Cannonical tranform of Phantasm metadata into GraphQL metadata. Provides * framework for Phantasm Plugin model; * * @author hhildebrand * */ public class FacetType<RuleForm extends ExistentialRuleform<RuleForm, Network>, Network extends NetworkRuleform<RuleForm>> implements PhantasmTraversal.PhantasmVisitor<RuleForm, Network> { private static final String ADD_TEMPLATE = "add%s"; private static final String APPLY_MUTATION = "Apply%s"; private static final String AT_RULEFORM = "@ruleform"; private static final String CREATE_INSTANCES_MUTATION = "CreateInstancesOf%s"; private static final String CREATE_MUTATION = "Create%s"; private static final String CREATE_TYPE = "%sCreate"; private static final String DESCRIPTION = "description"; private static final String ID = "id"; private static final String IMMEDIATE_TEMPLATE = "immediate%s"; private static final String INSTANCES_OF_QUERY = "InstancesOf%s"; private static final Logger log = LoggerFactory.getLogger(FacetType.class); private static final String NAME = "name"; private static final String REMOVE_MUTATION = "Remove%s"; private static final String REMOVE_TEMPLATE = "remove%s"; private static final String S_S_PLUGIN_CONVENTION = "%s.%s_Plugin"; private static final String SET_DESCRIPTION; private static final String SET_INDEX_TEMPLATE = "set%sIndex"; private static final String SET_KEY_TEMPLATE = "set%sKey"; private static final String SET_NAME; private static final String SET_TEMPLATE = "set%s"; private static final String STATE = "state"; private static final String UPDATE_INSTANCES_MUTATION = "UpdateInstancesOf%s"; private static final String UPDATE_MUTATION = "Update%s"; private static final String UPDATE_TYPE = "%sUpdate"; static { SET_NAME = String.format(SET_TEMPLATE, capitalized(NAME)); SET_DESCRIPTION = String.format(SET_TEMPLATE, capitalized(DESCRIPTION)); } public static Object invoke(Method method, DataFetchingEnvironment env) { try { return method.invoke(null, env); } catch (IllegalAccessException | IllegalArgumentException e) { throw new IllegalStateException(e); } catch (InvocationTargetException e) { throw new IllegalStateException(e.getTargetException()); } } public static Object invoke(Method method, DataFetchingEnvironment env, Model model, @SuppressWarnings("rawtypes") Phantasm instance) { try { return method.invoke(null, env, model, instance); } catch (InvocationTargetException e) { log.error("error invoking {} plugin {}", instance.toString(), method.toGenericString(), e.getTargetException()); return null; } catch (Throwable e) { log.error("error invoking {} plugin {}", instance.toString(), method.toGenericString(), e); return null; } } private static String capitalized(String field) { char[] chars = field.toCharArray(); chars[0] = Character.toUpperCase(chars[0]); return new String(chars); } private List<BiFunction<DataFetchingEnvironment, RuleForm, Object>> constructors = new ArrayList<>(); private graphql.schema.GraphQLInputObjectType.Builder createTypeBuilder; private String name; private Set<NetworkAuthorization<?>> references = new HashSet<>(); private Builder typeBuilder; private Map<String, BiFunction<PhantasmCRUD<RuleForm, Network>, Map<String, Object>, RuleForm>> updateTemplate = new HashMap<>(); private graphql.schema.GraphQLInputObjectType.Builder updateTypeBuilder; public FacetType(NetworkAuthorization<RuleForm> facet) { this.name = toTypeName(facet.getName()); typeBuilder = newObject().name(getName()) .description(facet.getNotes()); updateTypeBuilder = newInputObject().name(String.format(UPDATE_TYPE, getName())) .description(facet.getNotes()); createTypeBuilder = newInputObject().name(String.format(CREATE_TYPE, getName())) .description(facet.getNotes()); } /** * Build the top level queries and mutations * * @param query * - top level query * @param mutation * - top level mutation * @param facet * @return the references this facet has to other facets. */ public Set<NetworkAuthorization<?>> build(Builder query, Builder mutation, NetworkAuthorization<?> facetUntyped, List<Plugin> plugins, Model model, Map<Plugin, ClassLoader> executionScopes) { @SuppressWarnings("unchecked") NetworkAuthorization<RuleForm> facet = (NetworkAuthorization<RuleForm>) facetUntyped; build(facet); new PhantasmTraversal<RuleForm, Network>(model).traverse(facet, this); addPlugins(facet, plugins, executionScopes); GraphQLObjectType type = typeBuilder.build(); query.field(instance(facet, type)); query.field(instances(facet)); mutation.field(createInstance(facet)); mutation.field(createInstances(facet)); mutation.field(apply(facet)); mutation.field(update(facet)); mutation.field(updateInstances(facet)); mutation.field(remove(facet)); Set<NetworkAuthorization<?>> referenced = references; clear(); return referenced; } @SuppressWarnings({ "unchecked", "rawtypes" }) public PhantasmCRUD<RuleForm, Network> ctx(DataFetchingEnvironment env) { return (PhantasmCRUD) env.getContext(); } public String getName() { return name; } public GraphQLTypeReference referenceToType(String typeName) { return new GraphQLTypeReference(toTypeName(typeName)); } public GraphQLTypeReference referenceToUpdateType(String typeName) { return new GraphQLTypeReference(String.format(UPDATE_TYPE, toTypeName(typeName))); } @Override public String toString() { return String.format("FacetType [name=%s]", getName()); } @SuppressWarnings("unchecked") @Override public void visit(NetworkAuthorization<RuleForm> facet, AttributeAuthorization<RuleForm, Network> auth, String fieldName) { Attribute attribute = auth.getAuthorizedAttribute(); GraphQLOutputType type = typeOf(attribute); typeBuilder.field(newFieldDefinition().type(type) .name(fieldName) .description(attribute.getDescription()) .dataFetcher(env -> { Object value = ctx(env).getAttributeValue(facet, (RuleForm) env.getSource(), auth); if (value == null) { return null; } switch (attribute.getValueType()) { case NUMERIC: // GraphQL does not have a NUMERIC return type, so convert to float - ugly return ((BigDecimal) value).floatValue(); case TIMESTAMP: case JSON: // GraphQL does not have a generic map or timestamp return type, so stringify it. try { return new ObjectMapper().writeValueAsString(value); } catch (Exception e) { throw new IllegalStateException("Unable to write json value", e); } default: return value; } }) .build()); String setter = String.format(SET_TEMPLATE, capitalized(fieldName)); GraphQLInputType inputType; Function<Object, Object> converter = attribute.getValueType() == ValueType.JSON ? object -> { try { return new ObjectMapper().readValue((String) object, Map.class); } catch (IOException e) { throw new IllegalStateException(String.format("Cannot deserialize %s", object), e); } } : object -> object; if (auth.getAuthorizedAttribute() .getIndexed()) { updateTemplate.put(setter, (crud, update) -> crud.setAttributeValue(facet, (RuleForm) update.get(AT_RULEFORM), auth, (List<Object>) update.get(setter))); inputType = new GraphQLList(GraphQLString); } else if (auth.getAuthorizedAttribute() .getKeyed()) { updateTemplate.put(setter, (crud, update) -> crud.setAttributeValue(facet, (RuleForm) update.get(AT_RULEFORM), auth, (Map<String, Object>) update.get(setter))); inputType = GraphQLString; } else { updateTemplate.put(setter, (crud, update) -> crud.setAttributeValue(facet, (RuleForm) update.get(AT_RULEFORM), auth, (Object) converter.apply(update.get(setter)))); inputType = GraphQLString; } GraphQLInputObjectField field = newInputObjectField().type(inputType) .name(setter) .description(auth.getNotes()) .build(); updateTypeBuilder.field(field); createTypeBuilder.field(field); } @SuppressWarnings("unchecked") @Override public void visitChildren(NetworkAuthorization<RuleForm> facet, NetworkAuthorization<RuleForm> auth, String fieldName, NetworkAuthorization<RuleForm> child, String singularFieldName) { GraphQLOutputType type = referenceToType(child.getName()); type = new GraphQLList(type); typeBuilder.field(newFieldDefinition().type(type) .name(fieldName) .dataFetcher(env -> ctx(env).getChildren(facet, (RuleForm) env.getSource(), auth)) .description(auth.getNotes()) .build()); typeBuilder.field(newFieldDefinition().type(type) .name(String.format(IMMEDIATE_TEMPLATE, capitalized(fieldName))) .dataFetcher(env -> ctx(env).getImmediateChildren(facet, (RuleForm) env.getSource(), auth)) .description(auth.getNotes()) .build()); setChildren(facet, auth, fieldName); addChild(facet, auth, singularFieldName); addChildren(facet, auth, fieldName); removeChild(facet, auth, singularFieldName); removeChildren(facet, auth, fieldName); references.add(child); } @SuppressWarnings("unchecked") @Override public void visitChildren(NetworkAuthorization<RuleForm> facet, XDomainNetworkAuthorization<?, ?> auth, String fieldName, NetworkAuthorization<?> child, String singularFieldName) { GraphQLList type = new GraphQLList(referenceToType(child.getName())); typeBuilder.field(newFieldDefinition().type(type) .name(fieldName) .description(auth.getNotes()) .dataFetcher(env -> ctx(env).getChildren(facet, (RuleForm) env.getSource(), auth)) .build()); setChildren(facet, auth, fieldName, child); addChild(facet, auth, child, singularFieldName); addChildren(facet, auth, fieldName, child); removeChild(facet, auth, child, singularFieldName); removeChildren(facet, auth, fieldName, child); references.add(child); } @SuppressWarnings("unchecked") @Override public void visitSingular(NetworkAuthorization<RuleForm> facet, NetworkAuthorization<RuleForm> auth, String fieldName, NetworkAuthorization<RuleForm> child) { GraphQLOutputType type = referenceToType(child.getName()); typeBuilder.field(newFieldDefinition().type(type) .name(fieldName) .dataFetcher(env -> ctx(env).getSingularChild(facet, (RuleForm) env.getSource(), auth)) .description(auth.getNotes()) .build()); String setter = String.format(SET_TEMPLATE, capitalized(fieldName)); GraphQLInputObjectField field = newInputObjectField().type(GraphQLString) .name(setter) .description(auth.getNotes()) .build(); updateTypeBuilder.field(field); createTypeBuilder.field(field); updateTemplate.put(setter, (crud, update) -> { String id = (String) update.get(setter); return crud.setSingularChild(facet, (RuleForm) update.get(AT_RULEFORM), auth, id == null ? null : (RuleForm) crud.lookup(auth, id)); }); references.add(child); } @SuppressWarnings("unchecked") @Override public void visitSingular(NetworkAuthorization<RuleForm> facet, XDomainNetworkAuthorization<?, ?> auth, String fieldName, NetworkAuthorization<?> child) { typeBuilder.field(newFieldDefinition().type(referenceToType(child.getName())) .name(fieldName) .description(auth.getNotes()) .dataFetcher(env -> ctx(env).getSingularChild(facet, (RuleForm) env.getSource(), auth)) .build()); String setter = String.format(SET_TEMPLATE, capitalized(fieldName)); GraphQLInputObjectField pointerField = newInputObjectField().type(GraphQLString) .name(setter) .description(auth.getNotes()) .build(); updateTypeBuilder.field(pointerField); createTypeBuilder.field(pointerField); updateTemplate.put(setter, (crud, update) -> crud.setSingularChild(facet, (RuleForm) update.get(AT_RULEFORM), auth, crud.lookup(child, (String) update.get(setter)))); references.add(child); } @SuppressWarnings("unchecked") private void addChild(NetworkAuthorization<RuleForm> facet, NetworkAuthorization<RuleForm> auth, String singularFieldName) { String add = String.format(ADD_TEMPLATE, capitalized(singularFieldName)); GraphQLInputObjectField field = newInputObjectField().type(GraphQLString) .name(add) .description(auth.getNotes()) .build(); updateTypeBuilder.field(field); createTypeBuilder.field(field); updateTemplate.put(add, (crud, update) -> crud.addChild(facet, (RuleForm) update.get(AT_RULEFORM), auth, (RuleForm) crud.lookup(auth, (String) update.get(add)))); } @SuppressWarnings("unchecked") private void addChild(NetworkAuthorization<RuleForm> facet, XDomainNetworkAuthorization<?, ?> auth, NetworkAuthorization<?> child, String singularFieldName) { String add = String.format(ADD_TEMPLATE, capitalized(singularFieldName)); GraphQLInputObjectField field = newInputObjectField().type(GraphQLString) .name(add) .description(auth.getNotes()) .build(); updateTypeBuilder.field(field); createTypeBuilder.field(field); updateTemplate.put(add, (crud, update) -> crud.addChild(facet, (RuleForm) update.get(AT_RULEFORM), auth, crud.lookup(child, (String) update.get(add)))); } @SuppressWarnings("unchecked") private void addChildren(NetworkAuthorization<RuleForm> facet, NetworkAuthorization<RuleForm> auth, String fieldName) { String addChildren = String.format(ADD_TEMPLATE, capitalized(fieldName)); GraphQLInputObjectField field = newInputObjectField().type(new GraphQLList(GraphQLString)) .name(addChildren) .description(auth.getNotes()) .build(); updateTypeBuilder.field(field); createTypeBuilder.field(field); updateTemplate.put(addChildren, (crud, update) -> crud.addChildren(facet, (RuleForm) update.get(AT_RULEFORM), auth, (List<RuleForm>) crud.lookupRuleForm(auth, (List<String>) update.get(addChildren)))); } @SuppressWarnings("unchecked") private void addChildren(NetworkAuthorization<RuleForm> facet, XDomainNetworkAuthorization<?, ?> auth, String fieldName, NetworkAuthorization<?> child) { String addChildren = String.format(ADD_TEMPLATE, capitalized(fieldName)); GraphQLInputObjectField field = newInputObjectField().type(new GraphQLList(GraphQLString)) .name(addChildren) .description(auth.getNotes()) .build(); updateTypeBuilder.field(field); createTypeBuilder.field(field); updateTemplate.put(addChildren, (crud, update) -> crud.addChildren(facet, (RuleForm) update.get(AT_RULEFORM), auth, crud.lookup(child, (List<String>) update.get(addChildren)))); } private void addPlugins(NetworkAuthorization<RuleForm> facet, List<Plugin> plugins, Map<Plugin, ClassLoader> executionScopes) { plugins.forEach(plugin -> { ClassLoader executionScope = executionScopes.get(plugin); assert executionScope != null : String.format("%s execution scope is null!", plugin); String defaultImplementation = Optional.of(plugin.getPackageName()) .map(pkg -> String.format(S_S_PLUGIN_CONVENTION, pkg, plugin.getFacetName())) .orElse(null); if (defaultImplementation == null) { return; } build(plugin.getConstructor(), defaultImplementation, executionScope); plugin.getInstanceMethods() .forEach(method -> build(facet, method, defaultImplementation, executionScope)); }); } @SuppressWarnings("unchecked") private GraphQLFieldDefinition apply(NetworkAuthorization<RuleForm> facet) { List<BiFunction<DataFetchingEnvironment, RuleForm, Object>> detachedConstructors = constructors; return newFieldDefinition().name(String.format(APPLY_MUTATION, toTypeName(facet.getName()))) .description(String.format("Apply %s facet to the instance", toTypeName(facet.getName()))) .type(referenceToType(facet.getName())) .argument(newArgument().name(ID) .description("the id of the instance") .type(GraphQLString) .build()) .dataFetcher(env -> { RuleForm ruleform = (RuleForm) ctx(env).lookup(facet, (String) env.getArgument(ID)); PhantasmCRUD<RuleForm, Network> crud = ctx(env); return crud.apply(facet, ruleform, instance -> { detachedConstructors.forEach(constructor -> constructor.apply(env, instance)); return ruleform; }); }) .build(); } private void build(Constructor constructor, String defaultImplementation, ClassLoader executionScope) { Method method = getInstanceMethod(Optional.ofNullable(constructor.getImplementationClass()) .orElse(defaultImplementation), Optional.ofNullable(constructor.getImplementationMethod()) .orElse(constructor.getName()), constructor.toString(), executionScope); constructors.add((env, instance) -> { PhantasmCRUD<RuleForm, Network> crud = ctx(env); if (!checkInvoke(constructor, crud)) { log.info(String.format("Failed invoking %s by: %s", constructor, crud.getModel() .getCurrentPrincipal())); return null; } @SuppressWarnings("unchecked") Class<? extends Phantasm<RuleForm>> phantasm = (Class<? extends Phantasm<RuleForm>>) method.getParameterTypes()[2]; Model model = ctx(env).getModel(); return invoke(method, env, model, model.wrap(phantasm, instance)); }); } @SuppressWarnings("unchecked") private void build(NetworkAuthorization<RuleForm> facet) { typeBuilder.field(newFieldDefinition().type(GraphQLString) .name(ID) .description("The id of the facet instance") .build()); typeBuilder.field(newFieldDefinition().type(GraphQLString) .name(NAME) .description("The name of the facet instance") .build()); typeBuilder.field(newFieldDefinition().type(GraphQLString) .name(DESCRIPTION) .description("The description of the facet instance") .build()); updateTypeBuilder.field(newInputObjectField().type(new GraphQLNonNull(GraphQLString)) .name(ID) .description(String.format("the id of the updated %s", toTypeName(facet.getName()))) .build()); updateTypeBuilder.field(newInputObjectField().type(GraphQLString) .name(SET_NAME) .description(String.format("the name to update on %s", toTypeName(facet.getName()))) .build()); createTypeBuilder.field(newInputObjectField().type(new GraphQLNonNull(GraphQLString)) .name(SET_NAME) .description(String.format("the name to update on %s", toTypeName(facet.getName()))) .build()); updateTemplate.put(SET_NAME, (crud, update) -> crud.setName((RuleForm) update.get(AT_RULEFORM), (String) update.get(SET_NAME))); GraphQLInputObjectField field = newInputObjectField().type(GraphQLString) .name(SET_DESCRIPTION) .description(String.format("the description to update on %s", toTypeName(facet.getName()))) .build(); updateTypeBuilder.field(field); createTypeBuilder.field(field); updateTemplate.put(SET_DESCRIPTION, (crud, update) -> crud.setDescription((RuleForm) update.get(AT_RULEFORM), (String) update.get(SET_DESCRIPTION))); } private void build(NetworkAuthorization<RuleForm> facet, InstanceMethod instanceMethod, String defaultImplementation, ClassLoader executionScope) { Method method = getInstanceMethod(Optional.ofNullable(instanceMethod.getImplementationClass()) .orElse(defaultImplementation), Optional.ofNullable(instanceMethod.getImplementationMethod()) .orElse(instanceMethod.getName()), instanceMethod.toString(), executionScope); List<GraphQLArgument> arguments = instanceMethod.getArguments() .stream() .map(arg -> newArgument().name(arg.getName()) .description(arg.getDescription()) .type(inputTypeOf(arg.getInputType())) .build()) .collect(Collectors.toList()); @SuppressWarnings("unchecked") Class<? extends Phantasm<RuleForm>> phantasm = (Class<? extends Phantasm<RuleForm>>) method.getParameterTypes()[2]; typeBuilder.field(newFieldDefinition().type(outputTypeOf(instanceMethod.getReturnType())) .argument(arguments) .name(instanceMethod.getName()) .dataFetcher(env -> { @SuppressWarnings("unchecked") RuleForm instance = (RuleForm) env.getSource(); PhantasmCRUD<RuleForm, Network> crud = ctx(env); if (!checkInvoke(facet, instanceMethod, instance, crud)) { log.info(String.format("Failed invoking %s by: %s", instanceMethod, crud.getModel() .getCurrentPrincipal())); return null; } Model model = ctx(env).getModel(); return instance == null ? null : invoke(method, env, model, model.wrap(phantasm, instance)); }) .description(instanceMethod.getDescription()) .build()); } private boolean checkInvoke(Constructor constructor, PhantasmCRUD<RuleForm, Network> crud) { return crud.getModel() .getProductModel() .checkCapability(constructor.getRuleform(), crud.getINVOKE()); } private boolean checkInvoke(NetworkAuthorization<RuleForm> facet, InstanceMethod method, RuleForm instance, PhantasmCRUD<RuleForm, Network> crud) { Model model = crud.getModel(); NetworkedModel<RuleForm, Network, ?, ?> networkedModel = model.getNetworkedModel(instance); Relationship invoke = crud.getINVOKE(); return networkedModel.checkCapability(method.getRuleform(), invoke) && crud.checkInvoke(facet, instance); } private void clear() { this.references = null; this.typeBuilder = null; this.updateTypeBuilder = null; this.createTypeBuilder = null; this.updateTemplate = null; this.constructors = null; } @SuppressWarnings("unchecked") private GraphQLFieldDefinition createInstance(NetworkAuthorization<RuleForm> facet) { Map<String, BiFunction<PhantasmCRUD<RuleForm, Network>, Map<String, Object>, RuleForm>> detachedUpdate = updateTemplate; List<BiFunction<DataFetchingEnvironment, RuleForm, Object>> detachedConstructors = constructors; return newFieldDefinition().name(String.format(CREATE_MUTATION, toTypeName(facet.getName()))) .description(String.format("Create an instance of %s", toTypeName(facet.getName()))) .type(referenceToType(facet.getName())) .argument(newArgument().name(STATE) .description("the initial state to apply to the new instance") .type(new GraphQLNonNull(createTypeBuilder.build())) .build()) .dataFetcher(env -> { Map<String, Object> createState = (Map<String, Object>) env.getArgument(STATE); PhantasmCRUD<RuleForm, Network> crud = ctx(env); return crud.createInstance(facet, (String) createState.get(SET_NAME), (String) createState.get(SET_DESCRIPTION), instance -> { createState.remove(SET_NAME); createState.remove(SET_DESCRIPTION); update(instance, createState, crud, detachedUpdate); detachedConstructors.forEach(constructor -> constructor.apply(env, instance)); return instance; }); }) .build(); } @SuppressWarnings("unchecked") private GraphQLFieldDefinition createInstances(NetworkAuthorization<RuleForm> facet) { Map<String, BiFunction<PhantasmCRUD<RuleForm, Network>, Map<String, Object>, RuleForm>> detachedUpdate = updateTemplate; List<BiFunction<DataFetchingEnvironment, RuleForm, Object>> detachedConstructors = constructors; return newFieldDefinition().name(String.format(CREATE_INSTANCES_MUTATION, toTypeName(facet.getName()))) .description(String.format("Create instances of %s", toTypeName(facet.getName()))) .type(new GraphQLList(referenceToType(facet.getName()))) .argument(newArgument().name(STATE) .description("the initial state to apply to the new instance") .type(new GraphQLNonNull(new GraphQLList(createTypeBuilder.build()))) .build()) .dataFetcher(env -> { List<Map<String, Object>> createStates = (List<Map<String, Object>>) env.getArgument(STATE); PhantasmCRUD<RuleForm, Network> crud = ctx(env); return createStates.stream() .map(createState -> crud.createInstance(facet, (String) createState.get(SET_NAME), (String) createState.get(SET_DESCRIPTION), instance -> { createState.remove(SET_NAME); createState.remove(SET_DESCRIPTION); update(instance, createState, crud, detachedUpdate); detachedConstructors.forEach(constructor -> constructor.apply(env, instance)); return instance; })) .collect(Collectors.toList()); }) .build(); } private Class<?> getImplementation(String implementationClass, String type, ClassLoader executionScope) { if (implementationClass == null) { throw new IllegalStateException(String.format("No implementation class could be determined for %s in %s", type, getName())); } Class<?> clazz; try { clazz = executionScope.loadClass(implementationClass); } catch (ClassNotFoundException e) { log.warn("Error plugging in constructor {} into {}", type, getName(), e); throw new IllegalStateException(String.format("Error plugging in %s into %s: %s", type, getName(), e.toString()), e); } return clazz; } private Method getInstanceMethod(String implementationClass, String implementationMethod, String type, ClassLoader executionScope) { Class<?> clazz = getImplementation(implementationClass, type, executionScope); List<Method> candidates = Arrays.asList(clazz.getDeclaredMethods()) .stream() .filter(method -> Modifier.isStatic(method.getModifiers())) .filter(method -> method.getName() .equals(implementationMethod)) .filter(method -> method.getParameterTypes().length == 3) .filter(method -> method.getParameterTypes()[0].equals(DataFetchingEnvironment.class)) .filter(method -> method.getParameterTypes()[1].equals(Model.class)) .collect(Collectors.toList()); if (candidates.isEmpty()) { log.warn("Error plugging in {} into {}, no static method matches for {} in {}", type, getName(), implementationMethod, implementationClass); throw new IllegalStateException(String.format("Error plugging in %s into %s, no static method matches for method '%s' in %s", type, getName(), implementationMethod, implementationClass)); } if (candidates.size() > 1) { log.warn("Error plugging in {} into {}, multiple matches for {} in {}", type, getName(), implementationMethod, implementationClass); throw new IllegalStateException(String.format("Error plugging in %s into %s, multiple matches for static method '%s' in %s", type, getName(), implementationMethod, implementationClass)); } return candidates.get(0); } private GraphQLInputType inputTypeOf(String type) { type = type.trim(); if (type.startsWith("[")) { return new GraphQLList(inputTypeOf(type.substring(1, type.length() - 1))); } switch (type) { case "Int": return Scalars.GraphQLInt; case "String": return Scalars.GraphQLString; case "Boolean": return Scalars.GraphQLBoolean; case "Float": return Scalars.GraphQLFloat; default: throw new IllegalStateException(String.format("Invalid GraphQLType: %s", type)); } } private GraphQLFieldDefinition instance(NetworkAuthorization<RuleForm> facet, GraphQLObjectType type) { return newFieldDefinition().name(toTypeName(facet.getName())) .type(type) .argument(newArgument().name(ID) .description("id of the facet") .type(new GraphQLNonNull(GraphQLString)) .build()) .dataFetcher(env -> ctx(env).lookup(facet, (String) env.getArgument(ID))) .build(); } private GraphQLFieldDefinition instances(NetworkAuthorization<RuleForm> facet) { return newFieldDefinition().name(String.format(INSTANCES_OF_QUERY, toTypeName(facet.getName()))) .description(String.format("Return the instances of %s", toTypeName(facet.getName()))) .type(new GraphQLList(referenceToType(facet.getName()))) .dataFetcher(context -> ctx(context).getInstances(facet)) .build(); } private GraphQLOutputType outputTypeOf(String type) { if (type == null) { return Scalars.GraphQLString; } type = type.trim(); if (type.startsWith("[")) { return new GraphQLList(inputTypeOf(type.substring(1, type.length() - 1))); } switch (type) { case "Int": return Scalars.GraphQLInt; case "String": return Scalars.GraphQLString; case "Boolean": return Scalars.GraphQLBoolean; case "Float": return Scalars.GraphQLFloat; default: return referenceToType(type); } } @SuppressWarnings("unchecked") private GraphQLFieldDefinition remove(NetworkAuthorization<RuleForm> facet) { return newFieldDefinition().name(String.format(REMOVE_MUTATION, toTypeName(facet.getName()))) .type(referenceToType(facet.getName())) .description(String.format("Remove the %s facet from the instance", toTypeName(facet.getName()))) .argument(newArgument().name(ID) .description("the id of the instance") .type(GraphQLString) .build()) .dataFetcher(env -> ctx(env).remove(facet, (RuleForm) ctx(env).lookup(facet, (String) env.getArgument(ID)), true)) .build(); } @SuppressWarnings("unchecked") private void removeChild(NetworkAuthorization<RuleForm> facet, NetworkAuthorization<RuleForm> auth, String singularFieldName) { String remove = String.format(REMOVE_TEMPLATE, capitalized(singularFieldName)); updateTypeBuilder.field(newInputObjectField().type(GraphQLString) .name(remove) .description(auth.getNotes()) .build()); updateTemplate.put(remove, (crud, update) -> crud.removeChild(facet, (RuleForm) update.get(AT_RULEFORM), auth, (RuleForm) crud.lookup(auth, (String) update.get(remove)))); } @SuppressWarnings("unchecked") private void removeChild(NetworkAuthorization<RuleForm> facet, XDomainNetworkAuthorization<?, ?> auth, NetworkAuthorization<?> child, String singularFieldName) { String remove = String.format(REMOVE_TEMPLATE, capitalized(singularFieldName)); updateTypeBuilder.field(newInputObjectField().type(GraphQLString) .name(remove) .description(auth.getNotes()) .build()); updateTemplate.put(remove, (crud, update) -> crud.removeChild(facet, (RuleForm) update.get(AT_RULEFORM), auth, crud.lookup(child, (String) update.get(remove)))); } @SuppressWarnings("unchecked") private void removeChildren(NetworkAuthorization<RuleForm> facet, NetworkAuthorization<RuleForm> auth, String fieldName) { String removeChildren = String.format(REMOVE_TEMPLATE, capitalized(fieldName)); updateTypeBuilder.field(newInputObjectField().type(new GraphQLList(GraphQLString)) .name(removeChildren) .description(auth.getNotes()) .build()); updateTemplate.put(removeChildren, (crud, update) -> crud.removeChildren(facet, (RuleForm) update.get(AT_RULEFORM), auth, (List<RuleForm>) crud.lookupRuleForm(auth, (List<String>) update.get(removeChildren)))); } @SuppressWarnings("unchecked") private void removeChildren(NetworkAuthorization<RuleForm> facet, XDomainNetworkAuthorization<?, ?> auth, String fieldName, NetworkAuthorization<?> child) { String removeChildren = String.format(REMOVE_TEMPLATE, capitalized(fieldName)); updateTypeBuilder.field(newInputObjectField().type(new GraphQLList(GraphQLString)) .name(removeChildren) .description(auth.getNotes()) .build()); updateTemplate.put(removeChildren, (crud, update) -> crud.removeChildren(facet, (RuleForm) update.get(AT_RULEFORM), auth, crud.lookup(child, (List<String>) update.get(removeChildren)))); } @SuppressWarnings("unchecked") private void setChildren(NetworkAuthorization<RuleForm> facet, NetworkAuthorization<RuleForm> auth, String fieldName) { String setter = String.format(SET_TEMPLATE, capitalized(fieldName)); GraphQLInputObjectField field = newInputObjectField().type(new GraphQLList(GraphQLString)) .name(setter) .description(auth.getNotes()) .build(); updateTypeBuilder.field(field); createTypeBuilder.field(field); updateTemplate.put(setter, (crud, update) -> crud.setChildren(facet, (RuleForm) update.get(AT_RULEFORM), auth, (List<RuleForm>) crud.lookupRuleForm(auth, (List<String>) update.get(setter)))); } @SuppressWarnings("unchecked") private void setChildren(NetworkAuthorization<RuleForm> facet, XDomainNetworkAuthorization<?, ?> auth, String fieldName, NetworkAuthorization<?> child) { String setter = String.format(SET_TEMPLATE, capitalized(fieldName)); GraphQLInputObjectField field = newInputObjectField().type(GraphQLString) .name(setter) .description(auth.getNotes()) .build(); updateTypeBuilder.field(field); createTypeBuilder.field(field); updateTemplate.put(setter, (crud, update) -> crud.setChildren(facet, (RuleForm) update.get(AT_RULEFORM), auth, crud.lookup(child, (List<String>) update.get(setter)))); } private GraphQLOutputType typeOf(Attribute attribute) { GraphQLOutputType type = null; switch (attribute.getValueType()) { case BINARY: type = GraphQLString; // encoded binary break; case BOOLEAN: type = GraphQLBoolean; break; case INTEGER: type = GraphQLInt; break; case NUMERIC: type = GraphQLFloat; break; case TEXT: type = GraphQLString; break; case TIMESTAMP: type = GraphQLString; break; case JSON: type = GraphQLString; } return attribute.getIndexed() ? new GraphQLList(type) : type; } @SuppressWarnings("unchecked") private GraphQLFieldDefinition update(NetworkAuthorization<RuleForm> facet) { Map<String, BiFunction<PhantasmCRUD<RuleForm, Network>, Map<String, Object>, RuleForm>> detachedUpdateTemplate = updateTemplate; return newFieldDefinition().name(String.format(UPDATE_MUTATION, toTypeName(facet.getName()))) .type(referenceToType(facet.getName())) .description(String.format("Update the instance of %s", toTypeName(facet.getName()))) .argument(newArgument().name(STATE) .description("the update state to apply") .type(new GraphQLNonNull(updateTypeBuilder.build())) .build()) .dataFetcher(env -> { Map<String, Object> updateState = (Map<String, Object>) env.getArgument(STATE); PhantasmCRUD<RuleForm, Network> crud = ctx(env); RuleForm ruleform = (RuleForm) crud.lookup(facet, (String) updateState.get(ID)); update(ruleform, updateState, crud, detachedUpdateTemplate); return ruleform; }) .build(); } private void update(RuleForm ruleform, Map<String, Object> updateState, PhantasmCRUD<RuleForm, Network> crud, Map<String, BiFunction<PhantasmCRUD<RuleForm, Network>, Map<String, Object>, RuleForm>> updateTemplate) { updateState.put(AT_RULEFORM, ruleform); updateState.keySet() .stream() .filter(field -> !field.equals(ID) && !field.equals(AT_RULEFORM) && updateState.containsKey(field)) .forEach(field -> updateTemplate.get(field) .apply(crud, updateState)); } @SuppressWarnings("unchecked") private GraphQLFieldDefinition updateInstances(NetworkAuthorization<RuleForm> facet) { Map<String, BiFunction<PhantasmCRUD<RuleForm, Network>, Map<String, Object>, RuleForm>> detachedUpdateTemplate = updateTemplate; return newFieldDefinition().name(String.format(UPDATE_INSTANCES_MUTATION, toTypeName(facet.getName()))) .type(referenceToType(facet.getName())) .description(String.format("Update the instances of %s", toTypeName(facet.getName()))) .argument(newArgument().name(STATE) .description("the update state to apply") .type(new GraphQLNonNull(new GraphQLList(updateTypeBuilder.build()))) .build()) .dataFetcher(env -> { List<Map<String, Object>> updateStates = (List<Map<String, Object>>) env.getArgument(STATE); PhantasmCRUD<RuleForm, Network> crud = ctx(env); return updateStates.stream() .map(updateState -> { RuleForm ruleform = (RuleForm) crud.lookup(facet, (String) updateState.get(ID)); update(ruleform, updateState, crud, detachedUpdateTemplate); return ruleform; }) .collect(Collectors.toList()); }) .build(); } }
package org.eclipse.jetty.nested; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.util.Date; import java.util.Enumeration; import java.util.Locale; import java.util.Map.Entry; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletRequestWrapper; import javax.servlet.ServletResponse; import javax.servlet.ServletResponseWrapper; import javax.servlet.UnavailableException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import org.eclipse.jetty.continuation.Continuation; import org.eclipse.jetty.continuation.ContinuationListener; import org.eclipse.jetty.continuation.ContinuationSupport; import org.eclipse.jetty.http.HttpHeaders; import org.eclipse.jetty.util.StringUtil; import org.eclipse.jetty.util.log.Log; /** Dump Servlet Request. * */ public class Dump extends HttpServlet { boolean fixed; @Override public void init(ServletConfig config) throws ServletException { super.init(config); if (config.getInitParameter("unavailable")!=null && !fixed) { fixed=true; throw new UnavailableException("Unavailable test",Integer.parseInt(config.getInitParameter("unavailable"))); } } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } @Override public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { // Handle a dump of data final String data= request.getParameter("data"); final String chars= request.getParameter("chars"); final String block= request.getParameter("block"); final String dribble= request.getParameter("dribble"); final boolean flush= request.getParameter("flush")!=null?Boolean.parseBoolean(request.getParameter("flush")):false; if(request.getPathInfo()!=null && request.getPathInfo().toLowerCase().indexOf("script")!=-1) { response.sendRedirect(response.encodeRedirectURL(getServletContext().getContextPath() + "/dump/info")); return; } request.setCharacterEncoding("UTF-8"); if (request.getParameter("empty")!=null) { response.setStatus(200); response.flushBuffer(); return; } if (request.getParameter("sleep")!=null) { try { long s = Long.parseLong(request.getParameter("sleep")); if (request.getHeader(HttpHeaders.EXPECT)!=null &&request.getHeader(HttpHeaders.EXPECT).indexOf("102")>=0) { Thread.sleep(s/2); response.sendError(102); Thread.sleep(s/2); } else Thread.sleep(s); } catch (InterruptedException e) { return; } catch (Exception e) { throw new ServletException(e); } } if (request.getAttribute("RESUME")==null && request.getParameter("resume")!=null) { request.setAttribute("RESUME",Boolean.TRUE); final long resume=Long.parseLong(request.getParameter("resume")); new Thread(new Runnable() { public void run() { try { Thread.sleep(resume); } catch (InterruptedException e) { e.printStackTrace(); } Continuation continuation = ContinuationSupport.getContinuation(request); continuation.resume(); } }).start(); } if (request.getParameter("complete")!=null) { final long complete=Long.parseLong(request.getParameter("complete")); new Thread(new Runnable() { public void run() { try { Thread.sleep(complete); } catch (InterruptedException e) { e.printStackTrace(); } try { response.setContentType("text/html"); response.getOutputStream().println("<h1>COMPLETED</h1>"); Continuation continuation = ContinuationSupport.getContinuation(request); continuation.complete(); } catch (IOException e) { e.printStackTrace(); } } }).start(); } if (request.getParameter("suspend")!=null && request.getAttribute("SUSPEND")!=Boolean.TRUE) { request.setAttribute("SUSPEND",Boolean.TRUE); try { Continuation continuation = ContinuationSupport.getContinuation(request); continuation.setTimeout(Long.parseLong(request.getParameter("suspend"))); continuation.suspend(); continuation.addContinuationListener(new ContinuationListener() { public void onTimeout(Continuation continuation) { response.addHeader("Dump","onTimeout"); try { dump(response,data,chars,block,dribble,flush); continuation.complete(); } catch (IOException e) { Log.ignore(e); } } public void onComplete(Continuation continuation) { response.addHeader("Dump","onComplete"); } }); continuation.undispatch(); } catch(Exception e) { throw new ServletException(e); } } request.setAttribute("Dump", this); getServletContext().setAttribute("Dump",this); // getServletContext().log("dump "+request.getRequestURI()); // Force a content length response String length= request.getParameter("length"); if (length != null && length.length() > 0) { response.setContentLength(Integer.parseInt(length)); } // Handle a dump of data if (dump(response,data,chars,block,dribble,flush)) return; // handle an exception String info= request.getPathInfo(); if (info != null && info.endsWith("Exception")) { try { throw (Throwable) Thread.currentThread().getContextClassLoader().loadClass(info.substring(1)).newInstance(); } catch (Throwable th) { throw new ServletException(th); } } // test a reset String reset= request.getParameter("reset"); if (reset != null && reset.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.setHeader("SHOULD_NOT","BE SEEN"); response.reset(); } // handle an redirect String redirect= request.getParameter("redirect"); if (redirect != null && redirect.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendRedirect(response.encodeRedirectURL(redirect)); try { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); } catch(IOException e) { // ignored as stream is closed. } return; } // handle an error String error= request.getParameter("error"); if (error != null && error.length() > 0 && request.getAttribute("javax.servlet.error.status_code")==null) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendError(Integer.parseInt(error)); try { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); } catch(IllegalStateException e) { try { response.getWriter().println("NOR THIS!!"); } catch(IOException e2){} } catch(IOException e){} return; } // Handle a extra headers String headers= request.getParameter("headers"); if (headers != null && headers.length() > 0) { long h=Long.parseLong(headers); for (int i=0;i<h;i++) response.addHeader("Header"+i,"Value"+i); } String buffer= request.getParameter("buffer"); if (buffer != null && buffer.length() > 0) response.setBufferSize(Integer.parseInt(buffer)); String charset= request.getParameter("charset"); if (charset==null) charset="UTF-8"; response.setCharacterEncoding(charset); response.setContentType("text/html"); if (info != null && info.indexOf("Locale/") >= 0) { try { String locale_name= info.substring(info.indexOf("Locale/") + 7); Field f= java.util.Locale.class.getField(locale_name); response.setLocale((Locale)f.get(null)); } catch (Exception e) { e.printStackTrace(); response.setLocale(Locale.getDefault()); } } String cn= request.getParameter("cookie"); String cv=request.getParameter("cookiev"); if (cn!=null && cv!=null) { Cookie cookie= new Cookie(cn, cv); if (request.getParameter("version")!=null) cookie.setVersion(Integer.parseInt(request.getParameter("version"))); cookie.setComment("Cookie from dump servlet"); response.addCookie(cookie); } String pi= request.getPathInfo(); if (pi != null && pi.startsWith("/ex")) { OutputStream out= response.getOutputStream(); out.write("</H1>This text should be reset</H1>".getBytes()); if ("/ex0".equals(pi)) throw new ServletException("test ex0", new Throwable()); else if ("/ex1".equals(pi)) throw new IOException("test ex1"); else if ("/ex2".equals(pi)) throw new UnavailableException("test ex2"); else if (pi.startsWith("/ex3/")) throw new UnavailableException("test ex3",Integer.parseInt(pi.substring(5))); throw new RuntimeException("test"); } if ("true".equals(request.getParameter("close"))) response.setHeader("Connection","close"); String buffered= request.getParameter("buffered"); PrintWriter pout=null; try { pout =response.getWriter(); } catch(IllegalStateException e) { pout=new PrintWriter(new OutputStreamWriter(response.getOutputStream(),charset)); } if (buffered!=null) pout = new PrintWriter(new BufferedWriter(pout,Integer.parseInt(buffered))); try { pout.write("<html>\n<body>\n"); pout.write("<h1>Dump Servlet</h1>\n"); pout.write("<table width=\"95%\">"); pout.write("<tr>\n"); pout.write("<th align=\"right\">getMethod:&nbsp;</th>"); pout.write("<td>" + notag(request.getMethod())+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getContentLength:&nbsp;</th>"); pout.write("<td>"+Integer.toString(request.getContentLength())+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getContentType:&nbsp;</th>"); pout.write("<td>"+notag(request.getContentType())+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getRequestURI:&nbsp;</th>"); pout.write("<td>"+notag(request.getRequestURI())+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getRequestURL:&nbsp;</th>"); pout.write("<td>"+notag(request.getRequestURL().toString())+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getContextPath:&nbsp;</th>"); pout.write("<td>"+request.getContextPath()+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getServletPath:&nbsp;</th>"); pout.write("<td>"+notag(request.getServletPath())+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getPathInfo:&nbsp;</th>"); pout.write("<td>"+notag(request.getPathInfo())+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getPathTranslated:&nbsp;</th>"); pout.write("<td>"+notag(request.getPathTranslated())+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getQueryString:&nbsp;</th>"); pout.write("<td>"+notag(request.getQueryString())+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getProtocol:&nbsp;</th>"); pout.write("<td>"+request.getProtocol()+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getScheme:&nbsp;</th>"); pout.write("<td>"+request.getScheme()+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getServerName:&nbsp;</th>"); pout.write("<td>"+notag(request.getServerName())+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getServerPort:&nbsp;</th>"); pout.write("<td>"+Integer.toString(request.getServerPort())+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getLocalName:&nbsp;</th>"); pout.write("<td>"+request.getLocalName()+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getLocalAddr:&nbsp;</th>"); pout.write("<td>"+request.getLocalAddr()+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getLocalPort:&nbsp;</th>"); pout.write("<td>"+Integer.toString(request.getLocalPort())+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getRemoteUser:&nbsp;</th>"); pout.write("<td>"+request.getRemoteUser()+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getUserPrincipal:&nbsp;</th>"); pout.write("<td>"+request.getUserPrincipal()+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getRemoteAddr:&nbsp;</th>"); pout.write("<td>"+request.getRemoteAddr()+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getRemoteHost:&nbsp;</th>"); pout.write("<td>"+request.getRemoteHost()+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getRemotePort:&nbsp;</th>"); pout.write("<td>"+request.getRemotePort()+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getRequestedSessionId:&nbsp;</th>"); pout.write("<td>"+request.getRequestedSessionId()+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">isSecure():&nbsp;</th>"); pout.write("<td>"+request.isSecure()+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">isUserInRole(admin):&nbsp;</th>"); pout.write("<td>"+request.isUserInRole("admin")+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getLocale:&nbsp;</th>"); pout.write("<td>"+request.getLocale()+"</td>"); Enumeration locales= request.getLocales(); while (locales.hasMoreElements()) { pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getLocales:&nbsp;</th>"); pout.write("<td>"+locales.nextElement()+"</td>"); } pout.write("</tr><tr>\n"); pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Other HTTP Headers:</big></th>"); Enumeration h= request.getHeaderNames(); String name; while (h.hasMoreElements()) { name= (String)h.nextElement(); Enumeration h2= request.getHeaders(name); while (h2.hasMoreElements()) { String hv= (String)h2.nextElement(); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">"+notag(name)+":&nbsp;</th>"); pout.write("<td>"+notag(hv)+"</td>"); } } if ("true".equals(request.getParameter("env"))) { pout.write("</tr><tr>\n"); pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Environment&nbsp;System-Properties:&nbsp;</big></th>"); for (Entry<Object, Object> e : System.getProperties().entrySet()) { pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">" + notag(String.valueOf(e.getKey())) + ":&nbsp;</th>"); pout.write("<td>"+notag(String.valueOf(e.getValue()))+"</td>"); } } pout.write("</tr><tr>\n"); pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Request Parameters:</big></th>"); h= request.getParameterNames(); while (h.hasMoreElements()) { name= (String)h.nextElement(); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">"+notag(name)+":&nbsp;</th>"); pout.write("<td>"+notag(request.getParameter(name))+"</td>"); String[] values= request.getParameterValues(name); if (values == null) { pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">"+notag(name)+" Values:&nbsp;</th>"); pout.write("<td>"+"NULL!"+"</td>"); } else if (values.length > 1) { for (int i= 0; i < values.length; i++) { pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">"+notag(name)+"["+i+"]:&nbsp;</th>"); pout.write("<td>"+notag(values[i])+"</td>"); } } } pout.write("</tr><tr>\n"); pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Cookies:</big></th>"); Cookie[] cookies = request.getCookies(); for (int i=0; cookies!=null && i<cookies.length;i++) { Cookie cookie = cookies[i]; pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">"+notag(cookie.getName())+":&nbsp;</th>"); pout.write("<td>"+notag(cookie.getValue())+"</td>"); } String content_type=request.getContentType(); if (content_type!=null && !content_type.startsWith("application/x-www-form-urlencoded") && !content_type.startsWith("multipart/form-data")) { pout.write("</tr><tr>\n"); pout.write("<th align=\"left\" valign=\"top\" colspan=\"2\"><big><br/>Content:</big></th>"); pout.write("</tr><tr>\n"); pout.write("<td><pre>"); char[] content= new char[4096]; int len; try{ Reader in=request.getReader(); while((len=in.read(content))>=0) pout.write(notag(new String(content,0,len))); } catch(IOException e) { pout.write(e.toString()); } pout.write("</pre></td>"); } pout.write("</tr><tr>\n"); pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Request Attributes:</big></th>"); Enumeration a= request.getAttributeNames(); while (a.hasMoreElements()) { name= (String)a.nextElement(); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\" valign=\"top\">"+name.replace("."," .")+":&nbsp;</th>"); Object value=request.getAttribute(name); if (value instanceof File) { File file = (File)value; pout.write("<td>"+"<pre>" + file.getName()+" ("+file.length()+" "+new Date(file.lastModified())+ ")</pre>"+"</td>"); } else pout.write("<td>"+"<pre>" + toString(request.getAttribute(name)) + "</pre>"+"</td>"); } request.setAttribute("org.eclipse.jetty.servlet.MultiPartFilter.files",null); pout.write("</tr><tr>\n"); pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Servlet InitParameters:</big></th>"); a= getInitParameterNames(); while (a.hasMoreElements()) { name= (String)a.nextElement(); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">"+name+":&nbsp;</th>"); pout.write("<td>"+ toString(getInitParameter(name)) +"</td>"); } pout.write("</tr><tr>\n"); pout.write("<th align=\"left\" colspan=\"2\"><big><br/>ServletContext Misc:</big></th>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\" valign=\"top\">"+"servletContext.getContextPath()"+":&nbsp;</th>"); pout.write("<td>"+ getServletContext().getContextPath() + "</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\" valign=\"top\">"+"getServletContext().getRealPath(\"/WEB-INF/\")"+":&nbsp;</th>"); pout.write("<td>"+ getServletContext().getRealPath("/WEB-INF/") + "</td>"); String webinfRealPath = getServletContext().getRealPath("/WEB-INF/"); if (webinfRealPath != null) { try { File webInfRealPathFile = new File(webinfRealPath); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\" valign=\"top\">"+"new File(getServletContext().getRealPath(\"/WEB-INF/\"))"+":&nbsp;</th>"); pout.write("<td>exists()="+ webInfRealPathFile.exists() + "; isFile()="+webInfRealPathFile.isFile() + "; isDirectory()="+webInfRealPathFile.isDirectory() + "; isAbsolute()=" + webInfRealPathFile.isAbsolute() + "; canRead()=" + webInfRealPathFile.canRead() + "; canWrite()=" + webInfRealPathFile.canWrite() +"</td>"); if (webInfRealPathFile.exists() && webInfRealPathFile.isDirectory()) { File webxml = new File(webInfRealPathFile, "web.xml"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\" valign=\"top\">"+"new File(getServletContext().getRealPath(\"/WEB-INF/web.xml\"))"+":&nbsp;</th>"); pout.write("<td>exists()="+ webxml.exists() + "; isFile()="+webxml.isFile() + "; isDirectory()="+webxml.isDirectory() + "; isAbsolute()=" + webxml.isAbsolute() + "; canRead()=" + webxml.canRead() + "; canWrite()=" + webxml.canWrite() +"</td>"); } } catch (Throwable t) { pout.write("<th align=\"right\" valign=\"top\">"+"Error probing the java.io.File(getServletContext().getRealPath(\"/WEB-INF/\"))"+":&nbsp;</th>"); pout.write("<td>"+ t + "</td>"); } } pout.write("</tr><tr>\n"); pout.write("<th align=\"right\" valign=\"top\">"+"getServletContext().getServerInfo()"+":&nbsp;</th>"); pout.write("<td>"+ getServletContext().getServerInfo() + "</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\" valign=\"top\">"+"getServletContext().getServletContextName()"+":&nbsp;</th>"); pout.write("<td>"+ getServletContext().getServletContextName() + "</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Context InitParameters:</big></th>"); a= getServletContext().getInitParameterNames(); while (a.hasMoreElements()) { name= (String)a.nextElement(); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\" valign=\"top\">"+name.replace("."," .")+":&nbsp;</th>"); pout.write("<td>"+ toString(getServletContext().getInitParameter(name)) + "</td>"); } pout.write("</tr><tr>\n"); pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Context Attributes:</big></th>"); a= getServletContext().getAttributeNames(); while (a.hasMoreElements()) { name= (String)a.nextElement(); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\" valign=\"top\">"+name.replace("."," .")+":&nbsp;</th>"); pout.write("<td>"+"<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>"+"</td>"); } String res= request.getParameter("resource"); if (res != null && res.length() > 0) { pout.write("</tr><tr>\n"); pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Get Resource: \""+res+"\"</big></th>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getServletContext().getContext(...):&nbsp;</th>"); ServletContext context = getServletContext().getContext(res); pout.write("<td>"+context+"</td>"); if (context!=null) { String cp=context.getContextPath(); if (cp==null || "/".equals(cp)) cp=""; pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getServletContext().getContext(...),getRequestDispatcher(...):&nbsp;</th>"); pout.write("<td>"+getServletContext().getContext(res).getRequestDispatcher(res.substring(cp.length()))+"</td>"); } pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">this.getClass().getResource(...):&nbsp;</th>"); pout.write("<td>"+this.getClass().getResource(res)+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">this.getClass().getClassLoader().getResource(...):&nbsp;</th>"); pout.write("<td>"+this.getClass().getClassLoader().getResource(res)+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">Thread.currentThread().getContextClassLoader().getResource(...):&nbsp;</th>"); pout.write("<td>"+Thread.currentThread().getContextClassLoader().getResource(res)+"</td>"); pout.write("</tr><tr>\n"); pout.write("<th align=\"right\">getServletContext().getResource(...):&nbsp;</th>"); try{pout.write("<td>"+getServletContext().getResource(res)+"</td>");} catch(Exception e) {pout.write("<td>"+"" +e+"</td>");} } pout.write("</tr></table>\n"); pout.write("<h2>Request Wrappers</h2>\n"); ServletRequest rw=request; int w=0; while (rw !=null) { pout.write((w++)+": "+rw.getClass().getName()+"<br/>"); if (rw instanceof HttpServletRequestWrapper) rw=((HttpServletRequestWrapper)rw).getRequest(); else if (rw instanceof ServletRequestWrapper) rw=((ServletRequestWrapper)rw).getRequest(); else rw=null; } pout.write("<h2>Response Wrappers</h2>\n"); ServletResponse rsw=response; w=0; while (rsw !=null) { pout.write((w++)+": "+rsw.getClass().getName()+"<br/>"); if (rsw instanceof HttpServletResponseWrapper) rsw=((HttpServletResponseWrapper)rsw).getResponse(); else if (rsw instanceof ServletResponseWrapper) rsw=((ServletResponseWrapper)rsw).getResponse(); else rsw=null; } pout.write("<br/>"); pout.write("<h2>International Characters (UTF-8)</h2>"); pout.write("LATIN LETTER SMALL CAPITAL AE<br/>\n"); pout.write("Directly uni encoded(\\u1d01): \u1d01<br/>"); pout.write("HTML reference (&amp;AElig;): &AElig;<br/>"); pout.write("Decimal (&amp;#7425;): &#7425;<br/>"); pout.write("Javascript unicode (\\u1d01) : <script language='javascript'>document.write(\"\u1d01\");</script><br/>"); pout.write("<br/>"); pout.write("<h2>Form to generate GET content</h2>"); pout.write("<form method=\"GET\" action=\""+response.encodeURL(getURI(request))+"\">"); pout.write("TextField: <input type=\"text\" name=\"TextField\" value=\"value\"/><br/>\n"); pout.write("<input type=\"submit\" name=\"Action\" value=\"Submit\">"); pout.write("</form>"); pout.write("<br/>"); pout.write("<h2>Form to generate POST content</h2>"); pout.write("<form method=\"POST\" accept-charset=\"utf-8\" action=\""+response.encodeURL(getURI(request))+"\">"); pout.write("TextField: <input type=\"text\" name=\"TextField\" value=\"value\"/><br/>\n"); pout.write("Select: <select multiple name=\"Select\">\n"); pout.write("<option>ValueA</option>"); pout.write("<option>ValueB1,ValueB2</option>"); pout.write("<option>ValueC</option>"); pout.write("</select><br/>"); pout.write("<input type=\"submit\" name=\"Action\" value=\"Submit\"><br/>"); pout.write("</form>"); pout.write("<br/>"); pout.write("<h2>Form to generate UPLOAD content</h2>"); pout.write("<form method=\"POST\" enctype=\"multipart/form-data\" accept-charset=\"utf-8\" action=\""+ response.encodeURL(getURI(request))+(request.getQueryString()==null?"":("?"+request.getQueryString()))+ "\">"); pout.write("TextField: <input type=\"text\" name=\"TextField\" value=\"comment\"/><br/>\n"); pout.write("File 1: <input type=\"file\" name=\"file1\" /><br/>\n"); pout.write("File 2: <input type=\"file\" name=\"file2\" /><br/>\n"); pout.write("<input type=\"submit\" name=\"Action\" value=\"Submit\"><br/>"); pout.write("</form>"); pout.write("<h2>Form to set Cookie</h2>"); pout.write("<form method=\"POST\" action=\""+response.encodeURL(getURI(request))+"\">"); pout.write("cookie: <input type=\"text\" name=\"cookie\" /><br/>\n"); pout.write("value: <input type=\"text\" name=\"cookiev\" /><br/>\n"); pout.write("<input type=\"submit\" name=\"Action\" value=\"setCookie\">"); pout.write("</form>\n"); pout.write("<h2>Form to get Resource</h2>"); pout.write("<form method=\"POST\" action=\""+response.encodeURL(getURI(request))+"\">"); pout.write("resource: <input type=\"text\" name=\"resource\" /><br/>\n"); pout.write("<input type=\"submit\" name=\"Action\" value=\"getResource\">"); pout.write("</form>\n"); } catch (Exception e) { getServletContext().log("dump", e); } String lines= request.getParameter("lines"); if (lines!=null) { char[] line = "<span>A line of characters. Blah blah blah blah. blooble blooble</span></br>\n".toCharArray(); for (int l=Integer.parseInt(lines);l { pout.write("<span>"+l+" </span>"); pout.write(line); } } pout.write("</body>\n</html>\n"); pout.close(); if (pi != null) { if ("/ex4".equals(pi)) throw new ServletException("test ex4", new Throwable()); if ("/ex5".equals(pi)) throw new IOException("test ex5"); if ("/ex6".equals(pi)) throw new UnavailableException("test ex6"); } } @Override public String getServletInfo() { return "Dump Servlet"; } @Override public synchronized void destroy() { } private String getURI(HttpServletRequest request) { String uri= (String)request.getAttribute("javax.servlet.forward.request_uri"); if (uri == null) uri= request.getRequestURI(); return uri; } private static String toString(Object o) { if (o == null) return null; try { if (o.getClass().isArray()) { StringBuffer sb = new StringBuffer(); if (!o.getClass().getComponentType().isPrimitive()) { Object[] array= (Object[])o; for (int i= 0; i < array.length; i++) { if (i > 0) sb.append("\n"); sb.append(array.getClass().getComponentType().getName()); sb.append("["); sb.append(i); sb.append("]="); sb.append(toString(array[i])); } return sb.toString(); } else { int length = Array.getLength(o); for (int i=0;i<length;i++) { if (i > 0) sb.append("\n"); sb.append(o.getClass().getComponentType().getName()); sb.append("["); sb.append(i); sb.append("]="); sb.append(toString(Array.get(o, i))); } return sb.toString(); } } else return o.toString(); } catch (Exception e) { return e.toString(); } } private boolean dump(HttpServletResponse response, String data, String chars, String block, String dribble, boolean flush) throws IOException { if (data != null && data.length() > 0) { long d=Long.parseLong(data); int b=(block!=null&&block.length()>0)?Integer.parseInt(block):50; byte[] buf=new byte[b]; for (int i=0;i<b;i++) { buf[i]=(byte)('0'+(i%10)); if (i%10==9) buf[i]=(byte)'\n'; } buf[0]='o'; OutputStream out=response.getOutputStream(); response.setContentType("text/plain"); while (d > 0) { if (b==1) { out.write(d%80==0?'\n':'.'); d } else if (d>=b) { out.write(buf); d=d-b; } else { out.write(buf,0,(int)d); d=0; } if (dribble!=null) { out.flush(); try { Thread.sleep(Long.parseLong(dribble)); } catch (Exception e) { e.printStackTrace(); break; } } } if (flush) out.flush(); return true; } // Handle a dump of data if (chars != null && chars.length() > 0) { long d=Long.parseLong(chars); int b=(block!=null&&block.length()>0)?Integer.parseInt(block):50; char[] buf=new char[b]; for (int i=0;i<b;i++) { buf[i]=(char)('0'+(i%10)); if (i%10==9) buf[i]='\n'; } buf[0]='o'; response.setContentType("text/plain"); PrintWriter out=response.getWriter(); while (d > 0 && !out.checkError()) { if (b==1) { out.write(d%80==0?'\n':'.'); d } else if (d>=b) { out.write(buf); d=d-b; } else { out.write(buf,0,(int)d); d=0; } } return true; } return false; } private String notag(String s) { if (s==null) return "null"; s=StringUtil.replace(s,"&","&amp;"); s=StringUtil.replace(s,"<","&lt;"); s=StringUtil.replace(s,">","&gt;"); return s; } }
package com.qpark.maven.plugin.modelanalysis; import java.io.File; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.Marshaller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.qpark.eip.core.model.analysis.Analysis; import com.qpark.eip.core.model.analysis.UUIDProvider; import com.qpark.eip.model.docmodel.ClusterType; import com.qpark.eip.model.docmodel.ComplexMappingType; import com.qpark.eip.model.docmodel.ComplexType; import com.qpark.eip.model.docmodel.ComplexUUIDMappingType; import com.qpark.eip.model.docmodel.DataType; import com.qpark.eip.model.docmodel.DefaultMappingType; import com.qpark.eip.model.docmodel.DirectMappingType; import com.qpark.eip.model.docmodel.DomainType; import com.qpark.eip.model.docmodel.ElementType; import com.qpark.eip.model.docmodel.EnterpriseType; import com.qpark.eip.model.docmodel.FieldMappingType; import com.qpark.eip.model.docmodel.FieldType; import com.qpark.eip.model.docmodel.FlowFilterType; import com.qpark.eip.model.docmodel.FlowMapInOutType; import com.qpark.eip.model.docmodel.FlowProcessType; import com.qpark.eip.model.docmodel.FlowRuleType; import com.qpark.eip.model.docmodel.FlowSubRequestType; import com.qpark.eip.model.docmodel.FlowType; import com.qpark.eip.model.docmodel.InterfaceMappingType; import com.qpark.eip.model.docmodel.ObjectFactory; import com.qpark.eip.model.docmodel.OperationType; import com.qpark.eip.model.docmodel.RequestResponseDataType; import com.qpark.eip.model.docmodel.ServiceType; import com.qpark.maven.xmlbeans.ComplexTypeChild; import com.qpark.maven.xmlbeans.XsdContainer; import com.qpark.maven.xmlbeans.XsdsUtil; public class AnalysisProvider { private static class RequestResponseDataFieldContainer { FieldType childIn; FieldType childOut; RequestResponseDataType rr; RequestResponseDataFieldContainer(final RequestResponseDataType rr, final FieldType childIn, final FieldType childOut) { this.rr = rr; this.childIn = childIn; this.childOut = childOut; } } /** The prefix to identify flow filter input. */ public static final String FLOW_FILTER_PREFIX_IN = "filterIn"; /** The prefix to identify flow filter output. */ public static final String FLOW_FILTER_PREFIX_OUT = "filterOut"; /** The prefix to identify flow map method input. */ public static final String FLOW_MAP_PREFIX_IN = "mapIn"; /** The prefix to identify flow map method output. */ public static final String FLOW_MAP_PREFIX_OUT = "mapOut"; /** The prefix to identify flow filter input. */ public static final String FLOW_PROCESS_PREFIX_IN = "in"; /** The prefix to identify flow filter output. */ public static final String FLOW_PROCESS_PREFIX_OUT = "out"; /** The prefix to identify flow rule input. */ public static final String FLOW_RULE_PREFIX_IN = "ruleIn"; /** The prefix to identify flow rule output. */ public static final String FLOW_RULE_PREFIX_OUT = "ruleOut"; /** The prefix to identify flow sub request input. */ public static final String FLOW_SUBREQUEST_PREFIX_IN = "subRequest"; /** The prefix to identify flow sub request output. */ public static final String FLOW_SUBREQUEST_PREFIX_OUT = "subResponse"; private static XsdsUtil createXsdsUtil(final String basePackageName, final String modelPath) { File f = new File(modelPath); String messagePackageNameSuffix = "msg mapping flow"; XsdsUtil xsds = XsdsUtil.getInstance(f, basePackageName, messagePackageNameSuffix, "delta"); return xsds; } /** * Get name of the {@link RequestResponseDataType}. * * @param fieldName * the name of the field. * @param prefix * the prefix to subtract. * @return the name. */ private static String getFlowMethodName(final String fieldName, final String prefix) { String suffix = ""; if (fieldName.equals(prefix)) { suffix = ""; } else { suffix = fieldName.substring(prefix.length(), fieldName.length()); } if (suffix.contains(" suffix = suffix.substring(0, suffix.indexOf(' } return suffix; } // private XsdsUtil xsds; public static void main(final String[] args) { String xsdPath; xsdPath = "C:\\xnb\\dev\\git\\EIP\\qp-enterprise-integration-platform-sample\\sample-domain-gen\\domain-gen-jaxb\\target\\model"; xsdPath = "C:\\bus-dev\\src\\com.ses.domain.gen\\domain-gen-jaxb\\target\\model"; xsdPath = "C:\\xnb\\dev\\git\\EIP\\qp-enterprise-integration-platform-sample\\sample-domain-gen\\domain-gen-jaxb\\target\\model"; xsdPath = "C:\\xnb\\dev\\38\\EIP\\qp-enterprise-integration-platform-sample\\sample-domain-gen\\domain-gen-jaxb\\target\\model"; String basePackageName = "com.samples.platform"; String modelVersion = "4.0.0"; Analysis a = new AnalysisProvider().createEnterprise(basePackageName, modelVersion, basePackageName, xsdPath); // System.exit(0); try { ObjectFactory of = new ObjectFactory(); JAXBElement<EnterpriseType> enterprise = of .createEnterprise(a.getEnterprise()); JAXBContext context = JAXBContext .newInstance("com.qpark.eip.model.docmodel"); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter sw = new StringWriter(); marshaller.marshal(enterprise, sw); System.out.println(sw.toString()); } catch (Exception e) { e.printStackTrace(); } } private static boolean testFlowExecutionFieldName(final String fieldName, final String prefixIn, final String prefixOut, final String flowExecutionName) { boolean value = false; value = String.format("%s%s", prefixIn, flowExecutionName).toString() .equals(fieldName) || prefixIn.equals(fieldName) && String.format("%s%s", prefixIn, prefixOut).toString() .equals(flowExecutionName); return value; } private Analysis analysis; private EnterpriseType enterprise; /** The {@link org.slf4j.Logger}. */ private final Logger logger = LoggerFactory .getLogger(AnalysisProvider.class); private ObjectFactory of = new ObjectFactory(); private UUIDProvider uuidProvider; @SuppressWarnings("static-method") private void addFlowExecutionOrder(final String modelVersion, final String parentId, final String name, final ComplexType ct, final FlowProcessType value) { for (FieldType field : ct.getField()) { String fieldName = field.getName(); value.getFilter().stream() .filter(f -> testFlowExecutionFieldName(fieldName, FLOW_FILTER_PREFIX_IN, FLOW_FILTER_PREFIX_OUT, f.getName())) .findFirst() .ifPresent(f -> value.getExecutionOrder().add(f.getId())); value.getRule().stream() .filter(f -> testFlowExecutionFieldName(fieldName, FLOW_RULE_PREFIX_IN, FLOW_RULE_PREFIX_OUT, f.getName())) .findFirst() .ifPresent(f -> value.getExecutionOrder().add(f.getId())); value.getMapInOut().stream() .filter(f -> testFlowExecutionFieldName(fieldName, FLOW_MAP_PREFIX_IN, FLOW_MAP_PREFIX_OUT, f.getName())) .findFirst() .ifPresent(f -> value.getExecutionOrder().add(f.getId())); value.getSubRequest().stream() .filter(f -> testFlowExecutionFieldName(fieldName, FLOW_SUBREQUEST_PREFIX_IN, FLOW_SUBREQUEST_PREFIX_OUT, f.getName())) .findFirst() .ifPresent(f -> value.getExecutionOrder().add(f.getId())); } } private void addFlowFilter(final String modelVersion, final String parentId, final String name, final ComplexType ct, final FlowProcessType value) { List<RequestResponseDataFieldContainer> rrdfs = this .getFlowRequestResponse(ct, FLOW_FILTER_PREFIX_IN, FLOW_FILTER_PREFIX_OUT, modelVersion); for (RequestResponseDataFieldContainer rrdf : rrdfs) { FlowFilterType filter = this.of.createFlowFilterType(); filter.setName(rrdf.rr.getName()); filter.setNamespace(ct.getNamespace()); filter.setParentId(value.getId()); filter.setModelVersion(modelVersion); this.uuidProvider.setUUID(filter); rrdf.rr.setParentId(filter.getId()); filter.setFilterInOut(rrdf.rr); if (Objects.nonNull(rrdf.childIn)) { filter.setFilterInFieldDescription( rrdf.childIn.getDescription()); } if (Objects.nonNull(rrdf.childOut)) { filter.setFilterOutFieldDescription( rrdf.childOut.getDescription()); } value.getFilter().add(filter); } } private void addFlowMapping(final String modelVersion, final String parentId, final String name, final ComplexType ct, final FlowProcessType value) { List<RequestResponseDataFieldContainer> rrdfs = this .getFlowRequestResponse(ct, FLOW_MAP_PREFIX_IN, FLOW_MAP_PREFIX_OUT, modelVersion); for (RequestResponseDataFieldContainer rrdf : rrdfs) { FlowMapInOutType mapInOut = this.of.createFlowMapInOutType(); mapInOut.setName(rrdf.rr.getName()); mapInOut.setNamespace(ct.getNamespace()); mapInOut.setParentId(value.getId()); mapInOut.setModelVersion(modelVersion); this.uuidProvider.setUUID(mapInOut); rrdf.rr.setParentId(mapInOut.getId()); mapInOut.setMapInOut(rrdf.rr); if (Objects.nonNull(rrdf.childIn)) { mapInOut.setMapInFieldDescription( rrdf.childIn.getDescription()); } if (Objects.nonNull(rrdf.childOut)) { mapInOut.setMapOutFieldDescription( rrdf.childOut.getDescription()); } value.getMapInOut().add(mapInOut); for (RequestResponseDataFieldContainer rrdfx : rrdfs) { this.setFlowMapInOutTypeInterfaceMappingIds(mapInOut, rrdfx.rr.getRequestId()); this.setFlowMapInOutTypeInterfaceMappingIds(mapInOut, rrdfx.rr.getResponseId()); } } } private void addFlowRule(final String modelVersion, final String parentId, final String name, final ComplexType ct, final FlowProcessType value) { List<RequestResponseDataFieldContainer> rrdfs = this .getFlowRequestResponse(ct, FLOW_RULE_PREFIX_IN, FLOW_RULE_PREFIX_OUT, modelVersion); for (RequestResponseDataFieldContainer rrdf : rrdfs) { FlowRuleType rule = this.of.createFlowRuleType(); rule.setName(rrdf.rr.getName()); rule.setNamespace(ct.getNamespace()); rule.setParentId(value.getId()); rule.setModelVersion(modelVersion); this.uuidProvider.setUUID(rule); rrdf.rr.setParentId(rule.getId()); rule.setRuleInOut(rrdf.rr); if (Objects.nonNull(rrdf.childIn)) { rule.setRuleInFieldDescription(rrdf.childIn.getDescription()); } if (Objects.nonNull(rrdf.childOut)) { rule.setRuleOutFieldDescription(rrdf.childOut.getDescription()); } value.getRule().add(rule); } } private void addFlowSubRequest(final String modelVersion, final String parentId, final String name, final ComplexType ct, final FlowProcessType value) { List<RequestResponseDataFieldContainer> rrdfs = this .getFlowRequestResponse(ct, FLOW_SUBREQUEST_PREFIX_IN, FLOW_SUBREQUEST_PREFIX_OUT, modelVersion); for (RequestResponseDataFieldContainer rrdf : rrdfs) { FlowSubRequestType sub = this.of.createFlowSubRequestType(); sub.setName(rrdf.rr.getName()); sub.setNamespace(ct.getNamespace()); sub.setParentId(value.getId()); sub.setModelVersion(modelVersion); this.uuidProvider.setUUID(sub); rrdf.rr.setParentId(sub.getId()); sub.setSubRequestInOut(rrdf.rr); if (Objects.nonNull(rrdf.childIn)) { sub.setSubRequestFieldDescription( rrdf.childIn.getDescription()); } if (Objects.nonNull(rrdf.childOut)) { sub.setSubResponseFieldDescription( rrdf.childOut.getDescription()); } value.getSubRequest().add(sub); } } /** * Create the {@link Analysis} out of the mode. * * @param enterpriseName * the name of the enterprise. * @param basePackageName * the name of the base package, e.g <i>com.samples.platform</i>. * @param modelPath * the path, where the model could be found. * @return the {@link Analysis}. */ public Analysis createEnterprise(final String enterpriseName, final String modelVersion, final String basePackageName, final String modelPath) { return this.createEnterprise(enterpriseName, modelVersion, createXsdsUtil(basePackageName, modelPath)); } /** * Create the {@link Analysis} out of the mode. * * @param enterpriseName * the name of the enterprise. * @param xsds * the {@link XsdsUtil}. * @return the {@link Analysis}. */ public Analysis createEnterprise(final String enterpriseName, final String modelVersion, final XsdsUtil xsds) { this.logger.debug("+createEnterprise {} {}", enterpriseName, modelVersion); this.analysis = new Analysis(this.of.createEnterpriseType()); this.enterprise = this.analysis.getEnterprise(); this.enterprise.setName(enterpriseName); this.enterprise.setModelVersion(modelVersion); this.uuidProvider = new UUIDProvider(this.analysis); xsds.getXsdContainerMap().values().stream().forEach(file -> { DomainType domain = this.parseDomainType(file, modelVersion); this.parseClusterType(domain, file); }); xsds.getComplexTypes().stream().forEach(ct -> this.parseDataType( this.analysis.getCluster(ct.getTargetNamespace()), ct)); xsds.getComplexTypes().stream().forEach(ct -> this.setFieldTypes( this.analysis.getCluster(ct.getTargetNamespace()), ct)); xsds.getElementTypes().stream().forEach(et -> this.getElementType( this.analysis.getCluster(et.getTargetNamespace()), et)); xsds.getElementTypes().stream().filter(et -> et.isRequest()) .forEach(etRequest -> { com.qpark.maven.xmlbeans.ElementType etResponse = XsdsUtil .findResponse(etRequest, xsds.getElementTypes(), xsds); if (Objects.nonNull(etResponse)) { String ctRequestDescription = null; if (Objects.nonNull(etRequest.getComplexType())) { ctRequestDescription = etRequest.getComplexType() .getAnnotationDocumentation(); } String ctResponseDescription = null; if (Objects.nonNull(etResponse.getComplexType())) { ctResponseDescription = etResponse.getComplexType() .getAnnotationDocumentation(); } this.getServiceOperation( this.analysis.getCluster( etRequest.getTargetNamespace()), etRequest.getServiceId(), etRequest.getOperationName(), this.analysis.getElementType( etRequest.toQNameString()), ctRequestDescription, this.analysis.getElementType( etResponse.toQNameString()), ctResponseDescription); } }); xsds.getComplexTypes().stream() .filter(ct -> ct.isRequestType() && ct.isFlowInputType()) .forEach(ctRequest -> { com.qpark.maven.xmlbeans.ComplexType ctResponse = XsdsUtil .findResponse(ctRequest, xsds.getComplexTypes(), xsds); if (Objects.nonNull(ctResponse) && ctResponse.isFlowOutputType()) { FlowType flow = this.getFlowType( this.analysis.getCluster( ctRequest.getTargetNamespace()), (ComplexType) this.analysis .getDataType(ctRequest.toQNameString()), (ComplexType) this.analysis.getDataType( ctResponse.toQNameString())); this.enterprise.getFlows().add(flow); } }); this.analysis.getDataTypes().stream() .filter(dt -> FieldMappingType.class.isInstance(dt)) .map(dt -> (FieldMappingType) dt).forEach(fm -> { Set<String> fieldMappingIds = new TreeSet<String>(); Map<String, ComplexType> ctMap = new HashMap<String, ComplexType>(); fieldMappingIds.addAll(fm.getInput().stream().filter(in -> Objects.nonNull(in) && Objects.nonNull(in.getFieldTypeDefinitionId())) .map(in -> in.getFieldTypeDefinitionId()) .collect(Collectors.toList())); this.getFieldMappingInputTypes(fieldMappingIds, ctMap); ctMap.values().stream() .filter(ct -> Objects.nonNull(ct.getName())) .forEach(ct -> fm.getFieldMappingInputType() .add(ct.getId())); }); this.analysis.getDataTypes().stream() .filter(dt -> InterfaceMappingType.class.isInstance(dt)) .map(dt -> (InterfaceMappingType) dt).forEach(inf -> { Set<String> fieldMappingIds = new TreeSet<String>(); Map<String, ComplexType> ctMap = new HashMap<String, ComplexType>(); fieldMappingIds.addAll(inf.getFieldMappings().stream() .map(fm -> fm.getFieldTypeDefinitionId()) .collect(Collectors.toList())); this.getFieldMappingInputTypes(fieldMappingIds, ctMap); ctMap.values().stream() .filter(ct -> Objects.nonNull(ct.getName())) .forEach(ct -> inf.getFieldMappingInputType() .add(ct.getId())); }); this.logger.debug("-createEnterprise {} {}", enterpriseName, modelVersion); return this.analysis; } private void getFieldMappingInputTypes(final Set<String> fieldMappingIds, final Map<String, ComplexType> ctMap) { List<FieldMappingType> fieldMappings = this.analysis.getDataTypes() .stream().filter(dt -> FieldMappingType.class.isInstance(dt)) .map(dt -> (FieldMappingType) dt) .filter(fmt -> fieldMappingIds.contains(fmt.getId())) .collect(Collectors.toList()); if (Objects.nonNull(fieldMappings) && fieldMappings.size() > 0) { Set<String> ids = new TreeSet<String>(); fieldMappings.stream() .forEach( fm -> fm.getInput().stream() .filter(i -> Objects.nonNull(i.getName()) && !i.getName() .equals("interfaceName") && !i.getName().equals("value") && !i.getName().equals("return")) .forEach(i -> ids.add(i.getFieldTypeDefinitionId()))); this.analysis.getDataTypes().stream() .filter(dt -> ComplexType.class.isInstance(dt)) .map(dt -> (ComplexType) dt) .filter(ct -> ids.contains(ct.getId())) .forEach(ct -> ctMap.put(ct.getId(), ct)); this.getFieldMappingInputTypes(ids, ctMap); } } private ElementType getElementType(final ClusterType cluster, final com.qpark.maven.xmlbeans.ElementType element) { ElementType value = this.of.createElementType(); value.setDescription(element.getAnnotationDocumentation()); value.setName(element.toQNameString()); value.setNamespace(element.getTargetNamespace()); value.setModelVersion(cluster.getModelVersion()); value.setParentId(cluster.getId()); if (element.getElement().getType() != null) { String elemId = this.uuidProvider.getDataTypeUUID( String.valueOf(element.getElement().getType().getName()), cluster.getModelVersion()); DataType dt = (DataType) this.analysis.get(elemId); if (dt != null) { value.setComplexTypeId(dt.getId()); } } this.uuidProvider.setUUID(value); cluster.getElementType().add(value); return value; } private List<FieldType> getFieldTypes(final ClusterType cluster, final com.qpark.maven.xmlbeans.ComplexType element, final String parentId) { List<FieldType> value = new ArrayList<FieldType>(); int sequenceNumber = 0; for (ComplexTypeChild child : element.getChildren()) { DataType dt = this.parseDataType(cluster, child.getComplexType()); FieldType field = this.of.createFieldType(); field.setParentId(parentId); field.setModelVersion(cluster.getModelVersion()); field.setName(child.getChildName()); field.setSequenceNumber(sequenceNumber); field.setCardinality(child.getCardinality()); field.setCardinalityMaxOccurs(child.getMaxOccurs() == null ? null : child.getMaxOccurs().intValue()); field.setCardinalityMinOccurs(child.getMinOccurs() == null ? null : child.getMinOccurs().intValue()); field.setDescription(child.getAnnotationDocumentation()); field.setFieldTypeDefinitionId(dt == null ? null : dt.getId()); field.setListField(child.isList()); field.setNamespace(element.getTargetNamespace()); field.setOptionalField(child.isOptional()); this.uuidProvider.setUUID(field); value.add(field); sequenceNumber++; } return value; } private FlowProcessType getFlowProcessType(final String modelVersion, final String parentId, final String name, final ComplexType ct) { List<RequestResponseDataFieldContainer> rrdfs = this .getFlowRequestResponse(ct, FLOW_PROCESS_PREFIX_IN, FLOW_PROCESS_PREFIX_OUT, modelVersion); if (rrdfs.size() <= 0) { return null; } else { final FlowProcessType value = this.of.createFlowProcessType(); value.setName(name); value.setModelVersion(modelVersion); value.setParentId(parentId); value.setNamespace(ct.getNamespace()); this.uuidProvider.setUUID(value); rrdfs.get(0).rr.setParentId(value.getId()); value.setRequestResponse(rrdfs.get(0).rr); if (Objects.nonNull(rrdfs.get(0).childIn)) { value.setRequestFieldDescription( rrdfs.get(0).childIn.getDescription()); } if (Objects.nonNull(rrdfs.get(0).childOut)) { value.setResponseFieldDescription( rrdfs.get(0).childOut.getDescription()); } this.addFlowSubRequest(modelVersion, parentId, name, ct, value); this.addFlowFilter(modelVersion, parentId, name, ct, value); this.addFlowRule(modelVersion, parentId, name, ct, value); this.addFlowMapping(modelVersion, parentId, name, ct, value); this.addFlowExecutionOrder(modelVersion, parentId, name, ct, value); return value; } } /** * Get the list of {@link FlowRequestResponseNameContainer}s out of the flow * input or output type. * * @param ct * the {@link DataType} which is the flow input or output type. * @param prefixIn * the prefix of the request part. * @param prefixOut * the prefix of the response part. * @return the {@link FlowRequestResponseNameContainer}. */ private List<RequestResponseDataFieldContainer> getFlowRequestResponse( final ComplexType ct, final String prefixIn, final String prefixOut, final String modelVersion) { List<RequestResponseDataFieldContainer> requestResponses = new ArrayList<RequestResponseDataFieldContainer>(); RequestResponseDataFieldContainer rrf; RequestResponseDataType requestResponse = null; DataType request = null; DataType response = null; String name; Set<String> inChildrenFound = new TreeSet<String>(); for (FieldType childOut : ct.getField()) { if (childOut.getName().startsWith(prefixOut)) { name = getFlowMethodName(childOut.getName(), prefixOut); for (FieldType childIn : ct.getField()) { if (childIn.getName().equals(new StringBuffer(16) .append(prefixIn).append(name).toString())) { request = (DataType) this.analysis .get(childIn.getFieldTypeDefinitionId()); response = (DataType) this.analysis .get(childOut.getFieldTypeDefinitionId()); requestResponse = this.getRequestResponseDataType( modelVersion, null, request, response); if (name.trim().length() == 0) { name = String.format("%s%s", prefixIn, prefixOut) .toString(); } requestResponse.setName(name); rrf = new RequestResponseDataFieldContainer( requestResponse, childIn, childOut); requestResponses.add(rrf); inChildrenFound.add( new StringBuffer(requestResponse.getRequestId()) .append(requestResponse.getRequestId()) .toString()); } } } } for (FieldType childIn : ct.getField()) { if (childIn.getName().startsWith(prefixIn) && !inChildrenFound.contains(childIn.getName())) { name = getFlowMethodName(childIn.getName(), prefixIn); for (FieldType childOut : ct.getField()) { if (childOut.getName().equals(new StringBuffer(16) .append(prefixOut).append(name).toString())) { request = (DataType) this.analysis .get(childIn.getFieldTypeDefinitionId()); response = (DataType) this.analysis .get(childOut.getFieldTypeDefinitionId()); requestResponse = this.getRequestResponseDataType( modelVersion, null, request, response); if (name.trim().length() == 0) { name = String.format("%s%s", prefixIn, prefixOut) .toString(); } requestResponse.setName(name); if (!inChildrenFound.contains( new StringBuffer(requestResponse.getRequestId()) .append(requestResponse.getRequestId()) .toString())) { rrf = new RequestResponseDataFieldContainer( requestResponse, childIn, childOut); requestResponses.add(rrf); inChildrenFound.add(requestResponse.getName()); } } } } } return requestResponses; } private FlowType getFlowType(final ClusterType cluster, final ComplexType ctRequest, final ComplexType ctResponse) { FlowType value = this.of.createFlowType(); /* Parent is enterprise which does not have an id. */ value.setClusterId(cluster.getId()); value.setModelVersion(cluster.getModelVersion()); value.setName(ctRequest.getJavaClassName().substring(0, ctRequest.getJavaClassName().lastIndexOf("RequestType"))); value.setNamespace(ctRequest.getNamespace()); value.setDescription(ctRequest.getDescription()); value.setShortName(value.getName() .substring(value.getName().lastIndexOf('.') + 1)); this.uuidProvider.setUUID(value); value.setInvokeFlowDefinition( this.getRequestResponseDataType(cluster.getModelVersion(), value.getId(), ctRequest, ctResponse)); value.setExecuteRequest( this.getFlowProcessType(cluster.getModelVersion(), value.getId(), "executeRequest", ctRequest)); value.setProcessResponse( this.getFlowProcessType(cluster.getModelVersion(), value.getId(), "processResponse", ctResponse)); return value; } private RequestResponseDataType getRequestResponseDataType( final String modelVersion, final String parentId, final DataType request, final DataType response) { RequestResponseDataType value = this.of.createRequestResponseDataType(); value.setName(new StringBuffer(128).append(request.getName()) .append("#").append(response.getName()).toString()); value.setParentId(parentId); value.setModelVersion(modelVersion); value.setNamespace(request.getNamespace()); value.setRequestId(request.getId()); value.setRequestDescription(request.getDescription()); value.setResponseId(response.getId()); value.setResponseDescription(response.getDescription()); this.uuidProvider.setUUID(value); return value; } private OperationType getServiceOperation(final ClusterType cluster, final String serviceId, final String operationName, final ElementType request, final String ctRequestDescription, final ElementType response, final String ctResponseDescription) { ServiceType service = this.analysis.getServiceType(serviceId); if (service == null) { DomainType domain = (DomainType) this.analysis .get(cluster.getParentId()); service = this.of.createServiceType(); service.setName(serviceId); service.setModelVersion(cluster.getModelVersion()); this.uuidProvider.setUUID(service); service.setClusterId(cluster.getId()); service.setDescription(cluster.getDescription()); service.setNamespace(cluster.getName()); service.setPackageName(cluster.getPackageName()); service.setServiceId(serviceId); service.setSecurityRoleName( String.format("ROLE_%s", serviceId.toUpperCase())); domain.getService().add(service); } OperationType value = this.of.createOperationType(); value.setName(new StringBuffer(128).append(cluster.getPackageName()) .append(".").append(operationName).toString()); value.setNamespace(cluster.getName()); value.setModelVersion(cluster.getModelVersion()); value.setParentId(service.getId()); value.setSecurityRoleName(String.format("%s_%s", service.getSecurityRoleName(), operationName.toUpperCase())); value.setShortName(operationName); value.setRequestFieldDescription(ctRequestDescription); value.setResponseFieldDescription(ctResponseDescription); RequestResponseDataType rr = this.getRequestResponseDataType( cluster.getModelVersion(), service.getId(), request, response); value.setRequestResponse(rr); this.uuidProvider.setUUID(value); service.getOperation().add(value); return value; } /** * Get the {@link ClusterType} of the {@link XsdContainer}. * * @param domain * the {@link DomainType}. * @param file * the {@link XsdContainer}. * @return the {@link ClusterType}. */ private ClusterType parseClusterType(final DomainType domain, final XsdContainer file) { ClusterType value = this.analysis.getCluster(file.getTargetNamespace()); if (value == null) { value = this.of.createClusterType(); value.setName(file.getTargetNamespace()); value.setModelVersion(domain.getModelVersion()); this.uuidProvider.setUUID(value); value.setParentId(domain.getId()); domain.getCluster().add(value); value.setDescription(file.getAnnotationDocumentation()); value.setFileName(file.getFile().getName()); value.setPackageName(file.getPackageName()); value.setVersion(file.getVersion()); value.getWarning().addAll(file.getWarnings()); } return value; } private DataType parseDataType(final ClusterType cluster, final com.qpark.maven.xmlbeans.ComplexType ct) { String elemId = this.uuidProvider.getDataTypeUUID(ct.toQNameString(), cluster.getModelVersion()); DataType value = (DataType) this.analysis.get(elemId); if (value != null) { // Noting to do. } else if (ct.getTargetNamespace() .equals(XsdsUtil.QNAME_BASE_SCHEMA_NAMESPACE_URI) && this.analysis.getDataType(ct.toQNameString()) == null) { DataType dt = this.of.createDataType(); dt.setName(ct.toQNameString()); this.setDataType(cluster.getModelVersion(), ct, dt); this.uuidProvider.setUUID(dt); this.enterprise.getBasicDataTypes().add(dt); } else if (ct.isDefaultMappingType()) { DefaultMappingType x = this.of.createDefaultMappingType(); x.setParentId(cluster.getId()); x.setMappingType("default"); this.setDataType(cluster.getModelVersion(), ct, x); this.setDefaultMappingType(cluster.getModelVersion(), ct, x); cluster.getDefaultMappingType().add(x); value = x; } else if (ct.isDirectMappingType()) { DirectMappingType x = this.of.createDirectMappingType(); x.setParentId(cluster.getId()); x.setMappingType("direct"); this.setDataType(cluster.getModelVersion(), ct, x); this.setDirectMappingType(cluster.getModelVersion(), ct, x); cluster.getDirectMappingType().add(x); value = x; } else if (ct.isComplexMappingType()) { ComplexMappingType x = this.of.createComplexMappingType(); x.setParentId(cluster.getId()); x.setMappingType("complex"); this.setDataType(cluster.getModelVersion(), ct, x); cluster.getComplexMappingType().add(x); value = x; } else if (ct.isComplexUUIDMappingType()) { ComplexUUIDMappingType x = this.of.createComplexUUIDMappingType(); x.setParentId(cluster.getId()); x.setMappingType("complexUUID"); this.setDataType(cluster.getModelVersion(), ct, x); cluster.getComplexUUIDMappingType().add(x); value = x; } else if (ct.isInterfaceMappingType()) { InterfaceMappingType x = this.of.createInterfaceMappingType(); x.setParentId(cluster.getId()); this.setDataType(cluster.getModelVersion(), ct, x); cluster.getInterfaceMappingType().add(x); value = x; } else if (this.analysis.get(elemId) == null) { ComplexType x = this.of.createComplexType(); x.setParentId(cluster.getId()); this.setDataType(cluster.getModelVersion(), ct, x); x.setIsFlowInputType(ct.isFlowInputType()); x.setIsFlowOutputType(ct.isFlowOutputType()); x.setIsMappingRequestType(ct.isMapRequestType()); x.setIsMappingResponseType(ct.isMapResponseType()); cluster.getComplexType().add(x); if (ct.getParent() != null) { DataType parent = this.parseDataType(cluster, ct.getParent()); x.setDescendedFromId(parent.getId()); } for (com.qpark.maven.xmlbeans.ComplexType innerCt : ct .getInnerTypeDefs()) { this.parseDataType(cluster, innerCt); } value = x; } return value; } /** * Get the {@link DomainType} of the {@link XsdContainer}. If the * {@link DomainType} is not present at this stage, it will be created. * * @param file * the {@link XsdContainer}. * @return the {@link DomainType}. */ private DomainType parseDomainType(final XsdContainer file, final String modelVersion) { DomainType value = this.analysis .getDomainType(file.getDomainPathName()); if (value == null) { value = this.of.createDomainType(); value.setName(file.getDomainPathName()); value.setModelVersion(modelVersion); this.uuidProvider.setUUID(value); this.enterprise.getDomains().add(value); } return value; } private void setDataType(final String modelVersion, final com.qpark.maven.xmlbeans.ComplexType element, final DataType value) { value.setDescription(element.getAnnotationDocumentation()); value.setName(element.toQNameString()); value.setModelVersion(modelVersion); value.setNamespace(element.getTargetNamespace()); value.setJavaClassName(element.getClassNameFullQualified()); value.setJavaPackageName(element.getPackageName()); value.setShortName(element.getClassName()); this.uuidProvider.setUUID(value); } @SuppressWarnings("static-method") private void setDefaultMappingType(final String modelVersion, final com.qpark.maven.xmlbeans.ComplexType element, final DefaultMappingType value) { value.setDefaultValue(element.getDefaultValue()); if (value.getDescription() == null || value.getDescription().trim().length() == 0) { StringBuffer sb = new StringBuffer(64); sb.append("Default value: "); sb.append(element.getDefaultValue()); value.setDescription(sb.toString()); } } private void setDirectMappingType(final String modelVersion, final com.qpark.maven.xmlbeans.ComplexType ct, final DirectMappingType value) { if (Objects.nonNull(ct.getType()) && ct.getType().getName().getLocalPart().indexOf('.') > 0) { String accessorPart = ct.getType().getName().getLocalPart() .substring( ct.getType().getName().getLocalPart().indexOf('.') + 1, ct.getType().getName().getLocalPart().length()) .replace("MappingType", ""); ct.getChildren().stream() .filter(ctc -> Objects.nonNull(ctc.getComplexType()) && !ctc.getChildName().equals("value") && !ctc.getChildName().equals("return")) .findFirst().ifPresent(ctc -> { String ctId = this.uuidProvider.getDataTypeUUID( ctc.getComplexType().toQNameString(), modelVersion); value.setAccessorFieldId( this.uuidProvider.getFieldTypeUUID(accessorPart, ctId, modelVersion)); value.setAccessor(String.format("%s.%s", ctc.getChildName(), accessorPart)); }); } if (Objects.isNull(value.getAccessor())) { value.setAccessor(ct.getType().getName().getLocalPart() .replace("MappingType", "")); } if (Objects.nonNull(value.getAccessor())) { String[] strs = value.getAccessor().split("\\."); if (value.getDescription() == null || value.getDescription().trim().length() == 0 && strs.length > 0) { StringBuffer sb = new StringBuffer(64); sb.append("Get "); for (int i = strs.length - 1; i > 0; i sb.append(strs[i]).append(" of "); } sb.append(strs[0]).append("Type."); value.setDescription(sb.toString()); } } } @SuppressWarnings("static-method") private void setFieldMappingType(final FieldMappingType type, final List<FieldType> fields) { FieldType returnField = null; for (FieldType f : fields) { if (f.getName().equals("return")) { returnField = f; } } if (returnField != null) { type.setReturnValueTypeId(returnField.getFieldTypeDefinitionId()); } type.getInput().addAll(fields); } private void setFieldTypes(final ClusterType cluster, final com.qpark.maven.xmlbeans.ComplexType ct) { String elemId = this.uuidProvider.getDataTypeUUID(ct.toQNameString(), cluster.getModelVersion()); DataType dt = (DataType) this.analysis.get(elemId); List<FieldType> fields = this.getFieldTypes(cluster, ct, elemId); if (ComplexType.class.isInstance(dt)) { ((ComplexType) dt).getField().addAll(fields); } else if (InterfaceMappingType.class.isInstance(dt)) { ((InterfaceMappingType) dt).getFieldMappings().addAll(fields); } else if (FieldMappingType.class.isInstance(dt)) { this.setFieldMappingType((FieldMappingType) dt, fields); } } private void setFlowMapInOutTypeInterfaceMappingIds( final FlowMapInOutType mapInOut, final String dataTypeId) { DataType dt = (DataType) this.analysis.get(dataTypeId); if (dt != null && ComplexType.class.isInstance(dt)) { for (FieldType field : ((ComplexType) dt).getField()) { DataType dtx = (DataType) this.analysis .get(field.getFieldTypeDefinitionId()); if (dtx != null && InterfaceMappingType.class.isInstance(dtx) && !mapInOut.getInterfaceMappingId() .contains(field.getFieldTypeDefinitionId())) { mapInOut.getInterfaceMappingId() .add(field.getFieldTypeDefinitionId()); } } } } }
package sk.henrichg.phoneprofiles; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.provider.Settings; public class ScreenOnOffBroadcastReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { //Thread.setDefaultUncaughtExceptionHandler(new TopExceptionHandler()); PPApplication.logE("ScreenOnOffBroadcastReceiver.onReceive","xxx"); Context appContext = context.getApplicationContext(); if (!PPApplication.getApplicationStarted(appContext, true)) // application is not started return; PPApplication.logE("ScreenOnOffBroadcastReceiver.onReceive","application started"); boolean lockDeviceEnabled = false; if (PPApplication.lockDeviceActivity != null) { lockDeviceEnabled = true; PPApplication.lockDeviceActivity.finish(); PPApplication.lockDeviceActivity.overridePendingTransition(0, 0); } //PPApplication.loadPreferences(context); if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) PPApplication.logE("@@@ ScreenOnOffBroadcastReceiver.onReceive", "screen on"); else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { PPApplication.logE("@@@ ScreenOnOffBroadcastReceiver.onReceive", "screen off"); ActivateProfileHelper.setScreenUnlocked(appContext, false); if (ApplicationPreferences.notificationShowInStatusBar(appContext) && ApplicationPreferences.notificationHideInLockscreen(appContext)) { DataWrapper dataWrapper = new DataWrapper(appContext, true, false, 0); dataWrapper.getActivateProfileHelper().initialize(dataWrapper, appContext); //dataWrapper.getActivateProfileHelper().removeNotification(); //dataWrapper.getActivateProfileHelper().setAlarmForRecreateNotification(); Profile activatedProfile = dataWrapper.getActivatedProfile(); dataWrapper.getActivateProfileHelper().showNotification(activatedProfile); dataWrapper.invalidateDataWrapper(); } } if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) { PPApplication.logE("@@@ ScreenOnOffBroadcastReceiver.onReceive", "screen unlock"); ActivateProfileHelper.setScreenUnlocked(appContext, true); DataWrapper dataWrapper = new DataWrapper(appContext, true, false, 0); dataWrapper.getActivateProfileHelper().initialize(dataWrapper, appContext); if (ApplicationPreferences.notificationShowInStatusBar(appContext) && ApplicationPreferences.notificationHideInLockscreen(appContext)) { //dataWrapper.getActivateProfileHelper().removeNotification(); //dataWrapper.getActivateProfileHelper().setAlarmForRecreateNotification(); Profile activatedProfile = dataWrapper.getActivatedProfile(); dataWrapper.getActivateProfileHelper().showNotification(activatedProfile); } // change screen timeout if (lockDeviceEnabled && Permissions.checkLockDevice(appContext)) Settings.System.putInt(appContext.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, PPApplication.screenTimeoutBeforeDeviceLock); int screenTimeout = ActivateProfileHelper.getActivatedProfileScreenTimeout(appContext); if ((screenTimeout > 0) && (Permissions.checkScreenTimeout(context))) dataWrapper.getActivateProfileHelper().setScreenTimeout(screenTimeout); dataWrapper.invalidateDataWrapper(); // enable/disable keyguard Intent keyguardService = new Intent(appContext, KeyguardService.class); appContext.startService(keyguardService); } if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { PPApplication.logE("@@@ ScreenOnOffBroadcastReceiver.onReceive", "screen on"); if (ApplicationPreferences.notificationShowInStatusBar(appContext) && ApplicationPreferences.notificationHideInLockscreen(appContext)) { DataWrapper dataWrapper = new DataWrapper(appContext, true, false, 0); dataWrapper.getActivateProfileHelper().initialize(dataWrapper, appContext); //dataWrapper.getActivateProfileHelper().removeNotification(); //dataWrapper.getActivateProfileHelper().setAlarmForRecreateNotification(); Profile activatedProfile = dataWrapper.getActivatedProfile(); dataWrapper.getActivateProfileHelper().showNotification(activatedProfile); dataWrapper.invalidateDataWrapper(); } } } }
package br.edu.ifrn.helppet.dominio; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.RequiredArgsConstructor; import lombok.ToString; /** * * @author camila */ @Getter @Setter @ToString(exclude = "foto") @EqualsAndHashCode(exclude = {"foto", "nascimento", "localizacao"}) @Builder @AllArgsConstructor(access = AccessLevel.PUBLIC) @NoArgsConstructor(access = AccessLevel.PUBLIC) public class Usuario { private String nome; private String email; private String senha; private String foto; private String nascimento; private String localizacao; private String telefone; private Permissao permissao; }
package ua.com.fielden.platform.companion; import static java.lang.String.format; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; import static org.hibernate.LockOptions.UPGRADE; import static ua.com.fielden.platform.companion.helper.KeyConditionBuilder.createQueryByKey; import static ua.com.fielden.platform.dao.HibernateMappingsGenerator.ID_SEQUENCE_NAME; import static ua.com.fielden.platform.entity.AbstractEntity.ID; import static ua.com.fielden.platform.entity.ActivatableAbstractEntity.ACTIVE; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.from; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.select; import static ua.com.fielden.platform.entity.validation.custom.DefaultEntityValidator.validateWithoutCritOnly; import static ua.com.fielden.platform.reflection.ActivatableEntityRetrospectionHelper.addToResultIfApplicableFromActivatablePerspective; import static ua.com.fielden.platform.reflection.ActivatableEntityRetrospectionHelper.collectActivatableNotDirtyProperties; import static ua.com.fielden.platform.reflection.ActivatableEntityRetrospectionHelper.isNotSpecialActivatableToBeSkipped; import static ua.com.fielden.platform.reflection.Reflector.isMethodOverriddenOrDeclared; import static ua.com.fielden.platform.utils.DbUtils.nextIdValue; import static ua.com.fielden.platform.utils.Validators.findActiveDeactivatableDependencies; import java.lang.reflect.Field; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import org.apache.log4j.Logger; import org.hibernate.Session; import org.joda.time.DateTime; import ua.com.fielden.platform.dao.CommonEntityDao; import ua.com.fielden.platform.dao.exceptions.EntityAlreadyExists; import ua.com.fielden.platform.dao.exceptions.EntityCompanionException; import ua.com.fielden.platform.entity.AbstractEntity; import ua.com.fielden.platform.entity.AbstractPersistentEntity; import ua.com.fielden.platform.entity.AbstractUnionEntity; import ua.com.fielden.platform.entity.ActivatableAbstractEntity; import ua.com.fielden.platform.entity.annotation.DeactivatableDependencies; import ua.com.fielden.platform.entity.annotation.Required; import ua.com.fielden.platform.entity.factory.ICompanionObjectFinder; import ua.com.fielden.platform.entity.fetch.FetchModelReconstructor; import ua.com.fielden.platform.entity.meta.MetaProperty; import ua.com.fielden.platform.entity.meta.PropertyDescriptor; import ua.com.fielden.platform.entity.query.EntityAggregates; import ua.com.fielden.platform.entity.query.EntityFetcher; import ua.com.fielden.platform.entity.query.QueryExecutionContext; import ua.com.fielden.platform.entity.query.fluent.fetch; import ua.com.fielden.platform.entity.query.model.AggregatedResultQueryModel; import ua.com.fielden.platform.entity.query.model.EntityResultQueryModel; import ua.com.fielden.platform.error.Result; import ua.com.fielden.platform.reflection.AnnotationReflector; import ua.com.fielden.platform.reflection.Finder; import ua.com.fielden.platform.reflection.TitlesDescsGetter; import ua.com.fielden.platform.security.user.User; import ua.com.fielden.platform.types.tuples.T2; import ua.com.fielden.platform.utils.EntityUtils; /** * The default implementation of contract {@link IEntityActuator} to save/update persistent entities. * * @author TG Team * * @param <T> */ public final class PersistentEntitySaver<T extends AbstractEntity<?>> implements IEntityActuator<T> { private final Supplier<Session> session; private final Supplier<String> transactionGuid; private final Class<T> entityType; private final Class<? extends Comparable<?>> keyType; private final Supplier<Boolean> isFilterable; private final Supplier<ICompanionObjectFinder> coFinder; private final Supplier<QueryExecutionContext> newQueryExecutionContext; private final Supplier<User> user; private final Supplier<DateTime> now; private final Supplier<Boolean> skipRefetching; private final BiConsumer<T, List<String>> processAfterSaveEvent; private final Consumer<MetaProperty<?>> assignBeforeSave; private final BiFunction<Long, fetch<T>, T> findById; private final Function<EntityResultQueryModel<T>, Integer> kount; private Boolean targetEntityTypeHasValidateOverridden; private final Logger logger; public PersistentEntitySaver( final Supplier<Session> session, final Supplier<String> transactionGuid, final Class<T> entityType, final Class<? extends Comparable<?>> keyType, final Supplier<User> user, final Supplier<DateTime> now, final Supplier<Boolean> skipRefetching, final Supplier<Boolean> isFilterable, final Supplier<ICompanionObjectFinder> coFinder, final Supplier<QueryExecutionContext> newQueryExecutionContext, final BiConsumer<T, List<String>> processAfterSaveEvent, final Consumer<MetaProperty<?>> assignBeforeSave, final BiFunction<Long, fetch<T>, T> findById, final Function<EntityResultQueryModel<T>, Integer> count, final Logger logger ) { this.session = session; this.transactionGuid = transactionGuid; this.entityType = entityType; this.keyType = keyType; this.user = user; this.now = now; this.skipRefetching = skipRefetching; this.isFilterable = isFilterable; this.coFinder = coFinder; this.newQueryExecutionContext = newQueryExecutionContext; this.processAfterSaveEvent = processAfterSaveEvent; this.assignBeforeSave = assignBeforeSave; this.findById = findById; this.kount = count; this.logger = logger; } /** * Saves the provided entity. This method checks entity version and throws StaleObjectStateException if the provided entity is stale. There is no in-memory referential * integrity guarantee -- the returned instance is always a different instance. However, from the perspective of data loading, it is guaranteed that the object graph of the * returned instance contains the object graph of the passed in entity as its subgraph (i.e. it can be wider, but not narrower). * <p> * This method must be invoked in the context of an open DB session and supports saving only of persistent entities. Otherwise, an exception is thrown. */ @Override public T save(final T entity) { if (entity == null || !entity.isPersistent()) { throw new EntityCompanionException(format("Only non-null persistent entities are permitted for saving. Ether type [%s] is not persistent or entity is null.", entityType.getName())); } else if (!entity.isInstrumented()) { throw new EntityCompanionException(format("Uninstrumented entity of type [%s] cannot be saved.", entityType.getName())); } else if (!entity.isDirty() && validateEntity(entity).isSuccessful()) { logger.debug(format("Entity [%s] is not dirty (ID = %s). Saving is skipped. Entity refetched.", entity, entity.getId())); return skipRefetching.get() ? entity : findById.apply(entity.getId(), FetchModelReconstructor.reconstruct(entity)); } logger.debug(format("Start saving entity %s (ID = %s)", entity, entity.getId())); // need to capture names of dirty properties before the actual saving takes place and makes all properties not dirty // this is needed for executing after save event handler final List<String> dirtyProperties = entity.getDirtyProperties().stream().map(MetaProperty::getName).collect(toList()); final T resultantEntity; // let's try to save entity try { // firstly validate the entity final Result isValid = validateEntity(entity); if (!isValid.isSuccessful()) { throw isValid; } // entity is valid and we should proceed with saving // new and previously saved entities are handled differently if (!entity.isPersisted()) { // is it a new entity? resultantEntity = saveNewEntity(entity); } else { // so, this is a modified entity resultantEntity = saveModifiedEntity(entity); } } finally { logger.debug("Finished saving entity " + entity + " (ID = " + entity.getId() + ")"); } // this call never throws any exceptions processAfterSaveEvent.accept(resultantEntity, dirtyProperties); return resultantEntity; } /** * Chooses between overridden validation or an alternative default validation that skips crit-only properties. * * @param entity * @return */ private Result validateEntity(final T entity) { if (targetEntityTypeHasValidateOverridden == null) { this.targetEntityTypeHasValidateOverridden = isMethodOverriddenOrDeclared(AbstractEntity.class, entityType, "validate"); } return targetEntityTypeHasValidateOverridden ? entity.isValid() : entity.isValid(validateWithoutCritOnly); } /** * This is a helper method that is used during saving of the modified entity, which has been persisted previously, and ensures that no removal of required assignable before save properties has * happened. * * @param entity */ private void checkDirtyMarkedForAssignmentBeforeSaveProperties(final T entity) { final List<MetaProperty<?>> props = entity.getDirtyProperties().stream(). filter(p -> p.shouldAssignBeforeSave() && null != AnnotationReflector.getPropertyAnnotation(Required.class, entity.getType(), p.getName())). collect(Collectors.toList()); if (!props.isEmpty()) { for (final MetaProperty<?> prop : props) { if (prop.getValue() == null) { throw new EntityCompanionException(format("Property %s@%s is marked as assignable before save, but had its value removed.", prop.getName(), entity.getType().getName())); } } } } /** * Saves previously persisted and now modified entity. * * @param entity */ private T saveModifiedEntity(final T entity) { // let's first prevent not permissibly modifications that could not be checked any earlier than this, // which pertain to required and marked as assign before save properties that must have values checkDirtyMarkedForAssignmentBeforeSaveProperties(entity); // let's make sure that entity is not a duplicate final AggregatedResultQueryModel model = select(createQueryByKey(entityType, keyType, isFilterable.get(), entity.getKey())).yield().prop(AbstractEntity.ID).as(AbstractEntity.ID).modelAsAggregate(); final QueryExecutionContext queryExecutionContext = newQueryExecutionContext.get(); final List<EntityAggregates> ids = new EntityFetcher(queryExecutionContext).getEntities(from(model).lightweight().model()); final int count = ids.size(); if (count == 1 && entity.getId().longValue() != ((Number) ids.get(0).get(AbstractEntity.ID)).longValue()) { throw new EntityCompanionException(format("%s [%s] already exists.", TitlesDescsGetter.getEntityTitleAndDesc(entity.getType()).getKey(), entity)); } // load the entity directly from the session final T persistedEntity = (T) session.get().load(entity.getType(), entity.getId()); persistedEntity.setIgnoreEditableState(true); // check for data staleness and try to resolve the conflict is possible (refer if (persistedEntity.getVersion() != null && persistedEntity.getVersion() > entity.getVersion() && !canResolveConflict(entity, persistedEntity)) { throw new EntityCompanionException(format("Could not resolve conflicting changes. %s [%s] could not be saved.", TitlesDescsGetter.getEntityTitleAndDesc(entityType).getKey(), entity)); } // reconstruct entity fetch model for future retrieval at the end of the method call final Optional<fetch<T>> entityFetchOption = skipRefetching.get() ? Optional.empty() : Optional.of(FetchModelReconstructor.reconstruct(entity)); // proceed with property assignment from entity to persistent entity, which in case of a resolvable conflict acts like a fetch/rebase in git // it is essential that if a property is of an entity type it should be re-associated with the current session before being set // the easiest way to do that is to load entity by id using the current session for (final MetaProperty<?> prop : entity.getDirtyProperties()) { final Object value = prop.getValue(); if (shouldProcessAsActivatable(entity, prop)) { handleDirtyActivatableProperty(entity, persistedEntity, prop, value); } else if (value instanceof AbstractEntity && !(value instanceof PropertyDescriptor) && !(value instanceof AbstractUnionEntity)) { persistedEntity.set(prop.getName(), session.get().load(((AbstractEntity<?>) value).getType(), ((AbstractEntity<?>) value).getId())); } else { persistedEntity.set(prop.getName(), value); } } // end of processing dirty properties // handle ref counts of non-dirty activatable properties if (entity instanceof ActivatableAbstractEntity) { handleNonDirtyActivatableIfNecessary(entity, persistedEntity); } // perform meta-data assignment to capture the information about this modification if (entity instanceof AbstractPersistentEntity) { assignLastModificationInfo((AbstractPersistentEntity<?>) entity, (AbstractPersistentEntity<?>) persistedEntity); } // update entity session.get().update(persistedEntity); session.get().flush(); session.get().clear(); return entityFetchOption.map(fetch -> findById.apply(persistedEntity.getId(), fetch)).orElse(persistedEntity); } /** * Handles dirty activatable property in a special way that manages refCount of its current and previous values, but only if the entity being saving is an activatable that does * not fall into the category of those with type that governs deactivatable dependency of the entity being saved. * * @param entity * @param persistedEntity * @param prop * @param value */ private void handleDirtyActivatableProperty(final T entity, final T persistedEntity, final MetaProperty<?> prop, final Object value) { final String propName = prop.getName(); // if value is null then an activatable entity has been dereferenced and its refCount needs to be decremented // but only if the dereferenced value is an active activatable and the entity being saved is not being made active -- thus previously it was not counted as a reference if (value == null) { final MetaProperty<Boolean> activeProp = entity.getProperty(ACTIVE); final boolean beingActivated = activeProp.isDirty() && activeProp.getValue(); // get the latest value of the dereferenced activatable as the current value of the persisted entity version from the database and decrement its ref count // previous property value should not be null as it would become dirty, also, there was no property conflict, so it can be safely assumed that previous value is NOT null final ActivatableAbstractEntity<?> prevValue = (ActivatableAbstractEntity<?>) entity.getProperty(propName).getPrevValue(); final ActivatableAbstractEntity<?> persistedValue = (ActivatableAbstractEntity<?>) session.get().load(prop.getType(), prevValue.getId(), UPGRADE); // if persistedValue active and does not equal to the entity being saving then need to decrement its refCount if (!beingActivated && persistedValue.isActive() && !entity.equals(persistedValue)) { // avoid counting self-references persistedValue.setIgnoreEditableState(true); session.get().update(persistedValue.decRefCount()); } // assign null as the property value to actually dereference activatable persistedEntity.set(propName, null); } else { // otherwise there could be either referencing (i.e. before property was null) or a reference change (i.e. from one value to some other) // need to process previous property value final AbstractEntity<?> prevValue = (ActivatableAbstractEntity<?>) entity.getProperty(propName).getPrevValue(); if (prevValue != null && !entity.equals(prevValue)) { // need to decrement refCount for the dereferenced entity, but avoid counting self-references final ActivatableAbstractEntity<?> persistedValue = (ActivatableAbstractEntity<?>) session.get().load(prop.getType(), prevValue.getId(), UPGRADE); persistedValue.setIgnoreEditableState(true); session.get().update(persistedValue.decRefCount()); } // also need increment refCount for a newly referenced activatable final ActivatableAbstractEntity<?> persistedValue = (ActivatableAbstractEntity<?>) session.get().load(prop.getType(), ((AbstractEntity<?>) value).getId(), UPGRADE); if (!entity.equals(persistedValue)) { // avoid counting self-references // now let's check if the entity itself is an active activatable // as this influences the decision to increment refCount for the newly referenced activatable // because, if it's not then there is no reason to increment refCout for the referenced instance // in other words, inactive entity does not count as an active referencer if (entity.<Boolean>get(ACTIVE)) { persistedValue.setIgnoreEditableState(true); session.get().update(persistedValue.incRefCount()); } } // assign updated activatable as the property value persistedEntity.set(propName, persistedValue); } } /** * In case entity is activatable and has just been activated or deactivated, it is also necessary to make sure that all previously referenced activatables, which did not fall * into the dirty category and are active get their refCount increment or decremented accordingly * * @param entity * @param persistedEntity */ private void handleNonDirtyActivatableIfNecessary(final T entity, final T persistedEntity) { final MetaProperty<Boolean> activeProp = entity.getProperty(ACTIVE); // was activatable entity just activated? if (activeProp.isDirty()) { // let's collect activatable not dirty properties from entity to check them for activity and also to increment their refCount final Set<String> keyMembers = Finder.getKeyMembers(entity.getType()).stream().map(Field::getName).collect(Collectors.toSet()); for (final T2<String, Class<ActivatableAbstractEntity<?>>> propNameAndType : collectActivatableNotDirtyProperties(entity, keyMembers)) { // get value from a persisted version of entity, which is loaded by Hibernate // if a corresponding property is proxied due to insufficient fetch model, its value is retrieved lazily by Hibernate final AbstractEntity<?> value = persistedEntity.get(propNameAndType._1); if (value != null) { // if there is actually some value // load activatable value final ActivatableAbstractEntity<?> persistedValue = (ActivatableAbstractEntity<?>) session.get().load(propNameAndType._2, value.getId(), UPGRADE); persistedValue.setIgnoreEditableState(true); // if activatable property value is not a self-reference // then need to check if it is active and if so increment its refCount // otherwise, if activatable is not active then we've got an erroneous situation that should prevent activation of entity if (!entity.equals(persistedValue)) { if (activeProp.getValue()) { // is entity being activated? if (!persistedValue.isActive()) { // if activatable is not active then this is an error final String entityTitle = TitlesDescsGetter.getEntityTitleAndDesc(entity.getType()).getKey(); final String persistedValueTitle = TitlesDescsGetter.getEntityTitleAndDesc(propNameAndType._2).getKey(); throw new EntityCompanionException(format("%s [%s] has a reference to already inactive %s [%s].", entityTitle, entity, persistedValueTitle, persistedValue)); } else { // otherwise, increment refCount session.get().update(persistedValue.incRefCount()); } } else if (persistedValue.isActive()) { // is entity being deactivated, but is referencing an active activatable? session.get().update(persistedValue.decRefCount()); } } } } // separately need to perform deactivation of deactivatable dependencies in case where the entity being saved is deactivated if (!activeProp.getValue()) { final List<? extends ActivatableAbstractEntity<?>> deactivatables = findActiveDeactivatableDependencies((ActivatableAbstractEntity<?>) entity, coFinder.get()); for (final ActivatableAbstractEntity<?> deactivatable : deactivatables) { deactivatable.set(ACTIVE, false); final Result result = deactivatable.isValid(); if (result.isSuccessful()) { // persisting of deactivatables should go through the logic of companion save // and cannot be persisted by just using a call to Hibernate Session final CommonEntityDao co = coFinder.get().find(deactivatable.getType()); co.save(deactivatable); } else { throw result; } } } } } /** * This is a convenient predicate method that identifies whether the specified property need to be processed as an activatable reference. * * @param entity * @param prop * @return */ private boolean shouldProcessAsActivatable(final T entity, final MetaProperty<?> prop) { boolean shouldProcessAsActivatable; if (prop.isActivatable() && entity instanceof ActivatableAbstractEntity && isNotSpecialActivatableToBeSkipped(prop)) { final Class<? extends ActivatableAbstractEntity<?>> type = (Class<? extends ActivatableAbstractEntity<?>>) prop.getType(); final DeactivatableDependencies ddAnnotation = type.getAnnotation(DeactivatableDependencies.class); if (ddAnnotation != null && prop.isKey()) { shouldProcessAsActivatable = !Arrays.asList(ddAnnotation.value()).contains(entity.getType()); } else { shouldProcessAsActivatable = true; } } else { shouldProcessAsActivatable = false; } return shouldProcessAsActivatable; } /** * Determines whether automatic conflict resolves between the two entity instance is possible. The ability to resolve conflict automatically is based strictly on dirty * properties -- if dirty properties in <code>entity</code> are equals to the same properties in <code>persistedEntity</code> then the conflict can be resolved. * * @param entity * @param persistedEntity * @return */ private boolean canResolveConflict(final T entity, final T persistedEntity) { // comparison of property values is most likely to trigger lazy loading for (final MetaProperty<?> prop : entity.getDirtyProperties()) { final String name = prop.getName(); final Object oldValue = prop.getOriginalValue(); final Object newValue = prop.getValue(); final Object persistedValue = persistedEntity.get(name); if (EntityUtils.isConflicting(newValue, oldValue, persistedValue)) { return false; } } return true; } /** * Persists an entity that was not persisted before. Self-references are not possible for new entities simply because non-persisted instances are not permitted as property * values. Unless there is a special case of skipping entity exists validation, but then the developer would need to take case of that somehow specifically for each specific * case. * * @param entity */ private T saveNewEntity(final T entity) { // let's make sure that entity is not a duplicate final Integer count = kount.apply(createQueryByKey(entityType, keyType, isFilterable.get(), entity.getKey())); if (count > 0) { throw new EntityAlreadyExists(format("%s [%s] already exists.", TitlesDescsGetter.getEntityTitleAndDesc(entity.getType()).getKey(), entity)); } // process transactional assignments if (entity instanceof AbstractPersistentEntity) { assignCreationInfo((AbstractPersistentEntity<?>) entity); } assignPropertiesBeforeSave(entity); // reconstruct entity fetch model for future retrieval at the end of the method call final Optional<fetch<T>> entityFetchOption = skipRefetching.get() ? Optional.empty() : Optional.of(FetchModelReconstructor.reconstruct(entity)); // new entity might be activatable, but this has no effect on its refCount -- should be zero as no other entity could yet reference it // however, it might reference other activatable entities, which warrants update to their refCount. final boolean shouldProcessActivatableProperties; if (entity instanceof ActivatableAbstractEntity) { final ActivatableAbstractEntity<?> activatable = (ActivatableAbstractEntity<?>) entity; shouldProcessActivatableProperties = activatable.isActive(); } else { // refCount should not be updated if referenced by non-activatable shouldProcessActivatableProperties = false; // setting true would enable refCount update in case of saving non-activatable } if (shouldProcessActivatableProperties) { final Set<String> keyMembers = Finder.getKeyMembers(entity.getType()).stream().map(Field::getName).collect(toSet()); final Set<MetaProperty<? extends ActivatableAbstractEntity<?>>> activatableDirtyProperties = collectActivatableDirtyProperties(entity, keyMembers); for (final MetaProperty<? extends ActivatableAbstractEntity<?>> prop : activatableDirtyProperties) { if (prop.getValue() != null) { // need to update refCount for the activatable entity final ActivatableAbstractEntity<?> value = prop.getValue(); final ActivatableAbstractEntity<?> persistedEntity = (ActivatableAbstractEntity<?> ) session.get().load(value.getType(), value.getId(), UPGRADE); // the returned value could already be inactive due to some concurrent modification // therefore it is critical to ensure that the property of the current entity being saved can still accept the obtained value if it is inactive if (!persistedEntity.isActive()) { entity.beginInitialising(); entity.set(prop.getName(), persistedEntity); entity.endInitialising(); final Result res = prop.revalidate(false); if (!res.isSuccessful()) { throw res; } } persistedEntity.setIgnoreEditableState(true); session.get().update(persistedEntity.incRefCount()); } } } // save the entity session.get().save(entity.set(ID, nextIdValue(ID_SEQUENCE_NAME, session.get()))); session.get().flush(); session.get().clear(); return entityFetchOption.map(fetch -> findById.apply(entity.getId(), fetch)).orElse(entity); } /** * Collects properties that represent dirty activatable entities that should have their ref counts updated. * * @param entity * @return */ private Set<MetaProperty<? extends ActivatableAbstractEntity<?>>> collectActivatableDirtyProperties(final T entity, final Set<String> keyMembers) { final Set<MetaProperty<? extends ActivatableAbstractEntity<?>>> result = new HashSet<>(); for (final MetaProperty<?> prop : entity.getProperties().values()) { if (prop.isDirty() && prop.isActivatable() && isNotSpecialActivatableToBeSkipped(prop)) { addToResultIfApplicableFromActivatablePerspective(entity, keyMembers, result, prop); } } return result; } private void assignCreationInfo(final AbstractPersistentEntity<?> entity) { // unit tests utilise a permissive VIRTUAL_USER to persist a "current" user for the testing purposes // VIRTUAL_USER is transient and cannot be set as a value for properties of persistent entities // thus, a check for VIRTUAL_USER as a current user if (!User.system_users.VIRTUAL_USER.name().equals(currUserOrException().getKey())) { entity.set(AbstractPersistentEntity.CREATED_BY, currUserOrException()); } entity.set(AbstractPersistentEntity.CREATED_DATE, now.get().toDate()); entity.set(AbstractPersistentEntity.CREATED_TRANSACTION_GUID, transactionGuid.get()); } private void assignLastModificationInfo(final AbstractPersistentEntity<?> entity, final AbstractPersistentEntity<?> persistentEntity) { // if the entity is activatable and the only dirty property is refCount than there is no need to update the last-updated-by info if (entity instanceof ActivatableAbstractEntity) { final List<MetaProperty<?>> dirty = entity.getDirtyProperties(); if (dirty.size() == 1 && ActivatableAbstractEntity.REF_COUNT.equals(dirty.get(0).getName())) { return; } } // unit tests utilise a permissive VIRTUAL_USER to persist a "current" user for the testing purposes // VIRTUAL_USER is transient and cannot be set as a value for properties of persistent entities // thus, a check for VIRTUAL_USER as a current user if (!User.system_users.VIRTUAL_USER.name().equals(currUserOrException().getKey())) { persistentEntity.set(AbstractPersistentEntity.LAST_UPDATED_BY, currUserOrException()); persistentEntity.set(AbstractPersistentEntity.LAST_UPDATED_DATE, now.get().toDate()); persistentEntity.set(AbstractPersistentEntity.LAST_UPDATED_TRANSACTION_GUID, transactionGuid.get()); } } /** * Returns the current user if defined. Otherwise, throws an exception. * @return */ private User currUserOrException() { final User currUser = user.get(); if (currUser == null) { final String msg = "The current user is not defined."; logger.error(msg); throw new EntityCompanionException(msg); } return currUser; } /** * Assigns values to all properties marked for assignment before save. This method should be used only during saving of new entities. * * @param entity */ private void assignPropertiesBeforeSave(final T entity) { final List<MetaProperty<?>> props = entity.getProperties().values().stream(). filter(MetaProperty::shouldAssignBeforeSave).collect(Collectors.toList()); if (!props.isEmpty()) { final DateTime rightNow = now.get(); if (rightNow == null) { throw new EntityCompanionException("The now() constant has not been assigned!"); } for (final MetaProperty<?> prop : props) { final Object value = prop.getValue(); if (value == null) { if (User.class.isAssignableFrom(prop.getType())) { prop.setValue(currUserOrException()); } else if (Date.class.isAssignableFrom(prop.getType())) { prop.setValue(rightNow.toDate()); } else if (DateTime.class.isAssignableFrom(prop.getType())) { prop.setValue(rightNow); } else { assignBeforeSave.accept(prop); } if (prop.getValue() == null) { throw new EntityCompanionException(format("Property %s@%s is marked as assignable before save, but no value could be determined.", prop.getName(), entity.getType().getName())); } } } } } }
package dr.evomodel.treelikelihood; import dr.evolution.alignment.PatternList; import dr.evolution.tree.Tree; import dr.evolution.util.TaxonList; import dr.inference.model.AbstractModel; import dr.inference.model.Model; import dr.inference.model.Parameter; import dr.inference.model.Variable; import java.util.HashMap; import java.util.Map; /** * @author Andrew Rambaut * @author Alexei Drummond * @version $Id$ */ public abstract class TipPartialsModel extends AbstractModel { /** * @param name Model Name */ public TipPartialsModel(String name, TaxonList includeTaxa, TaxonList excludeTaxa) { super(name); this.includeTaxa = includeTaxa; this.excludeTaxa = excludeTaxa; } public final void setTree(Tree tree) { this.tree = tree; int extNodeCount = tree.getExternalNodeCount(); excluded = new boolean[extNodeCount]; if (includeTaxa != null) { for (int i = 0; i < extNodeCount; i++) { if (includeTaxa.getTaxonIndex(tree.getNodeTaxon(tree.getExternalNode(i))) == -1) { excluded[i] = true; } } } if (excludeTaxa != null) { for (int i = 0; i < extNodeCount; i++) { if (excludeTaxa.getTaxonIndex(tree.getNodeTaxon(tree.getExternalNode(i))) != -1) { excluded[i] = true; } } } states = new int[extNodeCount][]; taxaChanged(); } protected abstract void taxaChanged(); public final void setStates(PatternList patternList, int sequenceIndex, int nodeIndex, String taxonId) { if (patternCount == 0) { if (patternList != null) { throw new RuntimeException("The TipPartialsModel with id, " + getId() + ", has already been associated with a patternList."); } this.patternList = patternList; patternCount = patternList.getPatternCount(); stateCount = patternList.getDataType().getStateCount(); } if (this.states[nodeIndex] == null) { this.states[nodeIndex] = new int[patternCount]; } for (int i = 0; i < patternCount; i++) { this.states[nodeIndex][i] = patternList.getPatternState(sequenceIndex, i); } taxonMap.put(nodeIndex, taxonId); } protected void handleModelChangedEvent(Model model, Object object, int index) { fireModelChanged(); } /** * This method is called whenever a parameter is changed. * <p/> * It is strongly recommended that the model component sets a "dirty" flag and does no * further calculations. Recalculation is typically done when the model component is asked for * some information that requires them. This mechanism is 'lazy' so that this method * can be safely called multiple times with minimal computational cost. */ protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { fireModelChanged(); } /** * Additional state information, outside of the sub-model is stored by this call. */ protected void storeState() { } /** * After this call the model is guaranteed to have returned its extra state information to * the values coinciding with the last storeState call. * Sub-models are handled automatically and do not need to be considered in this method. */ protected void restoreState() { } /** * This call specifies that the current state is accept. Most models will not need to do anything. * Sub-models are handled automatically and do not need to be considered in this method. */ protected void acceptState() { } public abstract void getTipPartials(int nodeIndex, double[] tipPartials); protected int[][] states; protected boolean[] excluded; protected int patternCount = 0; protected int stateCount; protected TaxonList includeTaxa; protected TaxonList excludeTaxa; protected Tree tree; private PatternList patternList = null; protected Map<Integer, String> taxonMap = new HashMap<Integer, String>(); }
package ua.com.fielden.platform.security.session; import static java.lang.String.format; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchAll; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.from; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.select; import static ua.com.fielden.platform.security.session.Authenticator.fromString; import static ua.com.fielden.platform.security.session.Authenticator.mkToken; import java.security.SignatureException; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.apache.log4j.Logger; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import ua.com.fielden.platform.cypher.SessionIdentifierGenerator; import ua.com.fielden.platform.dao.CommonEntityDao; import ua.com.fielden.platform.dao.QueryExecutionModel; import ua.com.fielden.platform.dao.annotations.SessionRequired; import ua.com.fielden.platform.entity.query.IFilter; import ua.com.fielden.platform.entity.query.model.EntityResultQueryModel; import ua.com.fielden.platform.security.annotations.SessionHashingKey; import ua.com.fielden.platform.security.annotations.TrustedDeviceSessionDuration; import ua.com.fielden.platform.security.annotations.UntrustedDeviceSessionDuration; import ua.com.fielden.platform.security.user.User; import ua.com.fielden.platform.swing.review.annotations.EntityType; import ua.com.fielden.platform.utils.IUniversalConstants; import com.google.inject.Inject; /** * DAO implementation for companion object {@link IUserSession}. * * @author Developers * */ @EntityType(UserSession.class) public class UserSessionDao extends CommonEntityDao<UserSession> implements IUserSession { private final Logger logger = Logger.getLogger(UserSessionDao.class); /** A key to be used for hashing authenticators and series ID before storing them. */ private final String hashingKey; private final int trustedDurationMins; private final int untrustedDurationMins; private final SessionIdentifierGenerator crypto; private final IUniversalConstants constants; @Inject public UserSessionDao( final @SessionHashingKey String hashingKey, final @TrustedDeviceSessionDuration int trustedDurationMins, final @UntrustedDeviceSessionDuration int untrustedDurationMins, final IUniversalConstants constants, final SessionIdentifierGenerator crypto, final IFilter filter) { super(filter); this.constants = constants; this.hashingKey = hashingKey; this.trustedDurationMins = trustedDurationMins; this.untrustedDurationMins = untrustedDurationMins; this.crypto = crypto; } @Override public void clearAll(final User user) { super.defaultDelete(select(UserSession.class).where().prop("user").eq().val(user).model()); } @Override public void clearUntrusted(final User user) { final EntityResultQueryModel<UserSession> query = select(UserSession.class) .where() .prop("user").eq().val(user) .and().prop("trusted").eq().val(false) .model(); super.defaultDelete(query); } @Override public void clearAll() { super.defaultDelete(select(UserSession.class).model()); } @Override public void clearUntrusted() { final EntityResultQueryModel<UserSession> query = select(UserSession.class) .where() .prop("trusted").eq().val(false) .model(); super.defaultDelete(query); } @Override public void clearExpired(final User user) { final EntityResultQueryModel<UserSession> query = select(UserSession.class) .where() .prop("user").eq().val(user) .and().prop("expiryTime").lt().now() .model(); super.defaultDelete(query); } @Override public void clearExpired() { final EntityResultQueryModel<UserSession> query = select(UserSession.class) .where() .prop("expiryTime").lt().now() .model(); super.defaultDelete(query); } /** * Removes all sessions that are associated with users that have been associated with the provided series ID. There should at most be only one such user (but potentially * multiple sessions) due to cryptographic randomness of series IDs. * * @param seriesId * @return * @throws SignatureException */ private int removeSessionsForUsersBy(final String seriesId) { final EntityResultQueryModel<UserSession> query = select(UserSession.class).where().prop("seriesId").eq().prop(seriesHash(seriesId)).model(); final QueryExecutionModel<UserSession, EntityResultQueryModel<UserSession>> qem = from(query).with(fetchAll(UserSession.class)).model(); // count the number of session to be removed... final int count = count(query); if (count > 0) { // get all those sessions and using their users, clear all sessions (there could more than the ones retrieved) associated with those users final List<UserSession> all = getAllEntities(qem); final String users = all.stream().map(ss -> ss.getUser().getKey()).distinct().collect(Collectors.joining(", ")); logger.warn(format("Removing all sessions for user(s) %s due to a suspected stolen session authenticator.", users)); all.forEach(ss -> clearAll(ss.getUser())); } return count; } /** * A convenient method for hashing the passed in series id. * * @param seriesId * @return */ private String seriesHash(final String seriesId) { final String seriesIdHash; try { seriesIdHash = crypto.calculateRFC2104HMAC(seriesId, hashingKey); } catch (final SignatureException ex) { throw new IllegalStateException(ex); } return seriesIdHash; } /** * The main goal of this method is to validate and refresh the user session, which happens for each request. * The validation part has a very strong role for detecting fraudulent attempts to access the system or indications for already compromised users that had their authenticators stolen. * <p> * Please note that due to the fact that the first argument is a {@link User} instance, this * means that the username has already been verified and identified as belonging to an active user account. */ @Override @SessionRequired public Optional<UserSession> currentSession(final User user, final String authenticator) { // first reconstruct authenticator from string and then proceed with its validation // in case of validation failure, no reason should be provided to the outside as this could reveal too much information to a potential adversary final Authenticator auth = fromString(authenticator); // verify authenticator's authenticity using its hash and the application hashing key try { if (!auth.hash.equals(crypto.calculateRFC2104HMAC(auth.token, hashingKey))) { // authenticator has been tempered with logger.warn(format("The provided authenticator %s cannot be verified. A tempered authenticator is suspected.", auth)); // remove user sessions that are identified with the provided series ID // series ID is the only possibly reliable piece of the authenticator at this stage as it is hard to forge algorithmically // therefore, in the worst case scenario that an authenticator has been stolen and series ID is being reused, all sessions for users that are associated with that series ID should be removed // because those users (should really be just one due to serial ID cryptographic randomness) have most likely been compromised // it is also possible that the provided series ID is also fraudulent and does not match any existing sessions, then no problems -- just deny the access and request explicit re-authentication final int count = removeSessionsForUsersBy(auth.seriesId); logger.debug(format("Removed %s session(s) for series ID %s", count, auth.seriesId)); return Optional.empty(); } } catch (final SignatureException ex) { throw new IllegalStateException(ex); } // the provided authenticator has been verified based on its content and hash // the next logical thing to check is whether the user making the request and the user specified in the authenticator match if (!user.getKey().equals(auth.username)) { // authenticator has been stolen logger.warn(format("The provided authenticator %s does not reference the current user %s. A stolen authenticator is suspected.", auth, user.getKey())); // similarly as described previously, need to remove all sessions for user(s) that are associated with the series ID in the presented authenticator final int count = removeSessionsForUsersBy(auth.seriesId); logger.debug(format("Removed %s session(s) for series ID %s", count, auth.seriesId)); return Optional.empty(); } // so far so good, there is a hope that the current request is authentic, but there is still a chance that it is coming for an adversary... // let's find a persisted session, and there should be one if request is authentic, associated with the specified user and series ID final UserSession session = findByKeyAndFetch(fetchAll(UserSession.class), user, seriesHash(auth.seriesId)); // if persisted session does not exist for a seemingly valid authenticator then it is most likely due to an authenticator theft, and here is why: // an authenticator could have been stolen, and already successfully used by an adversary to access the system from a different device than the one authenticator was stolen from // then, when a legitimate user is trying to access the system by presenting the stolen authenticator, which was already used be an adversary (this leads to series ID regeneration), then there would be no session associated with it!!! // this means all sessions for this particular user should be invalidated (removed) to stop an adversary from accessing the system if (session == null) { logger.warn(format("A seemingly correct authenticator %s did not have a corresponding sesssion record. An authenticator theft is suspected. An adversary might have had access to the system as user %s", auth, user.getKey())); final int count = removeSessionsForUsersBy(auth.seriesId); logger.debug(format("Removed %s session(s) for series ID %s", count, auth.seriesId)); return Optional.empty(); } // only after we have a high probability for legitimate user request, the identified session needs to be check for expiry // for this either the authenticator's time portion or the time from the retrieved session could be used // but to provide one additional level of session verification, let's make sure that both times are identical // if they are not.... then most likely the database was tempered with... just log the problem, but proceed with further session validation // the thing is that the only way to reach this point of validation for an authenticator, it would need to be either valid or an adversary would needed to either steal it and no legitimate user yet used it, or forge it, which would // require an access to the server... in this unfortunate case there is no way to identify the actually stolen session... if (auth.expiryTime != session.getExpiryTime().getTime()) { final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS"); logger.warn(format("Session expiry time %s for authenticator %s differes to the persisted expiry time %s.", formatter.print(auth.expiryTime), auth, formatter.print(session.getExpiryTime().getTime()))); } // now let's check if session has expired, if it did then use this opportunity to clear all expired session for this user and return an empty result to trigger re-authentication if (auth.getExpiryTime().isBefore(constants.now().getMillis())) { // clean up expired sessions clearExpired(user); return Optional.empty(); } // if this point is reached then the identified session is considered valid // it needs to be updated with a new series ID and a refreshed expiry time, and returned as the result final String seriesId = crypto.nextSessionId(); session.setSeriesId(seriesHash(seriesId)); session.setLastAccess(constants.now().toDate()); final Date expiryTime = calcExpiryTime(session.isTrusted()); session.setExpiryTime(expiryTime); final UserSession updated = save(session); // assign authenticator, but in way not to disturb the entity meta-state updated.beginInitialising(); updated.setAuthenticator(mkAuthenticator(user, seriesId, expiryTime)); updated.endInitialising(); return Optional.of(updated); } @Override @SessionRequired public UserSession newSession(final User user, final boolean isDeviceTrusted) { try { // let's first construct the next series id final String seriesId = crypto.nextSessionId(); // and hash it for storage final String seriesIdHash = crypto.calculateRFC2104HMAC(seriesId, hashingKey); final UserSession session = user.getEntityFactory().newByKey(UserSession.class, user, seriesIdHash); session.setTrusted(isDeviceTrusted); final Date expiryTime = calcExpiryTime(isDeviceTrusted); session.setExpiryTime(expiryTime); session.setLastAccess(constants.now().toDate()); // authenticator needs to be computed and assigned after the session has been persisted // assign authenticator in way not to disturb the entity meta-state final UserSession saved = save(session); saved.beginInitialising(); saved.setAuthenticator(mkAuthenticator(user, seriesId, expiryTime)); saved.endInitialising(); return saved; } catch (final SignatureException e) { e.printStackTrace(); throw new IllegalStateException(e); } } /** * A convenient method for instantiating an authenticator. * * @param user * @param seriesId * @param expiryTime * @return */ private Authenticator mkAuthenticator(final User user, final String seriesId, final Date expiryTime) { try { final String token = mkToken(user.getKey(), seriesId, expiryTime); final String hash = crypto.calculateRFC2104HMAC(token, hashingKey); return new Authenticator(token, hash); } catch (final SignatureException ex) { throw new IllegalStateException(ex); } } /** * Calculates a session expiry time based on the notion of trusted and untrased devices. * * @param isDeviceTrusted * @return */ private Date calcExpiryTime(final boolean isDeviceTrusted) { return (isDeviceTrusted ? constants.now().plusMinutes(trustedDurationMins) : constants.now().plusMinutes(untrustedDurationMins)).toDate(); } }
package com.intellij.psi.impl.file.impl; import com.intellij.ide.scratch.ScratchUtil; import com.intellij.injected.editor.VirtualFileWindow; import com.intellij.model.ModelBranch; import com.intellij.model.ModelBranchImpl; import com.intellij.openapi.Disposable; import com.intellij.openapi.module.Module; import com.intellij.openapi.progress.ProgressIndicatorProvider; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.impl.LibraryScopeCache; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.impl.AnyPsiChangeListener; import com.intellij.psi.impl.ResolveScopeManager; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiSearchScopeUtil; import com.intellij.psi.search.SearchScope; import com.intellij.testFramework.LightVirtualFile; import com.intellij.util.containers.ConcurrentFactoryMap; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.indexing.AdditionalIndexableFileSet; import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Map; import static com.intellij.psi.impl.PsiManagerImpl.ANY_PSI_CHANGE_TOPIC; public final class ResolveScopeManagerImpl extends ResolveScopeManager implements Disposable { private final Project myProject; private final ProjectRootManager myProjectRootManager; private final PsiManager myManager; private final Map<VirtualFile, GlobalSearchScope> myDefaultResolveScopesCache; private final AdditionalIndexableFileSet myAdditionalIndexableFileSet; public ResolveScopeManagerImpl(Project project) { myProject = project; myProjectRootManager = ProjectRootManager.getInstance(project); myManager = PsiManager.getInstance(project); myAdditionalIndexableFileSet = new AdditionalIndexableFileSet(project); myDefaultResolveScopesCache = ConcurrentFactoryMap.create( key -> { VirtualFile file = key; VirtualFile original = key instanceof LightVirtualFile ? ((LightVirtualFile)key).getOriginalFile() : null; if (original != null) { file = original; } GlobalSearchScope scope = null; for (ResolveScopeProvider resolveScopeProvider : ResolveScopeProvider.EP_NAME.getExtensionList()) { scope = resolveScopeProvider.getResolveScope(file, myProject); if (scope != null) break; } if (scope == null) scope = getInherentResolveScope(file); for (ResolveScopeEnlarger enlarger : ResolveScopeEnlarger.EP_NAME.getExtensions()) { SearchScope extra = enlarger.getAdditionalResolveScope(file, myProject); if (extra != null) { scope = scope.union(extra); } } if (original != null && !scope.contains(key)) { scope = scope.union(GlobalSearchScope.fileScope(myProject, key)); } return scope; }, ContainerUtil::createConcurrentWeakKeySoftValueMap); myProject.getMessageBus().connect(this).subscribe(ANY_PSI_CHANGE_TOPIC, new AnyPsiChangeListener() { @Override public void beforePsiChanged(boolean isPhysical) { if (isPhysical) myDefaultResolveScopesCache.clear(); } }); // Make it explicit that registering and removing ResolveScopeProviders needs to clear the resolve scope cache // (even though normally registerRunnableToRunOnChange would be enough to clear the cache) ResolveScopeProvider.EP_NAME.addChangeListener(() -> myDefaultResolveScopesCache.clear(), this); ResolveScopeEnlarger.EP_NAME.addChangeListener(() -> myDefaultResolveScopesCache.clear(), this); } private GlobalSearchScope getResolveScopeFromProviders(@NotNull final VirtualFile vFile) { return myDefaultResolveScopesCache.get(vFile); } private GlobalSearchScope getInherentResolveScope(VirtualFile vFile) { ProjectFileIndex projectFileIndex = myProjectRootManager.getFileIndex(); Module module = projectFileIndex.getModuleForFile(vFile); if (module != null) { boolean includeTests = TestSourcesFilter.isTestSources(vFile, myProject); return GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module, includeTests); } if (!projectFileIndex.isInLibrary(vFile)) { GlobalSearchScope allScope = GlobalSearchScope.allScope(myProject); if (!allScope.contains(vFile)) { return GlobalSearchScope.fileScope(myProject, vFile).uniteWith(allScope); } return allScope; } return LibraryScopeCache.getInstance(myProject).getLibraryScope(projectFileIndex.getOrderEntriesForFile(vFile)); } @Override @NotNull public GlobalSearchScope getResolveScope(@NotNull PsiElement element) { ProgressIndicatorProvider.checkCanceled(); if (element instanceof PsiDirectory) { return getResolveScopeFromProviders(((PsiDirectory)element).getVirtualFile()); } PsiFile containingFile = element.getContainingFile(); if (containingFile instanceof PsiCodeFragment) { GlobalSearchScope forcedScope = ((PsiCodeFragment)containingFile).getForcedResolveScope(); if (forcedScope != null) { return forcedScope; } } if (containingFile != null) { PsiElement context = containingFile.getContext(); if (context != null) { return withFile(containingFile, getResolveScope(context)); } } if (containingFile == null) { return GlobalSearchScope.allScope(myProject); } GlobalSearchScope scope = getPsiFileResolveScope(containingFile); ModelBranch branch = ModelBranch.getPsiBranch(containingFile); return branch != null ? ((ModelBranchImpl)branch).modifyScope(scope) : scope; } @NotNull private GlobalSearchScope getPsiFileResolveScope(@NotNull PsiFile psiFile) { if (psiFile instanceof FileResolveScopeProvider) { return ((FileResolveScopeProvider)psiFile).getFileResolveScope(); } if (!psiFile.getOriginalFile().isPhysical()) { return withFile(psiFile, GlobalSearchScope.allScope(myProject)); } return getResolveScopeFromProviders(psiFile.getViewProvider().getVirtualFile()); } private GlobalSearchScope withFile(PsiFile containingFile, GlobalSearchScope scope) { return PsiSearchScopeUtil.isInScope(scope, containingFile) ? scope : scope.uniteWith(GlobalSearchScope.fileScope(myProject, containingFile.getViewProvider().getVirtualFile())); } @NotNull @Override public GlobalSearchScope getDefaultResolveScope(@NotNull final VirtualFile vFile) { final PsiFile psiFile = myManager.findFile(vFile); assert psiFile != null : "directory=" + vFile.isDirectory() + "; " + myProject; return getResolveScopeFromProviders(vFile); } @Override @NotNull public GlobalSearchScope getUseScope(@NotNull PsiElement element) { VirtualFile vDirectory; final VirtualFile virtualFile; final PsiFile containingFile; final GlobalSearchScope allScope = GlobalSearchScope.allScope(myManager.getProject()); if (element instanceof PsiDirectory) { vDirectory = ((PsiDirectory)element).getVirtualFile(); virtualFile = null; containingFile = null; } else { containingFile = element.getContainingFile(); if (containingFile == null) return allScope; virtualFile = containingFile.getVirtualFile(); if (virtualFile == null) return allScope; if (virtualFile instanceof VirtualFileWindow) { return GlobalSearchScope.fileScope(myProject, ((VirtualFileWindow)virtualFile).getDelegate()); } if (ScratchUtil.isScratch(virtualFile)) { return GlobalSearchScope.fileScope(myProject, virtualFile); } vDirectory = virtualFile.getParent(); } if (vDirectory == null) return allScope; final ProjectFileIndex projectFileIndex = myProjectRootManager.getFileIndex(); VirtualFile notNullVFile = virtualFile != null ? virtualFile : vDirectory; final Module module = projectFileIndex.getModuleForFile(notNullVFile); if (module == null) { final List<OrderEntry> entries = projectFileIndex.getOrderEntriesForFile(notNullVFile); if (entries.isEmpty() && (myAdditionalIndexableFileSet.isInSet(notNullVFile) || isFromAdditionalLibraries(notNullVFile))) { return allScope; } GlobalSearchScope result = LibraryScopeCache.getInstance(myProject).getLibraryUseScope(entries); return containingFile == null || virtualFile.isDirectory() || result.contains(virtualFile) ? result : GlobalSearchScope.fileScope(containingFile).uniteWith(result); } boolean isTest = TestSourcesFilter.isTestSources(vDirectory, myProject); return isTest ? GlobalSearchScope.moduleTestsWithDependentsScope(module) : GlobalSearchScope.moduleWithDependentsScope(module); } private boolean isFromAdditionalLibraries(@NotNull final VirtualFile file) { for (final AdditionalLibraryRootsProvider provider : AdditionalLibraryRootsProvider.EP_NAME.getExtensionList()) { for (final SyntheticLibrary library : provider.getAdditionalProjectLibraries(myProject)) { if (library.contains(file)) { return true; } } } return false; } @Override public void dispose() { } }
package edu.usc.glidein.service.impl; import java.rmi.RemoteException; import org.apache.log4j.Logger; import org.globus.wsrf.ResourceContext; import org.globus.wsrf.ResourceKey; import edu.usc.glidein.stubs.types.EmptyObject; import edu.usc.glidein.stubs.types.Glidein; public class GlideinService { private Logger logger = Logger.getLogger(GlideinService.class); private GlideinResourceHome getResourceHome() throws RemoteException { try { Object resourceHome = ResourceContext.getResourceContext().getResourceHome(); GlideinResourceHome glideinResourceHome = (GlideinResourceHome) resourceHome; return glideinResourceHome; } catch (Exception e) { String message = "Unable to find glidein resource home"; logger.error(message,e); throw new RemoteException(message, e); } } private GlideinResource getResource() throws RemoteException { try { Object resource = ResourceContext.getResourceContext().getResource(); GlideinResource glideinResource = (GlideinResource) resource; return glideinResource; } catch (Exception e) { String message = "Unable to find glidein resource"; logger.error(message,e); throw new RemoteException(message, e); } } private ResourceKey getResourceKey() throws RemoteException { try { return ResourceContext.getResourceContext().getResourceKey(); } catch (Exception e) { String message = "Unable to find glidein resource key"; logger.error(message,e); throw new RemoteException(message, e); } } public Glidein getGlidein(EmptyObject empty) throws RemoteException { return getResource().getGlidein(); } public EmptyObject start(EmptyObject empty) throws RemoteException { // TODO submit glidein job return new EmptyObject(); } public EmptyObject cancel(EmptyObject empty) throws RemoteException { // TODO cancel glidein job return new EmptyObject(); } public EmptyObject delete(EmptyObject empty) throws RemoteException { getResource().delete(); getResourceHome().remove(getResourceKey()); return new EmptyObject(); } }
package burlap.behavior.singleagent; import burlap.behavior.policy.Policy; import burlap.behavior.policy.PolicyUtils; import burlap.behavior.policy.RandomPolicy; import burlap.datastructures.AlphanumericSorting; import burlap.domain.singleagent.gridworld.GridWorldDomain; import burlap.domain.singleagent.gridworld.state.GridAgent; import burlap.domain.singleagent.gridworld.state.GridWorldState; import burlap.mdp.core.Action; import burlap.mdp.core.state.State; import burlap.mdp.singleagent.SADomain; import burlap.mdp.singleagent.environment.EnvironmentOutcome; import org.yaml.snakeyaml.Yaml; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class Episode { /** * The sequence of states observed */ public List<State> stateSequence = new ArrayList<State>(); /** * The sequence of actions taken */ public List<Action> actionSequence = new ArrayList<Action>(); /** * The sequence of rewards received. Note the reward stored at index i is the reward received at time step i+1. */ public List<Double> rewardSequence = new ArrayList<Double>(); /** * Creates a new EpisodeAnalysis object. Before recording transitions, the {@link #initializeInState(State)} method * should be called to set the initial state of the episode. */ public Episode(){ } /** * Initializes a new EpisodeAnalysis object with the initial state in which the episode started. * @param initialState the initial state of the episode */ public Episode(State initialState){ this.initializeInState(initialState); } /** * Initializes this object with the initial state in which the episode started. * @param initialState the initial state of the episode */ public void initializeInState(State initialState){ if(this.stateSequence.size() > 0){ throw new RuntimeException("Cannot initialize episode, because episode is already initialized in a state."); } this.stateSequence.add(initialState); } /** * Adds a state to the state sequence. In general, it is recommended that {@link #initializeInState(State)} method * along with subsequent calls to the {@link #transition(Action, State, double)} method is used instead, but this * method can be used to manually add a state. * @param s the state to add */ public void addState(State s){ stateSequence.add(s); } /** * Adds a GroundedAction to the action sequence. In general, it is recommended that {@link #initializeInState(State)} method * along with subsequent calls to the {@link #transition(Action, State, double)} method is used instead, but this * method can be used to manually add a GroundedAction. * @param ga the GroundedAction to add */ public void addAction(Action ga){ actionSequence.add(ga); } /** * Adds a reward to the reward sequence. In general, it is recommended that {@link #initializeInState(State)} method * along with subsequent calls to the {@link #transition(Action, State, double)} method is used instead, but this * method can be used to manually add a reward. * @param r the reward to add */ public void addReward(double r){ rewardSequence.add(r); } /** * Records a transition event where the agent applied the usingAction action in the last * state in this object's state sequence, transitioned to state nextState, and received reward r,. * @param usingAction the action the agent used that caused the transition * @param nextState the next state to which the agent transitioned * @param r the reward the agent received for this transition. */ public void transition(Action usingAction, State nextState, double r){ stateSequence.add(nextState); actionSequence.add(usingAction); rewardSequence.add(r); } /** * Records a transition event from the {@link EnvironmentOutcome}. Assumes that the last state recorded in * this {@link Episode} is the same as the previous state ({@link EnvironmentOutcome#o} in the {@link EnvironmentOutcome} * @param eo an {@link EnvironmentOutcome} specifying a new transition for this episode. */ public void transition(EnvironmentOutcome eo){ this.stateSequence.add(eo.op); this.actionSequence.add(eo.a); this.rewardSequence.add(eo.r); } /** * Returns the state observed at time step t. t=0 refers to the initial state. * @param t the time step of the episode * @return the state at time step t */ public State state(int t){ if(t >= this.stateSequence.size()){ throw new RuntimeException("Episode has nothing recorded for time step " + t); } return stateSequence.get(t); } /** * Returns the action taken in the state at time step t. t=0 refers to the action taken in the initial state. * @param t the time step of the episode * @return the action taken at time step t */ public Action action(int t){ if(t == this.actionSequence.size()){ throw new RuntimeException("Episode does not contain action at time step " + t + ". Note that an Episode " + "always has a final state at one time step larger than the last action time step " + "(the final state reached)."); } if(t > this.actionSequence.size()){ throw new RuntimeException("Episode has nothing recorded for time step " + t); } return actionSequence.get(t); } /** * Returns the reward received at timestep t. Note that the fist received reward will be at time step 1, which is the reward received * after taking the first action in the initial state. * @param t the time step of the episode * @return the ith reward received in this episode */ public double reward(int t){ if(t == 0){ throw new RuntimeException("Cannot return the reward received at time step 0; the first received reward occurs after the initial state at time step 1"); } if(t > rewardSequence.size()){ throw new RuntimeException("There are only " + this.rewardSequence.size() + " rewards recorded; cannot return the reward for time step " + t); } return rewardSequence.get(t-1); } /** * Returns the number of time steps in this episode, which is equivalent to the number of states. Note that * there will be no action in the last time step. * @return the number of time steps in this episode */ public int numTimeSteps(){ return stateSequence.size(); //state sequence will always have the most because of initial state and terminal state } /** * Returns the maximum time step index in this episode which is the {@link #numTimeSteps()}-1. Note that there * is will be no action in the last time step. * @return the maximum time step index in this episode */ public int maxTimeStep(){ return this.stateSequence.size()-1; } /** * Returns the number of actions, which is 1 less than the number of states. * @return the number of actions */ public int numActions(){ return this.actionSequence.size();} /** * Will return the discounted return received from the first state in the episode to the last state in the episode. * @param discountFactor the discount factor to compute the discounted return; should be on [0, 1] * @return the discounted return of the episode */ public double discountedReturn(double discountFactor){ double discount = 1.; double sum = 0.; for(double r : rewardSequence){ sum += discount*r; discount *= discountFactor; } return sum; } /** * This method will append execution results in e to this object's results. Note that it is assumed that the initial state in e * is the last state recorded in this object. This method is useful for appending the results of an option's execution * to a episode. * @param e the execution results to append to this episode. */ public void appendAndMergeEpisodeAnalysis(Episode e){ for(int i = 0; i < e.numTimeSteps()-1; i++){ this.transition(e.action(i), e.state(i+1), e.reward(i+1)); } } /** * Returns a string representing the actions taken in this episode. Actions are separated * by ';' characters. * @return a string representing the actions taken in this episode */ public String actionString(){ return this.actionString("; "); } /** * Returns a string representing the actions taken in this episode. Actions are separated * by the provided delimiter string. * @param delimiter the delimiter to separate actions in the string. * @return a string representing the actions taken in this episode */ public String actionString(String delimiter){ StringBuilder buf = new StringBuilder(); boolean first = true; for(Action ga : actionSequence){ if(!first){ buf.append(delimiter); } buf.append(ga.toString()); first = false; } return buf.toString(); } /** * Takes a {@link java.util.List} of {@link Episode} objects and writes them to a directory. * The format of the file names will be "baseFileName{index}.episode" where {index} represents the index of the * episode in the list. States must be serializable. * @param episodes the list of episodes to write to disk * @param directoryPath the directory path in which the episodes will be written * @param baseFileName the base file name to use for the episode files */ public static void writeEpisodes(List<Episode> episodes, String directoryPath, String baseFileName){ if(!directoryPath.endsWith("/")){ directoryPath += "/"; } for(int i = 0; i < episodes.size(); i++){ Episode ea = episodes.get(i); ea.write(directoryPath + baseFileName + i); } } /** * Writes this episode to a file. If the the directory for the specified file path do not exist, then they will be created. * If the file extension is not ".episode" will automatically be added. States must be serializable. * @param path the path to the file in which to write this episode. */ public void write(String path){ if(!path.endsWith(".episode")){ path = path + ".episode"; } File f = (new File(path)).getParentFile(); if(f != null){ f.mkdirs(); } try{ String str = this.serialize(); BufferedWriter out = new BufferedWriter(new FileWriter(path)); out.write(str); out.close(); }catch(Exception e){ System.out.println(e); } } /** * Takes a path to a directory containing .episode files and reads them all into a {@link java.util.List} * of {@link Episode} objects. * @param directoryPath the path to the directory containing the episode files * @return a {@link java.util.List} of {@link Episode} objects. */ public static List<Episode> readEpisodes(String directoryPath){ if(!directoryPath.endsWith("/")){ directoryPath = directoryPath + "/"; } File dir = new File(directoryPath); final String ext = ".episode"; FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { if(name.endsWith(ext)){ return true; } return false; } }; String[] children = dir.list(filter); Arrays.sort(children, new AlphanumericSorting()); List<Episode> eas = new ArrayList<Episode>(children.length); for(int i = 0; i < children.length; i++){ String episodeFile = directoryPath + children[i]; Episode ea = read(episodeFile); eas.add(ea); } return eas; } /** * Reads an episode that was written to a file and turns into an EpisodeAnalysis object. * @param path the path to the episode file. * @return an EpisodeAnalysis object. */ public static Episode read(String path){ //read whole file into string first String fcont = null; try{ fcont = new Scanner(new File(path)).useDelimiter("\\Z").next(); }catch(Exception E){ System.out.println(E); } return parseEpisode(fcont); } public String serialize(){ Yaml yaml = new Yaml(); String yamlOut = yaml.dump(this); return yamlOut; } /** * Returns a copy of this {@link Episode}. * @return a copy of this {@link Episode}. */ public Episode copy(){ Episode ep = new Episode(); ep.stateSequence = new ArrayList<State>(this.stateSequence); ep.actionSequence = new ArrayList<Action>(this.actionSequence); ep.rewardSequence = new ArrayList<Double>(this.rewardSequence); return ep; } public static Episode parseEpisode(String episodeString){ Yaml yaml = new Yaml(); Episode ea = (Episode)yaml.load(episodeString); return ea; } public static void main(String[] args) { GridWorldDomain gwd = new GridWorldDomain(11, 11); SADomain domain = gwd.generateDomain(); State s = new GridWorldState(new GridAgent(1, 3)); Policy p = new RandomPolicy(domain); Episode ea = PolicyUtils.rollout(p, s, domain.getModel(), 30); String yamlOut = ea.serialize(); System.out.println(yamlOut); System.out.println("\n\n"); Episode read = Episode.parseEpisode(yamlOut); System.out.println(read.actionString()); System.out.println(read.state(0).toString()); System.out.println(read.actionSequence.size()); System.out.println(read.stateSequence.size()); } }
package org.voltdb; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.concurrent.ExecutionException; import org.apache.hadoop_voltpatches.util.PureJavaCrc32C; import org.voltcore.logging.VoltLogger; import org.voltcore.utils.CoreUtils; import org.voltdb.CatalogContext.ProcedurePartitionInfo; import org.voltdb.VoltProcedure.VoltAbortException; import org.voltdb.catalog.PlanFragment; import org.voltdb.catalog.ProcParameter; import org.voltdb.catalog.Procedure; import org.voltdb.catalog.Statement; import org.voltdb.catalog.StmtParameter; import org.voltdb.client.BatchTimeoutOverrideType; import org.voltdb.client.ClientResponse; import org.voltdb.client.ProcedureInvocationType; import org.voltdb.compiler.AdHocPlannedStatement; import org.voltdb.compiler.AdHocPlannedStmtBatch; import org.voltdb.compiler.Language; import org.voltdb.compiler.ProcedureCompiler; import org.voltdb.dtxn.DtxnConstants; import org.voltdb.dtxn.TransactionState; import org.voltdb.exceptions.EEException; import org.voltdb.exceptions.SerializableException; import org.voltdb.exceptions.SpecifiedException; import org.voltdb.groovy.GroovyScriptProcedureDelegate; import org.voltdb.iv2.MpInitiator; import org.voltdb.iv2.UniqueIdGenerator; import org.voltdb.messaging.FragmentTaskMessage; import org.voltdb.planner.ActivePlanRepository; import org.voltdb.sysprocs.AdHocBase; import org.voltdb.types.TimestampType; import org.voltdb.utils.Encoder; import org.voltdb.utils.MiscUtils; import com.google_voltpatches.common.base.Charsets; public class ProcedureRunner { private static final VoltLogger log = new VoltLogger("HOST"); private static final boolean HOST_TRACE_ENABLED; static { HOST_TRACE_ENABLED = log.isTraceEnabled(); } // SQL statement queue info // This must be less than or equal to MAX_BATCH_COUNT in src/ee/execution/VoltDBEngine.h final static int MAX_BATCH_SIZE = 200; static class QueuedSQL { SQLStmt stmt; ParameterSet params; Expectation expectation = null; ByteBuffer serialization = null; } protected final ArrayList<QueuedSQL> m_batch = new ArrayList<QueuedSQL>(100); // cached fake SQLStmt array for single statement non-java procs QueuedSQL m_cachedSingleStmt = new QueuedSQL(); // never null boolean m_seenFinalBatch = false; // The name of a procedure to load at places about to run FragmentTasks // generated by this procedure in an MP txn. Currently used for // default procs that are auto-generated and whose plans might not be // loaded everywhere. Also used for @LoadMultipartitionTable because it // leverages the default procs' plan. // UTF-8 encoded string bytes byte[] m_procNameToLoadForFragmentTasks = null; // reflected info protected final String m_procedureName; protected final VoltProcedure m_procedure; protected Method m_procMethod; protected Class<?>[] m_paramTypes; // per txn state (are reset after call) protected TransactionState m_txnState; // used for sysprocs only protected byte m_statusCode = ClientResponse.SUCCESS; protected String m_statusString = null; // Status code that can be set by stored procedure upon invocation that will be returned with the response. protected byte m_appStatusCode = ClientResponse.UNINITIALIZED_APP_STATUS_CODE; protected String m_appStatusString = null; // cached txnid-seeded RNG so all calls to getSeededRandomNumberGenerator() for // a given call don't re-seed and generate the same number over and over private Random m_cachedRNG = null; // hooks into other parts of voltdb protected final SiteProcedureConnection m_site; protected final SystemProcedureExecutionContext m_systemProcedureContext; protected final CatalogSpecificPlanner m_csp; // per procedure state and catalog info protected ProcedureStatsCollector m_statsCollector; protected final Procedure m_catProc; protected final boolean m_isSysProc; protected final boolean m_isSinglePartition; protected final boolean m_hasJava; protected final boolean m_isReadOnly; protected final int m_partitionColumn; protected final VoltType m_partitionColumnType; protected final Language m_language; // dependency ids for ad hoc protected final static int AGG_DEPID = 1; // current hash of sql and params protected final PureJavaCrc32C m_inputCRC = new PureJavaCrc32C(); // running procedure info // - track the current call to voltExecuteSQL for logging progress protected int m_batchIndex; /** boolean flag to mark whether the previous batch execution has EE exception or not.*/ private long m_spBigBatchBeginToken; // Used to get around the "abstract" for StmtProcedures. // Path of least resistance? static class StmtProcedure extends VoltProcedure { public final SQLStmt sql = new SQLStmt("TBD"); } private final static Language.Visitor<String, VoltProcedure> procedureNameRetriever = new Language.Visitor<String, VoltProcedure>() { @Override public String visitJava(VoltProcedure p) { return p.getClass().getSimpleName(); } @Override public String visitGroovy(VoltProcedure p) { return ((GroovyScriptProcedureDelegate)p).getProcedureName(); } }; ProcedureRunner(VoltProcedure procedure, SiteProcedureConnection site, SystemProcedureExecutionContext sysprocContext, Procedure catProc, CatalogSpecificPlanner csp) { assert(m_inputCRC.getValue() == 0L); String language = catProc.getLanguage(); if (language != null && !language.trim().isEmpty()) { m_language = Language.valueOf(language.trim().toUpperCase()); } else if (procedure instanceof StmtProcedure){ m_language = null; } else { m_language = Language.JAVA; } if (procedure instanceof StmtProcedure) { m_procedureName = catProc.getTypeName().intern(); } else { m_procedureName = m_language.accept(procedureNameRetriever, procedure); } m_procedure = procedure; m_isSysProc = procedure instanceof VoltSystemProcedure; m_catProc = catProc; m_hasJava = catProc.getHasjava(); m_isReadOnly = catProc.getReadonly(); m_isSinglePartition = m_catProc.getSinglepartition(); if (m_isSinglePartition) { ProcedurePartitionInfo ppi = (ProcedurePartitionInfo)m_catProc.getAttachment(); m_partitionColumn = ppi.index; m_partitionColumnType = ppi.type; } else { m_partitionColumn = 0; m_partitionColumnType = null; } m_site = site; m_systemProcedureContext = sysprocContext; m_csp = csp; m_procedure.init(this); m_statsCollector = new ProcedureStatsCollector( m_site.getCorrespondingSiteId(), m_site.getCorrespondingPartitionId(), m_catProc); VoltDB.instance().getStatsAgent().registerStatsSource( StatsSelector.PROCEDURE, site.getCorrespondingSiteId(), m_statsCollector); reflect(); } public Procedure getCatalogProcedure() { return m_catProc; } public boolean isSystemProcedure() { return m_isSysProc; } /** * Note this fails for Sysprocs that use it in non-coordinating fragment work. Don't. * @return The transaction id for determinism, not for ordering. */ long getTransactionId() { StoredProcedureInvocation invocation = m_txnState.getInvocation(); if (invocation != null && ProcedureInvocationType.isDeprecatedInternalDRType(invocation.getType())) { return invocation.getOriginalTxnId(); } else { return m_txnState.txnId; } } Random getSeededRandomNumberGenerator() { // this value is memoized here and reset at the beginning of call(...). if (m_cachedRNG == null) { m_cachedRNG = new Random(getUniqueId()); } return m_cachedRNG; } @SuppressWarnings("finally") public ClientResponseImpl call(Object... paramListIn) { // verify per-txn state has been reset assert(m_statusCode == ClientResponse.SUCCESS); assert(m_statusString == null); assert(m_appStatusCode == ClientResponse.UNINITIALIZED_APP_STATUS_CODE); assert(m_appStatusString == null); assert(m_cachedRNG == null); // reset the hash of results m_inputCRC.reset(); // reset batch context info m_batchIndex = -1; // reset the beginning big batch undo token m_spBigBatchBeginToken = -1; // set procedure name in the site/ee m_site.setProcedureName(m_procedureName); // use local var to avoid warnings about reassigning method argument Object[] paramList = paramListIn; ClientResponseImpl retval = null; // assert no sql is queued assert(m_batch.size() == 0); try { m_statsCollector.beginProcedure(); VoltTable[] results = null; // inject sysproc execution context as the first parameter. if (isSystemProcedure()) { final Object[] combinedParams = new Object[paramList.length + 1]; combinedParams[0] = m_systemProcedureContext; for (int i=0; i < paramList.length; ++i) { combinedParams[i+1] = paramList[i]; } // swap the lists. paramList = combinedParams; } if (paramList.length != m_paramTypes.length) { m_statsCollector.endProcedure(false, true, null, null); String msg = "PROCEDURE " + m_procedureName + " EXPECTS " + String.valueOf(m_paramTypes.length) + " PARAMS, BUT RECEIVED " + String.valueOf(paramList.length); m_statusCode = ClientResponse.GRACEFUL_FAILURE; return getErrorResponse(m_statusCode, msg, null); } for (int i = 0; i < m_paramTypes.length; i++) { try { paramList[i] = ParameterConverter.tryToMakeCompatible(m_paramTypes[i], paramList[i]); // check the result type in an assert assert(ParameterConverter.verifyParameterConversion(paramList[i], m_paramTypes[i])); } catch (Exception e) { m_statsCollector.endProcedure(false, true, null, null); String msg = "PROCEDURE " + m_procedureName + " TYPE ERROR FOR PARAMETER " + i + ": " + e.toString(); m_statusCode = ClientResponse.GRACEFUL_FAILURE; return getErrorResponse(m_statusCode, msg, null); } } boolean error = false; boolean abort = false; // run a regular java class if (m_hasJava) { try { if (m_language == Language.JAVA) { if (HOST_TRACE_ENABLED) { log.trace("invoking... procMethod=" + m_procMethod.getName() + ", class=" + m_procMethod.getDeclaringClass().getName()); } try { Object rawResult = m_procMethod.invoke(m_procedure, paramList); results = getResultsFromRawResults(rawResult); } catch (IllegalAccessException e) { // If reflection fails, invoke the same error handling that other exceptions do throw new InvocationTargetException(e); } } else if (m_language == Language.GROOVY) { if (HOST_TRACE_ENABLED) { log.trace("invoking... groovy closure on class=" + getClass().getName()); } GroovyScriptProcedureDelegate proc = (GroovyScriptProcedureDelegate)m_procedure; Object rawResult = proc.invoke(paramList); results = getResultsFromRawResults(rawResult); } log.trace("invoked"); } catch (InvocationTargetException itex) { //itex.printStackTrace(); Throwable ex = itex.getCause(); if (ex instanceof VoltAbortException && !(ex instanceof EEException)) { abort = true; } else { error = true; } if (CoreUtils.isStoredProcThrowableFatalToServer(ex)) { // If the stored procedure attempted to do something other than linklibraray or instantiate // a missing object that results in an error, throw the error and let the server deal with // the condition as best as it can (usually a crashLocalVoltDB). try { m_statsCollector.endProcedure(false, true, null, null); } finally { // Ensure that ex is always re-thrown even if endProcedure throws an exception. throw (Error)ex; } } retval = getErrorResponse(ex); } } // single statement only work // (this could be made faster, but with less code re-use) else { assert(m_catProc.getStatements().size() == 1); try { m_cachedSingleStmt.params = getCleanParams(m_cachedSingleStmt.stmt, false, paramList); if (getNonVoltDBBackendIfExists() != null) { // Backend handling, such as HSQL or PostgreSQL VoltTable table = getNonVoltDBBackendIfExists().runSQLWithSubstitutions( m_cachedSingleStmt.stmt, m_cachedSingleStmt.params, m_cachedSingleStmt.stmt.statementParamTypes); results = new VoltTable[] { table }; } else { m_batch.add(m_cachedSingleStmt); results = voltExecuteSQL(true); } } catch (SerializableException ex) { retval = getErrorResponse(ex); } } // Record statistics for procedure call. StoredProcedureInvocation invoc = (m_txnState != null ? m_txnState.getInvocation() : null); ParameterSet paramSet = (invoc != null ? invoc.getParams() : null); m_statsCollector.endProcedure(abort, error, results, paramSet); // don't leave empty handed if (results == null) { results = new VoltTable[0]; } else if (results.length > Short.MAX_VALUE) { String statusString = "Stored procedure returns too much data. Exceeded maximum number of VoltTables: " + Short.MAX_VALUE; retval = new ClientResponseImpl( ClientResponse.GRACEFUL_FAILURE, ClientResponse.GRACEFUL_FAILURE, statusString, new VoltTable[0], statusString); } if (retval == null) { retval = new ClientResponseImpl( m_statusCode, m_appStatusCode, m_appStatusString, results, m_statusString); } int hash = (int) m_inputCRC.getValue(); if (ClientResponseImpl.isTransactionallySuccessful(retval.getStatus()) && (hash != 0)) { retval.setHash(hash); } if ((m_txnState != null) && // may be null for tests (m_txnState.getInvocation() != null) && (ProcedureInvocationType.isDeprecatedInternalDRType(m_txnState.getInvocation().getType()))) { retval.convertResultsToHashForDeterminism(); } } finally { // finally at the call(..) scope to ensure params can be // garbage collected and that the queue will be empty for // the next call m_batch.clear(); // reset other per-txn state m_txnState = null; m_statusCode = ClientResponse.SUCCESS; m_statusString = null; m_appStatusCode = ClientResponse.UNINITIALIZED_APP_STATUS_CODE; m_appStatusString = null; m_cachedRNG = null; m_cachedSingleStmt.params = null; m_cachedSingleStmt.expectation = null; m_seenFinalBatch = false; m_site.setProcedureName(null); } return retval; } /** * Check if the txn hashes to this partition. If not, it should be restarted. * @param txnState * @return true if the txn hashes to the current partition, false otherwise */ public boolean checkPartition(TransactionState txnState, TheHashinator hashinator) { if (m_isSinglePartition) { TheHashinator.HashinatorType hashinatorType = hashinator.getConfigurationType(); if (hashinatorType == TheHashinator.HashinatorType.LEGACY) { // Legacy hashinator is not used for elastic, no need to check partitioning. In fact, // since SP sysprocs all pass partitioning parameters as bytes, // they will hash to different partitions using the legacy hashinator. So don't do it. return true; } if (m_site.getCorrespondingPartitionId() == MpInitiator.MP_INIT_PID) { // SP txn misrouted to MPI, possible to happen during catalog update throw new ExpectedProcedureException("Single-partition procedure routed to multi-partition initiator"); } StoredProcedureInvocation invocation = txnState.getInvocation(); VoltType parameterType; Object parameterAtIndex; // check if AdHoc_RO_SP or AdHoc_RW_SP if (m_procedure instanceof AdHocBase) { // ClientInterface should pre-validate this param is valid parameterAtIndex = invocation.getParameterAtIndex(0); parameterType = VoltType.get((Byte) invocation.getParameterAtIndex(1)); } else { parameterType = m_partitionColumnType; parameterAtIndex = invocation.getParameterAtIndex(m_partitionColumn); } // Note that @LoadSinglepartitionTable has problems if the parititoning param // uses integers as bytes and isn't padded to 8b or using the right byte order. // Since this is not exposed to users, we're ok for now. The right fix is to probably // accept the right partitioning type from the user, then rewrite the params internally // before we initiate the proc (like adhocs). try { int partition = hashinator.getHashedPartitionForParameter(parameterType, parameterAtIndex); if (partition == m_site.getCorrespondingPartitionId()) { return true; } else { // Wrong partition, should restart the txn if (HOST_TRACE_ENABLED) { log.trace("Txn " + txnState.getInvocation().getProcName() + " will be restarted"); } } } catch (Exception e) { log.warn("Unable to check partitioning of transaction " + txnState.m_spHandle, e); } return false; } else { if (!m_catProc.getEverysite() && m_site.getCorrespondingPartitionId() != MpInitiator.MP_INIT_PID) { // MP txn misrouted to SPI, possible to happen during catalog update throw new ExpectedProcedureException("Multi-partition procedure routed to single-partition initiator"); } // For n-partition transactions, we need to rehash the partitioning values and check // if they still hash to the assigned partitions. // Note that when n-partition transaction runs, it's run on the MPI site, so calling // m_site.getCorrespondingPartitionId() will return the MPI's partition ID. We need // another way of getting what partitions were assigned to this transaction. return true; } } public void setupTransaction(TransactionState txnState) { m_txnState = txnState; } public TransactionState getTxnState() { assert(m_isSysProc); return m_txnState; } /** * If this returns non-null, then we're using a non-VoltDB backend, such * as HSQL or PostgreSQL. */ public NonVoltDBBackend getNonVoltDBBackendIfExists() { return m_site.getNonVoltDBBackendIfExists(); } public void setAppStatusCode(byte statusCode) { m_appStatusCode = statusCode; } public void setAppStatusString(String statusString) { m_appStatusString = statusString; } public void setProcNameToLoadForFragmentTasks(String procName) { if (procName != null) { m_procNameToLoadForFragmentTasks = procName.getBytes(Charsets.UTF_8); } else { m_procNameToLoadForFragmentTasks = null; } } /* * Extract the timestamp from the timestamp field we have been passing around * that is now a unique id with a timestamp encoded in the most significant bits ala * a pre-IV2 transaction id. */ public Date getTransactionTime() { return new Date(UniqueIdGenerator.getTimestampFromUniqueId(getUniqueId())); } /* * The timestamp field is no longer really a timestamp, it is a unique id that is time based * and is similar to a pre-IV2 transaction ID except the less significant bits are set * to allow matching partition counts with IV2. It's OK, still can do 512k txns/second per * partition so plenty of headroom. */ public long getUniqueId() { StoredProcedureInvocation invocation = m_txnState.getInvocation(); if (invocation != null && ProcedureInvocationType.isDeprecatedInternalDRType(invocation.getType())) { return invocation.getOriginalUniqueId(); } else { return m_txnState.uniqueId; } } /* * Cluster id is immutable and be persisted during the snapshot */ public int getClusterId() { return m_site.getCorrespondingClusterId(); } private void updateCRC(QueuedSQL queuedSQL) { if (!queuedSQL.stmt.isReadOnly) { m_inputCRC.update(queuedSQL.stmt.sqlCRC); try { ByteBuffer buf = ByteBuffer.allocate(queuedSQL.params.getSerializedSize()); queuedSQL.params.flattenToBuffer(buf); buf.flip(); m_inputCRC.update(buf.array()); queuedSQL.serialization = buf; } catch (IOException e) { log.error("Unable to compute CRC of parameters to " + "a SQL statement in procedure: " + m_procedureName, e); // don't crash // presumably, this will fail deterministically at all replicas // just log the error and hope people report it } } } public void voltQueueSQL(final SQLStmt stmt, Expectation expectation, Object... args) { if (stmt == null) { throw new IllegalArgumentException("SQLStmt parameter to voltQueueSQL(..) was null."); } QueuedSQL queuedSQL = new QueuedSQL(); queuedSQL.expectation = expectation; queuedSQL.params = getCleanParams(stmt, true, args); queuedSQL.stmt = stmt; updateCRC(queuedSQL); m_batch.add(queuedSQL); } public void voltQueueSQL(final String sql, Object... args) { if (sql == null || sql.isEmpty()) { throw new IllegalArgumentException("SQL statement '" + sql + "' is null or the empty string"); } try { AdHocPlannedStmtBatch batch = m_csp.plan(sql, args,m_isSinglePartition).get(); if (batch.errorMsg != null) { throw new VoltAbortException("Failed to plan sql '" + sql + "' error: " + batch.errorMsg); } if (m_isReadOnly && !batch.isReadOnly()) { throw new VoltAbortException("Attempted to queue DML adhoc sql '" + sql + "' from read only procedure"); } assert(1 == batch.plannedStatements.size()); QueuedSQL queuedSQL = new QueuedSQL(); AdHocPlannedStatement plannedStatement = batch.plannedStatements.get(0); long aggFragId = ActivePlanRepository.loadOrAddRefPlanFragment( plannedStatement.core.aggregatorHash, plannedStatement.core.aggregatorFragment, sql); long collectorFragId = 0; if (plannedStatement.core.collectorFragment != null) { collectorFragId = ActivePlanRepository.loadOrAddRefPlanFragment( plannedStatement.core.collectorHash, plannedStatement.core.collectorFragment, sql); } queuedSQL.stmt = SQLStmtAdHocHelper.createWithPlan( plannedStatement.sql, aggFragId, plannedStatement.core.aggregatorHash, true, collectorFragId, plannedStatement.core.collectorHash, true, plannedStatement.core.isReplicatedTableDML, plannedStatement.core.readOnly, plannedStatement.core.parameterTypes, m_site); Object[] argumentParams = args; // case handles if there were parameters OR // if there were no constants to pull out // In the current scheme, which does not support combining user-provided parameters // with planner-extracted parameters in the same statement, an original sql statement // containing parameters to match its provided arguments should bypass the parameterizer, // so there should be no extracted params. // The presence of extracted paremeters AND user-provided arguments can only arise when // the arguments have no user-specified parameters in the sql statement // to put these arguments to use -- these are invalid, so flag an error. // Even the special "partitioning argument" provided to @AdHocSpForTest with no // corresponding parameter in the sql should have been noted and discarded by the // dispatcher before reaching this ProcedureRunner. This opens the possibility of // supporting @AdHocSpForTest with queries that contain '?' parameters. if (plannedStatement.hasExtractedParams()) { if (args.length > 0) { throw new VoltAbortException( "Number of arguments provided was " + args.length + " where 0 were expected for statement: " + sql); } argumentParams = plannedStatement.extractedParamArray(); if (argumentParams.length != queuedSQL.stmt.statementParamTypes.length) { String msg = String.format( "The wrong number of arguments (" + argumentParams.length + " vs. the " + queuedSQL.stmt.statementParamTypes.length + " expected) were passed for the parameterized statement: %s", sql); throw new VoltAbortException(msg); } } queuedSQL.params = getCleanParams(queuedSQL.stmt, false, argumentParams); updateCRC(queuedSQL); m_batch.add(queuedSQL); } catch (Exception e) { if (e instanceof ExecutionException) { throw new VoltAbortException(e.getCause()); } if (e instanceof VoltAbortException) { throw (VoltAbortException) e; } throw new VoltAbortException(e); } } public VoltTable[] voltExecuteSQL(boolean isFinalSQL) { try { if (m_seenFinalBatch) { throw new RuntimeException("Procedure " + m_procedureName + " attempted to execute a batch " + "after claiming a previous batch was final " + "and will be aborted.\n Examine calls to " + "voltExecuteSQL() and verify that the call " + "with the argument value 'true' is actually " + "the final one"); } m_seenFinalBatch = isFinalSQL; // should check whether the batch is read only or not // e.g. read only query may have timed out... if (!m_isSinglePartition && m_txnState.needsRollback()) { throw new VoltAbortException("Multi-partition procedure " + m_procedureName + " attempted to execute new batch after hitting EE exception in a previous batch"); } // memo-ize the original batch size here int batchSize = m_batch.size(); // increment the number of voltExecuteSQL calls for this proc m_batchIndex++; m_site.setBatch(m_batchIndex); // if batch is small (or reasonable size), do it in one go if (batchSize <= MAX_BATCH_SIZE) { // invalidate this big batch begin token m_spBigBatchBeginToken = -1; return executeQueriesInABatch(m_batch, isFinalSQL); } // otherwise, break it into sub-batches else { if (! m_isReadOnly) { // increase 1 here to mark the next executing undo token m_spBigBatchBeginToken = m_site.getLatestUndoToken() + 1; } List<VoltTable[]> results = new ArrayList<VoltTable[]>(); while (m_batch.size() > 0) { int subSize = Math.min(MAX_BATCH_SIZE, m_batch.size()); // get the beginning of the batch (or all if small enough) // note: this is a view into the larger list and changes to it // will mutate the larger m_batch. List<QueuedSQL> subBatch = m_batch.subList(0, subSize); // decide if this sub-batch should be marked final boolean finalSubBatch = isFinalSQL && (subSize == m_batch.size()); // run the sub-batch and copy the sub-results into the list of lists of results // note: executeQueriesInABatch removes items from the batch as it runs. // this means subBatch will be empty after running and since subBatch is a // view on the larger batch, it removes subBatch.size() elements from m_batch. results.add(executeQueriesInABatch(subBatch, finalSubBatch)); } // merge the list of lists into something returnable VoltTable[] retval = MiscUtils.concatAll(new VoltTable[0], results); assert(retval.length == batchSize); return retval; } } finally { m_batch.clear(); } } protected VoltTable[] executeQueriesInABatch(List<QueuedSQL> batch, boolean isFinalSQL) { final int batchSize = batch.size(); VoltTable[] results = null; if (batchSize == 0) { return new VoltTable[] {}; } // If this is a non-VoltDB backend, run the queries directly in that // database (e.g. HSQL or PostgreSQL) if (getNonVoltDBBackendIfExists() != null) { results = new VoltTable[batchSize]; int i = 0; for (QueuedSQL qs : batch) { results[i++] = getNonVoltDBBackendIfExists().runSQLWithSubstitutions( qs.stmt, qs.params, qs.stmt.statementParamTypes); } } else if (m_isSinglePartition) { results = fastPath(batch); } else { results = slowPath(batch, isFinalSQL); } // check expectations int i = 0; for (QueuedSQL qs : batch) { Expectation.check(m_procedureName, qs.stmt, i, qs.expectation, results[i]); i++; } // clear the queued sql list for the next call batch.clear(); return results; } public byte[] voltLoadTable(String clusterName, String databaseName, String tableName, VoltTable data, boolean returnUniqueViolations, boolean shouldDRStream) throws VoltAbortException { if (data == null || data.getRowCount() == 0) { return null; } try { return m_site.loadTable(m_txnState.txnId, m_txnState.m_spHandle, m_txnState.uniqueId, clusterName, databaseName, tableName, data, returnUniqueViolations, shouldDRStream, false); } catch (EEException e) { throw new VoltAbortException("Failed to load table: " + tableName); } } public DependencyPair executeSysProcPlanFragment( TransactionState txnState, Map<Integer, List<VoltTable>> dependencies, long fragmentId, ParameterSet params) { setupTransaction(txnState); assert (m_procedure instanceof VoltSystemProcedure); VoltSystemProcedure sysproc = (VoltSystemProcedure) m_procedure; return sysproc.executePlanFragment(dependencies, fragmentId, params, m_systemProcedureContext); } private final void throwIfInfeasibleTypeConversion(SQLStmt stmt, Class <?> argClass, int argInd, VoltType expectedType) { if (argClass.isArray()) { // The statement parameter model doesn't currently support a // general concept of an array-typed parameter. Instead, it // defines certain special VoltTypes that are implicitly // convertible from specific array-typed arguments. // These are provided in the sqlType arg. // For example, // VARBINARY parameters accept byte[] arguments, // INLIST_OF_STRING parameters accept String[] arguments, // INLIST_OF_BIGINT parameters accept integer-typed array // arguments like long[], Long[], int[], Integer[], etc. if (expectedType.acceptsArray(argClass)) { return; } } else { VoltType argType = VoltType.typeFromClass(argClass); if (argType == expectedType) { return; } if (argType == VoltType.STRING) { // TODO: Should we consider String to be a universal donor type? if (expectedType.isNumber() || expectedType == VoltType.TIMESTAMP) { return; } } else if (argType.isNumber()) { if (expectedType.isNumber() || expectedType == VoltType.STRING || // Allow timestamp initialization from integer or even // float (microseconds), yet not decimal (?) // for backward compatibility. // TODO: Should we deprecate this soon as something // easy enough to work around and too easy to abuse? expectedType == VoltType.TIMESTAMP) { return; } } // Allow initialization of string or integer or even decimal or float? // (microseconds) yet not decimal (?) from timestamp, // for backward compatibility. // TODO: Should we deprecate some or all of these conversions soon as // something easy enough to work around and too easy to accidentally // abuse? else if (argType.isBackendIntegerType()) { if (expectedType.isNumber() || expectedType == VoltType.STRING) { return; } } // As new non-numeric types are added, early return cases need // to be added here IF the types are used as parameter types // and they are directly convertible from other non-array types // beyond string. } String argTypeName = argClass.getSimpleName(); String preferredType = expectedType.getMostCompatibleJavaTypeName(); throw new VoltTypeException("Procedure " + m_procedureName + ": Incompatible parameter type: can not convert type '"+ argTypeName + "' to '"+ expectedType.getName() + "' for arg " + argInd + " for SQL stmt: " + stmt.getText() + "." + " Try explicitly using a " + preferredType + " parameter."); } private final ParameterSet getCleanParams(SQLStmt stmt, boolean verifyTypeConv, Object... inArgs) { final byte stmtParamTypes[] = stmt.statementParamTypes; final int numParamTypes = stmtParamTypes.length; final Object[] args = new Object[numParamTypes]; if (inArgs.length != numParamTypes) { throw new VoltAbortException( "Number of arguments provided was " + inArgs.length + " where " + numParamTypes + " was expected for statement " + stmt.getText()); } for (int ii = 0; ii < numParamTypes; ii++) { VoltType type = VoltType.get(stmtParamTypes[ii]); // handle non-null values if (inArgs[ii] != null) { args[ii] = inArgs[ii]; assert(type != VoltType.INVALID); if (verifyTypeConv && type != VoltType.INVALID) { throwIfInfeasibleTypeConversion(stmt, args[ii].getClass(), ii, type); } continue; } // handle null values switch (type) { case TINYINT: args[ii] = Byte.MIN_VALUE; break; case SMALLINT: args[ii] = Short.MIN_VALUE; break; case INTEGER: args[ii] = Integer.MIN_VALUE; break; case BIGINT: args[ii] = Long.MIN_VALUE; break; case FLOAT: args[ii] = VoltType.NULL_FLOAT; break; case TIMESTAMP: args[ii] = new TimestampType(Long.MIN_VALUE); break; case STRING: args[ii] = VoltType.NULL_STRING_OR_VARBINARY; break; case VARBINARY: args[ii] = VoltType.NULL_STRING_OR_VARBINARY; break; case DECIMAL: args[ii] = VoltType.NULL_DECIMAL; break; case GEOGRAPHY_POINT: args[ii] = VoltType.NULL_POINT; break; case GEOGRAPHY: args[ii] = VoltType.NULL_GEOGRAPHY; break; default: throw new VoltAbortException("Unknown type " + type + " can not be converted to NULL representation for arg " + ii + " for SQL stmt: " + stmt.getText()); } } return ParameterSet.fromArrayNoCopy(args); } public void initSQLStmt(SQLStmt stmt, Statement catStmt) { int fragCount = catStmt.getFragments().size(); for (PlanFragment frag : catStmt.getFragments()) { byte[] planHash = Encoder.hexDecode(frag.getPlanhash()); byte[] plan = Encoder.decodeBase64AndDecompressToBytes(frag.getPlannodetree()); long id = ActivePlanRepository.loadOrAddRefPlanFragment(planHash, plan, catStmt.getSqltext()); boolean transactional = frag.getNontransactional() == false; SQLStmt.Frag stmtFrag = new SQLStmt.Frag(id, planHash, transactional); if (fragCount == 1 || frag.getHasdependencies()) { stmt.aggregator = stmtFrag; } else { stmt.collector = stmtFrag; } } stmt.isReadOnly = catStmt.getReadonly(); stmt.isReplicatedTableDML = catStmt.getReplicatedtabledml(); stmt.site = m_site; int numStatementParamTypes = catStmt.getParameters().size(); stmt.statementParamTypes = new byte[numStatementParamTypes]; for (StmtParameter param : catStmt.getParameters()) { int index = param.getIndex(); // Array-typed params currently only arise from in-lists. // Tweak the parameter's expected type accordingly. VoltType expectType = VoltType.get((byte)param.getJavatype()); if (param.getIsarray()) { if (expectType == VoltType.STRING) { expectType = VoltType.INLIST_OF_STRING; } else { expectType = VoltType.INLIST_OF_BIGINT; } } stmt.statementParamTypes[index] = expectType.getValue(); } } protected void reflect() { Map<String, SQLStmt> stmtMap; // fill in the sql for single statement procs if (m_catProc.getHasjava()) { // this is where, in the case of java procedures, m_procMethod is set m_paramTypes = m_language.accept(parametersTypeRetriever, this); if (m_procMethod == null && m_language == Language.JAVA) { throw new RuntimeException("No \"run\" method found in: " + m_procedure.getClass().getName()); } // iterate through the fields and deal with sql statements stmtMap = m_language.accept(sqlStatementsRetriever, this); } else { try { stmtMap = ProcedureCompiler.getValidSQLStmts(null, m_procedureName, m_procedure.getClass(), m_procedure, true); SQLStmt stmt = stmtMap.get(VoltDB.ANON_STMT_NAME); assert(stmt != null); Statement statement = m_catProc.getStatements().get(VoltDB.ANON_STMT_NAME); String s = statement.getSqltext(); SQLStmtAdHocHelper.setSQLStr(stmt, s); m_cachedSingleStmt.stmt = stmt; int numParams = m_catProc.getParameters().size(); m_paramTypes = new Class<?>[numParams]; for (ProcParameter param : m_catProc.getParameters()) { VoltType type = VoltType.get((byte) param.getType()); if (param.getIsarray()) { m_paramTypes[param.getIndex()] = type.vectorClassFromType(); continue; } // Paul doesn't understand why single-statement procedures // need to have their input parameter types widened here. // Is it not better to catch too-wide values in the ProcedureRunner // (ParameterConverter.tryToMakeCompatible) before falling through to the EE? if (type == VoltType.INTEGER) { type = VoltType.BIGINT; } else if (type == VoltType.SMALLINT) { type = VoltType.BIGINT; } else if (type == VoltType.TINYINT) { type = VoltType.BIGINT; } else if (type == VoltType.NUMERIC) { type = VoltType.FLOAT; } m_paramTypes[param.getIndex()] = type.classFromType(); } } catch (Exception e) { // shouldn't throw anything outside of the compiler e.printStackTrace(); } // iterate through the fields and deal with sql statements try { stmtMap = ProcedureCompiler.getValidSQLStmts(null, m_procedureName, m_procedure.getClass(), m_procedure, true); } catch (Exception e1) { // shouldn't throw anything outside of the compiler e1.printStackTrace(); return; } } for (final Entry<String, SQLStmt> entry : stmtMap.entrySet()) { String name = entry.getKey(); Statement s = m_catProc.getStatements().get(name); if (s != null) { /* * Cache all the information we need about the statements in this stored * procedure locally instead of pulling them from the catalog on * a regular basis. */ SQLStmt stmt = entry.getValue(); // done in a static method in an abstract class so users don't call it initSQLStmt(stmt, s); //LOG.fine("Found statement " + name); } } } private final static Language.Visitor<Class<?>[], ProcedureRunner> parametersTypeRetriever = new Language.Visitor<Class<?>[], ProcedureRunner>() { @Override public Class<?>[] visitJava(ProcedureRunner p) { Method[] methods = p.m_procedure.getClass().getDeclaredMethods(); for (final Method m : methods) { String name = m.getName(); if (name.equals("run")) { if (Modifier.isPublic(m.getModifiers()) == false) { continue; } p.m_procMethod = m; return m.getParameterTypes(); } } return null; } @Override public Class<?>[] visitGroovy(ProcedureRunner p) { return ((GroovyScriptProcedureDelegate)p.m_procedure).getParameterTypes(); } }; private final static Language.Visitor<Map<String,SQLStmt>, ProcedureRunner> sqlStatementsRetriever = new Language.Visitor<Map<String,SQLStmt>, ProcedureRunner>() { @Override public Map<String, SQLStmt> visitJava(ProcedureRunner p) { Map<String, SQLStmt> stmtMap = null; try { stmtMap = ProcedureCompiler.getValidSQLStmts(null, p.m_procedureName, p.m_procedure.getClass(), p.m_procedure, true); } catch (Exception e1) { // shouldn't throw anything outside of the compiler e1.printStackTrace(); } return stmtMap; } @Override public Map<String, SQLStmt> visitGroovy(ProcedureRunner p) { return ((GroovyScriptProcedureDelegate)p.m_procedure).getStatementMap(); } }; /** * Test whether or not the given stack frame is within a procedure invocation * @param stel a stack trace element * @return true if it is, false it is not */ protected boolean isProcedureStackTraceElement(StackTraceElement stel) { int lastPeriodPos = stel.getClassName().lastIndexOf('.'); if (lastPeriodPos == -1) { lastPeriodPos = 0; } else { ++lastPeriodPos; } // Account for inner classes too. Inner classes names comprise of the parent // class path followed by a dollar sign String simpleName = stel.getClassName().substring(lastPeriodPos); return simpleName.equals(m_procedureName) || (simpleName.startsWith(m_procedureName) && simpleName.charAt(m_procedureName.length()) == '$'); } /** * * @param e * @return A ClientResponse containing error information */ protected ClientResponseImpl getErrorResponse(Throwable eIn) { // use local var to avoid warnings about reassigning method argument Throwable e = eIn; boolean expected_failure = true; boolean hideStackTrace = false; StackTraceElement[] stack = e.getStackTrace(); ArrayList<StackTraceElement> matches = new ArrayList<StackTraceElement>(); for (StackTraceElement ste : stack) { if (isProcedureStackTraceElement(ste)) { matches.add(ste); } } byte status = ClientResponse.UNEXPECTED_FAILURE; StringBuilder msg = new StringBuilder(); if (e.getClass() == VoltAbortException.class) { status = ClientResponse.USER_ABORT; msg.append("USER ABORT\n"); } else if (e.getClass() == org.voltdb.exceptions.ConstraintFailureException.class) { status = ClientResponse.GRACEFUL_FAILURE; msg.append("CONSTRAINT VIOLATION\n"); } else if (e.getClass() == org.voltdb.exceptions.SQLException.class) { status = ClientResponse.GRACEFUL_FAILURE; msg.append("SQL ERROR\n"); } // Interrupt exception will be thrown when the procedure is killed by a user // or by a timeout in the middle of executing. else if (e.getClass() == org.voltdb.exceptions.InterruptException.class) { status = ClientResponse.GRACEFUL_FAILURE; msg.append("Transaction Interrupted\n"); } else if (e.getClass() == org.voltdb.ExpectedProcedureException.class) { String backendType = "HSQL"; if (getNonVoltDBBackendIfExists() instanceof PostgreSQLBackend) { backendType = "PostgreSQL"; } msg.append(backendType); msg.append("-BACKEND ERROR\n"); if (e.getCause() != null) { e = e.getCause(); } } else if (e.getClass() == org.voltdb.exceptions.TransactionRestartException.class) { status = ClientResponse.TXN_RESTART; msg.append("TRANSACTION RESTART\n"); } // SpecifiedException means the dev wants control over status and message else if (e.getClass() == SpecifiedException.class) { SpecifiedException se = (SpecifiedException) e; status = se.getStatus(); expected_failure = true; hideStackTrace = true; } else { msg.append("UNEXPECTED FAILURE:\n"); expected_failure = false; } // ensure the message is returned if we're not going to hit the verbose condition below if (expected_failure || hideStackTrace) { msg.append(" ").append(e.getMessage()); if (e instanceof org.voltdb.exceptions.InterruptException && m_isReadOnly) { int originalTimeout = VoltDB.instance().getConfig().getQueryTimeout(); int individualTimeout = m_txnState.getInvocation().getBatchTimeout(); if (BatchTimeoutOverrideType.isUserSetTimeout(individualTimeout)) { msg.append(" query-specific timeout period."); msg.append(" The query-specific timeout is currently " + individualTimeout/1000.0 + " seconds."); } else { msg.append(" default query timeout period."); } if (originalTimeout > 0 ) { msg.append(" The default query timeout is currently " + originalTimeout/1000.0 + " seconds and can be changed in the systemsettings section of the deployment file."); } else if (originalTimeout == 0) { msg.append(" The default query timeout is currently set to no timeout and can be changed in the systemsettings section of the deployment file."); } } } // Rarely hide the stack trace. // Right now, just for SpecifiedException, which is usually from sysprocs where the error is totally // known and not helpful to the user. if (!hideStackTrace) { // If the error is something we know can happen as part of normal operation, // reduce the verbosity. // Otherwise, generate more output for debuggability if (expected_failure) { for (StackTraceElement ste : matches) { msg.append("\n at "); msg.append(ste.getClassName()).append(".").append(ste.getMethodName()); msg.append("(").append(ste.getFileName()).append(":"); msg.append(ste.getLineNumber()).append(")"); } } else { Writer result = new StringWriter(); PrintWriter pw = new PrintWriter(result); e.printStackTrace(pw); msg.append(" ").append(result.toString()); } } return getErrorResponse( status, msg.toString(), e instanceof SerializableException ? (SerializableException)e : null); } protected ClientResponseImpl getErrorResponse(byte status, String msg, SerializableException e) { return new ClientResponseImpl( status, m_appStatusCode, m_appStatusString, new VoltTable[0], "VOLTDB ERROR: " + msg); } /** * Given the results of a procedure, convert it into a sensible array of VoltTables. * @throws InvocationTargetException */ final private VoltTable[] getResultsFromRawResults(Object result) throws InvocationTargetException { if (result == null) { return new VoltTable[0]; } if (result instanceof VoltTable[]) { VoltTable[] retval = (VoltTable[]) result; for (VoltTable table : retval) { if (table == null) { Exception e = new RuntimeException("VoltTable arrays with non-zero length cannot contain null values."); throw new InvocationTargetException(e); } } return retval; } if (result instanceof VoltTable) { return new VoltTable[] { (VoltTable) result }; } if (result instanceof Long) { VoltTable t = new VoltTable(new VoltTable.ColumnInfo("", VoltType.BIGINT)); t.addRow(result); return new VoltTable[] { t }; } throw new RuntimeException("Procedure didn't return acceptable type."); } VoltTable[] executeQueriesInIndividualBatches(List<QueuedSQL> batch, boolean finalTask) { assert(batch.size() > 0); VoltTable[] retval = new VoltTable[batch.size()]; ArrayList<QueuedSQL> microBatch = new ArrayList<QueuedSQL>(); for (int i = 0; i < batch.size(); i++) { QueuedSQL queuedSQL = batch.get(i); assert(queuedSQL != null); microBatch.add(queuedSQL); boolean isThisLoopFinalTask = finalTask && (i == (batch.size() - 1)); assert(microBatch.size() == 1); VoltTable[] results = executeQueriesInABatch(microBatch, isThisLoopFinalTask); assert(results != null); assert(results.length == 1); retval[i] = results[0]; microBatch.clear(); } return retval; } private VoltTable[] slowPath(List<QueuedSQL> batch, final boolean finalTask) { /* * Determine if reads and writes are mixed. Can't mix reads and writes * because the order of execution is wrong when replicated tables are * involved due to ENG-1232. */ boolean hasRead = false; boolean hasWrite = false; for (int i = 0; i < batch.size(); ++i) { final SQLStmt stmt = batch.get(i).stmt; if (stmt.isReadOnly) { hasRead = true; } else { hasWrite = true; } } /* * If they are all reads or all writes then we can use the batching * slow path Otherwise the order of execution will be interleaved * incorrectly so we have to do each statement individually. */ if (hasRead && hasWrite) { return executeQueriesInIndividualBatches(batch, finalTask); } else { return executeSlowHomogeneousBatch(batch, finalTask); } } /** * Used by executeSlowHomogeneousBatch() to build messages and keep track * of other information as the batch is processed. */ private static class BatchState { // needed to size arrays and check index arguments final int m_batchSize; // needed to get various IDs private final TransactionState m_txnState; // the set of dependency ids for the expected results of the batch // one per sql statment final int[] m_depsToResume; // these dependencies need to be received before the local stuff can run final int[] m_depsForLocalTask; // check if all local fragment work is non-transactional boolean m_localFragsAreNonTransactional = false; // the data and message for locally processed fragments final FragmentTaskMessage m_localTask; // the data and message for all sites in the transaction final FragmentTaskMessage m_distributedTask; // holds query results final VoltTable[] m_results; BatchState(int batchSize, TransactionState txnState, long siteId, boolean finalTask, String procedureName, byte[] procToLoad) { m_batchSize = batchSize; m_txnState = txnState; m_depsToResume = new int[batchSize]; m_depsForLocalTask = new int[batchSize]; m_results = new VoltTable[batchSize]; // the data and message for locally processed fragments m_localTask = new FragmentTaskMessage(m_txnState.initiatorHSId, siteId, m_txnState.txnId, m_txnState.uniqueId, m_txnState.isReadOnly(), false, txnState.isForReplay()); m_localTask.setProcedureName(procedureName); m_localTask.setBatchTimeout(m_txnState.getInvocation().getBatchTimeout()); // the data and message for all sites in the transaction m_distributedTask = new FragmentTaskMessage(m_txnState.initiatorHSId, siteId, m_txnState.txnId, m_txnState.uniqueId, m_txnState.isReadOnly(), finalTask, txnState.isForReplay()); m_distributedTask.setProcedureName(procedureName); // this works fine if procToLoad is NULL m_distributedTask.setProcNameToLoad(procToLoad); m_distributedTask.setBatchTimeout(m_txnState.getInvocation().getBatchTimeout()); } /* * Replicated fragment. */ void addStatement(int index, SQLStmt stmt, ByteBuffer params, SiteProcedureConnection site) { assert(index >= 0); assert(index < m_batchSize); assert(stmt != null); // if any frag is transactional, update this check if (stmt.aggregator.transactional == true) { m_localFragsAreNonTransactional = false; } // single aggregator fragment if (stmt.collector == null) { m_depsForLocalTask[index] = -1; // Add the local fragment data. if (stmt.inCatalog) { m_localTask.addFragment(stmt.aggregator.planHash, m_depsToResume[index], params); } else { byte[] planBytes = ActivePlanRepository.planForFragmentId(stmt.aggregator.id); m_localTask.addCustomFragment(stmt.aggregator.planHash, m_depsToResume[index], params, planBytes, stmt.getText()); } } // two fragments else { int outputDepId = m_txnState.getNextDependencyId() | DtxnConstants.MULTIPARTITION_DEPENDENCY; m_depsForLocalTask[index] = outputDepId; // Add local and distributed fragments. if (stmt.inCatalog) { m_localTask.addFragment(stmt.aggregator.planHash, m_depsToResume[index], params); m_distributedTask.addFragment(stmt.collector.planHash, outputDepId, params); } else { byte[] planBytes = ActivePlanRepository.planForFragmentId(stmt.aggregator.id); m_localTask.addCustomFragment(stmt.aggregator.planHash, m_depsToResume[index], params, planBytes, stmt.getText()); planBytes = ActivePlanRepository.planForFragmentId(stmt.collector.id); m_distributedTask.addCustomFragment(stmt.collector.planHash, outputDepId, params, planBytes, stmt.getText()); } } } } /* * Execute a batch of homogeneous queries, i.e. all reads or all writes. */ VoltTable[] executeSlowHomogeneousBatch(final List<QueuedSQL> batch, final boolean finalTask) { BatchState state = new BatchState(batch.size(), m_txnState, m_site.getCorrespondingSiteId(), finalTask, m_procedureName, m_procNameToLoadForFragmentTasks); // iterate over all sql in the batch, filling out the above data structures for (int i = 0; i < batch.size(); ++i) { QueuedSQL queuedSQL = batch.get(i); assert(queuedSQL.stmt != null); // Figure out what is needed to resume the proc int collectorOutputDepId = m_txnState.getNextDependencyId(); state.m_depsToResume[i] = collectorOutputDepId; // Build the set of params for the frags ByteBuffer paramBuf = null; try { if (queuedSQL.serialization != null) { paramBuf = ByteBuffer.allocate(queuedSQL.serialization.capacity()); paramBuf.put(queuedSQL.serialization); } else { paramBuf = ByteBuffer.allocate(queuedSQL.params.getSerializedSize()); queuedSQL.params.flattenToBuffer(paramBuf); } } catch (IOException e) { throw new RuntimeException("Error serializing parameters for SQL statement: " + queuedSQL.stmt.getText() + " with params: " + queuedSQL.params.toJSONString(), e); } assert(paramBuf != null); paramBuf.flip(); state.addStatement(i, queuedSQL.stmt, paramBuf, m_site); } // instruct the dtxn what's needed to resume the proc m_txnState.setupProcedureResume(finalTask, state.m_depsToResume); // create all the local work for the transaction for (int i = 0; i < state.m_depsForLocalTask.length; i++) { if (state.m_depsForLocalTask[i] < 0) { continue; } state.m_localTask.addInputDepId(i, state.m_depsForLocalTask[i]); } // note: non-transactional work only helps us if it's final work m_txnState.createLocalFragmentWork(state.m_localTask, state.m_localFragsAreNonTransactional && finalTask); if (!state.m_distributedTask.isEmpty()) { state.m_distributedTask.setBatch(m_batchIndex); m_txnState.createAllParticipatingFragmentWork(state.m_distributedTask); } // recursively call recursableRun and don't allow it to shutdown Map<Integer,List<VoltTable>> mapResults = m_site.recursableRun(m_txnState); assert(mapResults != null); assert(state.m_depsToResume != null); assert(state.m_depsToResume.length == batch.size()); // build an array of answers, assuming one result per expected id for (int i = 0; i < batch.size(); i++) { List<VoltTable> matchingTablesForId = mapResults.get(state.m_depsToResume[i]); assert(matchingTablesForId != null); assert(matchingTablesForId.size() == 1); state.m_results[i] = matchingTablesForId.get(0); } return state.m_results; } // Batch up pre-planned fragments, but handle ad hoc independently. private VoltTable[] fastPath(List<QueuedSQL> batch) { final int batchSize = batch.size(); Object[] params = new Object[batchSize]; long[] fragmentIds = new long[batchSize]; String[] sqlTexts = new String[batchSize]; int i = 0; for (final QueuedSQL qs : batch) { assert(qs.stmt.collector == null); fragmentIds[i] = qs.stmt.aggregator.id; // use the pre-serialized params if it exists if (qs.serialization != null) { params[i] = qs.serialization; } else { params[i] = qs.params; } sqlTexts[i] = qs.stmt.getText(); i++; } VoltTable[] results = null; try { results = m_site.executePlanFragments( batchSize, fragmentIds, null, params, sqlTexts, m_txnState.txnId, m_txnState.m_spHandle, m_txnState.uniqueId, m_isReadOnly); } catch (Throwable ex) { if (! m_isReadOnly) { // roll back the current batch and re-throw the EE exception m_site.truncateUndoLog(true, m_spBigBatchBeginToken >= 0 ? m_spBigBatchBeginToken: m_site.getLatestUndoToken(), m_txnState.m_spHandle, null); } throw ex; } return results; } }
package com.alibaba.excel.util; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import com.alibaba.excel.metadata.csv.CsvWorkbook; import com.alibaba.excel.metadata.data.DataFormatData; import com.alibaba.excel.metadata.data.WriteCellData; import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder; import com.alibaba.excel.write.metadata.style.WriteCellStyle; import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * @author jipengfei */ public class WorkBookUtil { private WorkBookUtil() {} public static void createWorkBook(WriteWorkbookHolder writeWorkbookHolder) throws IOException { switch (writeWorkbookHolder.getExcelType()) { case XLSX: if (writeWorkbookHolder.getTempTemplateInputStream() != null) { XSSFWorkbook xssfWorkbook = new XSSFWorkbook(writeWorkbookHolder.getTempTemplateInputStream()); writeWorkbookHolder.setCachedWorkbook(xssfWorkbook); if (writeWorkbookHolder.getInMemory()) { writeWorkbookHolder.setWorkbook(xssfWorkbook); } else { writeWorkbookHolder.setWorkbook(new SXSSFWorkbook(xssfWorkbook)); } return; } Workbook workbook; if (writeWorkbookHolder.getInMemory()) { workbook = new XSSFWorkbook(); } else { workbook = new SXSSFWorkbook(); } writeWorkbookHolder.setCachedWorkbook(workbook); writeWorkbookHolder.setWorkbook(workbook); return; case XLS: HSSFWorkbook hssfWorkbook; if (writeWorkbookHolder.getTempTemplateInputStream() != null) { hssfWorkbook = new HSSFWorkbook( new POIFSFileSystem(writeWorkbookHolder.getTempTemplateInputStream())); } else { hssfWorkbook = new HSSFWorkbook(); } writeWorkbookHolder.setCachedWorkbook(hssfWorkbook); writeWorkbookHolder.setWorkbook(hssfWorkbook); if (writeWorkbookHolder.getPassword() != null) { Biff8EncryptionKey.setCurrentUserPassword(writeWorkbookHolder.getPassword()); hssfWorkbook.writeProtectWorkbook(writeWorkbookHolder.getPassword(), StringUtils.EMPTY); } return; case CSV: CsvWorkbook csvWorkbook = new CsvWorkbook(new PrintWriter( new OutputStreamWriter(writeWorkbookHolder.getOutputStream(), writeWorkbookHolder.getCharset())), writeWorkbookHolder.getGlobalConfiguration().getLocale(), writeWorkbookHolder.getGlobalConfiguration().getUse1904windowing(), writeWorkbookHolder.getGlobalConfiguration().getUseScientificFormat()); writeWorkbookHolder.setCachedWorkbook(csvWorkbook); writeWorkbookHolder.setWorkbook(csvWorkbook); return; default: throw new UnsupportedOperationException("Wrong excel type."); } } public static Sheet createSheet(Workbook workbook, String sheetName) { return workbook.createSheet(sheetName); } public static Row createRow(Sheet sheet, int rowNum) { return sheet.createRow(rowNum); } public static Cell createCell(Row row, int colNum) { return row.createCell(colNum); } public static Cell createCell(Row row, int colNum, CellStyle cellStyle) { Cell cell = row.createCell(colNum); cell.setCellStyle(cellStyle); return cell; } public static Cell createCell(Row row, int colNum, CellStyle cellStyle, String cellValue) { Cell cell = createCell(row, colNum, cellStyle); cell.setCellValue(cellValue); return cell; } public static Cell createCell(Row row, int colNum, String cellValue) { Cell cell = row.createCell(colNum); cell.setCellValue(cellValue); return cell; } public static void fillDataFormat(WriteCellData<?> cellData, String format, String defaultFormat) { if (cellData.getWriteCellStyle() == null) { cellData.setWriteCellStyle(new WriteCellStyle()); } if (cellData.getWriteCellStyle().getDataFormatData() == null) { cellData.getWriteCellStyle().setDataFormatData(new DataFormatData()); } if (cellData.getWriteCellStyle().getDataFormatData().getFormat() == null) { if (format == null) { cellData.getWriteCellStyle().getDataFormatData().setFormat(defaultFormat); } else { cellData.getWriteCellStyle().getDataFormatData().setFormat(format); } } } }
package com.bina.varsim.types; import com.bina.varsim.fastqLiftover.types.GenomeInterval; import com.bina.varsim.fastqLiftover.types.GenomeLocation; import com.google.common.base.Joiner; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; public class ReadMapRecord { public static final String COLUMN_SEPARATOR = "\t"; public static final String MAP_BLOCK_SEPARATOR = ":"; private static final Joiner joiner = Joiner.on(MAP_BLOCK_SEPARATOR).skipNulls(); protected String readName; protected List<Collection<ReadMapBlock>> multiReadMapBlocks; public ReadMapRecord() { } public ReadMapRecord(final String readName, final List<Collection<ReadMapBlock>> multiReadMapBlocks) { this.readName = readName; this.multiReadMapBlocks = multiReadMapBlocks; } public ReadMapRecord(final String readName, final Collection<ReadMapBlock> ... multiReadMapBlocks) { this.readName = readName; this.multiReadMapBlocks = Arrays.asList(multiReadMapBlocks); } public ReadMapRecord(final String line) { final String[] fields = line.trim().split(COLUMN_SEPARATOR); readName = fields[0]; multiReadMapBlocks = new ArrayList<>(); for (int i = 1; i < fields.length; i++) { final Collection<ReadMapBlock> readMapBlocks = new ArrayList<>(); final String readMapStrings[] = fields[i].split(MAP_BLOCK_SEPARATOR, -1); for (final String readMapString : readMapStrings) { readMapBlocks.add(new ReadMapBlock(readMapString)); } multiReadMapBlocks.add(readMapBlocks); } } public String toString() { final StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(readName); stringBuilder.append(COLUMN_SEPARATOR); for (final Collection<ReadMapBlock> readMapBlocks : multiReadMapBlocks) { stringBuilder.append(COLUMN_SEPARATOR); stringBuilder.append(joiner.join(readMapBlocks)); } return stringBuilder.toString(); } public String getReadName() { return readName; } public void setReadName(String readName) { this.readName = readName; } public List<Collection<ReadMapBlock>> getMultiReadMapBlocks() { return multiReadMapBlocks; } public void setMultiReadMapBlocks(List<Collection<ReadMapBlock>> multiReadMapBlocks) { this.multiReadMapBlocks = multiReadMapBlocks; } public Collection<ReadMapBlock> getReadMapBlocks(final int index) { return multiReadMapBlocks.get(index); } public Collection<GenomeLocation> getUnclippedStarts(final int index) { final Collection<GenomeLocation> locations = new ArrayList<>(); for (final ReadMapBlock readMapBlock : getReadMapBlocks(index)) { locations.add(readMapBlock.getUnclippedStart()); } return locations; } }
package com.bwfcwalshy.flarebot; import com.bwfcwalshy.flarebot.music.MusicManager; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import sx.blah.discord.handle.obj.IChannel; import sx.blah.discord.handle.obj.IMessage; import sx.blah.discord.handle.obj.IUser; import sx.blah.discord.util.DiscordException; import sx.blah.discord.util.MissingPermissionsException; import sx.blah.discord.util.RequestBuffer; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URLEncoder; public class VideoThread extends Thread { // Keep this instance across all threads. Efficiency bitch! private static MusicManager manager; private String searchTerm; private IUser user; private IChannel channel; private boolean isUrl = false; private boolean isShortened = false; public VideoThread(String term, IUser user, IChannel channel) { this.searchTerm = term; this.user = user; this.channel = channel; if (manager == null) manager = FlareBot.getInstance().getMusicManager(); start(); } public VideoThread(String termOrUrl, IUser user, IChannel channel, boolean url, boolean shortened) { this.searchTerm = termOrUrl; this.user = user; this.channel = channel; this.isUrl = url; this.isShortened = shortened; if (manager == null) manager = FlareBot.getInstance().getMusicManager(); start(); } // Making sure these stay across all threads. private static final String SEARCH_URL = "https: private static final String YOUTUBE_URL = "https: private static final String EXTENSION = ".mp3"; @Override public void run() { long a = System.currentTimeMillis(); // TODO: Severely clean this up!!! // ^ EDIT BY Arsen: A space goes there.. try { IMessage message; String videoName; String videoFile; String link; String videoId; if (isUrl) { if (isShortened) { searchTerm = YOUTUBE_URL + searchTerm.replaceFirst("http(s)?://youtu\\.be", ""); } message = MessageUtils.sendMessage(channel, "Getting video from URL."); Document doc = Jsoup.connect(searchTerm).get(); videoId = searchTerm.replaceFirst("http(s)?://(www\\.)?youtube\\.com/watch\\?v=", ""); // Playlist if (videoId.contains("&list")) videoId.substring(0, videoId.indexOf("&list") + 5); videoName = MessageUtils.escapeFile(doc.title().replace(" - YouTube", "")); videoFile = videoName + "-" + videoId; link = searchTerm; } else { message = MessageUtils.sendMessage(channel, "Searching YouTube for '" + searchTerm + "'"); Document doc = Jsoup.connect(SEARCH_URL + URLEncoder.encode(searchTerm, "UTF-8")).get(); int i = 0; Element videoElement = doc.getElementsByClass("yt-lockup-title").get(i); Element lookedAt = videoElement.children().first(); while(lookedAt.hasClass("ad-badge")){ videoElement = doc.getElementsByClass("yt-lockup-title").get(++i); lookedAt = videoElement.children().first(); } link = videoElement.select("a").first().attr("href"); // I check the index of 2 chars so I need to add 2 Document doc2 = Jsoup.connect((link.startsWith("http") ? "" : YOUTUBE_URL) + link).get(); videoName = MessageUtils.escapeFile(doc2.title().substring(0, doc2.title().length() - 10)); videoId = link.substring(link.indexOf("v=") + 2); videoFile = videoName + "-" + videoId; link = YOUTUBE_URL + link; } File video = new File("cached" + File.separator + videoFile + EXTENSION); // if (video.exists()) { // manager.addSong(channel.getGuild().getID(), videoFile + EXTENSION); // RequestBuffer.request(() -> { // try { // message.edit(user.mention() + " added: **" + videoName + "** to the playlist!"); // FlareBot.LOGGER.error("Could not edit own message!", e); if (!video.exists()) { RequestBuffer.request(() -> { try { message.edit("Downloading video!"); } catch (MissingPermissionsException | DiscordException e) { FlareBot.LOGGER.error("Could not edit own message!", e); } }); ProcessBuilder builder = new ProcessBuilder("youtube-dl", "-o", "cached" + File.separator + "%(title)s-%(id)s.%(ext)s", "--extract-audio", "--audio-format" , "mp3", link); FlareBot.LOGGER.debug("Downloading"); builder.redirectErrorStream(true); Process process = builder.start(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { while (process.isAlive()) { String line; if ((line = reader.readLine()) != null) { FlareBot.LOGGER.info("[YT-DL] " + line); } } } process.waitFor(); if (process.exitValue() != 0) { RequestBuffer.request(() -> { try { message.edit("Could not download **" + videoName + "**!"); } catch (MissingPermissionsException | DiscordException e) { FlareBot.LOGGER.error("Could not edit own message!", e); } }); return; } } if (manager.addSong(channel.getGuild().getID(), video.getName())) { RequestBuffer.request(() -> { try { message.edit(user.mention() + " added: **" + videoName + "** to the playlist!"); } catch (MissingPermissionsException | DiscordException e) { FlareBot.LOGGER.error("Could not edit own message!", e); } }); } else RequestBuffer.request(() -> { try { message.edit("Failed to add **" + videoName + "**!"); } catch (MissingPermissionsException | DiscordException e) { FlareBot.LOGGER.error("Could not edit own message!", e); } }); } catch (IOException | InterruptedException e) { FlareBot.LOGGER.error(e.getMessage(), e); } long b = System.currentTimeMillis(); FlareBot.LOGGER.debug("Process took " + (b - a) + " milliseconds"); } }
package com.intellij.execution.impl; import com.intellij.execution.ExecutionBundle; import com.intellij.execution.Executor; import com.intellij.execution.RunnerAndConfigurationSettings; import com.intellij.execution.configuration.RemoteTargetAwareRunProfile; import com.intellij.execution.configurations.*; import com.intellij.execution.remote.RemoteTargetConfiguration; import com.intellij.execution.remote.RemoteTargetConfigurationKt; import com.intellij.execution.remote.RemoteTargetsListConfigurable; import com.intellij.execution.remote.RemoteTargetsManager; import com.intellij.execution.runners.ProgramRunner; import com.intellij.icons.AllIcons; import com.intellij.ide.DataManager; import com.intellij.ide.actions.ShowSettingsUtilImpl; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.options.SettingsEditorListener; import com.intellij.openapi.options.ex.SingleConfigurableEditor; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.ComboBox; import com.intellij.openapi.ui.ComponentValidator; import com.intellij.openapi.ui.ValidationInfo; import com.intellij.openapi.ui.panel.ComponentPanelBuilder; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.ProjectLevelVcsManager; import com.intellij.openapi.vcs.changes.VcsIgnoreManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.project.ProjectKt; import com.intellij.ui.DocumentAdapter; import com.intellij.ui.SimpleListCellRenderer; import com.intellij.ui.components.JBCheckBox; import com.intellij.ui.components.JBLabel; import com.intellij.ui.components.JBScrollPane; import com.intellij.ui.components.labels.ActionLink; import com.intellij.ui.components.panels.NonOpaquePanel; import com.intellij.ui.scale.JBUIScale; import com.intellij.util.ObjectUtils; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UI; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.SystemIndependent; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public final class SingleConfigurationConfigurable<Config extends RunConfiguration> extends BaseRCSettingsConfigurable { private static final Logger LOG = Logger.getInstance(SingleConfigurationConfigurable.class); private final PlainDocument myNameDocument = new PlainDocument(); @Nullable private final Executor myExecutor; private ValidationResult myLastValidationResult = null; private boolean myValidationResultValid = false; private MyValidatableComponent myComponent; private final String myDisplayName; private final String myHelpTopic; private final boolean myBrokenConfiguration; private boolean myStoreProjectConfiguration; private boolean myIsAllowRunningInParallel = false; private String myDefaultTargetName; private String myFolderName; private boolean myChangingNameFromCode; private SingleConfigurationConfigurable(@NotNull RunnerAndConfigurationSettings settings, @Nullable Executor executor) { super(new ConfigurationSettingsEditorWrapper(settings), settings); myExecutor = executor; final Config configuration = getConfiguration(); myDisplayName = getSettings().getName(); myHelpTopic = configuration.getType().getHelpTopic(); myBrokenConfiguration = !configuration.getType().isManaged(); setFolderName(getSettings().getFolderName()); setNameText(configuration.getName()); myNameDocument.addDocumentListener(new DocumentAdapter() { @Override public void textChanged(@NotNull DocumentEvent event) { setModified(true); if (!myChangingNameFromCode) { RunConfiguration runConfiguration = getSettings().getConfiguration(); if (runConfiguration instanceof LocatableConfigurationBase) { ((LocatableConfigurationBase) runConfiguration).setNameChangedByUser(true); } } } }); getEditor().addSettingsEditorListener(new SettingsEditorListener<RunnerAndConfigurationSettings>() { @Override public void stateChanged(@NotNull SettingsEditor<RunnerAndConfigurationSettings> settingsEditor) { myValidationResultValid = false; } }); } @NotNull public static <Config extends RunConfiguration> SingleConfigurationConfigurable<Config> editSettings(@NotNull RunnerAndConfigurationSettings settings, @Nullable Executor executor) { SingleConfigurationConfigurable<Config> configurable = new SingleConfigurationConfigurable<>(settings, executor); configurable.reset(); return configurable; } @Override void applySnapshotToComparison(RunnerAndConfigurationSettings original, RunnerAndConfigurationSettings snapshot) { snapshot.setTemporary(original.isTemporary()); snapshot.setName(getNameText()); RunConfiguration runConfiguration = snapshot.getConfiguration(); runConfiguration.setAllowRunningInParallel(myIsAllowRunningInParallel); if (runConfiguration instanceof RemoteTargetAwareRunProfile) { ((RemoteTargetAwareRunProfile)runConfiguration).setDefaultTargetName(myDefaultTargetName); } snapshot.setFolderName(myFolderName); } @Override boolean isSnapshotSpecificallyModified(@NotNull RunnerAndConfigurationSettings original, @NotNull RunnerAndConfigurationSettings snapshot) { return original.isShared() != myStoreProjectConfiguration; } @Override public void apply() throws ConfigurationException { RunnerAndConfigurationSettings settings = getSettings(); RunConfiguration runConfiguration = settings.getConfiguration(); settings.setName(getNameText()); runConfiguration.setAllowRunningInParallel(myIsAllowRunningInParallel); if (runConfiguration instanceof RemoteTargetAwareRunProfile) { ((RemoteTargetAwareRunProfile)runConfiguration).setDefaultTargetName(myDefaultTargetName); } settings.setFolderName(myFolderName); settings.setShared(myStoreProjectConfiguration); super.apply(); RunManagerImpl.getInstanceImpl(runConfiguration.getProject()).addConfiguration(settings); } @Override public void reset() { RunnerAndConfigurationSettings configuration = getSettings(); if (configuration instanceof RunnerAndConfigurationSettingsImpl) { configuration = ((RunnerAndConfigurationSettingsImpl)configuration).clone(); } setNameText(configuration.getName()); super.reset(); if (myComponent == null) { myComponent = new MyValidatableComponent(configuration.getConfiguration().getProject()); } myComponent.doReset(configuration); } void updateWarning() { myValidationResultValid = false; if (myComponent != null) { myComponent.updateWarning(); } } @Override public final JComponent createComponent() { myComponent.myNameText.setEnabled(!myBrokenConfiguration); JComponent result = myComponent.getWholePanel(); DataManager.registerDataProvider(result, dataId -> { if (ConfigurationSettingsEditorWrapper.CONFIGURATION_EDITOR_KEY.is(dataId)) { return getEditor(); } return null; }); return result; } final JComponent getValidationComponent() { return myComponent.myValidationPanel; } public boolean isStoreProjectConfiguration() { return myStoreProjectConfiguration; } @Nullable private ValidationResult getValidationResult() { if (!myValidationResultValid) { myLastValidationResult = null; RunnerAndConfigurationSettings snapshot = null; try { snapshot = createSnapshot(false); snapshot.setName(getNameText()); snapshot.checkSettings(myExecutor); for (Executor executor : Executor.EXECUTOR_EXTENSION_NAME.getExtensionList()) { ProgramRunner<?> runner = ProgramRunner.getRunner(executor.getId(), snapshot.getConfiguration()); if (runner != null) { checkConfiguration(runner, snapshot); } } } catch (ConfigurationException e) { myLastValidationResult = createValidationResult(snapshot, e); } myValidationResultValid = true; } return myLastValidationResult; } private ValidationResult createValidationResult(RunnerAndConfigurationSettings snapshot, ConfigurationException e) { if (!e.shouldShowInDumbMode() && DumbService.isDumb(getConfiguration().getProject())) return null; return new ValidationResult( e.getLocalizedMessage(), e instanceof RuntimeConfigurationException ? e.getTitle() : ExecutionBundle.message("invalid.data.dialog.title"), getQuickFix(snapshot, e)); } @Nullable private Runnable getQuickFix(RunnerAndConfigurationSettings snapshot, ConfigurationException exception) { Runnable quickFix = exception.getQuickFix(); if (quickFix != null && snapshot != null) { return () -> { quickFix.run(); getEditor().resetFrom(snapshot); }; } return quickFix; } private static void checkConfiguration(@NotNull ProgramRunner<?> runner, @NotNull RunnerAndConfigurationSettings snapshot) throws RuntimeConfigurationException { RunnerSettings runnerSettings = snapshot.getRunnerSettings(runner); ConfigurationPerRunnerSettings configurationSettings = snapshot.getConfigurationSettings(runner); try { runner.checkConfiguration(runnerSettings, configurationSettings); } catch (AbstractMethodError e) { //backward compatibility } } @Override public final void disposeUIResources() { super.disposeUIResources(); myComponent = null; } public final String getNameText() { try { return myNameDocument.getText(0, myNameDocument.getLength()); } catch (BadLocationException e) { LOG.error(e); return ""; } } public final void addNameListener(DocumentListener listener) { myNameDocument.addDocumentListener(listener); } public final void addSharedListener(ChangeListener changeListener) { myComponent.myCbStoreProjectConfiguration.addChangeListener(changeListener); } public final void setNameText(final String name) { myChangingNameFromCode = true; try { try { if (!myNameDocument.getText(0, myNameDocument.getLength()).equals(name)) { myNameDocument.replace(0, myNameDocument.getLength(), name, null); } } catch (BadLocationException e) { LOG.error(e); } } finally { myChangingNameFromCode = false; } } public final boolean isValid() { return getValidationResult() == null; } public final JTextField getNameTextField() { return myComponent.myNameText; } @Override public String getDisplayName() { return myDisplayName; } @Override public String getHelpTopic() { return myHelpTopic; } @NotNull public Config getConfiguration() { //noinspection unchecked return (Config)getSettings().getConfiguration(); } @NotNull public RunnerAndConfigurationSettings createSnapshot(boolean cloneBeforeRunTasks) throws ConfigurationException { RunnerAndConfigurationSettings snapshot = getEditor().getSnapshot(); RunConfiguration runConfiguration = snapshot.getConfiguration(); runConfiguration.setAllowRunningInParallel(myIsAllowRunningInParallel); if (runConfiguration instanceof RemoteTargetAwareRunProfile) { ((RemoteTargetAwareRunProfile)runConfiguration).setDefaultTargetName(myDefaultTargetName); } if (cloneBeforeRunTasks) { RunManagerImplKt.cloneBeforeRunTasks(runConfiguration); } return snapshot; } @Override public String toString() { return myDisplayName; } public void setFolderName(@Nullable String folderName) { if (!Comparing.equal(myFolderName, folderName)) { myFolderName = folderName; setModified(true); } } @Nullable public String getFolderName() { return myFolderName; } private class MyValidatableComponent { private JLabel myNameLabel; private JTextField myNameText; private JComponent myWholePanel; private JPanel myComponentPlace; private JBLabel myWarningLabel; private JButton myFixButton; private JSeparator mySeparator; private JCheckBox myCbStoreProjectConfiguration; private JBCheckBox myIsAllowRunningInParallelCheckBox; private JPanel myValidationPanel; private JBScrollPane myJBScrollPane; private JPanel myCbStoreProjectConfigurationPanel; private ComboBox<RemoteTargetConfiguration> myRunOnComboBox; private ActionLink myManageTargetsActionLink; private JPanel myRunOnPanel; private JBLabel myRunOnLabel; private JPanel myRunOnPanelInner; private final ComponentValidator myCbStoreProjectConfigurationValidator; private Runnable myQuickFix = null; MyValidatableComponent(@NotNull Project project) { myNameLabel.setLabelFor(myNameText); myNameText.setDocument(myNameDocument); getEditor().addSettingsEditorListener(settingsEditor -> updateWarning()); myWarningLabel.setCopyable(true); myWarningLabel.setAllowAutoWrapping(true); myWarningLabel.setIcon(AllIcons.General.BalloonError); myComponentPlace.setLayout(new GridBagLayout()); myComponentPlace.add(getEditorComponent(), new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, JBUI.emptyInsets(), 0, 0)); myComponentPlace.doLayout(); myFixButton.setIcon(AllIcons.Actions.QuickfixBulb); updateWarning(); myFixButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { if (myQuickFix == null) { return; } myQuickFix.run(); myValidationResultValid = false; updateWarning(); } }); myCbStoreProjectConfigurationValidator = new ComponentValidator(getEditor()).withValidator(() -> getStoreProjectConfigurationValidationInfo()) .withHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { VcsIgnoreManager.getInstance(getConfiguration().getProject()).removeRunConfigurationFromVcsIgnore(getConfiguration().getName()); myCbStoreProjectConfigurationValidator.revalidate(); } } }) .installOn(myCbStoreProjectConfiguration); myCbStoreProjectConfiguration.addActionListener(e -> { setModified(true); myStoreProjectConfiguration = myCbStoreProjectConfiguration.isSelected(); myCbStoreProjectConfigurationValidator.revalidate(); }); myIsAllowRunningInParallelCheckBox.addActionListener(e -> { setModified(true); myIsAllowRunningInParallel = myIsAllowRunningInParallelCheckBox.isSelected(); }); myJBScrollPane.setBorder(JBUI.Borders.empty()); myJBScrollPane.setViewportBorder(JBUI.Borders.empty()); ComponentPanelBuilder componentPanelBuilder = UI.PanelFactory.panel(myCbStoreProjectConfiguration); @SystemIndependent VirtualFile projectFile = project.getProjectFile(); if (projectFile != null) { componentPanelBuilder.withTooltip( ProjectKt.isDirectoryBased(project) ? ExecutionBundle.message("run.configuration.share.hint", ".idea folder") : ExecutionBundle.message("run.configuration.share.hint", projectFile.getName()) ); } componentPanelBuilder.addToPanel(myCbStoreProjectConfigurationPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, JBUI.emptyInsets(), 0, 0), false); Dimension nameSize = myNameLabel.getPreferredSize(); Dimension runOnSize = myRunOnLabel.getPreferredSize(); double width = Math.max(nameSize.getWidth(), runOnSize.getWidth()); myNameLabel.setPreferredSize(new Dimension((int)width, (int)nameSize.getHeight())); myRunOnLabel.setPreferredSize(new Dimension((int)width, (int)runOnSize.getHeight())); myRunOnPanel.setBorder(JBUI.Borders.emptyLeft(5)); UI.PanelFactory.panel(myRunOnPanelInner) .withComment(ExecutionBundle.message("edit.run.configuration.run.configuration.run.on.comment")) .addToPanel(myRunOnPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, JBUI.emptyInsets(), 0, 0)); myRunOnComboBox.addActionListener(e -> { String chosenTarget = getSelectedTargetName(); if (!StringUtil.equals(myDefaultTargetName, chosenTarget)) { setModified(true); myDefaultTargetName = chosenTarget; } }); myRunOnComboBox.setRenderer(SimpleListCellRenderer.create((l, v, i) -> { if (v == null) { l.setText("Local machine"); l.setIcon(AllIcons.Nodes.HomeFolder); } else { l.setText(v.getDisplayName()); l.setIcon(RemoteTargetConfigurationKt.getTargetType(v).getIcon()); } })); } @Nullable private ValidationInfo getStoreProjectConfigurationValidationInfo() { Project project = getConfiguration().getProject(); @SystemIndependent VirtualFile projectFile = project.getProjectFile(); if (projectFile == null) return null; if (!myCbStoreProjectConfiguration.isSelected()) return null; if (!ProjectLevelVcsManager.getInstance(project).hasActiveVcss()) { String fileAddToVcs = ProjectKt.isDirectoryBased(project) ? Project.DIRECTORY_STORE_FOLDER + "/runConfigurations" : projectFile.getName(); return new ValidationInfo(ExecutionBundle.message("run.configuration.share.vcs.disabled", fileAddToVcs), myCbStoreProjectConfiguration).asWarning(); } else if (VcsIgnoreManager.getInstance(getConfiguration().getProject()).isRunConfigurationVcsIgnored(getConfiguration().getName())) { return new ValidationInfo(ExecutionBundle.message("run.configuration.share.vcs.ignored", getConfiguration().getName()), myCbStoreProjectConfiguration).asWarning(); } return null; } private void doReset(RunnerAndConfigurationSettings settings) { RunConfiguration configuration = settings.getConfiguration(); boolean isManagedRunConfiguration = configuration.getType().isManaged(); myStoreProjectConfiguration = settings.isShared(); myCbStoreProjectConfiguration.setEnabled(isManagedRunConfiguration); myCbStoreProjectConfiguration.setSelected(myStoreProjectConfiguration); myCbStoreProjectConfiguration.setVisible(!settings.isTemplate()); myCbStoreProjectConfigurationValidator.revalidate(); boolean targetAware = configuration instanceof RemoteTargetAwareRunProfile; myRunOnPanel.setVisible(targetAware); myRunOnComboBox.removeAllItems(); if (targetAware) { String defaultTargetName = ((RemoteTargetAwareRunProfile)configuration).getDefaultTargetName(); resetRunOnComboBox(defaultTargetName); myDefaultTargetName = defaultTargetName; } myIsAllowRunningInParallel = configuration.isAllowRunningInParallel(); myIsAllowRunningInParallelCheckBox.setEnabled(isManagedRunConfiguration); myIsAllowRunningInParallelCheckBox.setSelected(myIsAllowRunningInParallel); myIsAllowRunningInParallelCheckBox.setVisible(settings.getFactory().getSingletonPolicy().isPolicyConfigurable()); } private void resetRunOnComboBox(@Nullable String targetNameToChoose) { myRunOnComboBox.addItem(null); RemoteTargetConfiguration targetToChoose = null; for (RemoteTargetConfiguration config : RemoteTargetsManager.getInstance().getTargets().resolvedConfigs()) { myRunOnComboBox.addItem(config); if (config.getDisplayName().equals(targetNameToChoose)) { targetToChoose = config; } } myRunOnComboBox.setSelectedItem(targetToChoose); if (targetNameToChoose != null && targetToChoose == null) { //todo[remoteServer]: add and show invalid value } } public final JComponent getWholePanel() { return myWholePanel; } public JComponent getEditorComponent() { return getEditor().getComponent(); } @Nullable public ValidationResult getValidationResult() { return SingleConfigurationConfigurable.this.getValidationResult(); } private void updateWarning() { final ValidationResult configurationException = getValidationResult(); if (configurationException != null) { mySeparator.setVisible(true); myWarningLabel.setVisible(true); myWarningLabel.setText(generateWarningLabelText(configurationException)); final Runnable quickFix = configurationException.getQuickFix(); if (quickFix == null) { myFixButton.setVisible(false); } else { myFixButton.setVisible(true); myQuickFix = quickFix; } myValidationPanel.setVisible(true); } else { mySeparator.setVisible(false); myWarningLabel.setVisible(false); myFixButton.setVisible(false); myValidationPanel.setVisible(false); } } @NonNls private String generateWarningLabelText(final ValidationResult configurationException) { return "<html><body><b>" + configurationException.getTitle() + ": </b>" + configurationException.getMessage() + "</body></html>"; } private void createUIComponents() { myComponentPlace = new NonOpaquePanel(); myManageTargetsActionLink = new ActionLink(ExecutionBundle.message("edit.run.configuration.run.configuration.manage.targets.label"), new DumbAwareAction() { @Override public void actionPerformed(@NotNull AnActionEvent e) { RemoteTargetsListConfigurable configurable = new RemoteTargetsListConfigurable(myProject); if (new SingleConfigurableEditor(myWholePanel, configurable, ShowSettingsUtilImpl.createDimensionKey(configurable), false) .showAndGet()) { String selectedName = getSelectedTargetName(); myRunOnComboBox.removeAllItems(); resetRunOnComboBox(selectedName); } } }); myJBScrollPane = new JBScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) { @Override public Dimension getMinimumSize() { Dimension d = super.getMinimumSize(); JViewport viewport = getViewport(); if (viewport != null) { Component view = viewport.getView(); if (view instanceof Scrollable) { d.width = ((Scrollable)view).getPreferredScrollableViewportSize().width; } if (view != null) { d.width = view.getMinimumSize().width; } } d.height = Math.max(d.height, JBUIScale.scale(400)); return d; } }; } @Nullable private String getSelectedTargetName() { return ObjectUtils.doIfCast(myRunOnComboBox.getSelectedItem(), RemoteTargetConfiguration.class, c -> c.getDisplayName()); } } }
package com.cisco.trex.stateless; import com.cisco.trex.stateless.model.*; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.*; import org.pcap4j.packet.*; import org.pcap4j.packet.namednumber.*; import org.pcap4j.util.ByteArrays; import org.pcap4j.util.MacAddress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zeromq.ZMQException; import java.io.IOException; import java.net.Inet4Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.StreamSupport; public class TRexClient { private static final Logger logger = LoggerFactory.getLogger(TRexClient.class); private static String JSON_RPC_VERSION = "2.0"; private static Integer API_VERSION_MAJOR = 3; private static Integer API_VERSION_MINOR = 0; private TRexTransport transport; private Gson gson = new Gson(); private String host; private String port; private String asyncPort; private String apiH; private String userName = ""; private Integer session_id = 123456789; private Map<Integer, String> portHandlers = new HashMap<>(); private List<String> supportedCmds = new ArrayList<>(); public TRexClient(String host, String port, String userName) { this.host = host; this.port = port; this.userName = userName; supportedCmds.add("api_sync"); supportedCmds.add("get_supported_cmds"); } public String callMethod(String methodName, Map<String, Object> payload) { logger.info("Call {} method.", methodName); if (!supportedCmds.contains(methodName)) { logger.error("Unsupported {} method.", methodName); throw new UnsupportedOperationException(); } String req = buildRequest(methodName, payload); return call(req); } private String buildRequest(String methodName, Map<String, Object> payload) { if (payload == null) { payload = new HashMap<>(); } Map<String, Object> parameters = new HashMap<>(); parameters.put("id", "aggogxls"); parameters.put("jsonrpc", JSON_RPC_VERSION); parameters.put("method", methodName); payload.put("api_h", apiH); parameters.put("params", payload); return gson.toJson(parameters); } private String call(String json) { logger.info("JSON Req: " + json); byte[] msg = transport.sendJson(json); if (msg == null) { int errNumber = transport.getSocket().base().errno(); String errMsg = "Unable to receive message from socket"; ZMQException zmqException = new ZMQException(errMsg, errNumber); logger.error(errMsg, zmqException); throw zmqException; } String response = new String(msg); logger.info("JSON Resp: " + response); return response; } public <T> TRexClientResult<T> callMethod(String methodName, Map<String, Object> parameters, Class<T> responseType) { logger.info("Call {} method.", methodName); if (!supportedCmds.contains(methodName)) { logger.error("Unsupported {} method.", methodName); throw new UnsupportedOperationException(); } TRexClientResult<T> result = new TRexClientResult<>(); try { RPCResponse response = transport.sendCommand(buildCommand(methodName, parameters)); if (!response.isFailed()) { T resutlObject = new ObjectMapper().readValue(response.getResult(), responseType); result.set(resutlObject); } else { result.setError(response.getError().getMessage()); } } catch (IOException e) { String errorMsg = "Error occurred during processing '"+methodName+"' method with params: " +parameters.toString(); logger.error(errorMsg, e); result.setError(errorMsg); return result; } return result; } private TRexCommand buildCommand(String methodName, Map<String, Object> parameters) { if (parameters == null) { parameters = new HashMap<>(); } parameters.put("api_h", apiH); Map<String, Object> payload = new HashMap<>(); payload.put("id", "aggogxls"); payload.put("jsonrpc", JSON_RPC_VERSION); payload.put("method", methodName); if(parameters.containsKey("port_id")) { Integer portId = (Integer) parameters.get("port_id"); String handler = portHandlers.get(portId); if (handler != null) { parameters.put("handler", handler); } } payload.put("params", parameters); return new TRexCommand(methodName, payload); } public void connect() { transport = new TRexTransport(this.host, this.port, 3000); serverAPISync(); supportedCmds.addAll(getSupportedCommands()); } private String getConnectionAddress() { return "tcp://"+host+":"+port; } private void serverAPISync() { logger.info("Sync API with the TRex"); Map<String, Object> apiVers = new HashMap<>(); apiVers.put("type", "core"); apiVers.put("major", API_VERSION_MAJOR); apiVers.put("minor", API_VERSION_MINOR); Map<String, Object> parameters = new HashMap<>(); parameters.put("api_vers", Arrays.asList(apiVers)); TRexClientResult<ApiVersion> result = callMethod("api_sync", parameters, ApiVersion.class); apiH = result.get().getApi_h(); logger.info("Received api_H: {}", apiH); } public void disconnect() { if (transport != null) { transport.getSocket().close(); transport = null; logger.info("Disconnected"); } else { logger.info("Already disconnected"); } } public void reconnect() { disconnect(); connect(); } // TODO: move to upper layer public List<Port> getPorts() { logger.info("Getting ports list."); List<Port> ports = getSystemInfo().getPorts(); ports.stream().forEach(port -> { TRexClientResult<PortStatus> result = getPortStatus(port.getIndex()); if (result.isFailed()) { return; } PortStatus status = result.get(); L2Configuration l2config = status.getAttr().getLayerConiguration().getL2Configuration(); port.hw_mac = l2config.getSrc(); port.dst_macaddr = l2config.getDst(); }); return ports; } public TRexClientResult<PortStatus> getPortStatus(int portIdx) { Map<String, Object> parameters = new HashMap<>(); parameters.put("port_id", portIdx); return callMethod("get_port_status", parameters, PortStatus.class); } public PortStatus acquirePort(int portIndex, Boolean force) { Map<String, Object> payload = createPayload(portIndex); payload.put("session_id", session_id); payload.put("user", userName); payload.put("force", force); String json = callMethod("acquire", payload); JsonElement response = new JsonParser().parse(json); String handler = response.getAsJsonArray().get(0).getAsJsonObject().get("result").getAsString(); portHandlers.put(portIndex, handler); return getPortStatus(portIndex).get(); } public void resetPort(int portIndex) { acquirePort(portIndex, true); stopTraffic(portIndex); removeAllStreams(portIndex); removeRxQueue(portIndex); serviceMode(portIndex, false); releasePort(portIndex); } private Map<String, Object> createPayload(int portIndex) { Map<String, Object> payload = new HashMap<>(); payload.put("port_id", portIndex); payload.put("api_h", apiH); String handler = portHandlers.get(portIndex); if (handler != null) { payload.put("handler", handler); } return payload; } public PortStatus releasePort(int portIndex) { Map<String, Object> payload = createPayload(portIndex); payload.put("user", userName); String result = callMethod("release", payload); portHandlers.remove(portIndex); return getPortStatus(portIndex).get(); } public List<String> getSupportedCommands() { Map<String, Object> payload = new HashMap<>(); payload.put("api_h", apiH); String json = callMethod("get_supported_cmds", payload); JsonElement response = new JsonParser().parse(json); JsonArray cmds = response.getAsJsonArray().get(0).getAsJsonObject().get("result").getAsJsonArray(); return StreamSupport.stream(cmds.spliterator(), false) .map(JsonElement::getAsString) .collect(Collectors.toList()); } public PortStatus serviceMode(int portIndex, Boolean isOn) { logger.info("Set service mode : {}", isOn ? "on" : "off"); Map<String, Object> payload = createPayload(portIndex); payload.put("enabled", isOn); String result = callMethod("service", payload); return getPortStatus(portIndex).get(); } public void addStream(int portIndex, Stream stream) { Map<String, Object> payload = createPayload(portIndex); payload.put("stream_id", stream.getId()); payload.put("stream", stream); callMethod("add_stream", payload); } public Stream getStream(int portIndex, int streamId) { Map<String, Object> payload = createPayload(portIndex); payload.put("get_pkt", true); payload.put("stream_id", streamId); String json = callMethod("get_stream", payload); JsonElement response = new JsonParser().parse(json); JsonObject stream = response.getAsJsonArray().get(0) .getAsJsonObject().get("result") .getAsJsonObject().get("stream") .getAsJsonObject(); return gson.fromJson(stream, Stream.class); } public void removeStream(int portIndex, int streamId) { Map<String, Object> payload = createPayload(portIndex); payload.put("stream_id", streamId); callMethod("remove_stream", payload); } public void removeAllStreams(int portIndex) { Map<String, Object> payload = createPayload(portIndex); callMethod("remove_all_streams", payload); } public List<Integer> getStreamIds(int portIndex) { Map<String, Object> payload = createPayload(portIndex); String json = callMethod("get_stream_list", payload); JsonElement response = new JsonParser().parse(json); JsonArray ids = response.getAsJsonArray().get(0).getAsJsonObject().get("result").getAsJsonArray(); return StreamSupport.stream(ids.spliterator(), false) .map(JsonElement::getAsInt) .collect(Collectors.toList()); } public SystemInfo getSystemInfo() { String json = callMethod("get_system_info", null); SystemInfoResponse response = gson.fromJson(json, SystemInfoResponse[].class)[0]; return response.getResult(); } public void startTraffic(int portIndex, double duration, boolean force, Map<String, Object> mul, int coreMask) { Map<String, Object> payload = createPayload(portIndex); payload.put("core_mask", coreMask); payload.put("mul", mul); payload.put("duration", duration); payload.put("force", force); callMethod("start_traffic", payload); } public void setRxQueue(int portIndex, int size) { Map<String, Object> payload = createPayload(portIndex); payload.put("type", "queue"); payload.put("enabled", true); payload.put("size", size); callMethod("set_rx_feature", payload); } public void removeRxQueue(int portIndex) { Map<String, Object> payload = createPayload(portIndex); payload.put("type", "queue"); payload.put("enabled", false); callMethod("set_rx_feature", payload); } public void sendPacket(int portIndex, Packet pkt) { Stream stream = build1PktSingleBurstStream(pkt); removeAllStreams(portIndex); addStream(portIndex, stream); Map<String, Object> mul = new HashMap<>(); mul.put("op", "abs"); mul.put("type", "pps"); mul.put("value", 1.0); startTraffic(portIndex, 1, true, mul, 1); stopTraffic(portIndex); } public String resolveArp(int portIndex, String srcIp, String dstIp) { removeRxQueue(portIndex); setRxQueue(portIndex, 1000); String srcMac = getPorts().get(portIndex).hw_mac; EthernetPacket pkt = buildArpPkt(srcMac, srcIp, dstIp); sendPacket(portIndex, pkt); Predicate<EthernetPacket> arpReplyFilter = etherPkt -> { if(etherPkt.contains(ArpPacket.class)) { ArpPacket arp = (ArpPacket) etherPkt.getPayload(); ArpOperation arpOp = arp.getHeader().getOperation(); String replyDstMac = arp.getHeader().getDstHardwareAddr().toString(); return ArpOperation.REPLY.equals(arpOp) && replyDstMac.equals(srcMac); } return false; }; List<org.pcap4j.packet.Packet> pkts = new ArrayList<>(); try { int steps = 10; while (steps > 0) { steps -= 1; Thread.sleep(500); pkts.addAll(getRxQueue(portIndex, arpReplyFilter)); if(pkts.size() > 0) { ArpPacket arpPacket = (ArpPacket) pkts.get(0).getPayload(); return arpPacket.getHeader().getSrcHardwareAddr().toString(); } } logger.info("Unable to get ARP reply in {} seconds", steps); } catch (InterruptedException ignored) {} finally { removeRxQueue(portIndex); } return null; } private static EthernetPacket buildArpPkt(String srcMac, String srcIp, String dstIp) { ArpPacket.Builder arpBuilder = new ArpPacket.Builder(); MacAddress srcMacAddress = MacAddress.getByName(srcMac); try { arpBuilder .hardwareType(ArpHardwareType.ETHERNET) .protocolType(EtherType.IPV4) .hardwareAddrLength((byte) MacAddress.SIZE_IN_BYTES) .protocolAddrLength((byte) ByteArrays.INET4_ADDRESS_SIZE_IN_BYTES) .operation(ArpOperation.REQUEST) .srcHardwareAddr(srcMacAddress) .srcProtocolAddr(InetAddress.getByName(srcIp)) .dstHardwareAddr(MacAddress.getByName("00:00:00:00:00:00")) .dstProtocolAddr(InetAddress.getByName(dstIp)); } catch (UnknownHostException e) { throw new IllegalArgumentException(e); } EthernetPacket.Builder etherBuilder = new EthernetPacket.Builder(); etherBuilder.dstAddr(MacAddress.ETHER_BROADCAST_ADDRESS) .srcAddr(srcMacAddress) .type(EtherType.ARP) .payloadBuilder(arpBuilder) .paddingAtBuild(true); return etherBuilder.build(); } private Stream build1PktSingleBurstStream(Packet pkt) { int stream_id = (int) (Math.random() * 1000); return new Stream( stream_id, true, 3, 0.0, new StreamMode( 1, 1, 1, 1.0, new StreamModeRate( StreamModeRate.Type.pps, 1.0 ), StreamMode.Type.single_burst ), -1, pkt, new StreamRxStats(true, true, true, stream_id), new StreamVM("", Collections.<VMInstruction>emptyList()), true ); } public List<Packet> getRxQueue(int portIndex, Predicate<EthernetPacket> filter) { Map<String, Object> payload = createPayload(portIndex); String json = callMethod("get_rx_queue_pkts", payload); JsonElement response = new JsonParser().parse(json); JsonArray pkts = response.getAsJsonArray().get(0) .getAsJsonObject().get("result") .getAsJsonObject() .getAsJsonArray("pkts"); return StreamSupport.stream(pkts.spliterator(), false) .map(this::buildEthernetPkt) .filter(filter) .collect(Collectors.toList()); } private EthernetPacket buildEthernetPkt(JsonElement jsonElement) { try { byte[] binary = Base64.getDecoder().decode(jsonElement.getAsJsonObject().get("binary").getAsString()); EthernetPacket pkt = EthernetPacket.newPacket(binary, 0, binary.length); logger.info("Received pkt: {}", pkt.toString()); return pkt; } catch (IllegalRawDataException e) { return null; } } public boolean setL3Mode(int portIndex, String nextHopMac, String sourceIp, String destinationIp) { Map<String, Object> payload = createPayload(portIndex); payload.put("src_addr", sourceIp); payload.put("dst_addr", destinationIp); if (nextHopMac != null) { payload.put("resolved_mac", nextHopMac); } callMethod("set_l3", payload); return true; } public void updatePortHandler(int portID, String handler) { portHandlers.put(portID, handler); } public void invalidatePortHandler(int portID) { portHandlers.remove(portID); } // TODO: move to upper layer public EthernetPacket sendIcmpEcho(int portIndex, String host, int reqId, int seqNumber, long waitResponse) throws UnknownHostException { Port port = getPorts().get(portIndex); PortStatus portStatus = getPortStatus(portIndex).get(); String srcIp = portStatus.getAttr().getLayerConiguration().getL3Configuration().getSrc(); EthernetPacket icmpRequest = buildIcmpV4Request(port.hw_mac, port.dst_macaddr, srcIp, host, reqId, seqNumber); removeAllStreams(portIndex); setRxQueue(portIndex, 1000); sendPacket(portIndex, icmpRequest); try { Thread.sleep(waitResponse); } catch (InterruptedException ignored) {} try { List<Packet> receivedPkts = getRxQueue(portIndex, etherPkt -> etherPkt.contains(IcmpV4EchoReplyPacket.class)); if (!receivedPkts.isEmpty()) { return (EthernetPacket) receivedPkts.get(0); } return null; } finally { removeRxQueue(portIndex); } } // TODO: move to upper layer private EthernetPacket buildIcmpV4Request(String srcMac, String dstMac, String srcIp, String dstIp, int reqId, int seqNumber) throws UnknownHostException { IcmpV4EchoPacket.Builder icmpReqBuilder = new IcmpV4EchoPacket.Builder(); icmpReqBuilder.identifier((short) reqId); icmpReqBuilder.sequenceNumber((short) seqNumber); IcmpV4CommonPacket.Builder icmpv4CommonPacketBuilder = new IcmpV4CommonPacket.Builder(); icmpv4CommonPacketBuilder.type(IcmpV4Type.ECHO) .code(IcmpV4Code.NO_CODE) .correctChecksumAtBuild(true) .payloadBuilder(icmpReqBuilder); IpV4Packet.Builder ipv4Builder = new IpV4Packet.Builder(); ipv4Builder.version(IpVersion.IPV4) .tos(IpV4Rfc791Tos.newInstance((byte) 0)) .ttl((byte) 64) .protocol(IpNumber.ICMPV4) .srcAddr((Inet4Address) Inet4Address.getByName(srcIp)) .dstAddr((Inet4Address) Inet4Address.getByName(dstIp)) .correctChecksumAtBuild(true) .correctLengthAtBuild(true) .payloadBuilder(icmpv4CommonPacketBuilder); EthernetPacket.Builder eb = new EthernetPacket.Builder(); eb.srcAddr(MacAddress.getByName(srcMac)) .dstAddr(MacAddress.getByName(dstMac)) .type(EtherType.IPV4) .paddingAtBuild(true) .payloadBuilder(ipv4Builder); return eb.build(); } public void stopTraffic(int portIndex) { Map<String, Object> payload = createPayload(portIndex); callMethod("stop_traffic", payload); } private class ApiVersionResponse { private String id; private String jsonrpc; private ApiVersionResult result; private class ApiVersionResult { private List<Map<String, String>> api_vers; public ApiVersionResult(List<Map<String, String>> api_vers) { this.api_vers = api_vers; } public String getApi_h() { return api_vers.get(0).get("api_h"); } } public ApiVersionResponse(String id, String jsonrpc, ApiVersionResult result) { this.id = id; this.jsonrpc = jsonrpc; this.result = result; } public String getApi_h() { return result.getApi_h(); } } private class SystemInfoResponse { private String id; private String jsonrpc; private SystemInfo result; public SystemInfo getResult() { return result; } } }
package com.facebook.litho; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.pm.ApplicationInfo; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.support.v4.util.LongSparseArray; import android.support.v4.view.accessibility.AccessibilityManagerCompat; import android.text.TextUtils; import android.view.View; import android.view.accessibility.AccessibilityManager; import com.facebook.litho.config.ComponentsConfiguration; import com.facebook.litho.displaylist.DisplayList; import com.facebook.litho.displaylist.DisplayListException; import com.facebook.litho.reference.BorderColorDrawableReference; import com.facebook.litho.reference.Reference; import com.facebook.infer.annotation.ThreadSafe; import com.facebook.yoga.YogaConstants; import com.facebook.yoga.YogaDirection; import com.facebook.yoga.YogaEdge; import static android.content.Context.ACCESSIBILITY_SERVICE; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1; import static android.os.Build.VERSION_CODES.M; import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO; import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO; import static com.facebook.litho.Component.isHostSpec; import static com.facebook.litho.Component.isLayoutSpecWithSizeSpec; import static com.facebook.litho.Component.isMountSpec; import static com.facebook.litho.Component.isMountViewSpec; import static com.facebook.litho.ComponentContext.NULL_LAYOUT; import static com.facebook.litho.ComponentLifecycle.MountType.NONE; import static com.facebook.litho.ComponentsLogger.ACTION_SUCCESS; import static com.facebook.litho.ComponentsLogger.EVENT_COLLECT_RESULTS; import static com.facebook.litho.ComponentsLogger.EVENT_CREATE_LAYOUT; import static com.facebook.litho.ComponentsLogger.EVENT_CSS_LAYOUT; import static com.facebook.litho.ComponentsLogger.PARAM_LOG_TAG; import static com.facebook.litho.ComponentsLogger.PARAM_TREE_DIFF_ENABLED; import static com.facebook.litho.MountItem.FLAG_DUPLICATE_PARENT_STATE; import static com.facebook.litho.MountState.ROOT_HOST_ID; import static com.facebook.litho.NodeInfo.FOCUS_SET_TRUE; import static com.facebook.litho.SizeSpec.EXACTLY; /** * The main role of {@link LayoutState} is to hold the output of layout calculation. This includes * mountable outputs and visibility outputs. A centerpiece of the class is {@link * #collectResults(InternalNode, LayoutState, DiffNode)} which prepares the before-mentioned outputs * based on the provided {@link InternalNode} for later use in {@link MountState}. */ class LayoutState { static final Comparator<LayoutOutput> sTopsComparator = new Comparator<LayoutOutput>() { @Override public int compare(LayoutOutput lhs, LayoutOutput rhs) { final int lhsTop = lhs.getBounds().top; final int rhsTop = rhs.getBounds().top; return lhsTop < rhsTop ? -1 : lhsTop > rhsTop ? 1 // Hosts should be higher for tops so that they are mounted first if possible. : isHostSpec(lhs.getComponent()) == isHostSpec(rhs.getComponent()) ? 0 : isHostSpec(lhs.getComponent()) ? -1 : 1; } }; static final Comparator<LayoutOutput> sBottomsComparator = new Comparator<LayoutOutput>() { @Override public int compare(LayoutOutput lhs, LayoutOutput rhs) { final int lhsBottom = lhs.getBounds().bottom; final int rhsBottom = rhs.getBounds().bottom; return lhsBottom < rhsBottom ? -1 : lhsBottom > rhsBottom ? 1 // Hosts should be lower for bottoms so that they are mounted first if possible. : isHostSpec(lhs.getComponent()) == isHostSpec(rhs.getComponent()) ? 0 : isHostSpec(lhs.getComponent()) ? 1 : -1; } }; private static final int[] DRAWABLE_STATE_ENABLED = new int[]{android.R.attr.state_enabled}; private static final int[] DRAWABLE_STATE_NOT_ENABLED = new int[]{}; private ComponentContext mContext; private TransitionContext mTransitionContext; private Component<?> mComponent; private int mWidthSpec; private int mHeightSpec; private final List<LayoutOutput> mMountableOutputs = new ArrayList<>(8); private final List<VisibilityOutput> mVisibilityOutputs = new ArrayList<>(8); private final LongSparseArray<Integer> mOutputsIdToPositionMap = new LongSparseArray<>(8); private final LayoutStateOutputIdCalculator mLayoutStateOutputIdCalculator; private final ArrayList<LayoutOutput> mMountableOutputTops = new ArrayList<>(); private final ArrayList<LayoutOutput> mMountableOutputBottoms = new ArrayList<>(); private final List<TestOutput> mTestOutputs; private InternalNode mLayoutRoot; private DiffNode mDiffTreeRoot; // Reference count will be initialized to 1 in init(). private final AtomicInteger mReferenceCount = new AtomicInteger(-1); private int mWidth; private int mHeight; private int mCurrentX; private int mCurrentY; private int mCurrentLevel = 0; // Holds the current host marker in the layout tree. private long mCurrentHostMarker = -1; private int mCurrentHostOutputPosition = -1; private boolean mShouldDuplicateParentState = true; private boolean mShouldGenerateDiffTree = false; private int mComponentTreeId = -1; private AccessibilityManager mAccessibilityManager; private boolean mAccessibilityEnabled = false; private StateHandler mStateHandler; LayoutState() { mLayoutStateOutputIdCalculator = new LayoutStateOutputIdCalculator(); mTestOutputs = ComponentsConfiguration.isEndToEndTestRun ? new ArrayList<TestOutput>(8) : null; } /** * Acquires a new layout output for the internal node and its associated component. It returns * null if there's no component associated with the node as the mount pass only cares about nodes * that will potentially mount content into the component host. */ @Nullable private static LayoutOutput createGenericLayoutOutput( InternalNode node, LayoutState layoutState) { final Component<?> component = node.getComponent(); // Skip empty nodes and layout specs because they don't mount anything. if (component == null || component.getLifecycle().getMountType() == NONE) { return null; } return createLayoutOutput( component, layoutState, node, true /* useNodePadding */, node.getImportantForAccessibility(), layoutState.mShouldDuplicateParentState); } private static LayoutOutput createHostLayoutOutput(LayoutState layoutState, InternalNode node) { final LayoutOutput hostOutput = createLayoutOutput( HostComponent.create(), layoutState, node, false /* useNodePadding */, node.getImportantForAccessibility(), node.isDuplicateParentStateEnabled()); hostOutput.getViewNodeInfo().setTransitionKey(node.getTransitionKey()); return hostOutput; } private static LayoutOutput createDrawableLayoutOutput( Component<?> component, LayoutState layoutState, InternalNode node) { return createLayoutOutput( component, layoutState, node, false /* useNodePadding */, IMPORTANT_FOR_ACCESSIBILITY_NO, layoutState.mShouldDuplicateParentState); } private static LayoutOutput createLayoutOutput( Component<?> component, LayoutState layoutState, InternalNode node, boolean useNodePadding, int importantForAccessibility, boolean duplicateParentState) { final boolean isMountViewSpec = isMountViewSpec(component); final LayoutOutput layoutOutput = ComponentsPools.acquireLayoutOutput(); layoutOutput.setComponent(component); layoutOutput.setImportantForAccessibility(importantForAccessibility); // The mount operation will need both the marker for the target host and its matching // parent host to ensure the correct hierarchy when nesting the host views. layoutOutput.setHostMarker(layoutState.mCurrentHostMarker); if (layoutState.mCurrentHostOutputPosition >= 0) { final LayoutOutput hostOutput = layoutState.mMountableOutputs.get(layoutState.mCurrentHostOutputPosition); final Rect hostBounds = hostOutput.getBounds(); layoutOutput.setHostTranslationX(hostBounds.left); layoutOutput.setHostTranslationY(hostBounds.top); } int l = layoutState.mCurrentX + node.getX(); int t = layoutState.mCurrentY + node.getY(); int r = l + node.getWidth(); int b = t + node.getHeight(); final int paddingLeft = useNodePadding ? node.getPaddingLeft() : 0; final int paddingTop = useNodePadding ? node.getPaddingTop() : 0; final int paddingRight = useNodePadding ? node.getPaddingRight() : 0; final int paddingBottom = useNodePadding ? node.getPaddingBottom() : 0; // View mount specs are able to set their own attributes when they're mounted. // Non-view specs (drawable and layout) always transfer their view attributes // to their respective hosts. // Moreover, if the component mounts a view, then we apply padding to the view itself later on. // Otherwise, apply the padding to the bounds of the layout output. if (isMountViewSpec) { layoutOutput.setNodeInfo(node.getNodeInfo()); // Acquire a ViewNodeInfo, set it up and release it after passing it to the LayoutOutput. final ViewNodeInfo viewNodeInfo = ViewNodeInfo.acquire(); viewNodeInfo.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom); viewNodeInfo.setLayoutDirection(node.getResolvedLayoutDirection()); viewNodeInfo.setExpandedTouchBounds(node, l, t, r, b); layoutOutput.setViewNodeInfo(viewNodeInfo); viewNodeInfo.release(); } else { l += paddingLeft; t += paddingTop; r -= paddingRight; b -= paddingBottom; } layoutOutput.setBounds(l, t, r, b); int flags = 0; if (duplicateParentState) { flags |= FLAG_DUPLICATE_PARENT_STATE; } layoutOutput.setFlags(flags); return layoutOutput; } /** * Acquires a {@link VisibilityOutput} object and computes the bounds for it using the information * stored in the {@link InternalNode}. */ private static VisibilityOutput createVisibilityOutput( InternalNode node, LayoutState layoutState) { final int l = layoutState.mCurrentX + node.getX(); final int t = layoutState.mCurrentY + node.getY(); final int r = l + node.getWidth(); final int b = t + node.getHeight(); final EventHandler visibleHandler = node.getVisibleHandler(); final EventHandler focusedHandler = node.getFocusedHandler(); final EventHandler fullImpressionHandler = node.getFullImpressionHandler(); final EventHandler invisibleHandler = node.getInvisibleHandler(); final VisibilityOutput visibilityOutput = ComponentsPools.acquireVisibilityOutput(); final Component<?> handlerComponent; // Get the component from the handler that is not null. If more than one is not null, then // getting the component from any of them works. if (visibleHandler != null) { handlerComponent = (Component<?>) visibleHandler.mHasEventDispatcher; } else if (focusedHandler != null) { handlerComponent = (Component<?>) focusedHandler.mHasEventDispatcher; } else if (fullImpressionHandler != null) { handlerComponent = (Component<?>) fullImpressionHandler.mHasEventDispatcher; } else { handlerComponent = (Component<?>) invisibleHandler.mHasEventDispatcher; } visibilityOutput.setComponent(handlerComponent); visibilityOutput.setBounds(l, t, r, b); visibilityOutput.setVisibleEventHandler(visibleHandler); visibilityOutput.setFocusedEventHandler(focusedHandler); visibilityOutput.setFullImpressionEventHandler(fullImpressionHandler); visibilityOutput.setInvisibleEventHandler(invisibleHandler); return visibilityOutput; } private static TestOutput createTestOutput( InternalNode node, LayoutState layoutState, LayoutOutput layoutOutput) { final int l = layoutState.mCurrentX + node.getX(); final int t = layoutState.mCurrentY + node.getY(); final int r = l + node.getWidth(); final int b = t + node.getHeight(); final TestOutput output = ComponentsPools.acquireTestOutput(); output.setTestKey(node.getTestKey()); output.setBounds(l, t, r, b); output.setHostMarker(layoutState.mCurrentHostMarker); if (layoutOutput != null) { output.setLayoutOutputId(layoutOutput.getId()); } return output; } private static boolean isLayoutDirectionRTL(Context context) { ApplicationInfo applicationInfo = context.getApplicationInfo(); if ((SDK_INT >= JELLY_BEAN_MR1) && (applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_RTL) != 0) { int layoutDirection = getLayoutDirection(context); return layoutDirection == View.LAYOUT_DIRECTION_RTL; } return false; } @TargetApi(JELLY_BEAN_MR1) private static int getLayoutDirection(Context context) { return context.getResources().getConfiguration().getLayoutDirection(); } /** * Determine if a given {@link InternalNode} within the context of a given {@link LayoutState} * requires to be wrapped inside a view. * * @see #needsHostView(InternalNode, LayoutState) */ private static boolean hasViewContent(InternalNode node, LayoutState layoutState) { final Component<?> component = node.getComponent(); final NodeInfo nodeInfo = node.getNodeInfo(); final boolean implementsAccessibility = (nodeInfo != null && nodeInfo.hasAccessibilityHandlers()) || (component != null && component.getLifecycle().implementsAccessibility()); final int importantForAccessibility = node.getImportantForAccessibility(); // A component has accessibility content if: // 1. Accessibility is currently enabled. // 2. Accessibility hasn't been explicitly disabled on it // i.e. IMPORTANT_FOR_ACCESSIBILITY_NO. // 3. Any of these conditions are true: // - It implements accessibility support. // - It has a content description. // - It has importantForAccessibility set as either IMPORTANT_FOR_ACCESSIBILITY_YES // or IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS. // IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS should trigger an inner host // so that such flag is applied in the resulting view hierarchy after the component // tree is mounted. Click handling is also considered accessibility content but // this is already covered separately i.e. click handler is not null. final boolean hasAccessibilityContent = layoutState.mAccessibilityEnabled && importantForAccessibility != IMPORTANT_FOR_ACCESSIBILITY_NO && (implementsAccessibility || (nodeInfo != null && !TextUtils.isEmpty(nodeInfo.getContentDescription())) || importantForAccessibility != IMPORTANT_FOR_ACCESSIBILITY_AUTO); final boolean hasTouchEventHandlers = (nodeInfo != null && nodeInfo.hasTouchEventHandlers()); final boolean hasViewTag = (nodeInfo != null && nodeInfo.getViewTag() != null); final boolean hasViewTags = (nodeInfo != null && nodeInfo.getViewTags() != null); final boolean isFocusableSetTrue = (nodeInfo != null && nodeInfo.getFocusState() == FOCUS_SET_TRUE); return hasTouchEventHandlers || hasViewTag || hasViewTags || hasAccessibilityContent || isFocusableSetTrue; } /** * Collects layout outputs and release the layout tree. The layout outputs hold necessary * information to be used by {@link MountState} to mount components into a {@link ComponentHost}. * <p/> * Whenever a component has view content (view tags, click handler, etc), a new host 'marker' * is added for it. The mount pass will use the markers to decide which host should be used * for each layout output. The root node unconditionally generates a layout output corresponding * to the root host. * <p/> * The order of layout outputs follows a depth-first traversal in the tree to ensure the hosts * will be created at the right order when mounting. The host markers will be define which host * each mounted artifacts will be attached to. * <p/> * At this stage all the {@link InternalNode} for which we have LayoutOutputs that can be recycled * will have a DiffNode associated. If the CachedMeasures are valid we'll try to recycle both the * host and the contents (including background/foreground). In all other cases instead we'll only * try to re-use the hosts. In some cases the host's structure might change between two updates * even if the component is of the same type. This can happen for example when a click listener is * added. To avoid trying to re-use the wrong host type we explicitly check that after all the * children for a subtree have been added (this is when the actual host type is resolved). If the * host type changed compared to the one in the DiffNode we need to refresh the ids for the whole * subtree in order to ensure that the MountState will unmount the subtree and mount it again on * the correct host. * <p/> * * @param node InternalNode to process. * @param layoutState the LayoutState currently operating. * @param parentDiffNode whether this method also populates the diff tree and assigns the root * to mDiffTreeRoot. */ private static void collectResults( InternalNode node, LayoutState layoutState, DiffNode parentDiffNode) { if (node.hasNewLayout()) { node.markLayoutSeen(); } final Component<?> component = node.getComponent(); // Early return if collecting results of a node holding a nested tree. if (node.isNestedTreeHolder()) { // If the nested tree is defined, it has been resolved during a measure call during // layout calculation. InternalNode nestedTree = resolveNestedTree( node, SizeSpec.makeSizeSpec(node.getWidth(), EXACTLY), SizeSpec.makeSizeSpec(node.getHeight(), EXACTLY)); if (nestedTree == NULL_LAYOUT) { return; } // Account for position of the holder node. layoutState.mCurrentX += node.getX(); layoutState.mCurrentY += node.getY(); collectResults(nestedTree, layoutState, parentDiffNode); layoutState.mCurrentX -= node.getX(); layoutState.mCurrentY -= node.getY(); return; } final boolean shouldGenerateDiffTree = layoutState.mShouldGenerateDiffTree; final DiffNode currentDiffNode = node.getDiffNode(); final boolean shouldUseCachedOutputs = isMountSpec(component) && currentDiffNode != null; final boolean isCachedOutputUpdated = shouldUseCachedOutputs && node.areCachedMeasuresValid(); final DiffNode diffNode; if (shouldGenerateDiffTree) { diffNode = createDiffNode(node, parentDiffNode); if (parentDiffNode == null) { layoutState.mDiffTreeRoot = diffNode; } } else { diffNode = null; } final boolean needsHostView = needsHostView(node, layoutState); final long currentHostMarker = layoutState.mCurrentHostMarker; final int currentHostOutputPosition = layoutState.mCurrentHostOutputPosition; int hostLayoutPosition = -1; // 1. Insert a host LayoutOutput if we have some interactive content to be attached to. if (needsHostView) { hostLayoutPosition = addHostLayoutOutput(node, layoutState, diffNode); layoutState.mCurrentLevel++; layoutState.mCurrentHostMarker = layoutState.mMountableOutputs.get(hostLayoutPosition).getId(); layoutState.mCurrentHostOutputPosition = hostLayoutPosition; } // We need to take into account flattening when setting duplicate parent state. The parent after // flattening may no longer exist. Therefore the value of duplicate parent state should only be // true if the path between us (inclusive) and our inner/root host (exclusive) all are // duplicate parent state. final boolean shouldDuplicateParentState = layoutState.mShouldDuplicateParentState; layoutState.mShouldDuplicateParentState = needsHostView || (shouldDuplicateParentState && node.isDuplicateParentStateEnabled()); // Generate the layoutOutput for the given node. final LayoutOutput layoutOutput = createGenericLayoutOutput(node, layoutState); if (layoutOutput != null) { final long previousId = shouldUseCachedOutputs ? currentDiffNode.getContent().getId() : -1; layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState( layoutOutput, layoutState.mCurrentLevel, LayoutOutput.TYPE_CONTENT, previousId, isCachedOutputUpdated); } // If we don't need to update this output we can safely re-use the display list from the // previous output. if (isCachedOutputUpdated) { layoutOutput.setDisplayList(currentDiffNode.getContent().getDisplayList()); } // 2. Add background if defined. final Reference<? extends Drawable> background = node.getBackground(); if (background != null) { if (layoutOutput != null && layoutOutput.hasViewNodeInfo()) { layoutOutput.getViewNodeInfo().setBackground(background); } else { final LayoutOutput convertBackground = (currentDiffNode != null) ? currentDiffNode.getBackground() : null; final LayoutOutput backgroundOutput = addDrawableComponent( node, layoutState, convertBackground, background, LayoutOutput.TYPE_BACKGROUND); if (diffNode != null) { diffNode.setBackground(backgroundOutput); } } } // 3. Now add the MountSpec (either View or Drawable) to the Outputs. if (isMountSpec(component)) { // Notify component about its final size. component.getLifecycle().onBoundsDefined(layoutState.mContext, node, component); addMountableOutput(layoutState, layoutOutput); addLayoutOutputIdToPositionsMap( layoutState.mOutputsIdToPositionMap, layoutOutput, layoutState.mMountableOutputs.size() - 1); if (diffNode != null) { diffNode.setContent(layoutOutput); } } // 4. Add border color if defined. if (node.shouldDrawBorders()) { final LayoutOutput convertBorder = (currentDiffNode != null) ? currentDiffNode.getBorder() : null; final LayoutOutput borderOutput = addDrawableComponent( node, layoutState, convertBorder, getBorderColorDrawable(node), LayoutOutput.TYPE_BORDER); if (diffNode != null) { diffNode.setBorder(borderOutput); } } // 5. Extract the Transitions. if (SDK_INT >= ICE_CREAM_SANDWICH) { if (node.getTransitionKey() != null) { layoutState .getOrCreateTransitionContext() .addTransitionKey(node.getTransitionKey()); } if (component != null) { Transition transition = component.getLifecycle().onLayoutTransition( layoutState.mContext, component); if (transition != null) { layoutState.getOrCreateTransitionContext().add(transition); } } } layoutState.mCurrentX += node.getX(); layoutState.mCurrentY += node.getY(); // We must process the nodes in order so that the layout state output order is correct. for (int i = 0, size = node.getChildCount(); i < size; i++) { collectResults( node.getChildAt(i), layoutState, diffNode); } layoutState.mCurrentX -= node.getX(); layoutState.mCurrentY -= node.getY(); // 6. Add foreground if defined. final Reference<? extends Drawable> foreground = node.getForeground(); if (foreground != null) { if (layoutOutput != null && layoutOutput.hasViewNodeInfo() && SDK_INT >= M) { layoutOutput.getViewNodeInfo().setForeground(foreground); } else { final LayoutOutput convertForeground = (currentDiffNode != null) ? currentDiffNode.getForeground() : null; final LayoutOutput foregroundOutput = addDrawableComponent( node, layoutState, convertForeground, foreground, LayoutOutput.TYPE_FOREGROUND); if (diffNode != null) { diffNode.setForeground(foregroundOutput); } } } // 7. Add VisibilityOutputs if any visibility-related event handlers are present. if (node.hasVisibilityHandlers()) { final VisibilityOutput visibilityOutput = createVisibilityOutput(node, layoutState); final long previousId = shouldUseCachedOutputs ? currentDiffNode.getVisibilityOutput().getId() : -1; layoutState.mLayoutStateOutputIdCalculator.calculateAndSetVisibilityOutputId( visibilityOutput, layoutState.mCurrentLevel, previousId); layoutState.mVisibilityOutputs.add(visibilityOutput); if (diffNode != null) { diffNode.setVisibilityOutput(visibilityOutput); } } // 8. If we're in a testing environment, maintain an additional data structure with // information about nodes that we can query later. if (layoutState.mTestOutputs != null && !TextUtils.isEmpty(node.getTestKey())) { final TestOutput testOutput = createTestOutput(node, layoutState, layoutOutput); layoutState.mTestOutputs.add(testOutput); } // All children for the given host have been added, restore the previous // host, level, and duplicate parent state value in the recursive queue. if (layoutState.mCurrentHostMarker != currentHostMarker) { layoutState.mCurrentHostMarker = currentHostMarker; layoutState.mCurrentHostOutputPosition = currentHostOutputPosition; layoutState.mCurrentLevel } layoutState.mShouldDuplicateParentState = shouldDuplicateParentState; Collections.sort(layoutState.mMountableOutputTops, sTopsComparator); Collections.sort(layoutState.mMountableOutputBottoms, sBottomsComparator); } private static void calculateAndSetHostOutputIdAndUpdateState( InternalNode node, LayoutOutput hostOutput, LayoutState layoutState, boolean isCachedOutputUpdated) { if (layoutState.isLayoutRoot(node)) { // The root host (ComponentView) always has ID 0 and is unconditionally // set as dirty i.e. no need to use shouldComponentUpdate(). hostOutput.setId(ROOT_HOST_ID); // Special case where the host marker of the root host is pointing to itself. hostOutput.setHostMarker(ROOT_HOST_ID); hostOutput.setUpdateState(LayoutOutput.STATE_DIRTY); } else { layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState( hostOutput, layoutState.mCurrentLevel, LayoutOutput.TYPE_HOST, -1, isCachedOutputUpdated); } } private static LayoutOutput addDrawableComponent( InternalNode node, LayoutState layoutState, LayoutOutput recycle, Reference<? extends Drawable> reference, @LayoutOutput.LayoutOutputType int type) { final Component<DrawableComponent> drawableComponent = DrawableComponent.create(reference); drawableComponent.setScopedContext( ComponentContext.withComponentScope(node.getContext(), drawableComponent)); final boolean isOutputUpdated; if (recycle != null) { isOutputUpdated = !drawableComponent.getLifecycle().shouldComponentUpdate( recycle.getComponent(), drawableComponent); } else { isOutputUpdated = false; } final long previousId = recycle != null ? recycle.getId() : -1; final LayoutOutput output = addDrawableLayoutOutput( drawableComponent, layoutState, node, type, previousId, isOutputUpdated); return output; } private static Reference<? extends Drawable> getBorderColorDrawable(InternalNode node) { if (!node.shouldDrawBorders()) { throw new RuntimeException("This node does not support drawing border color"); } return BorderColorDrawableReference.create(node.getContext()) .color(node.getBorderColor()) .borderLeft(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.LEFT))) .borderTop(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.TOP))) .borderRight(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.RIGHT))) .borderBottom(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.BOTTOM))) .build(); } private static void addLayoutOutputIdToPositionsMap( LongSparseArray outputsIdToPositionMap, LayoutOutput layoutOutput, int position) { if (outputsIdToPositionMap != null) { outputsIdToPositionMap.put(layoutOutput.getId(), position); } } private static LayoutOutput addDrawableLayoutOutput( Component<DrawableComponent> drawableComponent, LayoutState layoutState, InternalNode node, @LayoutOutput.LayoutOutputType int layoutOutputType, long previousId, boolean isCachedOutputUpdated) { drawableComponent.getLifecycle().onBoundsDefined( layoutState.mContext, node, drawableComponent); final LayoutOutput drawableLayoutOutput = createDrawableLayoutOutput( drawableComponent, layoutState, node); layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState( drawableLayoutOutput, layoutState.mCurrentLevel, layoutOutputType, previousId, isCachedOutputUpdated); addMountableOutput(layoutState, drawableLayoutOutput); addLayoutOutputIdToPositionsMap( layoutState.mOutputsIdToPositionMap, drawableLayoutOutput, layoutState.mMountableOutputs.size() - 1); return drawableLayoutOutput; } static void releaseNodeTree(InternalNode node, boolean isNestedTree) { if (node == NULL_LAYOUT) { throw new IllegalArgumentException("Cannot release a null node tree"); } for (int i = node.getChildCount() - 1; i >= 0; i final InternalNode child = node.getChildAt(i); if (isNestedTree && node.hasNewLayout()) { node.markLayoutSeen(); } // A node must be detached from its parent *before* being released (otherwise the parent would // retain a reference to a node that may get re-used by another thread) node.removeChildAt(i); releaseNodeTree(child, isNestedTree); } if (node.hasNestedTree() && node.getNestedTree() != NULL_LAYOUT) { releaseNodeTree(node.getNestedTree(), true); } ComponentsPools.release(node); } /** * If we have an interactive LayoutSpec or a MountSpec Drawable, we need to insert an * HostComponent in the Outputs such as it will be used as a HostView at Mount time. View * MountSpec are not allowed. * * @return The position the HostLayoutOutput was inserted. */ private static int addHostLayoutOutput( InternalNode node, LayoutState layoutState, DiffNode diffNode) { final Component<?> component = node.getComponent(); // Only the root host is allowed to wrap view mount specs as a layout output // is unconditionally added for it. if (isMountViewSpec(component) && !layoutState.isLayoutRoot(node)) { throw new IllegalArgumentException("We shouldn't insert a host as a parent of a View"); } final LayoutOutput hostLayoutOutput = createHostLayoutOutput(layoutState, node); // The component of the hostLayoutOutput will be set later after all the // children got processed. addMountableOutput(layoutState, hostLayoutOutput); final int hostOutputPosition = layoutState.mMountableOutputs.size() - 1; if (diffNode != null) { diffNode.setHost(hostLayoutOutput); } calculateAndSetHostOutputIdAndUpdateState( node, hostLayoutOutput, layoutState, false); addLayoutOutputIdToPositionsMap( layoutState.mOutputsIdToPositionMap, hostLayoutOutput, hostOutputPosition); return hostOutputPosition; } static <T extends ComponentLifecycle> LayoutState calculate( ComponentContext c, Component<T> component, int componentTreeId, int widthSpec, int heightSpec, boolean shouldGenerateDiffTree, DiffNode previousDiffTreeRoot) { // Detect errors internal to components component.markLayoutStarted(); LayoutState layoutState = ComponentsPools.acquireLayoutState(c); layoutState.mShouldGenerateDiffTree = shouldGenerateDiffTree; layoutState.mComponentTreeId = componentTreeId; layoutState.mAccessibilityManager = (AccessibilityManager) c.getSystemService(ACCESSIBILITY_SERVICE); layoutState.mAccessibilityEnabled = isAccessibilityEnabled(layoutState.mAccessibilityManager); layoutState.mComponent = component; layoutState.mWidthSpec = widthSpec; layoutState.mHeightSpec = heightSpec; component.applyStateUpdates(c); final InternalNode root = createAndMeasureTreeForComponent( component.getScopedContext(), component, null, // nestedTreeHolder is null because this is measuring the root component tree. widthSpec, heightSpec, previousDiffTreeRoot); switch (SizeSpec.getMode(widthSpec)) { case SizeSpec.EXACTLY: layoutState.mWidth = SizeSpec.getSize(widthSpec); break; case SizeSpec.AT_MOST: layoutState.mWidth = Math.min(root.getWidth(), SizeSpec.getSize(widthSpec)); break; case SizeSpec.UNSPECIFIED: layoutState.mWidth = root.getWidth(); break; } switch (SizeSpec.getMode(heightSpec)) { case SizeSpec.EXACTLY: layoutState.mHeight = SizeSpec.getSize(heightSpec); break; case SizeSpec.AT_MOST: layoutState.mHeight = Math.min(root.getHeight(), SizeSpec.getSize(heightSpec)); break; case SizeSpec.UNSPECIFIED: layoutState.mHeight = root.getHeight(); break; } layoutState.mLayoutStateOutputIdCalculator.clear(); // Reset markers before collecting layout outputs. layoutState.mCurrentHostMarker = -1; final ComponentsLogger logger = c.getLogger(); if (root == NULL_LAYOUT) { return layoutState; } layoutState.mLayoutRoot = root; ComponentsSystrace.beginSection("collectResults:" + component.getSimpleName()); if (logger != null) { logger.eventStart(EVENT_COLLECT_RESULTS, component, PARAM_LOG_TAG, c.getLogTag()); } collectResults(root, layoutState, null); if (logger != null) { logger.eventEnd(EVENT_COLLECT_RESULTS, component, ACTION_SUCCESS); } ComponentsSystrace.endSection(); if (!ComponentsConfiguration.IS_INTERNAL_BUILD && layoutState.mLayoutRoot != null) { releaseNodeTree(layoutState.mLayoutRoot, false /* isNestedTree */); layoutState.mLayoutRoot = null; } if (ThreadUtils.isMainThread() && ComponentsConfiguration.shouldGenerateDisplayLists) { collectDisplayLists(layoutState); } return layoutState; } void preAllocateMountContent() { if (mMountableOutputs != null && !mMountableOutputs.isEmpty()) { for (int i = 0, size = mMountableOutputs.size(); i < size; i++) { final Component component = mMountableOutputs.get(i).getComponent(); if (Component.isMountViewSpec(component)) { final ComponentLifecycle lifecycle = component.getLifecycle(); if (!lifecycle.hasBeenPreallocated()) { final int poolSize = lifecycle.poolSize(); int insertedCount = 0; while (insertedCount < poolSize && ComponentsPools.canAddMountContentToPool(mContext, lifecycle)) { ComponentsPools.release( mContext, lifecycle, lifecycle.createMountContent(mContext)); insertedCount++; } lifecycle.setWasPreallocated(); } } } } } private static void collectDisplayLists(LayoutState layoutState) { final Rect rect = new Rect(); final ComponentContext context = layoutState.mContext; final Activity activity = findActivityInContext(context); if (activity == null || activity.isFinishing() || isActivityDestroyed(activity)) { return; } for (int i = 0, count = layoutState.getMountableOutputCount(); i < count; i++) { final LayoutOutput output = layoutState.getMountableOutputAt(i);
package com.github.ansell.csv.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Map; import java.util.concurrent.TimeUnit; import org.apache.http.HttpVersion; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.fluent.Request; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.protocol.RequestAcceptEncoding; import org.apache.http.client.protocol.ResponseContentEncoding; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.cache.BasicHttpCacheStorage; import org.apache.http.impl.client.cache.CacheConfig; import org.apache.http.impl.client.cache.CachingHttpClientBuilder; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonPointer; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.jsonldjava.utils.JarCacheStorage; /** * JSON utilities used by CSV processors. * * @author Peter Ansell p_ansell@yahoo.com */ public class JSONUtil { private static final String DEFAULT_ACCEPT_HEADER = "application/json, application/javascript;q=0.5, text/javascript;q=0.5, text/plain;q=0.2, */*;q=0.1"; private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); private static final JsonFactory JSON_FACTORY = new JsonFactory(JSON_MAPPER); /** * Default to 120 second timeout. */ private static final int DEFAULT_TIMEOUT = 120 * 1000; private static volatile CloseableHttpClient DEFAULT_HTTP_CLIENT = null; public static JsonNode httpGetJSON(String url) throws JsonProcessingException, IOException { return httpGetJSON(url, 0, 0, TimeUnit.NANOSECONDS); } public static JsonNode httpGetJSON(String url, int maxRetries, long sleepTime, TimeUnit sleepUnit) throws JsonProcessingException, IOException { return httpGetJSON(url, maxRetries, sleepTime, sleepUnit, DEFAULT_TIMEOUT); } public static JsonNode httpGetJSON(String url, int maxRetries, long sleepTime, TimeUnit sleepUnit, int timeout) throws JsonProcessingException, IOException { for (int retries = 0; retries <= maxRetries; retries++) { try (final InputStream stream = openStreamForURL(new java.net.URL(url), getDefaultHttpClient(), DEFAULT_ACCEPT_HEADER, timeout); final Reader input = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));) { return JSON_MAPPER.readTree(input); } catch (JsonProcessingException e) { System.err.println("Found Json error for URL: " + url + " on retry number " + (retries + 1) + " maxRetries=" + maxRetries); e.printStackTrace(System.err); throw e; } catch (IOException e) { if (retries >= maxRetries) { System.err.println("Found maximum number of retries on retry number " + (retries + 1) + " maxRetries=" + maxRetries); e.printStackTrace(System.err); throw e; } try { System.err.println("Found exception on retry number " + (retries + 1)); e.printStackTrace(System.err); Thread.sleep(TimeUnit.MILLISECONDS.convert(sleepTime, sleepUnit) * (retries + 1)); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); throw new IOException("Interrupted while waiting to retry : Max retries (" + maxRetries + ") exceeded for : " + url); } } } throw new IOException("Max retries (" + maxRetries + ") exceeded for : " + url); } public static String queryJSON(String url, String jpath) throws JsonProcessingException, IOException { return queryJSON(url, JsonPointer.compile(jpath)); } public static String queryJSON(String url, JsonPointer jpath) throws JsonProcessingException, IOException { try (final InputStream stream = openStreamForURL(new java.net.URL(url), getDefaultHttpClient()); final Reader input = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));) { return queryJSON(input, jpath); } } public static JsonNode loadJSON(Path path) throws JsonProcessingException, IOException { try (final Reader input = Files.newBufferedReader(path, StandardCharsets.UTF_8);) { return loadJSON(input); } } public static JsonNode loadJSON(Reader input) throws JsonProcessingException, IOException { return JSON_MAPPER.readTree(input); } public static String queryJSON(Reader input, String jpath) throws JsonProcessingException, IOException { return queryJSON(input, JsonPointer.compile(jpath)); } public static String queryJSON(Reader input, JsonPointer jpath) throws JsonProcessingException, IOException { JsonNode root = JSON_MAPPER.readTree(input); return queryJSONNode(root, jpath).asText(); } public static JsonNode queryJSONNode(JsonNode input, String jpath) throws JsonProcessingException, IOException { return queryJSONNode(input, JsonPointer.compile(jpath)); } public static JsonNode queryJSONNode(JsonNode input, JsonPointer jpath) throws JsonProcessingException, IOException { return input.at(jpath); } public static String queryJSONNodeAsText(JsonNode input, String jpath) throws JsonProcessingException, IOException { return queryJSONNodeAsText(input, JsonPointer.compile(jpath)); } public static String queryJSONNodeAsText(JsonNode input, JsonPointer jpath) throws JsonProcessingException, IOException { return queryJSONNode(input, jpath).asText(); } public static String queryJSONPost(String url, Map<String, Object> postVariables, String jpath) throws JsonProcessingException, IOException { StringWriter serialisedVariables = new StringWriter(); toPrettyPrint(postVariables, serialisedVariables); String postVariableString = serialisedVariables.toString(); String result = Request.Post(url).useExpectContinue().version(HttpVersion.HTTP_1_1) .bodyString(postVariableString, ContentType.DEFAULT_TEXT).execute().returnContent() .asString(StandardCharsets.UTF_8); String result2 = queryJSON(new StringReader(result), jpath); return result2; } public static JsonNode httpPostJSON(String url, Map<String, Object> postVariables) throws JsonProcessingException, IOException { StringWriter serialisedVariables = new StringWriter(); toPrettyPrint(postVariables, serialisedVariables); String postVariableString = serialisedVariables.toString(); try (InputStream inputStream = Request.Post(url).useExpectContinue().version(HttpVersion.HTTP_1_1) .bodyString(postVariableString, ContentType.DEFAULT_TEXT).execute().returnContent().asStream(); Reader inputReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) { return JSON_MAPPER.readTree(inputReader); } } public static void toPrettyPrint(Reader input, Writer output) throws IOException { final JsonGenerator jw = JSON_FACTORY.createGenerator(output); jw.useDefaultPrettyPrinter(); JsonParser parser = JSON_FACTORY.createParser(input); jw.writeObject(parser.readValueAsTree()); } public static void toPrettyPrint(Map<String, Object> input, Writer output) throws IOException { final JsonGenerator jw = JSON_FACTORY.createGenerator(output); jw.useDefaultPrettyPrinter(); jw.writeObject(input); } public static void toPrettyPrint(JsonNode input, Writer output) throws IOException { final JsonGenerator jw = JSON_FACTORY.createGenerator(output); jw.useDefaultPrettyPrinter(); jw.writeObject(input); } public static String toPrettyPrint(JsonNode input) throws IOException { Writer output = new StringWriter(); final JsonGenerator jw = JSON_FACTORY.createGenerator(output); jw.useDefaultPrettyPrinter(); jw.writeObject(input); return output.toString(); } public static InputStream openStreamForURL(java.net.URL url, CloseableHttpClient httpClient) throws IOException { return openStreamForURL(url, httpClient, DEFAULT_ACCEPT_HEADER); } public static InputStream openStreamForURL(java.net.URL url, CloseableHttpClient httpClient, String acceptHeader) throws IOException { return openStreamForURL(url, httpClient, acceptHeader, DEFAULT_TIMEOUT); } public static InputStream openStreamForURL(java.net.URL url, CloseableHttpClient httpClient, String acceptHeader, int timeout) throws IOException { final String protocol = url.getProtocol(); if (!protocol.equalsIgnoreCase("http") && !protocol.equalsIgnoreCase("https")) { return url.openStream(); } final HttpGet request = new HttpGet(url.toExternalForm()); request.addHeader("Accept", acceptHeader); RequestConfig.Builder requestConfig = RequestConfig.custom(); requestConfig.setConnectTimeout(timeout); requestConfig.setConnectionRequestTimeout(timeout); requestConfig.setSocketTimeout(timeout); request.setConfig(requestConfig.build()); final CloseableHttpResponse response = httpClient.execute(request); final int status = response.getStatusLine().getStatusCode(); if (status != 200 && status != 203) { throw new IOException("Can't retrieve " + url + ", status code: " + status); } return response.getEntity().getContent(); } public static CloseableHttpClient getDefaultHttpClient() { CloseableHttpClient result = DEFAULT_HTTP_CLIENT; if (result == null) { synchronized (JSONUtil.class) { result = DEFAULT_HTTP_CLIENT; if (result == null) { result = DEFAULT_HTTP_CLIENT = JSONUtil.createDefaultHttpClient(); } } } return result; } private static CloseableHttpClient createDefaultHttpClient() { // Common CacheConfig for both the JarCacheStorage and the underlying // BasicHttpCacheStorage final CacheConfig cacheConfig = CacheConfig.custom().setMaxCacheEntries(1000).setMaxObjectSize(1024 * 128) .build(); RequestConfig config = RequestConfig.custom() .setConnectTimeout(DEFAULT_TIMEOUT) .setConnectionRequestTimeout(DEFAULT_TIMEOUT) .setSocketTimeout(DEFAULT_TIMEOUT).build(); CloseableHttpClient result = CachingHttpClientBuilder.create() // allow caching .setCacheConfig(cacheConfig) // Wrap the local JarCacheStorage around a BasicHttpCacheStorage .setHttpCacheStorage(new JarCacheStorage(null, cacheConfig, new BasicHttpCacheStorage(cacheConfig))) // Support compressed data // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/httpagent.html#d5e1238 .addInterceptorFirst(new RequestAcceptEncoding()).addInterceptorFirst(new ResponseContentEncoding()) // use system defaults for proxy etc. .useSystemProperties() .setDefaultRequestConfig(config) .build(); return result; } }
package com.intellij.openapi.editor.impl; import com.intellij.codeInsight.hint.HintManagerImpl; import com.intellij.icons.AllIcons; import com.intellij.ide.PowerSaveMode; import com.intellij.ide.actions.ActionsCollector; import com.intellij.internal.statistic.eventLog.FeatureUsageData; import com.intellij.internal.statistic.service.fus.collectors.FUCounterUsageLogger; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.impl.ActionButton; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorBundle; import com.intellij.openapi.editor.markup.*; import com.intellij.openapi.ui.popup.*; import com.intellij.openapi.util.NlsContexts; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.AncestorListenerAdapter; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.components.DropDownLink; import com.intellij.ui.components.labels.LinkLabel; import com.intellij.ui.components.panels.NonOpaquePanel; import com.intellij.ui.popup.PopupState; import com.intellij.ui.scale.JBUIScale; import com.intellij.util.Alarm; import com.intellij.util.IJSwingUtilities; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.GridBag; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import com.intellij.xml.util.XmlStringUtil; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.event.AncestorEvent; import javax.swing.event.AncestorListener; import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.List; import java.util.*; import java.util.function.Supplier; class InspectionPopupManager { private static final int DELTA_X = 6; private static final int DELTA_Y = 6; private final Supplier<AnalyzerStatus> statusSupplier; private final Editor myEditor; private final AnAction compactViewAction; private final JPanel myContent = new JPanel(new GridBagLayout()); private final ComponentPopupBuilder myPopupBuilder; private final Map<String, JProgressBar> myProgressBarMap = new HashMap<>(); private final AncestorListener myAncestorListener; private final JBPopupListener myPopupListener; private final PopupState<JBPopup> myPopupState = PopupState.forPopup(); private final Alarm popupAlarm = new Alarm(); private final List<DropDownLink<?>> levelLinks = new ArrayList<>(); private JBPopup myPopup; private boolean insidePopup; InspectionPopupManager(@NotNull Supplier<AnalyzerStatus> statusSupplier, @NotNull Editor editor, @NotNull AnAction compactViewAction) { this.statusSupplier = statusSupplier; this.myEditor = editor; this.compactViewAction = compactViewAction; myContent.setOpaque(true); myContent.setBackground(UIUtil.getToolTipBackground()); myPopupBuilder = JBPopupFactory.getInstance().createComponentPopupBuilder(myContent, null). setCancelOnClickOutside(true). setCancelCallback(() -> getAnalyzerStatus() == null || getAnalyzerStatus().getController().canClosePopup()); myAncestorListener = new AncestorListenerAdapter() { @Override public void ancestorMoved(AncestorEvent event) { hidePopup(); } }; myPopupListener = new JBPopupListener() { @Override public void onClosed(@NotNull LightweightWindowEvent event) { if (statusSupplier.get() != null) { statusSupplier.get().getController().onClosePopup(); } myEditor.getComponent().removeAncestorListener(myAncestorListener); } }; myContent.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent event) { insidePopup = true; } @Override public void mouseExited(MouseEvent event) { Point point = event.getPoint(); if (!myContent.getBounds().contains(point) || point.x == 0 || point.y == 0) { insidePopup = false; if (canClose()) { hidePopup(); } } } }); } private boolean canClose() { return !insidePopup && levelLinks.stream().allMatch(l -> l.getPopupState().isHidden()); } void updateUI() { IJSwingUtilities.updateComponentTreeUI(myContent); } void scheduleShow(@NotNull InputEvent event) { popupAlarm.cancelAllRequests(); popupAlarm.addRequest(() -> showPopup(event), Registry.intValue("ide.tooltip.initialReshowDelay")); } void scheduleHide() { popupAlarm.cancelAllRequests(); popupAlarm.addRequest(() -> { if (canClose()) { hidePopup(); } }, Registry.intValue("ide.tooltip.initialDelay.highlighter")); } void showPopup(@NotNull InputEvent event) { hidePopup(); if (myPopupState.isRecentlyHidden()) return; // do not show new popup updateContentPanel(getAnalyzerStatus().getController()); myPopup = myPopupBuilder.createPopup(); myPopup.addListener(myPopupListener); myPopupState.prepareToShow(myPopup); myEditor.getComponent().addAncestorListener(myAncestorListener); JComponent owner = (JComponent)event.getComponent(); Dimension size = myContent.getPreferredSize(); size.width = Math.max(size.width, JBUIScale.scale(296)); RelativePoint point = new RelativePoint(owner, new Point(owner.getWidth() - owner.getInsets().right + JBUIScale.scale(DELTA_X) - size.width, owner.getHeight() + JBUIScale.scale(DELTA_Y))); myPopup.setSize(size); myPopup.show(point); } void hidePopup() { if (myPopup != null && !myPopup.isDisposed()) { myPopup.cancel(); } myPopup = null; } private AnalyzerStatus getAnalyzerStatus() { return statusSupplier.get(); } private void updateContentPanel(@NotNull UIController controller) { java.util.List<PassWrapper> passes = getAnalyzerStatus().getPasses(); Set<String> presentableNames = ContainerUtil.map2Set(passes, p -> p.getPresentableName()); if (!presentableNames.isEmpty() && myProgressBarMap.keySet().equals(presentableNames)) { for (PassWrapper pass : passes) { myProgressBarMap.get(pass.getPresentableName()).setValue(pass.toPercent()); } return; } myContent.removeAll(); levelLinks.clear(); GridBag gc = new GridBag().nextLine().next(). anchor(GridBagConstraints.LINE_START). weightx(1). fillCellHorizontally(). insets(10, 10, 10, 0); boolean hasTitle = StringUtil.isNotEmpty(getAnalyzerStatus().getTitle()); if (hasTitle) { myContent.add(new JLabel(XmlStringUtil.wrapInHtml(getAnalyzerStatus().getTitle())), gc); } else if (StringUtil.isNotEmpty(getAnalyzerStatus().getDetails())) { myContent.add(new JLabel(XmlStringUtil.wrapInHtml(getAnalyzerStatus().getDetails())), gc); } else if (getAnalyzerStatus().getExpandedStatus().size() > 0 && getAnalyzerStatus().getAnalyzingType() != AnalyzingType.EMPTY) { myContent.add(createDetailsPanel(), gc); } Presentation presentation = new Presentation(); presentation.setIcon(AllIcons.Actions.More); presentation.putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, Boolean.TRUE); java.util.List<AnAction> actions = controller.getActions(); if (!actions.isEmpty()) { ActionButton menuButton = new ActionButton(new MenuAction(actions, compactViewAction), presentation, ActionPlaces.EDITOR_POPUP, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE); myContent.add(menuButton, gc.next().anchor(GridBagConstraints.LINE_END).weightx(0).insets(10, 6, 10, 6)); } myProgressBarMap.clear(); JPanel myProgressPanel = new NonOpaquePanel(new GridBagLayout()); GridBag progressGC = new GridBag(); for (PassWrapper pass : passes) { myProgressPanel.add(new JLabel(pass.getPresentableName() + ": "), progressGC.nextLine().next().anchor(GridBagConstraints.LINE_START).weightx(0).insets(0, 10, 0, 6)); JProgressBar pb = new JProgressBar(0, 100); pb.setValue(pass.toPercent()); myProgressPanel.add(pb, progressGC.next().anchor(GridBagConstraints.LINE_START).weightx(1).fillCellHorizontally().insets(0, 0, 0, 6)); myProgressBarMap.put(pass.getPresentableName(), pb); } myContent.add(myProgressPanel, gc.nextLine().next().anchor(GridBagConstraints.LINE_START).fillCellHorizontally().coverLine().weightx(1)); if (hasTitle) { int topIndent = !myProgressBarMap.isEmpty() ? 10 : 0; gc.nextLine().next().anchor(GridBagConstraints.LINE_START).fillCellHorizontally().coverLine().weightx(1).insets(topIndent, 10, 10, 6); if (StringUtil.isNotEmpty(getAnalyzerStatus().getDetails())) { myContent.add(new JLabel(XmlStringUtil.wrapInHtml(getAnalyzerStatus().getDetails())), gc); } else if (getAnalyzerStatus().getExpandedStatus().size() > 0 && getAnalyzerStatus().getAnalyzingType() != AnalyzingType.EMPTY) { myContent.add(createDetailsPanel(), gc); } else if (!passes.isEmpty()){ myProgressPanel.setBorder(JBUI.Borders.emptyBottom(12)); } } myContent.add(createLowerPanel(controller), gc.nextLine().next().anchor(GridBagConstraints.LINE_START).fillCellHorizontally().coverLine().weightx(1)); } void updateVisiblePopup() { if (myPopup != null && myPopup.isVisible()) { updateContentPanel(getAnalyzerStatus().getController()); Dimension size = myContent.getPreferredSize(); size.width = Math.max(size.width, JBUIScale.scale(296)); myPopup.setSize(size); } } private @NotNull JComponent createDetailsPanel() { @Nls StringBuilder text = new StringBuilder(); for (int i = 0; i < getAnalyzerStatus().getExpandedStatus().size(); i++) { boolean last = i == getAnalyzerStatus().getExpandedStatus().size() - 1; StatusItem item = getAnalyzerStatus().getExpandedStatus().get(i); String detailsText = item.getDetailsText(); text.append(detailsText != null ? detailsText : item.getText()); if (!last) { text.append(", "); } else if (getAnalyzerStatus().getAnalyzingType() != AnalyzingType.COMPLETE) { text.append(" ").append(EditorBundle.message("iw.found.so.far.suffix")); } } return new JLabel(text.toString()); } private @NotNull JPanel createLowerPanel(@NotNull UIController controller) { JPanel panel = new JPanel(new GridBagLayout()); GridBag gc = new GridBag().nextLine(); if (PowerSaveMode.isEnabled()) { panel.add(new TrackableLinkLabel(EditorBundle.message("iw.disable.powersave"), () ->{ PowerSaveMode.setEnabled(false); hidePopup(); }), gc.next().anchor(GridBagConstraints.LINE_START)); } else { java.util.List<LanguageHighlightLevel> levels = controller.getHighlightLevels(); if (levels.size() == 1) { DropDownLink<?> link = createDropDownLink(levels.get(0), controller, EditorBundle.message("iw.highlight.label") + " "); levelLinks.add(link); panel.add(link, gc.next()); } else if (levels.size() > 1) { for(LanguageHighlightLevel level: levels) { DropDownLink<?> link = createDropDownLink(level, controller, level.getLangID() + ": "); levelLinks.add(link); panel.add(link, gc.next().anchor(GridBagConstraints.LINE_START).gridx > 0 ? gc.insetLeft(8) : gc); } } } panel.add(Box.createHorizontalGlue(), gc.next().fillCellHorizontally().weightx(1.0)); controller.fillHectorPanels(panel, gc); panel.setOpaque(true); panel.setBackground(UIUtil.getToolTipActionBackground()); panel.setBorder(JBUI.Borders.empty(4, 10)); return panel; } private @NotNull DropDownLink<InspectionsLevel> createDropDownLink(@NotNull LanguageHighlightLevel level, @NotNull UIController controller, @NotNull @Nls String prefix) { return new DropDownLink<>(level.getLevel(), controller.getAvailableLevels(), inspectionsLevel -> { controller.setHighLightLevel(level.copy(level.getLangID(), inspectionsLevel)); myContent.revalidate(); Dimension size = myContent.getPreferredSize(); size.width = Math.max(size.width, JBUIScale.scale(296)); myPopup.setSize(size); // Update statistics FeatureUsageData data = new FeatureUsageData(). addProject(myEditor.getProject()). addLanguage(level.getLangID()). addData("level", inspectionsLevel.name()); FUCounterUsageLogger.getInstance().logEvent("inspection.widget", "highlight.level.changed", data); }, true) { @NotNull @Override protected String itemToString(InspectionsLevel item) { return prefix + item.toString(); } }; } private static final class MenuAction extends DefaultActionGroup implements HintManagerImpl.ActionToIgnore { private MenuAction(@NotNull List<? extends AnAction> actions, @NotNull AnAction compactViewAction) { setPopup(true); addAll(actions); add(compactViewAction); } } private static final class TrackableLinkLabel extends LinkLabel<Object> { private InputEvent myEvent; private TrackableLinkLabel(@NotNull @NlsContexts.LinkLabel String text, @NotNull Runnable action) { super(text, null); setListener((__, ___) -> { action.run(); ActionsCollector.getInstance().record(null, myEvent, getClass()); }, null); } @Override public void doClick(InputEvent e) { myEvent = e; super.doClick(e); } } }
package com.github.juanmf.java2plant; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.net.URL; import java.net.URLClassLoader; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import com.github.juanmf.java2plant.util.TypesHelper; import org.reflections.Reflections; import org.reflections.scanners.ResourcesScanner; import org.reflections.scanners.SubTypesScanner; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; import org.reflections.util.FilterBuilder; import com.github.juanmf.java2plant.render.PlantRenderer; import com.github.juanmf.java2plant.render.filters.Filter; import com.github.juanmf.java2plant.structure.Aggregation; import com.github.juanmf.java2plant.structure.Extension; import com.github.juanmf.java2plant.structure.Relation; import com.github.juanmf.java2plant.structure.Use; public class Parser { public static ClassLoader CLASS_LOADER = null; /** * Parse the given package recursively, then iterates over found types to fetch their relations. * * @param packageToPase The root package to be parsed. * * @return PlantUML src code of a Collaboration Diagram for the types found in package and all * related Types. */ public static String parse(String packageToPase, Filter<Class<? extends Relation>> relationTypeFilter, Filter<Class<?>> classesFilter, Filter<Relation> relationsFilter) throws ClassNotFoundException { List<ClassLoader> classLoadersList = new LinkedList<>(); return parse(packageToPase, relationTypeFilter, classesFilter, classLoadersList, relationsFilter); } public static String parse(String packageToPase, Filter<Class<? extends Relation>> relationTypeFilter, Filter<Class<?>> classesFilter, ClassLoader classLoader, Filter<Relation> relationsFilter) { List<ClassLoader> classLoadersList = new LinkedList<>(); classLoadersList.add(classLoader); return parse(packageToPase, relationTypeFilter, classesFilter, classLoadersList, relationsFilter); } public static String parse(String packageToPase, Filter<Class<? extends Relation>> relationTypeFilter, Filter<Class<?>> classesFilter, List<ClassLoader> classLoadersList, Filter<Relation> relationsFilter) { Set<Relation> relations = new HashSet<Relation>(); Set<Class<?>> classes = getTypes(packageToPase, classLoadersList); for (Class<?> aClass : classes) { addFromTypeRelations(relations, aClass); } return new PlantRenderer(classes, relations, relationTypeFilter, classesFilter, relationsFilter).render(); } private static Set<Class<?>> getTypes(String packageToPase, List<ClassLoader> classLoadersList) { classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); Collection<URL> urls = ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0])); CLASS_LOADER = new URLClassLoader(urls.toArray(new URL[0])); Reflections reflections = new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false /* exclude Object.class */), new ResourcesScanner()) .setUrls(urls) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(packageToPase)))); Set<String> types = reflections.getAllTypes(); Set<Class<?>> classes = new HashSet<>(); for (String type: types) { try { classes.add(Class.forName(type, true, CLASS_LOADER)); } catch (ClassNotFoundException e) { System.out.println("ClassNotFoundException: " + e.getMessage()); continue; } } return classes; } protected static void addFromTypeRelations(Set<Relation> relations, Class<?> fromType) { addImplementations(relations, fromType); addExtensions(relations, fromType); addAggregations(relations, fromType); addUses(relations, fromType); } protected static void addImplementations(Set<Relation> relations, Class<?> fromType) { Class<?>[] interfaces = fromType.getInterfaces(); for (Class<?> i : interfaces) { Relation anImplements = new Extension(fromType, i.getName()); relations.add(anImplements); } } protected static void addExtensions(Set<Relation> relations, Class<?> fromType) { Class<?> superclass = fromType.getSuperclass(); if (null == superclass || Object.class.equals(superclass)) { return; } Relation extension = new Extension(fromType, superclass.getName()); relations.add(extension); } protected static void addAggregations(Set<Relation> relations, Class<?> fromType) { Field[] declaredFields = fromType.getDeclaredFields(); for (Field f : declaredFields) { if (! Modifier.isPrivate(f.getModifiers())) { addAggregation(relations, fromType, f); } } } protected static void addUses(Set<Relation> relations, Class<?> fromType) { Method[] methods = fromType.getDeclaredMethods(); for (Method m: methods) { if (! Modifier.isPrivate(m.getModifiers())) { addMethodUses(relations, fromType, m); } } Constructor<?>[] constructors = fromType.getDeclaredConstructors(); for (Constructor<?> c: constructors) { if (! Modifier.isPrivate(c.getModifiers())) { addConstructorUses(relations, fromType, c); } } } protected static void addConstructorUses(Set<Relation> relations, Class<?> fromType, Constructor<?> c) { Type[] genericParameterTypes = c.getGenericParameterTypes(); for(int i = 0; i < genericParameterTypes.length; i++) { addConstructorUse(relations, fromType, genericParameterTypes[i], c); } } protected static void addMethodUses(Set<Relation> relations, Class<?> fromType, Method m) { Type[] genericParameterTypes = m.getGenericParameterTypes(); for(int i = 0; i < genericParameterTypes.length; i++) { addMethodUse(relations, fromType, genericParameterTypes[i], m); } } protected static void addConstructorUse(Set<Relation> relations, Class<?> fromType, Type toType, Constructor<?> c) { String name = TypesHelper.getSimpleName(c.getName()) + "()"; addUse(relations, fromType, toType, c, name); } protected static void addUse(Set<Relation> relations, Class<?> fromType, Type toType, Member m, String msg) { // String toName = toType.getName(); String toName = toType.toString(); if (isMulti(toType)) { if (! ((Class) toType).isArray()) { if (toType instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) toType; Set<String> typeVars = getTypeParams(pt); for (String t : typeVars) { msg += toName; Relation use = new Use(fromType, t, m, msg); relations.add(use); } return; } } toName = ((Class) toType).getCanonicalName().replace("[]", ""); msg += ": []"; } Relation use = new Use(fromType, toName, m, msg); relations.add(use); } protected static void addMethodUse(Set<Relation> relations, Class<?> fromType, Type fromParameterType, Method m) { String name = TypesHelper.getSimpleName(m.getName()) + "()"; addUse(relations, fromType, fromParameterType, m, name); } protected static boolean isMulti(Type delegateType) { return (delegateType instanceof Class) && (((Class) delegateType).isArray() || Collection.class.isAssignableFrom((Class) delegateType) || Map.class.isAssignableFrom((Class) delegateType)); } protected static void addAggregation(Set<Relation> relations, Class<?> fromType, Field f) { Class<?> delegateType = f.getType(); String varName = f.getName(); String toCardinal = "1"; String toName = delegateType.getName(); if (isMulti(delegateType)) { toCardinal = "*"; if (! delegateType.isArray()) { Set<String> typeVars = getTypeParams(f); for (String type : typeVars) { Relation aggregation = new Aggregation( fromType, type, f, toCardinal, varName + ": " + delegateType.getName()); relations.add(aggregation); } return; } toName = delegateType.getCanonicalName().replace("[]", ""); } Relation aggregation = new Aggregation(fromType, toName, f, toCardinal, varName); relations.add(aggregation); } protected static Set<String> getTypeParams(Field f) { Type tp = f.getGenericType(); if (tp instanceof ParameterizedType) { Set<String> typeVars = getTypeParams((ParameterizedType) tp); return typeVars; } return Collections.emptySet(); } protected static Set<String> getTypeParams(ParameterizedType f) { Set<String> typeVars = new HashSet<>(); Type[] actualTypeArguments = f.getActualTypeArguments(); for (Type t: actualTypeArguments) { typeVars.add(t.toString().replace("class ", "")); } return typeVars; } }
package com.intellij.openapi.fileTypes.impl; import com.google.common.annotations.VisibleForTesting; import com.intellij.diagnostic.PluginException; import com.intellij.ide.highlighter.custom.SyntaxTable; import com.intellij.ide.plugins.PluginManagerCore; import com.intellij.ide.plugins.StartupAbortedException; import com.intellij.ide.util.PropertiesComponent; import com.intellij.lang.Language; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.ExtensionPointListener; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.extensions.PluginDescriptor; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.fileEditor.impl.LoadTextUtil; import com.intellij.openapi.fileTypes.*; import com.intellij.openapi.fileTypes.ex.ExternalizableFileType; import com.intellij.openapi.fileTypes.ex.FileTypeChooser; import com.intellij.openapi.fileTypes.ex.FileTypeIdentifiableByVirtualFile; import com.intellij.openapi.fileTypes.ex.FileTypeManagerEx; import com.intellij.openapi.options.NonLazySchemeProcessor; import com.intellij.openapi.options.SchemeManager; import com.intellij.openapi.options.SchemeManagerFactory; import com.intellij.openapi.options.SchemeState; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.ByteArraySequence; import com.intellij.openapi.util.io.ByteSequence; 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.util.text.StringUtilRt; import com.intellij.openapi.vfs.VFileProperty; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.VirtualFileWithId; import com.intellij.openapi.vfs.newvfs.BulkFileListener; import com.intellij.openapi.vfs.newvfs.FileAttribute; import com.intellij.openapi.vfs.newvfs.FileSystemInterface; import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent; import com.intellij.openapi.vfs.newvfs.events.VFileEvent; import com.intellij.openapi.vfs.newvfs.impl.StubVirtualFile; import com.intellij.testFramework.LightVirtualFile; import com.intellij.ui.GuiUtils; import com.intellij.util.*; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.concurrency.BoundedTaskExecutor; import com.intellij.util.concurrency.EdtExecutorService; import com.intellij.util.containers.ConcurrentPackedBitsArray; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.HashSetQueue; import com.intellij.util.io.URLUtil; import com.intellij.util.messages.MessageBus; import com.intellij.util.messages.MessageBusConnection; import gnu.trove.THashMap; import gnu.trove.THashSet; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import org.jetbrains.ide.PooledThreadExecutor; import org.jetbrains.jps.model.fileTypes.FileNameMatcherFactory; import java.io.*; import java.lang.reflect.Field; import java.net.URL; import java.nio.channels.FileChannel; import java.util.*; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.StreamSupport; @State(name = "FileTypeManager", storages = @Storage("filetypes.xml"), additionalExportFile = FileTypeManagerImpl.FILE_SPEC ) public class FileTypeManagerImpl extends FileTypeManagerEx implements PersistentStateComponent<Element>, Disposable { private static final ExtensionPointName<FileTypeBean> EP_NAME = ExtensionPointName.create("com.intellij.fileType"); private static final Logger LOG = Logger.getInstance(FileTypeManagerImpl.class); // You must update all existing default configurations accordingly private static final int VERSION = 17; private static final ThreadLocal<Pair<VirtualFile, FileType>> FILE_TYPE_FIXED_TEMPORARILY = new ThreadLocal<>(); // cached auto-detected file type. If the file was auto-detected as plain text or binary // then the value is null and AUTO_DETECTED_* flags stored in packedFlags are used instead. static final Key<FileType> DETECTED_FROM_CONTENT_FILE_TYPE_KEY = Key.create("DETECTED_FROM_CONTENT_FILE_TYPE_KEY"); // must be sorted @SuppressWarnings("SpellCheckingInspection") static final String DEFAULT_IGNORED = "*.hprof;*.pyc;*.pyo;*.rbc;*.yarb;*~;.DS_Store;.git;.hg;.svn;CVS;__pycache__;_svn;vssver.scc;vssver2.scc;"; private static boolean RE_DETECT_ASYNC = !ApplicationManager.getApplication().isUnitTestMode(); private final Set<FileType> myDefaultTypes = new THashSet<>(); private FileTypeIdentifiableByVirtualFile[] mySpecialFileTypes = FileTypeIdentifiableByVirtualFile.EMPTY_ARRAY; private FileTypeAssocTable<FileType> myPatternsTable = new FileTypeAssocTable<>(); private final IgnoredPatternSet myIgnoredPatterns = new IgnoredPatternSet(); private final IgnoredFileCache myIgnoredFileCache = new IgnoredFileCache(myIgnoredPatterns); private final FileTypeAssocTable<FileType> myInitialAssociations = new FileTypeAssocTable<>(); private final Map<FileNameMatcher, String> myUnresolvedMappings = new THashMap<>(); private final RemovedMappingTracker myRemovedMappingTracker = new RemovedMappingTracker(); private final Map<String, FileTypeBean> myPendingFileTypes = new HashMap<>(); private final FileTypeAssocTable<FileTypeBean> myPendingAssociations = new FileTypeAssocTable<>(); @NonNls private static final String ELEMENT_FILETYPE = "filetype"; @NonNls private static final String ELEMENT_IGNORE_FILES = "ignoreFiles"; @NonNls private static final String ATTRIBUTE_LIST = "list"; @NonNls private static final String ATTRIBUTE_VERSION = "version"; @NonNls private static final String ATTRIBUTE_NAME = "name"; @NonNls private static final String ATTRIBUTE_DESCRIPTION = "description"; private static class StandardFileType { @NotNull private final FileType fileType; @NotNull private final List<FileNameMatcher> matchers; private StandardFileType(@NotNull FileType fileType, @NotNull List<FileNameMatcher> matchers) { this.fileType = fileType; this.matchers = matchers; } } private final MessageBus myMessageBus; private final Map<String, StandardFileType> myStandardFileTypes = new LinkedHashMap<>(); @NonNls private static final String[] FILE_TYPES_WITH_PREDEFINED_EXTENSIONS = {"JSP", "JSPX", "DTD", "HTML", "Properties", "XHTML"}; private final SchemeManager<FileType> mySchemeManager; @NonNls static final String FILE_SPEC = "filetypes"; // these flags are stored in 'packedFlags' as chunks of four bits private static final byte AUTO_DETECTED_AS_TEXT_MASK = 1; // set if the file was auto-detected as text private static final byte AUTO_DETECTED_AS_BINARY_MASK = 1<<1; // set if the file was auto-detected as binary // set if auto-detection was performed for this file. // if some detector returned some custom file type, it's stored in DETECTED_FROM_CONTENT_FILE_TYPE_KEY file key. // otherwise if auto-detected as text or binary, the result is stored in AUTO_DETECTED_AS_TEXT_MASK|AUTO_DETECTED_AS_BINARY_MASK bits private static final byte AUTO_DETECT_WAS_RUN_MASK = 1<<2; private static final byte ATTRIBUTES_WERE_LOADED_MASK = 1<<3; // set if AUTO_* bits above were loaded from the file persistent attributes and saved to packedFlags private final ConcurrentPackedBitsArray packedFlags = new ConcurrentPackedBitsArray(4); private final AtomicInteger counterAutoDetect = new AtomicInteger(); private final AtomicLong elapsedAutoDetect = new AtomicLong(); private final Object PENDING_INIT_LOCK = new Object(); private MultiValuesMap<FileType, FileTypeDetector> myFileTypeDetectorMap; private final List<FileTypeDetector> myUntypedFileTypeDetectors = new ArrayList<>(); private final Object FILE_TYPE_DETECTOR_MAP_LOCK = new Object(); public FileTypeManagerImpl() { int fileTypeChangedCounter = PropertiesComponent.getInstance().getInt("fileTypeChangedCounter", 0); fileTypeChangedCount = new AtomicInteger(fileTypeChangedCounter); autoDetectedAttribute = new FileAttribute("AUTO_DETECTION_CACHE_ATTRIBUTE", fileTypeChangedCounter, true); myMessageBus = ApplicationManager.getApplication().getMessageBus(); mySchemeManager = SchemeManagerFactory.getInstance().create(FILE_SPEC, new NonLazySchemeProcessor<FileType, AbstractFileType>() { @NotNull @Override public AbstractFileType readScheme(@NotNull Element element, boolean duringLoad) { if (!duringLoad) { fireBeforeFileTypesChanged(); } AbstractFileType type = (AbstractFileType)loadFileType(element, false); if (!duringLoad) { fireFileTypesChanged(type, null); } return type; } @NotNull @Override public SchemeState getState(@NotNull FileType fileType) { if (!(fileType instanceof AbstractFileType) || !shouldSave(fileType)) { return SchemeState.NON_PERSISTENT; } if (!myDefaultTypes.contains(fileType)) { return SchemeState.POSSIBLY_CHANGED; } return ((AbstractFileType)fileType).isModified() ? SchemeState.POSSIBLY_CHANGED : SchemeState.NON_PERSISTENT; } @NotNull @Override public Element writeScheme(@NotNull AbstractFileType fileType) { Element root = new Element(ELEMENT_FILETYPE); root.setAttribute("binary", String.valueOf(fileType.isBinary())); if (!StringUtil.isEmpty(fileType.getDefaultExtension())) { root.setAttribute("default_extension", fileType.getDefaultExtension()); } root.setAttribute(ATTRIBUTE_DESCRIPTION, fileType.getDescription()); root.setAttribute(ATTRIBUTE_NAME, fileType.getName()); fileType.writeExternal(root); Element map = new Element(AbstractFileType.ELEMENT_EXTENSION_MAP); writeExtensionsMap(map, fileType, false); if (!map.getChildren().isEmpty()) { root.addContent(map); } return root; } @Override public void onSchemeDeleted(@NotNull AbstractFileType scheme) { GuiUtils.invokeLaterIfNeeded(() -> { Application app = ApplicationManager.getApplication(); app.runWriteAction(() -> fireBeforeFileTypesChanged()); myPatternsTable.removeAllAssociations(scheme); app.runWriteAction(() -> fireFileTypesChanged(null, scheme)); }, ModalityState.NON_MODAL); } }); // this should be done BEFORE reading state initStandardFileTypes(); myMessageBus.connect(this).subscribe(VirtualFileManager.VFS_CHANGES, new BulkFileListener() { @Override public void after(@NotNull List<? extends VFileEvent> events) { Collection<VirtualFile> files = ContainerUtil.map2Set(events, (Function<VFileEvent, VirtualFile>)event -> { VirtualFile file = event instanceof VFileCreateEvent ? /* avoid expensive find child here */ null : event.getFile(); VirtualFile filtered = file != null && wasAutoDetectedBefore(file) && isDetectable(file) ? file : null; if (toLog()) { log("F: after() VFS event " + event + "; filtered file: " + filtered + " (file: " + file + "; wasAutoDetectedBefore(file): " + (file == null ? null : wasAutoDetectedBefore(file)) + "; isDetectable(file): " + (file == null ? null : isDetectable(file)) + "; file.getLength(): " + (file == null ? null : file.getLength()) + "; file.isValid(): " + (file == null ? null : file.isValid()) + "; file.is(VFileProperty.SPECIAL): " + (file == null ? null : file.is(VFileProperty.SPECIAL)) + "; packedFlags.get(id): " + (file instanceof VirtualFileWithId ? readableFlags(packedFlags.get(((VirtualFileWithId)file).getId())) : null) + "; file.getFileSystem():" + (file == null ? null : file.getFileSystem()) + ")"); } return filtered; }); files.remove(null); if (toLog()) { log("F: after() VFS events: " + events+"; files: "+files); } if (!files.isEmpty() && RE_DETECT_ASYNC) { if (toLog()) { log("F: after() queued to redetect: " + files); } synchronized (filesToRedetect) { if (filesToRedetect.addAll(files)) { awakeReDetectExecutor(); } } } } }); myIgnoredPatterns.setIgnoreMasks(DEFAULT_IGNORED); FileTypeDetector.EP_NAME.addExtensionPointListener(new ExtensionPointListener<FileTypeDetector>() { @Override public void extensionAdded(@NotNull FileTypeDetector extension, @NotNull PluginDescriptor pluginDescriptor) { synchronized (FILE_TYPE_DETECTOR_MAP_LOCK) { myFileTypeDetectorMap = null; } } @Override public void extensionRemoved(@NotNull FileTypeDetector extension, @NotNull PluginDescriptor pluginDescriptor) { synchronized (FILE_TYPE_DETECTOR_MAP_LOCK) { myFileTypeDetectorMap = null; } } }, this); EP_NAME.addExtensionPointListener(new ExtensionPointListener<FileTypeBean>() { @Override public void extensionAdded(@NotNull FileTypeBean extension, @NotNull PluginDescriptor pluginDescriptor) { fireBeforeFileTypesChanged(); initializeMatchers(extension); FileType fileType = instantiateFileTypeBean(extension); fireFileTypesChanged(fileType, null); } @Override public void extensionRemoved(@NotNull FileTypeBean extension, @NotNull PluginDescriptor pluginDescriptor) { final FileType fileType = findFileTypeByName(extension.name); unregisterFileType(fileType); if (fileType instanceof LanguageFileType) { final LanguageFileType languageFileType = (LanguageFileType)fileType; if (!languageFileType.isSecondary()) { Language.unregisterLanguage(languageFileType.getLanguage()); } } } }, this); } @VisibleForTesting void initStandardFileTypes() { loadFileTypeBeans(); FileTypeConsumer consumer = new FileTypeConsumer() { @Override public void consume(@NotNull FileType fileType) { register(fileType, parse(fileType.getDefaultExtension())); } @Override public void consume(@NotNull final FileType fileType, String extensions) { register(fileType, parse(extensions)); } @Override public void consume(@NotNull final FileType fileType, @NotNull final FileNameMatcher... matchers) { register(fileType, new ArrayList<>(Arrays.asList(matchers))); } @Override public FileType getStandardFileTypeByName(@NotNull final String name) { final StandardFileType type = myStandardFileTypes.get(name); return type != null ? type.fileType : null; } private void register(@NotNull FileType fileType, @NotNull List<FileNameMatcher> fileNameMatchers) { instantiatePendingFileTypeByName(fileType.getName()); for (FileNameMatcher matcher : fileNameMatchers) { FileTypeBean pendingTypeByMatcher = myPendingAssociations.findAssociatedFileType(matcher); if (pendingTypeByMatcher != null) { PluginId id = pendingTypeByMatcher.getPluginId(); if (id == null || id.getIdString().equals(PluginManagerCore.CORE_PLUGIN_ID)) { instantiateFileTypeBean(pendingTypeByMatcher); } } } final StandardFileType type = myStandardFileTypes.get(fileType.getName()); if (type != null) { type.matchers.addAll(fileNameMatchers); } else { myStandardFileTypes.put(fileType.getName(), new StandardFileType(fileType, fileNameMatchers)); } } }; //noinspection deprecation FileTypeFactory.FILE_TYPE_FACTORY_EP.processWithPluginDescriptor((factory, pluginDescriptor) -> { try { factory.createFileTypes(consumer); } catch (ProcessCanceledException e) { throw e; } catch (StartupAbortedException e) { throw e; } catch (Throwable e) { throw new StartupAbortedException("Cannot create file types", new PluginException(e, pluginDescriptor.getPluginId())); } }); for (StandardFileType pair : myStandardFileTypes.values()) { registerFileTypeWithoutNotification(pair.fileType, pair.matchers, true); } try { URL defaultFileTypesUrl = FileTypeManagerImpl.class.getResource("/defaultFileTypes.xml"); if (defaultFileTypesUrl != null) { Element defaultFileTypesElement = JDOMUtil.load(URLUtil.openStream(defaultFileTypesUrl)); for (Element e : defaultFileTypesElement.getChildren()) { if ("filetypes".equals(e.getName())) { for (Element element : e.getChildren(ELEMENT_FILETYPE)) { String fileTypeName = element.getAttributeValue(ATTRIBUTE_NAME); if (myPendingFileTypes.get(fileTypeName) != null) continue; loadFileType(element, true); } } else if (AbstractFileType.ELEMENT_EXTENSION_MAP.equals(e.getName())) { readGlobalMappings(e, true); } } if (PlatformUtils.isIdeaCommunity()) { Element extensionMap = new Element(AbstractFileType.ELEMENT_EXTENSION_MAP); extensionMap.addContent(new Element(AbstractFileType.ELEMENT_MAPPING) .setAttribute(AbstractFileType.ATTRIBUTE_EXT, "jspx") .setAttribute(AbstractFileType.ATTRIBUTE_TYPE, "XML")); //noinspection SpellCheckingInspection extensionMap.addContent(new Element(AbstractFileType.ELEMENT_MAPPING) .setAttribute(AbstractFileType.ATTRIBUTE_EXT, "tagx") .setAttribute(AbstractFileType.ATTRIBUTE_TYPE, "XML")); readGlobalMappings(extensionMap, true); } } } catch (Exception e) { LOG.error(e); } } private void loadFileTypeBeans() { final List<FileTypeBean> fileTypeBeans = EP_NAME.getExtensionList(); for (FileTypeBean bean : fileTypeBeans) { initializeMatchers(bean); } for (FileTypeBean bean : fileTypeBeans) { if (bean.implementationClass == null) continue; if (myPendingFileTypes.containsKey(bean.name)) { LOG.error(new PluginException("Trying to override already registered file type " + bean.name, bean.getPluginId())); continue; } myPendingFileTypes.put(bean.name, bean); for (FileNameMatcher matcher : bean.getMatchers()) { myPendingAssociations.addAssociation(matcher, bean); } } // Register additional extensions for file types for (FileTypeBean bean : fileTypeBeans) { if (bean.implementationClass != null) continue; FileTypeBean oldBean = myPendingFileTypes.get(bean.name); if (oldBean == null) { LOG.error(new PluginException("Trying to add extensions to non-registered file type " + bean.name, bean.getPluginId())); continue; } oldBean.addMatchers(bean.getMatchers()); for (FileNameMatcher matcher : bean.getMatchers()) { myPendingAssociations.addAssociation(matcher, oldBean); } } } private static void initializeMatchers(FileTypeBean bean) { bean.addMatchers(ContainerUtil.concat( parse(bean.extensions), parse(bean.fileNames, token -> new ExactFileNameMatcher(token)), parse(bean.fileNamesCaseInsensitive, token -> new ExactFileNameMatcher(token, true)), parse(bean.patterns, token -> FileNameMatcherFactory.getInstance().createMatcher(token)))); } private void instantiatePendingFileTypes() { final Collection<FileTypeBean> fileTypes = new ArrayList<>(myPendingFileTypes.values()); for (FileTypeBean fileTypeBean : fileTypes) { final StandardFileType type = myStandardFileTypes.get(fileTypeBean.name); if (type != null) { type.matchers.addAll(fileTypeBean.getMatchers()); } else { instantiateFileTypeBean(fileTypeBean); } } } private FileType instantiateFileTypeBean(@NotNull FileTypeBean fileTypeBean) { FileType fileType; PluginId pluginId = fileTypeBean.getPluginDescriptor().getPluginId(); try { @SuppressWarnings("unchecked") Class<FileType> beanClass = (Class<FileType>)Class.forName(fileTypeBean.implementationClass, true, fileTypeBean.getPluginDescriptor().getPluginClassLoader()); if (fileTypeBean.fieldName != null) { Field field = beanClass.getDeclaredField(fileTypeBean.fieldName); field.setAccessible(true); fileType = (FileType)field.get(null); } else { // uncached - cached by FileTypeManagerImpl and not by bean fileType = ReflectionUtil.newInstance(beanClass, false); } } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) { LOG.error(new PluginException(e, pluginId)); return null; } if (!fileType.getName().equals(fileTypeBean.name)) { LOG.error(new PluginException("Incorrect name specified in <fileType>, should be " + fileType.getName() + ", actual " + fileTypeBean.name, pluginId)); } if (fileType instanceof LanguageFileType) { final LanguageFileType languageFileType = (LanguageFileType)fileType; String expectedLanguage = languageFileType.isSecondary() ? null : languageFileType.getLanguage().getID(); if (!Comparing.equal(fileTypeBean.language, expectedLanguage)) { LOG.error(new PluginException("Incorrect language specified in <fileType> for " + fileType.getName() + ", should be " + expectedLanguage + ", actual " + fileTypeBean.language, pluginId)); } } final StandardFileType standardFileType = new StandardFileType(fileType, fileTypeBean.getMatchers()); myStandardFileTypes.put(fileTypeBean.name, standardFileType); registerFileTypeWithoutNotification(standardFileType.fileType, standardFileType.matchers, true); myPendingAssociations.removeAllAssociations(fileTypeBean); myPendingFileTypes.remove(fileTypeBean.name); return fileType; } @TestOnly boolean toLog; private boolean toLog() { return toLog; } private static void log(String message) { LOG.debug(message + " - "+Thread.currentThread()); } private final Executor reDetectExecutor = AppExecutorUtil.createBoundedApplicationPoolExecutor("FileTypeManager Redetect Pool", PooledThreadExecutor.INSTANCE, 1, this); private final HashSetQueue<VirtualFile> filesToRedetect = new HashSetQueue<>(); private static final int CHUNK_SIZE = 10; private void awakeReDetectExecutor() { reDetectExecutor.execute(() -> { List<VirtualFile> files = new ArrayList<>(CHUNK_SIZE); synchronized (filesToRedetect) { for (int i = 0; i < CHUNK_SIZE; i++) { VirtualFile file = filesToRedetect.poll(); if (file == null) break; files.add(file); } } if (files.size() == CHUNK_SIZE) { awakeReDetectExecutor(); } reDetect(files); }); } @TestOnly public void drainReDetectQueue() { try { ((BoundedTaskExecutor)reDetectExecutor).waitAllTasksExecuted(1, TimeUnit.MINUTES); } catch (Exception e) { throw new RuntimeException(e); } } @TestOnly @NotNull Collection<VirtualFile> dumpReDetectQueue() { synchronized (filesToRedetect) { return new ArrayList<>(filesToRedetect); } } @TestOnly static void reDetectAsync(boolean enable) { RE_DETECT_ASYNC = enable; } private void reDetect(@NotNull Collection<? extends VirtualFile> files) { List<VirtualFile> changed = new ArrayList<>(); List<VirtualFile> crashed = new ArrayList<>(); for (VirtualFile file : files) { boolean shouldRedetect = wasAutoDetectedBefore(file) && isDetectable(file); if (toLog()) { log("F: reDetect("+file.getName()+") " + file.getName() + "; shouldRedetect: " + shouldRedetect); } if (shouldRedetect) { int id = ((VirtualFileWithId)file).getId(); long flags = packedFlags.get(id); FileType before = ObjectUtils.notNull(textOrBinaryFromCachedFlags(flags), ObjectUtils.notNull(file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY), PlainTextFileType.INSTANCE)); FileType after = getByFile(file); if (toLog()) { log("F: reDetect(" + file.getName() + ") prepare to redetect. flags: " + readableFlags(flags) + "; beforeType: " + before.getName() + "; afterByFileType: " + (after == null ? null : after.getName())); } if (after == null || mightBeReplacedByDetectedFileType(after)) { try { after = detectFromContentAndCache(file, null); } catch (IOException e) { crashed.add(file); if (toLog()) { log("F: reDetect(" + file.getName() + ") " + "before: " + before.getName() + "; after: crashed with " + e.getMessage() + "; now getFileType()=" + file.getFileType().getName() + "; getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY): " + file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY)); } continue; } } else { // back to standard file type // detected by conventional methods, no need to run detect-from-content file.putUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY, null); flags = 0; packedFlags.set(id, flags); } if (toLog()) { log("F: reDetect(" + file.getName() + ") " + "before: " + before.getName() + "; after: " + after.getName() + "; now getFileType()=" + file.getFileType().getName() + "; getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY): " + file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY)); } if (before != after) { changed.add(file); } } } if (!changed.isEmpty()) { ApplicationManager.getApplication().invokeLater(() -> FileContentUtilCore.reparseFiles(changed), ApplicationManager.getApplication().getDisposed()); } if (!crashed.isEmpty()) { // do not re-scan locked or invalid files too often to avoid constant disk thrashing if that condition is permanent EdtExecutorService.getScheduledExecutorInstance().schedule(() -> FileContentUtilCore.reparseFiles(crashed), 10, TimeUnit.SECONDS); } } private boolean wasAutoDetectedBefore(@NotNull VirtualFile file) { if (file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY) != null) { return true; } if (file instanceof VirtualFileWithId) { int id = ((VirtualFileWithId)file).getId(); // do not re-detect binary files return (packedFlags.get(id) & (AUTO_DETECT_WAS_RUN_MASK | AUTO_DETECTED_AS_BINARY_MASK)) == AUTO_DETECT_WAS_RUN_MASK; } return false; } @Override @NotNull public FileType getStdFileType(@NotNull @NonNls String name) { StandardFileType stdFileType; synchronized (PENDING_INIT_LOCK) { instantiatePendingFileTypeByName(name); stdFileType = myStandardFileTypes.get(name); } return stdFileType != null ? stdFileType.fileType : PlainTextFileType.INSTANCE; } private void instantiatePendingFileTypeByName(@NonNls @NotNull String name) { final FileTypeBean bean = myPendingFileTypes.get(name); if (bean != null) { instantiateFileTypeBean(bean); } } @Override public void initializeComponent() { if (!myUnresolvedMappings.isEmpty()) { instantiatePendingFileTypes(); } if (!myUnresolvedMappings.isEmpty()) { for (StandardFileType pair : myStandardFileTypes.values()) { registerReDetectedMappings(pair); } } // resolve unresolved mappings initialized before certain plugin initialized if (!myUnresolvedMappings.isEmpty()) { for (StandardFileType pair : myStandardFileTypes.values()) { bindUnresolvedMappings(pair.fileType); } } boolean isAtLeastOneStandardFileTypeHasBeenRead = false; for (FileType fileType : mySchemeManager.loadSchemes()) { isAtLeastOneStandardFileTypeHasBeenRead |= myInitialAssociations.hasAssociationsFor(fileType); } if (isAtLeastOneStandardFileTypeHasBeenRead) { restoreStandardFileExtensions(); } } @Override @NotNull public FileType getFileTypeByFileName(@NotNull String fileName) { return getFileTypeByFileName((CharSequence)fileName); } @Override @NotNull public FileType getFileTypeByFileName(@NotNull CharSequence fileName) { synchronized (PENDING_INIT_LOCK) { final FileTypeBean pendingFileType = myPendingAssociations.findAssociatedFileType(fileName); if (pendingFileType != null) { return ObjectUtils.notNull(instantiateFileTypeBean(pendingFileType), UnknownFileType.INSTANCE); } FileType type = myPatternsTable.findAssociatedFileType(fileName); return ObjectUtils.notNull(type, UnknownFileType.INSTANCE); } } public void freezeFileTypeTemporarilyIn(@NotNull VirtualFile file, @NotNull Runnable runnable) { FileType fileType = file.getFileType(); Pair<VirtualFile, FileType> old = FILE_TYPE_FIXED_TEMPORARILY.get(); FILE_TYPE_FIXED_TEMPORARILY.set(Pair.create(file, fileType)); if (toLog()) { log("F: freezeFileTypeTemporarilyIn(" + file.getName() + ") to " + fileType.getName()+" in "+Thread.currentThread()); } try { runnable.run(); } finally { if (old == null) { FILE_TYPE_FIXED_TEMPORARILY.remove(); } else { FILE_TYPE_FIXED_TEMPORARILY.set(old); } if (toLog()) { log("F: unfreezeFileType(" + file.getName() + ") in "+Thread.currentThread()); } } } @Override @NotNull public FileType getFileTypeByFile(@NotNull VirtualFile file) { return getFileTypeByFile(file, null); } @Override @NotNull public FileType getFileTypeByFile(@NotNull VirtualFile file, @Nullable byte[] content) { FileType overriddenFileType = FileTypeOverrider.EP_NAME.computeSafeIfAny((overrider) -> overrider.getOverriddenFileType(file)); if (overriddenFileType != null) { return overriddenFileType; } FileType fileType = getByFile(file); if (!(file instanceof StubVirtualFile)) { if (fileType == null) { return getOrDetectFromContent(file, content); } if (mightBeReplacedByDetectedFileType(fileType)) { FileType detectedFromContent = getOrDetectFromContent(file, content); if (detectedFromContent != UnknownFileType.INSTANCE && detectedFromContent != PlainTextFileType.INSTANCE) { return detectedFromContent; } } } return ObjectUtils.notNull(fileType, UnknownFileType.INSTANCE); } private static boolean mightBeReplacedByDetectedFileType(FileType fileType) { return fileType instanceof PlainTextLikeFileType && fileType.isReadOnly(); } @Nullable // null means all conventional detect methods returned UnknownFileType.INSTANCE, have to detect from content public FileType getByFile(@NotNull VirtualFile file) { Pair<VirtualFile, FileType> fixedType = FILE_TYPE_FIXED_TEMPORARILY.get(); if (fixedType != null && fixedType.getFirst().equals(file)) { FileType fileType = fixedType.getSecond(); if (toLog()) { log("F: getByFile(" + file.getName() + ") was frozen to " + fileType.getName()+" in "+Thread.currentThread()); } return fileType; } if (file instanceof LightVirtualFile) { FileType fileType = ((LightVirtualFile)file).getAssignedFileType(); if (fileType != null) { return fileType; } } for (FileTypeIdentifiableByVirtualFile type : mySpecialFileTypes) { if (type.isMyFileType(file)) { if (toLog()) { log("F: getByFile(" + file.getName() + "): Special file type: " + type.getName()); } return type; } } FileType fileType = getFileTypeByFileName(file.getNameSequence()); if (fileType == UnknownFileType.INSTANCE) { fileType = null; } if (toLog()) { log("F: getByFile(" + file.getName() + ") By name file type: "+(fileType == null ? null : fileType.getName())); } return fileType; } @NotNull private FileType getOrDetectFromContent(@NotNull VirtualFile file, @Nullable byte[] content) { if (!isDetectable(file)) return UnknownFileType.INSTANCE; if (file instanceof VirtualFileWithId) { int id = ((VirtualFileWithId)file).getId(); long flags = packedFlags.get(id); if (!BitUtil.isSet(flags, ATTRIBUTES_WERE_LOADED_MASK)) { flags = readFlagsFromCache(file); flags = BitUtil.set(flags, ATTRIBUTES_WERE_LOADED_MASK, true); packedFlags.set(id, flags); if (toLog()) { log("F: getOrDetectFromContent(" + file.getName() + "): readFlagsFromCache() = " + readableFlags(flags)); } } boolean autoDetectWasRun = BitUtil.isSet(flags, AUTO_DETECT_WAS_RUN_MASK); if (autoDetectWasRun) { FileType type = textOrBinaryFromCachedFlags(flags); if (toLog()) { log("F: getOrDetectFromContent("+file.getName()+"):" + " cached type = "+(type==null?null:type.getName())+ "; packedFlags.get(id):"+ readableFlags(flags)+ "; getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY): "+file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY)); } if (type != null) { return type; } } } FileType fileType = file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY); if (toLog()) { log("F: getOrDetectFromContent("+file.getName()+"): " + "getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY) = "+(fileType == null ? null : fileType.getName())); } if (fileType == null) { // run autodetection try { fileType = detectFromContentAndCache(file, content); } catch (IOException e) { fileType = UnknownFileType.INSTANCE; } } if (toLog()) { log("F: getOrDetectFromContent("+file.getName()+"): getFileType after detect run = "+fileType.getName()); } return fileType; } @NotNull private static String readableFlags(long flags) { String result = ""; if (BitUtil.isSet(flags, ATTRIBUTES_WERE_LOADED_MASK)) result += (result.isEmpty() ? "" :" | ") + "ATTRIBUTES_WERE_LOADED_MASK"; if (BitUtil.isSet(flags, AUTO_DETECT_WAS_RUN_MASK)) result += (result.isEmpty() ? "" :" | ") + "AUTO_DETECT_WAS_RUN_MASK"; if (BitUtil.isSet(flags, AUTO_DETECTED_AS_BINARY_MASK)) result += (result.isEmpty() ? "" :" | ") + "AUTO_DETECTED_AS_BINARY_MASK"; if (BitUtil.isSet(flags, AUTO_DETECTED_AS_TEXT_MASK)) result += (result.isEmpty() ? "" :" | ") + "AUTO_DETECTED_AS_TEXT_MASK"; return result; } private volatile FileAttribute autoDetectedAttribute; // read auto-detection flags from the persistent FS file attributes. If file attributes are absent, return 0 for flags // returns three bits value for AUTO_DETECTED_AS_TEXT_MASK, AUTO_DETECTED_AS_BINARY_MASK and AUTO_DETECT_WAS_RUN_MASK bits protected byte readFlagsFromCache(@NotNull VirtualFile file) { boolean wasAutoDetectRun = false; byte status = 0; try (DataInputStream stream = autoDetectedAttribute.readAttribute(file)) { status = stream == null ? 0 : stream.readByte(); wasAutoDetectRun = stream != null; } catch (IOException ignored) { } status = BitUtil.set(status, AUTO_DETECT_WAS_RUN_MASK, wasAutoDetectRun); return (byte)(status & (AUTO_DETECTED_AS_TEXT_MASK | AUTO_DETECTED_AS_BINARY_MASK | AUTO_DETECT_WAS_RUN_MASK)); } // store auto-detection flags to the persistent FS file attributes // writes AUTO_DETECTED_AS_TEXT_MASK, AUTO_DETECTED_AS_BINARY_MASK bits only protected void writeFlagsToCache(@NotNull VirtualFile file, int flags) { try (DataOutputStream stream = autoDetectedAttribute.writeAttribute(file)) { stream.writeByte(flags & (AUTO_DETECTED_AS_TEXT_MASK | AUTO_DETECTED_AS_BINARY_MASK)); } catch (IOException e) { LOG.error(e); } } void clearCaches() { packedFlags.clear(); if (toLog()) { log("F: clearCaches()"); } } private void clearPersistentAttributes() { int count = fileTypeChangedCount.incrementAndGet(); autoDetectedAttribute = autoDetectedAttribute.newVersion(count); PropertiesComponent.getInstance().setValue("fileTypeChangedCounter", Integer.toString(count)); if (toLog()) { log("F: clearPersistentAttributes()"); } } @Nullable //null means the file was not auto-detected as text/binary private static FileType textOrBinaryFromCachedFlags(long flags) { return BitUtil.isSet(flags, AUTO_DETECTED_AS_TEXT_MASK) ? PlainTextFileType.INSTANCE : BitUtil.isSet(flags, AUTO_DETECTED_AS_BINARY_MASK) ? UnknownFileType.INSTANCE : null; } private void cacheAutoDetectedFileType(@NotNull VirtualFile file, @NotNull FileType fileType) { boolean wasAutodetectedAsText = fileType == PlainTextFileType.INSTANCE; boolean wasAutodetectedAsBinary = fileType == UnknownFileType.INSTANCE; int flags = BitUtil.set(0, AUTO_DETECTED_AS_TEXT_MASK, wasAutodetectedAsText); flags = BitUtil.set(flags, AUTO_DETECTED_AS_BINARY_MASK, wasAutodetectedAsBinary); writeFlagsToCache(file, flags); if (file instanceof VirtualFileWithId) { int id = ((VirtualFileWithId)file).getId(); flags = BitUtil.set(flags, AUTO_DETECT_WAS_RUN_MASK, true); flags = BitUtil.set(flags, ATTRIBUTES_WERE_LOADED_MASK, true); packedFlags.set(id, flags); if (wasAutodetectedAsText || wasAutodetectedAsBinary) { file.putUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY, null); if (toLog()) { log("F: cacheAutoDetectedFileType("+file.getName()+") " + "cached to " + fileType.getName() + " flags = "+ readableFlags(flags)+ "; getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY): "+file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY)); } return; } } file.putUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY, fileType); if (toLog()) { log("F: cacheAutoDetectedFileType("+file.getName()+") " + "cached to " + fileType.getName() + " flags = "+ readableFlags(flags)+ "; getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY): "+file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY)); } } @Override public FileType findFileTypeByName(@NotNull String fileTypeName) { FileType type = getStdFileType(fileTypeName); // TODO: Abstract file types are not std one, so need to be restored specially, // currently there are 6 of them and restoration does not happen very often so just iteration is enough if (type == PlainTextFileType.INSTANCE && !fileTypeName.equals(type.getName())) { for (FileType fileType: mySchemeManager.getAllSchemes()) { if (fileTypeName.equals(fileType.getName())) { return fileType; } } } return type; } private static boolean isDetectable(@NotNull final VirtualFile file) { if (file.isDirectory() || !file.isValid() || file.is(VFileProperty.SPECIAL) || file.getLength() == 0) { // for empty file there is still hope its type will change return false; } return file.getFileSystem() instanceof FileSystemInterface; } private int readSafely(@NotNull InputStream stream, @NotNull byte[] buffer, int offset, int length) throws IOException { int n = stream.read(buffer, offset, length); if (n <= 0) { // maybe locked because someone else is writing to it // repeat inside read action to guarantee all writes are finished if (toLog()) { log("F: processFirstBytes(): inputStream.read() returned "+n+"; retrying with read action. stream="+ streamInfo(stream)); } n = ReadAction.compute(() -> stream.read(buffer, offset, length)); if (toLog()) { log("F: processFirstBytes(): under read action inputStream.read() returned "+n+"; stream="+ streamInfo(stream)); } } return n; } @NotNull private FileType detectFromContentAndCache(@NotNull final VirtualFile file, @Nullable byte[] content) throws IOException { long start = System.currentTimeMillis(); FileType fileType = detectFromContent(file, content, FileTypeDetector.EP_NAME.getExtensionList()); cacheAutoDetectedFileType(file, fileType); counterAutoDetect.incrementAndGet(); long elapsed = System.currentTimeMillis() - start; elapsedAutoDetect.addAndGet(elapsed); return fileType; } @NotNull private FileType detectFromContent(@NotNull VirtualFile file, @Nullable byte[] content, @NotNull Iterable<? extends FileTypeDetector> detectors) throws IOException { FileType fileType; if (content != null) { fileType = detect(file, content, content.length, detectors); } else { try (InputStream inputStream = ((FileSystemInterface)file.getFileSystem()).getInputStream(file)) { if (toLog()) { log("F: detectFromContentAndCache(" + file.getName() + "):" + " inputStream=" + streamInfo(inputStream)); } int fileLength = (int)file.getLength(); int bufferLength = StreamSupport.stream(detectors.spliterator(), false) .map(FileTypeDetector::getDesiredContentPrefixLength) .max(Comparator.naturalOrder()) .orElse(FileUtilRt.getUserContentLoadLimit()); byte[] buffer = fileLength <= FileUtilRt.THREAD_LOCAL_BUFFER_LENGTH ? FileUtilRt.getThreadLocalBuffer() : new byte[Math.min(fileLength, bufferLength)]; int n = readSafely(inputStream, buffer, 0, buffer.length); fileType = detect(file, buffer, n, detectors); if (toLog()) { try (InputStream newStream = ((FileSystemInterface)file.getFileSystem()).getInputStream(file)) { byte[] buffer2 = new byte[50]; int n2 = newStream.read(buffer2, 0, buffer2.length); log("F: detectFromContentAndCache(" + file.getName() + "): result: " + fileType.getName() + "; stream: " + streamInfo(inputStream) + "; newStream: " + streamInfo(newStream) + "; read: " + n2 + "; buffer: " + Arrays.toString(buffer2)); } } } } if (LOG.isDebugEnabled()) { LOG.debug(file + "; type=" + fileType.getDescription() + "; " + counterAutoDetect); } return fileType; } @NotNull private FileType detect(@NotNull VirtualFile file, @NotNull byte[] bytes, int length, @NotNull Iterable<? extends FileTypeDetector> detectors) { if (length <= 0) return UnknownFileType.INSTANCE; // use PlainTextFileType because it doesn't supply its own charset detector // help set charset in the process to avoid double charset detection from content return LoadTextUtil.processTextFromBinaryPresentationOrNull(bytes, length, file, true, true, PlainTextFileType.INSTANCE, (@Nullable CharSequence text) -> { if (toLog()) { log("F: detectFromContentAndCache.processFirstBytes(" + file.getName() + "): bytes length=" + length + "; isText=" + (text != null) + "; text='" + (text == null ? null : StringUtil.first(text, 100, true)) + "'" + ", detectors=" + detectors); } FileType detected = null; ByteSequence firstBytes = new ByteArraySequence(bytes, 0, length); for (FileTypeDetector detector : detectors) { try { detected = detector.detect(file, firstBytes, text); } catch (Exception e) { LOG.error("Detector " + detector + " (" + detector.getClass() + ") exception occurred:", e); } if (detected != null) { if (toLog()) { log("F: detectFromContentAndCache.processFirstBytes(" + file.getName() + "): detector " + detector + " type as " + detected.getName()); } break; } } if (detected == null) { detected = text == null ? UnknownFileType.INSTANCE : PlainTextFileType.INSTANCE; if (toLog()) { log("F: detectFromContentAndCache.processFirstBytes(" + file.getName() + "): " + "no detector was able to detect. assigned " + detected.getName()); } } return detected; }); } // for diagnostics @SuppressWarnings("ConstantConditions") private static Object streamInfo(@NotNull InputStream stream) throws IOException { if (stream instanceof BufferedInputStream) { InputStream in = ReflectionUtil.getField(stream.getClass(), stream, InputStream.class, "in"); byte[] buf = ReflectionUtil.getField(stream.getClass(), stream, byte[].class, "buf"); int count = ReflectionUtil.getField(stream.getClass(), stream, int.class, "count"); int pos = ReflectionUtil.getField(stream.getClass(), stream, int.class, "pos"); return "BufferedInputStream(buf=" + (buf == null ? null : Arrays.toString(Arrays.copyOf(buf, count))) + ", count=" + count + ", pos=" + pos + ", in=" + streamInfo(in) + ")"; } if (stream instanceof FileInputStream) { String path = ReflectionUtil.getField(stream.getClass(), stream, String.class, "path"); FileChannel channel = ReflectionUtil.getField(stream.getClass(), stream, FileChannel.class, "channel"); boolean closed = ReflectionUtil.getField(stream.getClass(), stream, boolean.class, "closed"); int available = stream.available(); File file = new File(path); return "FileInputStream(path=" + path + ", available=" + available + ", closed=" + closed + ", channel=" + channel + ", channel.size=" + (channel == null ? null : channel.size()) + ", file.exists=" + file.exists() + ", file.content='" + FileUtil.loadFile(file) + "')"; } return stream; } @Nullable private Collection<FileTypeDetector> getDetectorsForType(@NotNull FileType fileType) { synchronized (FILE_TYPE_DETECTOR_MAP_LOCK) { if (myFileTypeDetectorMap == null) { myFileTypeDetectorMap = new MultiValuesMap<>(); for (FileTypeDetector detector : FileTypeDetector.EP_NAME.getExtensionList()) { Collection<? extends FileType> detectedFileTypes = detector.getDetectedFileTypes(); if (detectedFileTypes != null) { for (FileType type : detectedFileTypes) { myFileTypeDetectorMap.put(type, detector); } } else { myUntypedFileTypeDetectors.add(detector); if (ApplicationManager.getApplication().isInternal()) { LOG.error(PluginException.createByClass( "File type detector " + detector + " does not implement getDetectedFileTypes(), leading to suboptimal performance. Please implement the method.", null, detector.getClass())); } } } } return myFileTypeDetectorMap.get(fileType); } } @Override public boolean isFileOfType(@NotNull VirtualFile file, @NotNull FileType type) { if (mightBeReplacedByDetectedFileType(type) || type.equals(UnknownFileType.INSTANCE)) { // a file has unknown file type if none of file type detectors matched it // for plain text file type, we run file type detection based on content return file.getFileType().equals(type); } if (file instanceof LightVirtualFile) { FileType assignedFileType = ((LightVirtualFile)file).getAssignedFileType(); if (assignedFileType != null) { return type.equals(assignedFileType); } } FileType overriddenFileType = FileTypeOverrider.EP_NAME.computeSafeIfAny((overrider) -> overrider.getOverriddenFileType(file)); if (overriddenFileType != null) { return overriddenFileType.equals(type); } if (type instanceof FileTypeIdentifiableByVirtualFile && ((FileTypeIdentifiableByVirtualFile)type).isMyFileType(file)) { return true; } FileType fileTypeByFileName = getFileTypeByFileName(file.getNameSequence()); if (fileTypeByFileName == type) { return true; } if (fileTypeByFileName != UnknownFileType.INSTANCE) { return false; } if (file instanceof StubVirtualFile || !isDetectable(file)) { return false; } FileType detectedFromContentFileType = file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY); if (detectedFromContentFileType != null) { return detectedFromContentFileType.equals(type); } Collection<FileTypeDetector> detectors = getDetectorsForType(type); if (detectors != null || !myUntypedFileTypeDetectors.isEmpty()) { Iterable<FileTypeDetector> applicableDetectors = detectors != null ? ContainerUtil.concat(detectors, myUntypedFileTypeDetectors) : myUntypedFileTypeDetectors; try { FileType detectedType = detectFromContent(file, null, applicableDetectors); if (detectedType != UnknownFileType.INSTANCE && detectedType != PlainTextFileType.INSTANCE) { cacheAutoDetectedFileType(file, detectedType); } if (detectedType.equals(type)) { return true; } } catch (IOException ignored) { } } return false; } @Override public LanguageFileType findFileTypeByLanguage(@NotNull Language language) { synchronized (PENDING_INIT_LOCK) { for (FileTypeBean bean : myPendingFileTypes.values()) { if (language.getID().equals(bean.language)) { return (LanguageFileType)instantiateFileTypeBean(bean); } } } // Do not use getRegisteredFileTypes() to avoid instantiating all pending file types return language.findMyFileType(mySchemeManager.getAllSchemes().toArray(FileType.EMPTY_ARRAY)); } @Override @NotNull public FileType getFileTypeByExtension(@NotNull String extension) { synchronized (PENDING_INIT_LOCK) { final FileTypeBean pendingFileType = myPendingAssociations.findByExtension(extension); if (pendingFileType != null) { return ObjectUtils.notNull(instantiateFileTypeBean(pendingFileType), UnknownFileType.INSTANCE); } FileType type = myPatternsTable.findByExtension(extension); return ObjectUtils.notNull(type, UnknownFileType.INSTANCE); } } @Override @Deprecated public void registerFileType(@NotNull FileType fileType) { registerFileType(fileType, ArrayUtilRt.EMPTY_STRING_ARRAY); } @Override public void registerFileType(@NotNull final FileType type, @NotNull final List<? extends FileNameMatcher> defaultAssociations) { DeprecatedMethodException.report("Use fileType extension instead."); ApplicationManager.getApplication().runWriteAction(() -> { fireBeforeFileTypesChanged(); registerFileTypeWithoutNotification(type, defaultAssociations, true); fireFileTypesChanged(type, null); }); } @Override public void unregisterFileType(@NotNull final FileType fileType) { ApplicationManager.getApplication().runWriteAction(() -> { fireBeforeFileTypesChanged(); unregisterFileTypeWithoutNotification(fileType); myStandardFileTypes.remove(fileType.getName()); fireFileTypesChanged(null, fileType); }); } private void unregisterFileTypeWithoutNotification(@NotNull FileType fileType) { myPatternsTable.removeAllAssociations(fileType); myInitialAssociations.removeAllAssociations(fileType); mySchemeManager.removeScheme(fileType); if (fileType instanceof FileTypeIdentifiableByVirtualFile) { final FileTypeIdentifiableByVirtualFile fakeFileType = (FileTypeIdentifiableByVirtualFile)fileType; mySpecialFileTypes = ArrayUtil.remove(mySpecialFileTypes, fakeFileType, FileTypeIdentifiableByVirtualFile.ARRAY_FACTORY); } } @Override @NotNull public FileType[] getRegisteredFileTypes() { synchronized (PENDING_INIT_LOCK) { instantiatePendingFileTypes(); } Collection<FileType> fileTypes = mySchemeManager.getAllSchemes(); return fileTypes.toArray(FileType.EMPTY_ARRAY); } @Override @NotNull public String getExtension(@NotNull String fileName) { return FileUtilRt.getExtension(fileName); } @Override @NotNull public String getIgnoredFilesList() { Set<String> masks = myIgnoredPatterns.getIgnoreMasks(); return masks.isEmpty() ? "" : StringUtil.join(masks, ";") + ";"; } @Override public void setIgnoredFilesList(@NotNull String list) { fireBeforeFileTypesChanged(); myIgnoredFileCache.clearCache(); myIgnoredPatterns.setIgnoreMasks(list); fireFileTypesChanged(); } @Override public boolean isIgnoredFilesListEqualToCurrent(@NotNull String list) { Set<String> tempSet = new THashSet<>(); StringTokenizer tokenizer = new StringTokenizer(list, ";"); while (tokenizer.hasMoreTokens()) { tempSet.add(tokenizer.nextToken()); } return tempSet.equals(myIgnoredPatterns.getIgnoreMasks()); } @Override public boolean isFileIgnored(@NotNull String name) { return myIgnoredPatterns.isIgnored(name); } @Override public boolean isFileIgnored(@NotNull VirtualFile file) { return myIgnoredFileCache.isFileIgnored(file); } @Override @NotNull public String[] getAssociatedExtensions(@NotNull FileType type) { synchronized (PENDING_INIT_LOCK) { instantiatePendingFileTypeByName(type.getName()); //noinspection deprecation return myPatternsTable.getAssociatedExtensions(type); } } @Override @NotNull public List<FileNameMatcher> getAssociations(@NotNull FileType type) { synchronized (PENDING_INIT_LOCK) { instantiatePendingFileTypeByName(type.getName()); return myPatternsTable.getAssociations(type); } } @Override public void associate(@NotNull FileType type, @NotNull FileNameMatcher matcher) { associate(type, matcher, true); } @Override public void removeAssociation(@NotNull FileType type, @NotNull FileNameMatcher matcher) { removeAssociation(type, matcher, true); } @Override public void fireBeforeFileTypesChanged() { FileTypeEvent event = new FileTypeEvent(this, null, null); myMessageBus.syncPublisher(TOPIC).beforeFileTypesChanged(event); } private final AtomicInteger fileTypeChangedCount; @Override public void fireFileTypesChanged() { fireFileTypesChanged(null, null); } public void fireFileTypesChanged(@Nullable FileType addedFileType, @Nullable FileType removedFileType) { clearCaches(); clearPersistentAttributes(); myMessageBus.syncPublisher(TOPIC).fileTypesChanged(new FileTypeEvent(this, addedFileType, removedFileType)); } private final Map<FileTypeListener, MessageBusConnection> myAdapters = new HashMap<>(); @Override public void addFileTypeListener(@NotNull FileTypeListener listener) { final MessageBusConnection connection = myMessageBus.connect(); connection.subscribe(TOPIC, listener); myAdapters.put(listener, connection); } @Override public void removeFileTypeListener(@NotNull FileTypeListener listener) { final MessageBusConnection connection = myAdapters.remove(listener); if (connection != null) { connection.disconnect(); } } @Override public void loadState(@NotNull Element state) { int savedVersion = StringUtilRt.parseInt(state.getAttributeValue(ATTRIBUTE_VERSION), 0); for (Element element : state.getChildren()) { if (element.getName().equals(ELEMENT_IGNORE_FILES)) { myIgnoredPatterns.setIgnoreMasks(element.getAttributeValue(ATTRIBUTE_LIST)); } else if (AbstractFileType.ELEMENT_EXTENSION_MAP.equals(element.getName())) { readGlobalMappings(element, false); } } if (savedVersion < 4) { if (savedVersion == 0) { addIgnore(".svn"); } if (savedVersion < 2) { restoreStandardFileExtensions(); } addIgnore("*.pyc"); addIgnore("*.pyo"); addIgnore(".git"); } if (savedVersion < 5) { addIgnore("*.hprof"); } if (savedVersion < 6) { addIgnore("_svn"); } if (savedVersion < 7) { addIgnore(".hg"); } if (savedVersion < 8) { addIgnore("*~"); } if (savedVersion < 9) { addIgnore("__pycache__"); } if (savedVersion < 11) { addIgnore("*.rbc"); } if (savedVersion < 13) { // we want *.lib back since it's an important user artifact for CLion, also for IDEA project itself, since we have some libs. unignoreMask("*.lib"); } if (savedVersion < 15) { // we want .bundle back, bundler keeps useful data there unignoreMask(".bundle"); } if (savedVersion < 16) { // we want .tox back to allow users selecting interpreters from it unignoreMask(".tox"); } if (savedVersion < 17) { addIgnore("*.rbc"); } myIgnoredFileCache.clearCache(); String counter = JDOMExternalizer.readString(state, "fileTypeChangedCounter"); if (counter != null) { fileTypeChangedCount.set(StringUtilRt.parseInt(counter, 0)); autoDetectedAttribute = autoDetectedAttribute.newVersion(fileTypeChangedCount.get()); } } private void unignoreMask(@NotNull final String maskToRemove) { final Set<String> masks = new LinkedHashSet<>(myIgnoredPatterns.getIgnoreMasks()); masks.remove(maskToRemove); myIgnoredPatterns.clearPatterns(); for (final String each : masks) { myIgnoredPatterns.addIgnoreMask(each); } } private void readGlobalMappings(@NotNull Element e, boolean isAddToInit) { for (Pair<FileNameMatcher, String> association : AbstractFileType.readAssociations(e)) { FileType type = getFileTypeByName(association.getSecond()); FileNameMatcher matcher = association.getFirst(); final FileTypeBean pendingFileTypeBean = myPendingAssociations.findAssociatedFileType(matcher); if (pendingFileTypeBean != null) { instantiateFileTypeBean(pendingFileTypeBean); } if (type != null) { if (PlainTextFileType.INSTANCE == type) { FileType newFileType = myPatternsTable.findAssociatedFileType(matcher); if (newFileType != null && newFileType != PlainTextFileType.INSTANCE && newFileType != UnknownFileType.INSTANCE) { myRemovedMappingTracker.add(matcher, newFileType.getName(), false); } } associate(type, matcher, false); if (isAddToInit) { myInitialAssociations.addAssociation(matcher, type); } } else { myUnresolvedMappings.put(matcher, association.getSecond()); } } myRemovedMappingTracker.load(e); for (RemovedMappingTracker.RemovedMapping mapping : myRemovedMappingTracker.getRemovedMappings()) { FileType fileType = getFileTypeByName(mapping.getFileTypeName()); if (fileType != null) { removeAssociation(fileType, mapping.getFileNameMatcher(), false); } } } private void addIgnore(@NonNls @NotNull String ignoreMask) { myIgnoredPatterns.addIgnoreMask(ignoreMask); } private void restoreStandardFileExtensions() { for (final String name : FILE_TYPES_WITH_PREDEFINED_EXTENSIONS) { final StandardFileType stdFileType = myStandardFileTypes.get(name); if (stdFileType != null) { FileType fileType = stdFileType.fileType; for (FileNameMatcher matcher : myPatternsTable.getAssociations(fileType)) { FileType defaultFileType = myInitialAssociations.findAssociatedFileType(matcher); if (defaultFileType != null && defaultFileType != fileType) { removeAssociation(fileType, matcher, false); associate(defaultFileType, matcher, false); } } for (FileNameMatcher matcher : myInitialAssociations.getAssociations(fileType)) { associate(fileType, matcher, false); } } } } @NotNull @Override public Element getState() { Element state = new Element("state"); Set<String> masks = myIgnoredPatterns.getIgnoreMasks(); String ignoreFiles; if (masks.isEmpty()) { ignoreFiles = ""; } else { String[] strings = ArrayUtilRt.toStringArray(masks); Arrays.sort(strings); ignoreFiles = StringUtil.join(strings, ";") + ";"; } if (!ignoreFiles.equalsIgnoreCase(DEFAULT_IGNORED)) { // empty means empty list - we need to distinguish null and empty to apply or not to apply default value state.addContent(new Element(ELEMENT_IGNORE_FILES).setAttribute(ATTRIBUTE_LIST, ignoreFiles)); } Element map = new Element(AbstractFileType.ELEMENT_EXTENSION_MAP); List<FileType> notExternalizableFileTypes = new ArrayList<>(); for (FileType type : mySchemeManager.getAllSchemes()) { if (!(type instanceof AbstractFileType) || myDefaultTypes.contains(type)) { notExternalizableFileTypes.add(type); } } if (!notExternalizableFileTypes.isEmpty()) { Collections.sort(notExternalizableFileTypes, Comparator.comparing(FileType::getName)); for (FileType type : notExternalizableFileTypes) { writeExtensionsMap(map, type, true); } } myRemovedMappingTracker.save(map); if (!myUnresolvedMappings.isEmpty()) { FileNameMatcher[] unresolvedMappingKeys = myUnresolvedMappings.keySet().toArray(new FileNameMatcher[0]); Arrays.sort(unresolvedMappingKeys, Comparator.comparing(FileNameMatcher::getPresentableString)); for (FileNameMatcher fileNameMatcher : unresolvedMappingKeys) { Element content = AbstractFileType.writeMapping(myUnresolvedMappings.get(fileNameMatcher), fileNameMatcher, true); if (content != null) { map.addContent(content); } } } if (!map.getChildren().isEmpty()) { state.addContent(map); } if (!state.getChildren().isEmpty()) { state.setAttribute(ATTRIBUTE_VERSION, String.valueOf(VERSION)); } return state; } private void writeExtensionsMap(@NotNull Element map, @NotNull FileType type, boolean specifyTypeName) { List<FileNameMatcher> associations = myPatternsTable.getAssociations(type); Set<FileNameMatcher> defaultAssociations = new THashSet<>(myInitialAssociations.getAssociations(type)); for (FileNameMatcher matcher : associations) { boolean isDefaultAssociationContains = defaultAssociations.remove(matcher); if (!isDefaultAssociationContains && shouldSave(type)) { Element content = AbstractFileType.writeMapping(type.getName(), matcher, specifyTypeName); if (content != null) { map.addContent(content); } } } myRemovedMappingTracker.saveRemovedMappingsForFileType(map, type.getName(), defaultAssociations, specifyTypeName); } // Helper methods @Nullable private FileType getFileTypeByName(@NotNull String name) { synchronized (PENDING_INIT_LOCK) { instantiatePendingFileTypeByName(name); return mySchemeManager.findSchemeByName(name); } } @NotNull private static List<FileNameMatcher> parse(@Nullable String semicolonDelimited) { return parse(semicolonDelimited, token -> new ExtensionFileNameMatcher(token)); } @NotNull private static List<FileNameMatcher> parse(@Nullable String semicolonDelimited, Function<? super String, ? extends FileNameMatcher> matcherFactory) { if (semicolonDelimited == null) { return Collections.emptyList(); } StringTokenizer tokenizer = new StringTokenizer(semicolonDelimited, FileTypeConsumer.EXTENSION_DELIMITER, false); ArrayList<FileNameMatcher> list = new ArrayList<>(semicolonDelimited.length() / "py;".length()); while (tokenizer.hasMoreTokens()) { list.add(matcherFactory.fun(tokenizer.nextToken().trim())); } return list; } /** * Registers a standard file type. Doesn't notifyListeners any change events. */ private void registerFileTypeWithoutNotification(@NotNull FileType fileType, @NotNull List<? extends FileNameMatcher> matchers, boolean addScheme) { if (addScheme) { mySchemeManager.addScheme(fileType); } for (FileNameMatcher matcher : matchers) { myPatternsTable.addAssociation(matcher, fileType); myInitialAssociations.addAssociation(matcher, fileType); } if (fileType instanceof FileTypeIdentifiableByVirtualFile) { mySpecialFileTypes = ArrayUtil.append(mySpecialFileTypes, (FileTypeIdentifiableByVirtualFile)fileType, FileTypeIdentifiableByVirtualFile.ARRAY_FACTORY); } } private void bindUnresolvedMappings(@NotNull FileType fileType) { for (FileNameMatcher matcher : new THashSet<>(myUnresolvedMappings.keySet())) { String name = myUnresolvedMappings.get(matcher); if (Comparing.equal(name, fileType.getName())) { myPatternsTable.addAssociation(matcher, fileType); myUnresolvedMappings.remove(matcher); } } for (FileNameMatcher matcher : myRemovedMappingTracker.getMappingsForFileType(fileType.getName())) { removeAssociation(fileType, matcher, false); } } @NotNull private FileType loadFileType(@NotNull Element typeElement, boolean isDefault) { String fileTypeName = typeElement.getAttributeValue(ATTRIBUTE_NAME); String fileTypeDescr = typeElement.getAttributeValue(ATTRIBUTE_DESCRIPTION); String iconPath = typeElement.getAttributeValue("icon"); String extensionsStr = StringUtil.nullize(typeElement.getAttributeValue("extensions")); if (isDefault && extensionsStr != null) { // todo support wildcards extensionsStr = filterAlreadyRegisteredExtensions(extensionsStr); } FileType type = isDefault ? getFileTypeByName(fileTypeName) : null; if (type != null) { return type; } Element element = typeElement.getChild(AbstractFileType.ELEMENT_HIGHLIGHTING); if (element == null) { type = new UserBinaryFileType(); } else { SyntaxTable table = AbstractFileType.readSyntaxTable(element); type = new AbstractFileType(table); ((AbstractFileType)type).initSupport(); } setFileTypeAttributes((UserFileType)type, fileTypeName, fileTypeDescr, iconPath); registerFileTypeWithoutNotification(type, parse(extensionsStr), isDefault); if (isDefault) { myDefaultTypes.add(type); if (type instanceof ExternalizableFileType) { ((ExternalizableFileType)type).markDefaultSettings(); } } else { Element extensions = typeElement.getChild(AbstractFileType.ELEMENT_EXTENSION_MAP); if (extensions != null) { for (Pair<FileNameMatcher, String> association : AbstractFileType.readAssociations(extensions)) { associate(type, association.getFirst(), false); } for (RemovedMappingTracker.RemovedMapping removedAssociation : RemovedMappingTracker.readRemovedMappings(extensions)) { removeAssociation(type, removedAssociation.getFileNameMatcher(), false); } } } return type; } @Nullable private String filterAlreadyRegisteredExtensions(@NotNull String semicolonDelimited) { StringTokenizer tokenizer = new StringTokenizer(semicolonDelimited, FileTypeConsumer.EXTENSION_DELIMITER, false); StringBuilder builder = null; while (tokenizer.hasMoreTokens()) { String extension = tokenizer.nextToken().trim(); if (myPendingAssociations.findByExtension(extension) == null && getFileTypeByExtension(extension) == UnknownFileType.INSTANCE) { if (builder == null) { builder = new StringBuilder(); } else if (builder.length() > 0) { builder.append(FileTypeConsumer.EXTENSION_DELIMITER); } builder.append(extension); } } return builder == null ? null : builder.toString(); } private static void setFileTypeAttributes(@NotNull UserFileType fileType, @Nullable String name, @Nullable String description, @Nullable String iconPath) { if (!StringUtil.isEmptyOrSpaces(iconPath)) { fileType.setIconPath(iconPath); } if (description != null) { fileType.setDescription(description); } if (name != null) { fileType.setName(name); } } private static boolean shouldSave(@NotNull FileType fileType) { return fileType != UnknownFileType.INSTANCE && !fileType.isReadOnly(); } // Setup @NotNull FileTypeAssocTable<FileType> getExtensionMap() { synchronized (PENDING_INIT_LOCK) { instantiatePendingFileTypes(); } return myPatternsTable; } void setPatternsTable(@NotNull Set<? extends FileType> fileTypes, @NotNull FileTypeAssocTable<FileType> assocTable) { Map<FileNameMatcher, FileType> removedMappings = getExtensionMap().getRemovedMappings(assocTable, fileTypes); fireBeforeFileTypesChanged(); for (FileType existing : getRegisteredFileTypes()) { if (!fileTypes.contains(existing)) { mySchemeManager.removeScheme(existing); } } for (FileType fileType : fileTypes) { mySchemeManager.addScheme(fileType); if (fileType instanceof AbstractFileType) { ((AbstractFileType)fileType).initSupport(); } } myPatternsTable = assocTable.copy(); fireFileTypesChanged(); myRemovedMappingTracker.removeMatching((matcher, fileTypeName) -> { FileType fileType = getFileTypeByName(fileTypeName); return fileType != null && assocTable.isAssociatedWith(fileType, matcher); }); for (Map.Entry<FileNameMatcher, FileType> entry : removedMappings.entrySet()) { myRemovedMappingTracker.add(entry.getKey(), entry.getValue().getName(), true); } } public void associate(@NotNull FileType fileType, @NotNull FileNameMatcher matcher, boolean fireChange) { if (!myPatternsTable.isAssociatedWith(fileType, matcher)) { if (fireChange) { fireBeforeFileTypesChanged(); } myPatternsTable.addAssociation(matcher, fileType); if (fireChange) { fireFileTypesChanged(); } } } public void removeAssociation(@NotNull FileType fileType, @NotNull FileNameMatcher matcher, boolean fireChange) { if (myPatternsTable.isAssociatedWith(fileType, matcher)) { if (fireChange) { fireBeforeFileTypesChanged(); } myPatternsTable.removeAssociation(matcher, fileType); if (fireChange) { fireFileTypesChanged(); } } } @Override @Nullable public FileType getKnownFileTypeOrAssociate(@NotNull VirtualFile file) { FileType type = file.getFileType(); if (type == UnknownFileType.INSTANCE) { type = FileTypeChooser.associateFileType(file.getName()); } return type; } @Override public FileType getKnownFileTypeOrAssociate(@NotNull VirtualFile file, @NotNull Project project) { return FileTypeChooser.getKnownFileTypeOrAssociate(file, project); } private void registerReDetectedMappings(@NotNull StandardFileType pair) { FileType fileType = pair.fileType; if (fileType == PlainTextFileType.INSTANCE) return; for (FileNameMatcher matcher : pair.matchers) { registerReDetectedMapping(fileType.getName(), matcher); if (matcher instanceof ExtensionFileNameMatcher) { // also check exact file name matcher ExtensionFileNameMatcher extMatcher = (ExtensionFileNameMatcher)matcher; registerReDetectedMapping(fileType.getName(), new ExactFileNameMatcher("." + extMatcher.getExtension())); } } } private void registerReDetectedMapping(@NotNull String fileTypeName, @NotNull FileNameMatcher matcher) { String typeName = myUnresolvedMappings.get(matcher); if (typeName != null && !typeName.equals(fileTypeName)) { if (!myRemovedMappingTracker.hasRemovedMapping(matcher)) { myRemovedMappingTracker.add(matcher, fileTypeName, false); } myUnresolvedMappings.remove(matcher); } } @NotNull RemovedMappingTracker getRemovedMappingTracker() { return myRemovedMappingTracker; } @TestOnly void clearForTests() { for (StandardFileType fileType : myStandardFileTypes.values()) { myPatternsTable.removeAllAssociations(fileType.fileType); } for (FileType type : myDefaultTypes) { myPatternsTable.removeAllAssociations(type); } myStandardFileTypes.clear(); myDefaultTypes.clear(); myUnresolvedMappings.clear(); myRemovedMappingTracker.clear(); for (FileTypeBean bean : myPendingFileTypes.values()) { myPendingAssociations.removeAllAssociations(bean); } myPendingFileTypes.clear(); mySchemeManager.setSchemes(Collections.emptyList()); } @Override public void dispose() { LOG.info(String.format("%s auto-detected files. Detection took %s ms", counterAutoDetect, elapsedAutoDetect)); } }
//FILE: Device.java //PROJECT: Micro-Manager //SUBSYSTEM: mmstudio // This file is distributed in the hope that it will be useful, // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. // CVS: $Id$ package org.micromanager.conf; import java.util.ArrayList; import java.util.Hashtable; import java.util.Vector; import mmcorej.BooleanVector; import mmcorej.CMMCore; import mmcorej.DeviceType; import mmcorej.LongVector; import mmcorej.MMCoreJ; import mmcorej.StrVector; import org.micromanager.utils.PropertyItem; /** * Data structure describing a general MM device. * Part of the MicroscopeModel. * */public class Device { private String name_; private String adapterName_; private String library_; private PropertyItem properties_[]; private ArrayList<PropertyItem> setupProperties_; private String description_; private DeviceType type_; private Hashtable<Integer, Label> setupLabels_; private double delayMs_; private boolean usesDelay_; private int numPos_ = 0; private boolean discoverable_; private String master_; // discoverable devices record which hub they are on private Vector<String> slaves_; // hubs record their peripheral devices public Device(String name, String lib, String adapterName, String descr, boolean discoverable, String master,Vector<String> slaves ) { name_ = name; library_ = lib; adapterName_ = adapterName; description_ = descr; type_ = DeviceType.AnyType; setupLabels_ = new Hashtable<Integer, Label>(); properties_ = new PropertyItem[0]; setupProperties_ = new ArrayList<PropertyItem>(); usesDelay_ = false; delayMs_ = 0.0; discoverable_ = discoverable; master_ = master; slaves_ = slaves; } public Device(String name, String lib, String adapterName, String descr, boolean discoverable) { name_ = name; library_ = lib; adapterName_ = adapterName; description_ = descr; type_ = DeviceType.AnyType; setupLabels_ = new Hashtable<Integer, Label>(); properties_ = new PropertyItem[0]; setupProperties_ = new ArrayList<PropertyItem>(); usesDelay_ = false; delayMs_ = 0.0; discoverable_ = discoverable; master_ = ""; slaves_ = new Vector<String>(); } public Device(String name, String lib, String adapterName, String descr) { name_ = name; library_ = lib; adapterName_ = adapterName; description_ = descr; type_ = DeviceType.AnyType; setupLabels_ = new Hashtable<Integer, Label>(); properties_ = new PropertyItem[0]; setupProperties_ = new ArrayList<PropertyItem>(); usesDelay_ = false; delayMs_ = 0.0; discoverable_ = false; master_ = ""; slaves_ = new Vector<String>(); } public Device(String name, String lib, String adapterName) { this(name, lib, adapterName, ""); } public void setTypeByInt(int typeNum) { type_ = DeviceType.swigToEnum(typeNum); } public int getTypeAsInt() { return type_.swigValue(); } /** * Obtain all properties and their current values. * @param core * @throws Exception */ public void loadDataFromHardware(CMMCore core) throws Exception { StrVector propNames = core.getDevicePropertyNames(name_); properties_ = new PropertyItem[(int) propNames.size()]; // delayMs_ = core.getDeviceDelayMs(name_); // NOTE: do not load the delay value from the hardware // we will always use settings defined in the config file type_ = core.getDeviceType(name_); usesDelay_ = core.usesDeviceDelay(name_); for (int j=0; j<propNames.size(); j++){ properties_[j] = new PropertyItem(); properties_[j].name = propNames.get(j); properties_[j].value = core.getProperty(name_, propNames.get(j)); properties_[j].readOnly = core.isPropertyReadOnly(name_, propNames.get(j)); properties_[j].preInit = core.isPropertyPreInit(name_, propNames.get(j)); properties_[j].type = core.getPropertyType(name_, propNames.get(j)); StrVector values = core.getAllowedPropertyValues(name_, propNames.get(j)); properties_[j].allowed = new String[(int)values.size()]; for (int k=0; k<values.size(); k++){ properties_[j].allowed[k] = values.get(k); } properties_[j].sort(); } if (type_ == DeviceType.StateDevice) { numPos_ = core.getNumberOfStates(name_); } else numPos_ = 0; } public static Device[] getLibraryContents(String libName, CMMCore core) throws Exception { StrVector adapterNames = core.getAvailableDevices(libName); StrVector devDescrs = core.getAvailableDeviceDescriptions(libName); LongVector devTypes = core.getAvailableDeviceTypes(libName); BooleanVector disco = core.getDeviceDiscoverability(libName); Device[] devList = new Device[(int)adapterNames.size()]; for (int i=0; i<adapterNames.size(); i++) { // not all adapters fill this yet boolean isDiscoverable = false; if( i < disco.size()) isDiscoverable = disco.get(i); devList[i] = new Device("Undefined", libName, adapterNames.get(i), devDescrs.get(i),isDiscoverable); devList[i].setTypeByInt(devTypes.get(i)); } return devList; } /** * @return Returns the name. */ public String getName() { return name_; } /** * @return Returns the adapterName. */ public String getAdapterName() { return adapterName_; } public String getDescription() { return description_; } public void addSetupProperty(PropertyItem prop) { setupProperties_.add(prop); } public void addSetupLabel(Label lab) { setupLabels_.put(new Integer(lab.state_), lab); } public void getSetupLabelsFromHardware(CMMCore core) throws Exception { // we can only add the state labels after initialization of the device!! if (type_ == DeviceType.StateDevice) { StrVector stateLabels = core.getStateLabels(name_); for (int state = 0; state < numPos_; state++) { setSetupLabel(state, stateLabels.get(state)); } } } public String getLibrary() { return library_; } public int getNumberOfProperties() { return properties_.length; } public PropertyItem getProperty(int idx) { return properties_[idx]; } public String getPropertyValue(String propName) throws MMConfigFileException { PropertyItem p = findProperty(propName); if (p == null) throw new MMConfigFileException("Property " + propName + " is not defined"); return p.value; } public void setPropertyValue(String name, String value) throws MMConfigFileException { PropertyItem p = findProperty(name); if (p == null) throw new MMConfigFileException("Property " + name + " is not defined"); p.value = value; } public int getNumberOfSetupProperties() { return setupProperties_.size(); } public PropertyItem getSetupProperty(int idx) { return setupProperties_.get(idx); } public String getSetupPropertyValue(String propName) throws MMConfigFileException { PropertyItem p = findSetupProperty(propName); if (p == null) throw new MMConfigFileException("Property " + propName + " is not defined"); return p.value; } public void setSetupPropertyValue(String name, String value) throws MMConfigFileException { PropertyItem p = findSetupProperty(name); if (p == null) throw new MMConfigFileException("Property " + name + " is not defined"); p.value = value; } public boolean isStateDevice() { return type_ == DeviceType.StateDevice; } public boolean isSerialPort() { return type_ == DeviceType.SerialDevice; } public boolean isCamera() { return type_ == DeviceType.CameraDevice; } public int getNumberOfSetupLabels() { return setupLabels_.size(); } // public String[] getLabels() { // return labels_; public Label getSetupLabel(int j) { return (Label) setupLabels_.values().toArray()[j]; } public void setSetupLabel(int pos, String label) { Label l = setupLabels_.get(new Integer(pos)); if (l == null) { // label does not exist so we must create one setupLabels_.put(new Integer(pos), new Label(label, pos)); } else l.label_ = label; } public boolean isCore() { return name_.contentEquals(new StringBuffer().append(MMCoreJ.getG_Keyword_CoreDevice())); } public void setName(String newName) { name_ = newName; } public PropertyItem findProperty(String name) { for (int i=0; i<properties_.length; i++) { PropertyItem p = properties_[i]; if (p.name.contentEquals(new StringBuffer().append(name))) return p; } return null; } public PropertyItem findSetupProperty(String name) { for (int i=0; i<setupProperties_.size(); i++) { PropertyItem p = setupProperties_.get(i); if (p.name.contentEquals(new StringBuffer().append(name))) return p; } return null; } public double getDelay() { return delayMs_; } public void setDelay(double delayMs) { delayMs_ = delayMs; } public boolean usesDelay() { return usesDelay_; } public int getNumberOfStates() { return numPos_; } public String getVerboseType() { // String devType = new String("unknown"); // if (type_ == DeviceType.CameraDevice) { // devType = "Camera"; // } else if (type_ == DeviceType.SerialDevice) { // devType = "Serial port"; // } else if (type_ == DeviceType.ShutterDevice) { // devType = "Shutter"; // } else if (type_ == DeviceType.) if (type_ == DeviceType.AnyType) return ""; else return type_.toString(); } public boolean isDiscoverable(){ return discoverable_; } public void setDiscoverable(boolean v){ discoverable_ = v; } public Vector<String> getSlaves(){ return slaves_; } public void setSlaves(Vector<String> slaves){ slaves_ = slaves; } public String getMaster(){ return master_; } public void setMaster(String m){ master_ = m; } }
package com.ikueb.mapextractor; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.regex.Pattern; import java.util.stream.Collector; import java.util.stream.Collector.Characteristics; import java.util.stream.Collectors; import java.util.stream.Stream; /** * An utility class providing: * <ul> * <li>A set of helper methods to easily convert {@link Stream}s of {@link CharSequence} * s to either {@link Properties} or {@link Map} instances. * <ul> * <li>These methods operate on streams and reproduces the parsing logic in * {@link Properties#load(java.io.Reader)} as closely as possible. The only differences * are no support for multi-line values and the default key delimiter can only be * escaped with {@code "\"} once.</li> * </ul> * </li> * <li>A set of collectors to be used in {@link Stream#collect(Collector)} as terminal * operations. * <ul> * <li>These methods are meant to be drop-in replacements for the standard JDK * {@code Collectors.toMap()} methods, but with a {@code regex} prefixed argument to * split each stream element into key-value pairings.</li> * </ul> * </li> * </ul> */ public final class MapExtractor { /** * Predicate for matching comments. */ private static final Predicate<? super CharSequence> COMMENTS = v -> Pattern .compile("^\\s*[#!]").matcher(v).find(); /** * Regular expression for matching key delimiters (taking care to check if they are * escaped). */ private static final String REGEX_DELIMITER = "(?<!\\\\)[:=]"; private static final String JOIN_DELIMITER = ", "; private MapExtractor() { // empty } /** * Handles the stream like the line-oriented format for loading a {@link Properties} * instance, except that multi-line values are not supported and the default key * delimiter can only be escaped with {@code "\"} once. * * @param entries lines to process * @return a {@link Properties} instance based on {@code entries} * @see Properties#load(java.io.Reader) */ public static Properties asProperties(final Stream<? extends CharSequence> entries) { final Properties props = new Properties(); props.putAll(skipComments(entries).collect(toMap(REGEX_DELIMITER, toKey(), toValue(), (a, b) -> { return b; }))); return props; } /** * Handles the stream like the line-oriented format for loading a {@link Properties} * instance, except that values for the same key are put into a {@link List} and * multi-line values are not supported and the default key delimiter can only be * escaped with {@code "\"} once. * * @param entries lines to process * @return a {@link Map} */ public static Map<String, List<String>> groupingBy( final Stream<? extends CharSequence> entries) { return skipComments(entries).collect(groupingBy(REGEX_DELIMITER, toKey(), toValue())); } public static Map<String, String> simpleMap( final Stream<? extends CharSequence> entries) { return skipComments(entries).collect(toMap(REGEX_DELIMITER, toKey(), toValue())); } /** * Handles the stream like the line-oriented format for loading a {@link Properties} * instance, except that values for the same key are joined, multi-line values are * not supported and the default key delimiter can only be escaped with {@code "\"} * once. * * @param entries lines to process * @return a {@link Map} */ public static Map<String, String> simpleMapAndJoin( final Stream<? extends CharSequence> entries) { return simpleMapAndJoin(entries, JOIN_DELIMITER); } /** * Handles the stream like the line-oriented format for loading a {@link Properties} * instance, except that values for the same key are joined using * {@code joinDelimiter}, multi-line values are not supported and the default key * delimiter can only be escaped with {@code "\"} once. * * @param entries lines to process * @param joinDelimiter the join delimiter to use * @return a {@link Map} */ public static Map<String, String> simpleMapAndJoin( final Stream<? extends CharSequence> entries, final String joinDelimiter) { return skipComments(entries).collect(toMapAndJoin(REGEX_DELIMITER, joinDelimiter)); } /** * With the exception of the first argument {@code regex} for splitting each stream * element, this method is meant to be used in a similar way as the equivalent in * the {@link Collectors} class, except that the third argument {@code valueMapper} * exists to do the conversion of map values as well, instead of using the stream * elements. * <p> * Implementation note: the aggregation on values is done by mapping each value as a * single-element {@link List}, and then calling * {@link List#addAll(java.util.Collection)} as the merge function to * {@link MapExtractor#toMap(String, Function, Function, BinaryOperator)}. * * @param regex the delimiter to use * @param keyMapper * @param valueMapper * @return a {@link Map} * @see Collectors#groupingBy(Function) */ public static <K, V> Collector<CharSequence, ?, Map<K, List<V>>> groupingBy( final String regex, final Function<? super CharSequence, K> keyMapper, final Function<? super CharSequence, V> valueMapper) { return toMap(regex, keyMapper, enlist(valueMapper), joinList()); } /** * Handles the stream like the line-oriented format for loading a {@link Properties} * instance, except that values for the same key are joined using * {@code joinDelimiter}, multi-line values are not supported and the default key * delimiter can only be escaped with {@code "\"} once. * * @param regex the delimiter to use * @param joinDelimiter the join delimiter to use * @return a {@link Collector} */ public static Collector<CharSequence, ?, Map<String, String>> toMapAndJoin( final String regex, final String joinDelimiter) { return toMap(regex, toKey(), toValue(), join(joinDelimiter)); } /** * With the exception of the first argument {@code regex} for splitting each stream * element, this method is meant to be used in the same way as the equivalent in the * {@link Collectors} class. * * @param regex the delimiter to use * @param keyMapper * @param valueMapper * @return a {@link Map} * @see Collectors#toMap(Function, Function) */ public static <K, V> Collector<CharSequence, ?, Map<K, V>> toMap( final String regex, final Function<? super CharSequence, K> keyMapper, final Function<? super CharSequence, V> valueMapper) { return toMap(regex, keyMapper, valueMapper, duplicateKeyMergeThrower()); } /** * With the exception of the first argument {@code regex} for splitting each stream * element, this method is meant to be used in the same way as the equivalent in the * {@link Collectors} class. * * @param regex the delimiter to use * @param keyMapper * @param valueMapper * @param mergeFunction * @return a {@link Map} * @see Collectors#toMap(Function, Function, BinaryOperator) */ public static <K, V> Collector<CharSequence, ?, Map<K, V>> toMap( final String regex, final Function<? super CharSequence, K> keyMapper, final Function<? super CharSequence, V> valueMapper, final BinaryOperator<V> mergeFunction) { return toMap(regex, keyMapper, valueMapper, mergeFunction, HashMap::new); } /** * With the exception of the first argument {@code regex} for splitting each stream * element, this method is meant to be used in the same way as the equivalent in the * {@link Collectors} class. * * @param regex the delimiter to use * @param keyMapper * @param valueMapper * @param mergeFunction * @param mapSupplier * @return a {@link Map} * @see Collectors#toMap(Function, Function, BinaryOperator, Supplier) */ public static <K, V, M extends Map<K, V>> Collector<CharSequence, ?, M> toMap( final String regex, final Function<? super CharSequence, K> keyMapper, final Function<? super CharSequence, V> valueMapper, final BinaryOperator<V> mergeFunction, final Supplier<M> mapSupplier) { Stream.of(regex, keyMapper, valueMapper, mergeFunction, mapSupplier) .forEach(Objects::requireNonNull); return Collector.of(mapSupplier, (m, i) -> { CharSequence[] pair = splitWith(regex).apply(i); m.merge(keyMapper.apply(pair[0]), valueMapper.apply(pair[1]), mergeFunction); }, (a, b) -> { b.entrySet().stream().forEach( entry -> a.merge(entry.getKey(), entry.getValue(), mergeFunction)); return a; }, Characteristics.IDENTITY_FINISH); } /** * Filters the stream for comments, i.e. elements with the first non-whitespace * character as {@code "#"} or {@code "!"}. * * @param stream the stream to filter * @return a {@link Predicate} to skip comment lines */ private static <T extends CharSequence> Stream<T> skipComments( final Stream<T> stream) { return stream.filter(COMMENTS.negate()); } /** * Splits {@code entry} with {@code regex} into a pair of sub-{@link String}s using * {@link String#split(String, int)} (the second argument being {@code 2}). * * @param regex the delimiter to use * @return a pair of {@link String}s, the second element will be an empty * {@link String} ({@code ""}) if there is no second sub-{@link String} from * the split */ private static Function<? super CharSequence, CharSequence[]> splitWith( final String regex) { return v -> { String[] result = v.toString().split(regex, 2); return result.length == 2 ? result : new String[] { result[0], "" }; }; } /** * @return a {@link Function} that treats the input as a key by trimming it and * removing {@code "\"} characters */ private static Function<? super CharSequence, String> toKey() { return k -> k.toString().trim().replace("\\", ""); } /** * @return a {@link Function} that treats the input as a value by trimming * whitespace characters from the front only */ private static Function<? super CharSequence, String> toValue() { return v -> v.toString().replaceFirst("^\\s+", ""); } /** * @param mapper the mapper to apply first * @return a {@link Function} that wraps an element in an {@link ArrayList} */ private static <T, U> Function<? super T, List<U>> enlist( final Function<? super T, U> mapper) { return mapper.andThen(v -> new ArrayList<>(Arrays.asList(v))); } /** * @return the first {@link List} appended with the contents of the second one */ private static <T> BinaryOperator<List<T>> joinList() { return (a, b) -> { a.addAll(b); return a; }; } /** * @param delimiter the delimiter to use for joining {@link String}s * @return a joined {@link String} on the {@code delimiter} */ private static BinaryOperator<String> join(final String delimiter) { return (a, b) -> String.join(delimiter, a, b); } private static <T> BinaryOperator<T> duplicateKeyMergeThrower() { return (a, b) -> { throw new IllegalStateException(String.format( "Duplicate key for values \"%s\" and \"%s\".", a, b)); }; } }
package org.elasticsearch.xpack.ml.integration; import org.elasticsearch.ElasticsearchStatusException; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.AggregatorFactories; import org.elasticsearch.test.junit.annotations.TestLogging; import org.elasticsearch.xpack.ml.MachineLearning; import org.elasticsearch.xpack.ml.MlMetadata; import org.elasticsearch.xpack.ml.action.CloseJobAction; import org.elasticsearch.xpack.ml.action.GetDatafeedsStatsAction; import org.elasticsearch.xpack.ml.action.GetJobsStatsAction; import org.elasticsearch.xpack.ml.action.OpenJobAction; import org.elasticsearch.xpack.ml.action.PostDataAction; import org.elasticsearch.xpack.ml.action.PutDatafeedAction; import org.elasticsearch.xpack.ml.action.PutJobAction; import org.elasticsearch.xpack.ml.action.StartDatafeedAction; import org.elasticsearch.xpack.ml.datafeed.DatafeedConfig; import org.elasticsearch.xpack.ml.datafeed.DatafeedState; import org.elasticsearch.xpack.ml.job.config.AnalysisConfig; import org.elasticsearch.xpack.ml.job.config.DataDescription; import org.elasticsearch.xpack.ml.job.config.Detector; import org.elasticsearch.xpack.ml.job.config.Job; import org.elasticsearch.xpack.ml.job.config.JobState; import org.elasticsearch.xpack.ml.job.config.JobTaskStatus; import org.elasticsearch.xpack.ml.support.BaseMlIntegTestCase; import org.elasticsearch.xpack.persistent.PersistentTasksCustomMetaData; import org.elasticsearch.xpack.persistent.PersistentTasksCustomMetaData.PersistentTask; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; public class BasicDistributedJobsIT extends BaseMlIntegTestCase { public void testFailOverBasics() throws Exception { internalCluster().ensureAtLeastNumDataNodes(4); ensureStableCluster(4); Job.Builder job = createJob("fail-over-basics-job"); PutJobAction.Request putJobRequest = new PutJobAction.Request(job); PutJobAction.Response putJobResponse = client().execute(PutJobAction.INSTANCE, putJobRequest).actionGet(); assertTrue(putJobResponse.isAcknowledged()); ensureGreen(); OpenJobAction.Request openJobRequest = new OpenJobAction.Request(job.getId()); client().execute(OpenJobAction.INSTANCE, openJobRequest).actionGet(); assertBusy(() -> { GetJobsStatsAction.Response statsResponse = client().execute(GetJobsStatsAction.INSTANCE, new GetJobsStatsAction.Request(job.getId())).actionGet(); assertEquals(JobState.OPENED, statsResponse.getResponse().results().get(0).getState()); }); internalCluster().stopRandomDataNode(); ensureStableCluster(3); ensureGreen(); assertBusy(() -> { GetJobsStatsAction.Response statsResponse = client().execute(GetJobsStatsAction.INSTANCE, new GetJobsStatsAction.Request(job.getId())).actionGet(); assertEquals(JobState.OPENED, statsResponse.getResponse().results().get(0).getState()); }); internalCluster().stopRandomDataNode(); ensureStableCluster(2); ensureGreen(); assertBusy(() -> { GetJobsStatsAction.Response statsResponse = client().execute(GetJobsStatsAction.INSTANCE, new GetJobsStatsAction.Request(job.getId())).actionGet(); assertEquals(JobState.OPENED, statsResponse.getResponse().results().get(0).getState()); }); } public void testFailOverBasics_withDataFeeder() throws Exception { internalCluster().ensureAtLeastNumDataNodes(4); ensureStableCluster(4); Detector.Builder d = new Detector.Builder("count", null); AnalysisConfig.Builder analysisConfig = new AnalysisConfig.Builder(Collections.singletonList(d.build())); analysisConfig.setSummaryCountFieldName("doc_count"); analysisConfig.setBucketSpan(TimeValue.timeValueHours(1)); Job.Builder job = new Job.Builder("fail-over-basics_with-data-feeder-job"); job.setAnalysisConfig(analysisConfig); job.setDataDescription(new DataDescription.Builder()); PutJobAction.Request putJobRequest = new PutJobAction.Request(job); PutJobAction.Response putJobResponse = client().execute(PutJobAction.INSTANCE, putJobRequest).actionGet(); assertTrue(putJobResponse.isAcknowledged()); DatafeedConfig.Builder configBuilder = createDatafeedBuilder("data_feed_id", job.getId(), Collections.singletonList("*")); configBuilder.setAggregations(AggregatorFactories.builder().addAggregator(AggregationBuilders.histogram("time").interval(300000))); configBuilder.setFrequency(TimeValue.timeValueMinutes(2)); DatafeedConfig config = configBuilder.build(); PutDatafeedAction.Request putDatafeedRequest = new PutDatafeedAction.Request(config); PutDatafeedAction.Response putDatadeedResponse = client().execute(PutDatafeedAction.INSTANCE, putDatafeedRequest).actionGet(); assertTrue(putDatadeedResponse.isAcknowledged()); ensureGreen(); OpenJobAction.Request openJobRequest = new OpenJobAction.Request(job.getId()); client().execute(OpenJobAction.INSTANCE, openJobRequest).actionGet(); assertBusy(() -> { GetJobsStatsAction.Response statsResponse = client().execute(GetJobsStatsAction.INSTANCE, new GetJobsStatsAction.Request(job.getId())).actionGet(); assertEquals(JobState.OPENED, statsResponse.getResponse().results().get(0).getState()); }); StartDatafeedAction.Request startDataFeedRequest = new StartDatafeedAction.Request(config.getId(), 0L); client().execute(StartDatafeedAction.INSTANCE, startDataFeedRequest); assertBusy(() -> { GetDatafeedsStatsAction.Response statsResponse = client().execute(GetDatafeedsStatsAction.INSTANCE, new GetDatafeedsStatsAction.Request(config.getId())).actionGet(); assertEquals(1, statsResponse.getResponse().results().size()); assertEquals(DatafeedState.STARTED, statsResponse.getResponse().results().get(0).getDatafeedState()); }); internalCluster().stopRandomDataNode(); ensureStableCluster(3); ensureGreen(); assertBusy(() -> { GetJobsStatsAction.Response statsResponse = client().execute(GetJobsStatsAction.INSTANCE, new GetJobsStatsAction.Request(job.getId())).actionGet(); assertEquals(JobState.OPENED, statsResponse.getResponse().results().get(0).getState()); }); assertBusy(() -> { GetDatafeedsStatsAction.Response statsResponse = client().execute(GetDatafeedsStatsAction.INSTANCE, new GetDatafeedsStatsAction.Request(config.getId())).actionGet(); assertEquals(1, statsResponse.getResponse().results().size()); assertEquals(DatafeedState.STARTED, statsResponse.getResponse().results().get(0).getDatafeedState()); }); internalCluster().stopRandomDataNode(); ensureStableCluster(2); ensureGreen(); assertBusy(() -> { GetJobsStatsAction.Response statsResponse = client().execute(GetJobsStatsAction.INSTANCE, new GetJobsStatsAction.Request(job.getId())).actionGet(); assertEquals(JobState.OPENED, statsResponse.getResponse().results().get(0).getState()); }); assertBusy(() -> { GetDatafeedsStatsAction.Response statsResponse = client().execute(GetDatafeedsStatsAction.INSTANCE, new GetDatafeedsStatsAction.Request(config.getId())).actionGet(); assertEquals(1, statsResponse.getResponse().results().size()); assertEquals(DatafeedState.STARTED, statsResponse.getResponse().results().get(0).getDatafeedState()); }); } public void testJobAutoClose() throws Exception { internalCluster().ensureAtMostNumDataNodes(0); internalCluster().startNode(Settings.builder().put(MachineLearning.ML_ENABLED.getKey(), false)); internalCluster().startNode(Settings.builder().put(MachineLearning.ML_ENABLED.getKey(), true)); client().admin().indices().prepareCreate("data") .addMapping("type", "time", "type=date") .get(); IndexRequest indexRequest = new IndexRequest("data", "type"); indexRequest.source("time", 1407081600L); client().index(indexRequest).get(); indexRequest = new IndexRequest("data", "type"); indexRequest.source("time", 1407082600L); client().index(indexRequest).get(); indexRequest = new IndexRequest("data", "type"); indexRequest.source("time", 1407083600L); client().index(indexRequest).get(); refresh(); Job.Builder job = createScheduledJob("job_id"); PutJobAction.Request putJobRequest = new PutJobAction.Request(job); PutJobAction.Response putJobResponse = client().execute(PutJobAction.INSTANCE, putJobRequest).actionGet(); assertTrue(putJobResponse.isAcknowledged()); DatafeedConfig config = createDatafeed("data_feed_id", job.getId(), Collections.singletonList("data")); PutDatafeedAction.Request putDatafeedRequest = new PutDatafeedAction.Request(config); PutDatafeedAction.Response putDatadeedResponse = client().execute(PutDatafeedAction.INSTANCE, putDatafeedRequest) .actionGet(); assertTrue(putDatadeedResponse.isAcknowledged()); client().execute(OpenJobAction.INSTANCE, new OpenJobAction.Request(job.getId())).get(); StartDatafeedAction.Request startDatafeedRequest = new StartDatafeedAction.Request(config.getId(), 0L); startDatafeedRequest.getParams().setEndTime(1492616844L); client().execute(StartDatafeedAction.INSTANCE, startDatafeedRequest).get(); assertBusy(() -> { GetJobsStatsAction.Response.JobStats jobStats = getJobStats(job.getId()); assertEquals(3L, jobStats.getDataCounts().getProcessedRecordCount()); assertEquals(JobState.CLOSED, jobStats.getState()); }); } @TestLogging("org.elasticsearch.xpack.persistent:TRACE,org.elasticsearch.cluster.service:DEBUG,org.elasticsearch.xpack.ml.action:DEBUG") public void testDedicatedMlNode() throws Exception { internalCluster().ensureAtMostNumDataNodes(0); // start 2 non ml node that will never get a job allocated. (but ml apis are accessable from this node) internalCluster().startNode(Settings.builder().put(MachineLearning.ML_ENABLED.getKey(), false)); internalCluster().startNode(Settings.builder().put(MachineLearning.ML_ENABLED.getKey(), false)); // start ml node if (randomBoolean()) { internalCluster().startNode(Settings.builder().put(MachineLearning.ML_ENABLED.getKey(), true)); } else { // the default is based on 'xpack.ml.enabled', which is enabled in base test class. internalCluster().startNode(); } ensureStableCluster(3); String jobId = "dedicated-ml-node-job"; Job.Builder job = createJob(jobId); PutJobAction.Request putJobRequest = new PutJobAction.Request(job); PutJobAction.Response putJobResponse = client().execute(PutJobAction.INSTANCE, putJobRequest).actionGet(); assertTrue(putJobResponse.isAcknowledged()); OpenJobAction.Request openJobRequest = new OpenJobAction.Request(job.getId()); client().execute(OpenJobAction.INSTANCE, openJobRequest).actionGet(); assertBusy(() -> { ClusterState clusterState = client().admin().cluster().prepareState().get().getState(); PersistentTasksCustomMetaData tasks = clusterState.getMetaData().custom(PersistentTasksCustomMetaData.TYPE); PersistentTask task = tasks.getTask(MlMetadata.jobTaskId(jobId)); DiscoveryNode node = clusterState.nodes().resolveNode(task.getExecutorNode()); Map<String, String> expectedNodeAttr = new HashMap<>(); expectedNodeAttr.put(MachineLearning.ML_ENABLED_NODE_ATTR, "true"); assertEquals(expectedNodeAttr, node.getAttributes()); JobTaskStatus jobTaskStatus = (JobTaskStatus) task.getStatus(); assertNotNull(jobTaskStatus); assertEquals(JobState.OPENED, jobTaskStatus.getState()); }); logger.info("stop the only running ml node"); internalCluster().stopRandomNode(settings -> settings.getAsBoolean(MachineLearning.ML_ENABLED.getKey(), true)); ensureStableCluster(2); assertBusy(() -> { // job should get and remain in a failed state and // the status remains to be opened as from ml we didn't had the chance to set the status to failed: assertJobTask(jobId, JobState.OPENED, false); }); logger.info("start ml node"); internalCluster().startNode(Settings.builder().put(MachineLearning.ML_ENABLED.getKey(), true)); ensureStableCluster(3); assertBusy(() -> { // job should be re-opened: assertJobTask(jobId, JobState.OPENED, true); }); } public void testMaxConcurrentJobAllocations() throws Exception { int numMlNodes = 2; internalCluster().ensureAtMostNumDataNodes(0); // start non ml node, but that will hold the indices logger.info("Start non ml node:"); String nonMlNode = internalCluster().startNode(Settings.builder() .put(MachineLearning.ML_ENABLED.getKey(), false)); logger.info("Starting ml nodes"); internalCluster().startNodes(numMlNodes, Settings.builder() .put("node.data", false) .put("node.master", false) .put(MachineLearning.ML_ENABLED.getKey(), true).build()); ensureStableCluster(numMlNodes + 1); int maxConcurrentJobAllocations = randomIntBetween(1, 4); client().admin().cluster().prepareUpdateSettings() .setTransientSettings(Settings.builder() .put(MachineLearning.CONCURRENT_JOB_ALLOCATIONS.getKey(), maxConcurrentJobAllocations)) .get(); // Sample each cs update and keep track each time a node holds more than `maxConcurrentJobAllocations` opening jobs. List<String> violations = new CopyOnWriteArrayList<>(); internalCluster().clusterService(nonMlNode).addListener(event -> { PersistentTasksCustomMetaData tasks = event.state().metaData().custom(PersistentTasksCustomMetaData.TYPE); if (tasks == null) { return; } for (DiscoveryNode node : event.state().nodes()) { Collection<PersistentTask<?>> foundTasks = tasks.findTasks(OpenJobAction.TASK_NAME, task -> { JobTaskStatus jobTaskState = (JobTaskStatus) task.getStatus(); return node.getId().equals(task.getExecutorNode()) && (jobTaskState == null || jobTaskState.isStatusStale(task)); }); int count = foundTasks.size(); if (count > maxConcurrentJobAllocations) { violations.add("Observed node [" + node.getName() + "] with [" + count + "] opening jobs on cluster state version [" + event.state().version() + "]"); } } }); int numJobs = numMlNodes * 10; for (int i = 0; i < numJobs; i++) { Job.Builder job = createJob(Integer.toString(i)); PutJobAction.Request putJobRequest = new PutJobAction.Request(job); PutJobAction.Response putJobResponse = client().execute(PutJobAction.INSTANCE, putJobRequest).actionGet(); assertTrue(putJobResponse.isAcknowledged()); OpenJobAction.Request openJobRequest = new OpenJobAction.Request(job.getId()); client().execute(OpenJobAction.INSTANCE, openJobRequest).actionGet(); } assertBusy(checkAllJobsAreAssignedAndOpened(numJobs)); logger.info("stopping ml nodes"); for (int i = 0; i < numMlNodes; i++) { // fork so stopping all ml nodes proceeds quicker: Runnable r = () -> { try { internalCluster() .stopRandomNode(settings -> settings.getAsBoolean(MachineLearning.ML_ENABLED.getKey(), false)); } catch (IOException e) { logger.error("error stopping node", e); } }; new Thread(r).start(); } ensureStableCluster(1, nonMlNode); assertBusy(() -> { ClusterState state = client(nonMlNode).admin().cluster().prepareState().get().getState(); PersistentTasksCustomMetaData tasks = state.metaData().custom(PersistentTasksCustomMetaData.TYPE); assertEquals(numJobs, tasks.taskMap().size()); for (PersistentTask<?> task : tasks.taskMap().values()) { assertNull(task.getExecutorNode()); } }); logger.info("re-starting ml nodes"); internalCluster().startNodes(numMlNodes, Settings.builder() .put("node.data", false) .put("node.master", false) .put(MachineLearning.ML_ENABLED.getKey(), true).build()); ensureStableCluster(1 + numMlNodes); assertBusy(checkAllJobsAreAssignedAndOpened(numJobs), 30, TimeUnit.SECONDS); assertEquals("Expected no violations, but got [" + violations + "]", 0, violations.size()); } public void testMlIndicesNotAvailable() throws Exception { internalCluster().ensureAtMostNumDataNodes(0); // start non ml node, but that will hold the indices logger.info("Start non ml node:"); ensureStableCluster(1); logger.info("Starting ml node"); String mlNode = internalCluster().startNode(Settings.builder() .put("node.data", false) .put(MachineLearning.ML_ENABLED.getKey(), true)); ensureStableCluster(2); String jobId = "ml-indices-not-available-job"; Job.Builder job = createFareQuoteJob(jobId); PutJobAction.Request putJobRequest = new PutJobAction.Request(job); PutJobAction.Response putJobResponse = client().execute(PutJobAction.INSTANCE, putJobRequest).actionGet(); assertTrue(putJobResponse.isAcknowledged()); OpenJobAction.Request openJobRequest = new OpenJobAction.Request(job.getId()); client().execute(OpenJobAction.INSTANCE, openJobRequest).actionGet(); PostDataAction.Request postDataRequest = new PostDataAction.Request(jobId); postDataRequest.setContent(new BytesArray( "{\"airline\":\"AAL\",\"responsetime\":\"132.2046\",\"sourcetype\":\"farequote\",\"time\":\"1403481600\"}\n" + "{\"airline\":\"JZA\",\"responsetime\":\"990.4628\",\"sourcetype\":\"farequote\",\"time\":\"1403481700\"}" ), XContentType.JSON); PostDataAction.Response response = client().execute(PostDataAction.INSTANCE, postDataRequest).actionGet(); assertEquals(2, response.getDataCounts().getProcessedRecordCount()); CloseJobAction.Request closeJobRequest = new CloseJobAction.Request(jobId); client().execute(CloseJobAction.INSTANCE, closeJobRequest).actionGet(); assertBusy(() -> { ClusterState clusterState = client().admin().cluster().prepareState().get().getState(); PersistentTasksCustomMetaData tasks = clusterState.getMetaData().custom(PersistentTasksCustomMetaData.TYPE); assertEquals(0, tasks.taskMap().size()); }); logger.info("Stop data node"); internalCluster().stopRandomNode(settings -> settings.getAsBoolean("node.data", true)); ensureStableCluster(1); Exception e = expectThrows(ElasticsearchStatusException.class, () -> client().execute(OpenJobAction.INSTANCE, openJobRequest).actionGet()); assertTrue(e.getMessage().startsWith("Could not open job because no suitable nodes were found, allocation explanation")); assertTrue(e.getMessage().endsWith("because not all primary shards are active for the following indices [.ml-anomalies-shared]]")); logger.info("Start data node"); String nonMlNode = internalCluster().startNode(Settings.builder() .put("node.data", true) .put(MachineLearning.ML_ENABLED.getKey(), false)); ensureStableCluster(2, mlNode); ensureStableCluster(2, nonMlNode); ensureYellow(); // at least the primary shards of the indices a job uses should be started client().execute(OpenJobAction.INSTANCE, openJobRequest).actionGet(); assertBusy(() -> assertJobTask(jobId, JobState.OPENED, true)); } private void assertJobTask(String jobId, JobState expectedState, boolean hasExecutorNode) { ClusterState clusterState = client().admin().cluster().prepareState().get().getState(); PersistentTasksCustomMetaData tasks = clusterState.getMetaData().custom(PersistentTasksCustomMetaData.TYPE); assertEquals(1, tasks.taskMap().size()); PersistentTask<?> task = MlMetadata.getJobTask(jobId, tasks); assertNotNull(task); if (hasExecutorNode) { assertNotNull(task.getExecutorNode()); assertFalse(task.needsReassignment(clusterState.nodes())); DiscoveryNode node = clusterState.nodes().resolveNode(task.getExecutorNode()); Map<String, String> expectedNodeAttr = new HashMap<>(); expectedNodeAttr.put(MachineLearning.ML_ENABLED_NODE_ATTR, "true"); assertEquals(expectedNodeAttr, node.getAttributes()); JobTaskStatus jobTaskStatus = (JobTaskStatus) task.getStatus(); assertNotNull(jobTaskStatus); assertEquals(expectedState, jobTaskStatus.getState()); } else { assertNull(task.getExecutorNode()); } } private Runnable checkAllJobsAreAssignedAndOpened(int numJobs) { return () -> { ClusterState state = client().admin().cluster().prepareState().get().getState(); PersistentTasksCustomMetaData tasks = state.metaData().custom(PersistentTasksCustomMetaData.TYPE); assertEquals(numJobs, tasks.taskMap().size()); for (PersistentTask<?> task : tasks.taskMap().values()) { assertNotNull(task.getExecutorNode()); JobTaskStatus jobTaskStatus = (JobTaskStatus) task.getStatus(); assertNotNull(jobTaskStatus); assertEquals(JobState.OPENED, jobTaskStatus.getState()); } }; } }
package com.ilamstone.publicfortests; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashSet; import java.util.UUID; import java.util.logging.Logger; import org.assertj.core.internal.asm.Opcodes; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Handle; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.util.TraceClassVisitor; public class PFTGen { private static final Logger log = Logger.getLogger(PFTGen.class.getName()); static class TransformVisitor extends ClassVisitor { final Class<?> originalClass; final String originalClassInternalName; final String newClassInternalName; final ClassNode node = new ClassNode(); final HashSet<String> pftMethods = new HashSet<String>(); final HashSet<String> extraIfaces = new HashSet<String>(); public TransformVisitor(Class<?> originalClass) { super(Opcodes.ASM5); this.cv = node; this.originalClass = originalClass; this.originalClassInternalName = Type.getInternalName(originalClass); this.newClassInternalName = originalClass.getPackage().getName().replace('.', '/') + "/GeneratedClass" + UUID.randomUUID(); findPftMethodsAndInterfaces(); } public void findPftMethodsAndInterfaces() { for (Method m : originalClass.getDeclaredMethods()) { PublicForTests pft = m.getAnnotation(PublicForTests.class); if (pft != null) { try { Class<?> ifaceClass = Class.forName(pft.value()); String method = m.getName() + Type.getMethodDescriptor(m); pftMethods.add(method); extraIfaces.add(Type.getInternalName(ifaceClass)); } catch (ClassNotFoundException e) { log.warning(() -> "Testing interface '" + pft.value() + "' not found for method '" + m.toGenericString() + "'"); log.warning(() -> " This method will not be made public; This may cause ClassCastExceptions later on..."); } } } } @Override public void visit(int version, int access, String name, String signature, String superName, String[] originalInterfaces) { ArrayList<String> newIfaces = new ArrayList<String>(); for (String iface : originalInterfaces) { newIfaces.add(iface); } newIfaces.addAll(extraIfaces); super.visit(version, access, newClassInternalName, signature, superName, newIfaces.toArray(new String[newIfaces.size()])); } class TransformMethodVisitor extends MethodVisitor { public TransformMethodVisitor(MethodVisitor delegate) { super(Opcodes.ASM5, delegate); } @Override public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { if (originalClassInternalName.equals(owner)) { // We need to rewrite references to the original class to our new class. // This will probably be mostly INVOKESPECIALS, but also INVOKESTATICS as well. // In either case, refer to the method in our new class. Without this classes won't // verify when they call their own private methods. owner = newClassInternalName; } super.visitMethodInsn(opcode, owner, name, desc, itf); } @Override public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) { Object[] newArgs = new Object[bsmArgs.length]; for (int i = 0; i < bsmArgs.length; i++) { Object o = bsmArgs[i]; if (o instanceof Handle) { Handle h = (Handle)o; if (originalClassInternalName.equals(h.getOwner())) { newArgs[i] = new Handle(h.getTag(), newClassInternalName, h.getName(), h.getDesc(), h.isInterface()); } else { newArgs[i] = o; } } else { newArgs[i] = o; } } super.visitInvokeDynamicInsn(name, desc, bsm, newArgs); } @Override public void visitFieldInsn(int opcode, String owner, String name, String desc) { if (originalClassInternalName.equals(owner)) { owner = newClassInternalName; } super.visitFieldInsn(opcode, owner, name, desc); } } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { if (pftMethods.contains(name + desc)) { access = access & ~Opcodes.ACC_PRIVATE & ~Opcodes.ACC_PROTECTED; access = access | Opcodes.ACC_PUBLIC; } return new TransformMethodVisitor(cv.visitMethod(access, name, desc, signature, exceptions)); } public ClassNode getNode() { return this.node; } } static ClassNode generateNewClassNode(Class<?> clz, boolean trace) throws IOException { String clzInternalName = Type.getInternalName(clz); ClassReader reader = new ClassReader(clzInternalName); TransformVisitor visitor = new TransformVisitor(clz); reader.accept(visitor, ClassReader.SKIP_DEBUG); if (trace) { visitor.getNode().accept(new TraceClassVisitor(new PrintWriter(System.out))); } return visitor.getNode(); } static byte[] generateBytecode(ClassNode node) { ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); node.accept(writer); return writer.toByteArray(); } static Class<?> defineClass(ClassLoader loader, ClassNode node) { byte[] code = generateBytecode(node); try { Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", String.class, byte[].class, int.class, int.class); defineClass.setAccessible(true); return (Class<?>)defineClass.invoke(loader, node.name.replace('/', '.'), code, 0, code.length); } catch (NoSuchMethodException e) { System.err.println("NoSuchMethodException: defineClass on ClassLoader"); throw new RuntimeException("Unrecoverable Error", e); } catch (InvocationTargetException e) { System.err.println("InvocationTargetException: in defineClass: " + e.getMessage()); throw new RuntimeException("Unrecoverable Error", e); } catch (IllegalAccessException e) { System.err.println("IllegalAccessException: in defineClass: " + e.getMessage()); throw new RuntimeException("Unrecoverable Error", e); } } @SuppressWarnings("unchecked") public static <I> Class<I> getTestingClass(ClassLoader loader, Class<?> clz, boolean trace) { try { return (Class<I>)defineClass(loader, generateNewClassNode(clz, trace)); } catch (IOException e) { System.err.println("IOException: in getTestingClass: " + e.getMessage()); throw new RuntimeException("Unrecoverable Error", e); } } public static <I> Class<I> getTestingClass(ClassLoader loader, Class<?> clz) { return getTestingClass(loader, clz, false); } public static <I> Class<I> getTestingClass(Class<?> clz) { return getTestingClass(PFTGen.class.getClassLoader(), clz); } public static <I> Class<I> getTestingClass(Class<?> clz, boolean trace) { return getTestingClass(PFTGen.class.getClassLoader(), clz, trace); } }
package com.siyeh.ig.classlayout; import com.intellij.codeInsight.daemon.GroupNames; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.search.PsiSearchHelper; import com.intellij.psi.search.SearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.ClassInspection; import com.siyeh.ig.InspectionGadgetsFix; import org.jetbrains.annotations.NotNull; public class StaticInheritanceInspection extends ClassInspection{ public String getDisplayName(){ return "Static inheritance"; } public String getGroupDisplayName(){ return GroupNames.CLASSLAYOUT_GROUP_NAME; } public String buildErrorString(PsiElement location){ return "Interface #ref is implemented only for its static constants #loc"; } protected InspectionGadgetsFix buildFix(PsiElement location){ return new StaticInheritanceFix(); } private static class StaticInheritanceFix extends InspectionGadgetsFix{ public String getName(){ return "Replace inheritance with qualified references"; } public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException{ final PsiJavaCodeReferenceElement referenceElement = (PsiJavaCodeReferenceElement) descriptor.getPsiElement(); final String referencedClassName = referenceElement.getText(); final PsiClass iface = (PsiClass) referenceElement.resolve(); assert iface != null; final PsiField[] allFields = iface.getAllFields(); final PsiClass implementingClass = PsiTreeUtil.getParentOfType(referenceElement, PsiClass.class); final PsiManager manager = referenceElement.getManager(); final PsiSearchHelper searchHelper = manager.getSearchHelper(); assert implementingClass != null; final SearchScope searchScope = implementingClass.getUseScope(); for(final PsiField field : allFields){ final PsiReference[] references = searchHelper.findReferences(field, searchScope, false); for(PsiReference reference1 : references){ if(!(reference1 instanceof PsiReferenceExpression)) { continue; } final PsiReferenceExpression reference = (PsiReferenceExpression) reference1; if(reference.isQualified()){ final PsiExpression qualifier = reference.getQualifierExpression(); final String referenceName = reference.getReferenceName(); if(qualifier instanceof PsiReferenceExpression){ final PsiElement referent = ((PsiReferenceExpression) qualifier).resolve(); if(referent!=null && !referent.equals(iface)){ replaceExpression(reference, referencedClassName + '.' + referenceName); } } else{ replaceExpression(reference, referencedClassName + '.' + referenceName); } } else{ final String referenceText = reference.getText(); replaceExpression(reference, referencedClassName + '.' + referenceText); } } } deleteElement(referenceElement); } } public BaseInspectionVisitor buildVisitor(){ return new StaticInheritanceVisitor(); } private static class StaticInheritanceVisitor extends BaseInspectionVisitor{ public void visitClass(@NotNull PsiClass aClass){ // no call to super, so it doesn't drill down final PsiReferenceList implementsList = aClass.getImplementsList(); if(implementsList == null){ return; } final PsiJavaCodeReferenceElement[] refs = implementsList.getReferenceElements(); for(final PsiJavaCodeReferenceElement ref : refs){ final PsiClass iface = (PsiClass) ref.resolve(); if(iface != null){ if(interfaceContainsOnlyConstants(iface)){ registerError(ref); } } } } private boolean interfaceContainsOnlyConstants(PsiClass iface){ if(iface.getAllFields().length == 0){ // ignore it, it's either a true interface or just a marker return false; } if(iface.getMethods().length != 0){ return false; } final PsiClass[] parentInterfaces = iface.getInterfaces(); for(final PsiClass parentInterface : parentInterfaces){ if(!interfaceContainsOnlyConstants(parentInterface)){ return false; } } return true; } } }
package org.fundacionjala.automation.framework.maps.admin.locations; public class UpdateLocationMap { public static final String SAVE_BUTTON = "//span[text()='Save']/parent::button"; public static final String CANCEL_BUTTON = "//span[text()='Cancel']/parent::button"; public static final String LOCATION_NAME_FIELD = "//input[@id='location-add-name']"; public static final String LOCATION_DISPLAY_NAME_FIELD = "//input[@id='location-add-display-name']"; public static final String LOCATION_DESCRIPTION_AREA = "//textarea[@id='location-add-description']"; public static final String ADD_PARENT_LOCATION_BUTTON = "//div[@id='location-add-parent-location']/following::button[1]"; public static final String PARENT_LOCATION_FIELD = "//div[@id='location-add-parent-location']"; public static final String LOCATION_ASSOCIATION_LINK = "//a[text()='Location Associations']"; }
package com.justjournal.ctl; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpSession; import javax.sql.DataSource; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @Slf4j @RequestMapping("/image") @Controller public class ImageController { @Autowired private JdbcTemplate jdbcTemplate; @RequestMapping("/{id}") public ResponseEntity<byte[]> getByPath(@PathVariable("id") final int id) throws IOException { return get(id); } @RequestMapping("") public ResponseEntity<byte[]> get(@RequestParam("id") final int id) throws IOException { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); DataSource ds; Connection conn; PreparedStatement stmt = null; if (id < 1) { return new ResponseEntity<byte[]>(HttpStatus.BAD_REQUEST); } try { ds = jdbcTemplate.getDataSource(); conn = ds.getConnection(); stmt = conn.prepareStatement("CALL getimage(?)"); stmt.setInt(1, id); final ResultSet rs = stmt.executeQuery(); if (rs.next()) { final BufferedInputStream img = new BufferedInputStream(rs.getBinaryStream("image")); byte[] buf = new byte[4 * 1024]; // 4k buffer int len; while ((len = img.read(buf, 0, buf.length)) != -1) byteArrayOutputStream.write(buf, 0, len); final HttpHeaders headers = new HttpHeaders(); headers.setExpires(180); final String t = rs.getString("mimetype").trim(); if (t.equalsIgnoreCase(MediaType.IMAGE_GIF_VALUE)) headers.setContentType(MediaType.IMAGE_GIF); else if (t.equalsIgnoreCase(MediaType.IMAGE_JPEG_VALUE)) headers.setContentType(MediaType.IMAGE_JPEG); else if (t.equalsIgnoreCase(MediaType.IMAGE_PNG_VALUE)) headers.setContentType(MediaType.IMAGE_PNG); rs.close(); stmt.close(); conn.close(); return new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK); } rs.close(); stmt.close(); conn.close(); return new ResponseEntity<byte[]>(HttpStatus.NOT_FOUND); } catch (Exception e) { log.warn("Could not load image: " + e.toString()); return new ResponseEntity<byte[]>(HttpStatus.INTERNAL_SERVER_ERROR); } finally { try { if (stmt != null) stmt.close(); } catch (final SQLException sqlEx) { // ignore -- as we can't do anything about it here log.error(sqlEx.getMessage(), sqlEx); } } } @RequestMapping(value = "", method = RequestMethod.POST) public ResponseEntity upload(@RequestPart("file") MultipartFile file, HttpSession session) throws IOException { assert jdbcTemplate != null; final int rowsAffected; final Integer userIDasi = (Integer) session.getAttribute("auth.uid"); int userID = 0; if (userIDasi != null) { userID = userIDasi; } /* Make sure we are logged in */ if (userID < 1) { return new ResponseEntity(HttpStatus.FORBIDDEN); } final String contentType = file.getContentType(); final long sizeInBytes = file.getSize(); // must be large enough if (file.isEmpty() || sizeInBytes < 500) { return new ResponseEntity(HttpStatus.BAD_REQUEST); } byte[] data = file.getBytes(); Connection conn = null; PreparedStatement stmt = null; // create statement PreparedStatement stmtOn = null; // turn on avatar preference. PreparedStatement stmtRemove = null; // delete old ones try { // TODO: make this spring friendly conn = jdbcTemplate.getDataSource().getConnection(); stmtRemove = conn.prepareStatement("DELETE FROM user_pic WHERE id=? LIMIT 1"); stmtRemove.setInt(1, userID); stmtRemove.execute(); // do the create of the image stmt = conn.prepareStatement("INSERT INTO user_pic (id,date_modified,mimetype,image) VALUES(?,now(),?,?)"); stmt.setInt(1, userID); stmt.setString(2, contentType); stmt.setBytes(3, data); stmt.execute(); rowsAffected = stmt.getUpdateCount(); stmt.close(); // turn on avatars. stmtOn = conn.prepareStatement("UPDATE user_pref SET show_avatar=? WHERE id=? LIMIT 1"); stmtOn.setString(1, "Y"); stmtOn.setInt(2, userID); stmtOn.execute(); if (stmtOn.getUpdateCount() != 1) log.debug("error turning on avatar."); stmtOn.close(); conn.close(); conn.close(); log.info("RowsAffected: " + rowsAffected); if (rowsAffected == 1) return new ResponseEntity(HttpStatus.CREATED); } catch (final Exception e) { log.error("Error on database connection inserting avatar.", e); return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } finally { /* * Close any JDBC instances here that weren't * explicitly closed during normal code path, so * that we don't 'leak' resources... */ try { if (stmt != null) stmt.close(); } catch (final SQLException sqlEx) { // ignore -- as we can't do anything about it here log.error(sqlEx.getMessage(), sqlEx); } try { stmtOn.close(); } catch (SQLException sqlEx) { // ignore -- as we can't do anything about it here log.debug(sqlEx.getMessage()); } try { stmtRemove.close(); } catch (SQLException sqlEx) { // ignore -- as we can't do anything about it here log.debug(sqlEx.getMessage()); } try { if (conn != null) conn.close(); } catch (final SQLException sqlEx) { // ignore -- as we can't do anything about it here log.error(sqlEx.getMessage(), sqlEx); } } return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public ResponseEntity delete(@PathVariable("id") final int id, final HttpSession session) { // Retreive user id final Integer userIDasi = (Integer) session.getAttribute("auth.uid"); // convert Integer to int type int userID = 0; if (userIDasi != null) { userID = userIDasi; } /* Make sure we are logged in */ if (userID < 1) { return new ResponseEntity(HttpStatus.FORBIDDEN); } try { jdbcTemplate.execute("DELETE FROM user_pic WHERE id='" + id + "';"); jdbcTemplate.execute("UPDATE user_pref SET show_avatar='N' WHERE id='" + id + "' LIMIT 1"); } catch (final DataAccessException dae) { log.error(dae.getMessage(), dae); return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } return new ResponseEntity(HttpStatus.OK); } }
package com.gazbert.bxbot.ui.server.repository.remote.impl; import com.gazbert.bxbot.ui.server.domain.bot.BotConfig; import com.gazbert.bxbot.ui.server.domain.engine.EngineConfig; import com.gazbert.bxbot.ui.server.repository.remote.EngineConfigRepository; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.http.client.support.BasicAuthorizationInterceptor; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; /** * A REST client implementation of the remote Engine config repository. * * @author gazbert */ @Repository("engineConfigRepository") @Transactional public class EngineConfigRepositoryRestClient implements EngineConfigRepository { private static final Logger LOG = LogManager.getLogger(); private static final String REST_ENDPOINT_PATH = "/config/engine"; private RestTemplate restTemplate; public EngineConfigRepositoryRestClient(RestTemplateBuilder restTemplateBuilder) { this.restTemplate = restTemplateBuilder.build(); } @Override public EngineConfig get(BotConfig botConfig) { try { restTemplate.getInterceptors().clear(); restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor( botConfig.getUsername(), botConfig.getPassword())); final String endpointUrl = botConfig.getBaseUrl() + REST_ENDPOINT_PATH; LOG.info(() -> "Fetching EngineConfig from: " + endpointUrl); final EngineConfig config = restTemplate.getForObject(endpointUrl, EngineConfig.class); LOG.info(() -> "Response received from remote Bot: " + config); return config; } catch(RestClientException e) { LOG.error("Failed to invoke remote bot! Details: " + e.getMessage(), e); return null; } } @Override public EngineConfig save(BotConfig botConfig, EngineConfig engineConfig) { LOG.info(() -> "About to save EngineConfig: " + engineConfig); restTemplate.getInterceptors().clear(); restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor( botConfig.getUsername(), botConfig.getPassword())); final String endpointUrl = botConfig.getBaseUrl() + REST_ENDPOINT_PATH; LOG.info(() -> "Sending EngineConfig to: " + endpointUrl); final HttpEntity<EngineConfig> requestUpdate = new HttpEntity<>(engineConfig); final ResponseEntity<EngineConfig> savedConfig = restTemplate.exchange( endpointUrl, HttpMethod.PUT, requestUpdate, EngineConfig.class); LOG.info(() -> "Response received from remote Bot: " + savedConfig); return savedConfig.getBody(); } }
package com.librato.metrics; import com.codahale.metrics.*; import com.codahale.metrics.Timer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; public class LibratoReporter extends ScheduledReporter implements MetricsLibratoBatch.RateConverter, MetricsLibratoBatch.DurationConverter { private static final Logger LOG = LoggerFactory.getLogger(LibratoReporter.class); private final DeltaTracker deltaTracker; private final String source; private final long timeout; private final TimeUnit timeoutUnit; private final Sanitizer sanitizer; private final HttpPoster httpPoster; private final String prefix; private final String prefixDelimiter; private final Pattern sourceRegex; private final boolean deleteIdleStats; private final boolean omitComplexGauges; protected final MetricRegistry registry; protected final Clock clock; protected final MetricExpansionConfig expansionConfig; /** * Private. Use builder instead. */ private LibratoReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit, Sanitizer customSanitizer, String source, long timeout, TimeUnit timeoutUnit, Clock clock, MetricExpansionConfig expansionConfig, HttpPoster httpPoster, String prefix, String prefixDelimiter, Pattern sourceRegex, boolean deleteIdleStats, boolean omitComplexGauges) { super(registry, name, filter, rateUnit, durationUnit); this.registry = registry; this.sanitizer = customSanitizer; this.source = source; this.timeout = timeout; this.timeoutUnit = timeoutUnit; this.clock = clock; this.expansionConfig = expansionConfig; this.httpPoster = httpPoster; this.prefix = prefix; this.prefixDelimiter = prefixDelimiter; this.sourceRegex = sourceRegex; this.deltaTracker = new DeltaTracker(new DeltaMetricSupplier(registry)); this.deleteIdleStats = deleteIdleStats; this.omitComplexGauges = omitComplexGauges; } public double convertMetricDuration(double duration) { return convertDuration(duration); } public double convertMetricRate(double rate) { return convertRate(rate); } /** * Used to supply metrics to the delta tracker on initialization. Uses the metric name conversion * to ensure that the correct names are supplied for the metric. */ class DeltaMetricSupplier implements DeltaTracker.MetricSupplier { final MetricRegistry registry; DeltaMetricSupplier(MetricRegistry registry) { this.registry = registry; } public Map<String, Metric> getMetrics() { final Map<String, Metric> map = new HashMap<String, Metric>(); for (Map.Entry<String, Metric> entry : registry.getMetrics().entrySet()) { // todo: ensure the name here is what we expect final String name = entry.getKey(); map.put(name, entry.getValue()); } return map; } } /** * Starts the reporter polling at the given period. * * @param period the amount of time between polls * @param unit the unit for {@code period} */ @Override public void start(long period, TimeUnit unit) { LOG.debug("Reporter starting at fixed rate of every {} {}", period, unit); super.start(period, unit); } @Override public void stop() { // Stop the scheduling of tasks before stopping the http client which the // tasks use super.stop(); try { httpPoster.close(); } catch (IOException e) { // Intentional NOP } } @Override public void report() { try { super.report(); } catch (Exception exception) { LOG.warn("Error sending report to librato", exception); } } @Override public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) { final long epoch = TimeUnit.MILLISECONDS.toSeconds(clock.getTime()); final MetricsLibratoBatch batch = new MetricsLibratoBatch( LibratoBatch.DEFAULT_BATCH_SIZE, sanitizer, timeout, timeoutUnit, expansionConfig, httpPoster, prefix, prefixDelimiter, deltaTracker, this, this, sourceRegex, omitComplexGauges); for (Map.Entry<String, Gauge> entry : gauges.entrySet()) { batch.addGauge(entry.getKey(), entry.getValue()); } for (Map.Entry<String, Counter> entry : counters.entrySet()) { batch.addCounter(entry.getKey(), entry.getValue()); } for (Map.Entry<String, Histogram> entry : histograms.entrySet()) { String name = entry.getKey(); Histogram histogram = entry.getValue(); if (skipMetric(name, histogram)) { continue; } batch.addHistogram(entry.getKey(), histogram); } for (Map.Entry<String, Meter> entry : meters.entrySet()) { String name = entry.getKey(); Meter meter = entry.getValue(); if (skipMetric(name, meter)) { continue; } batch.addMeter(name, meter); } for (Map.Entry<String, Timer> entry : timers.entrySet()) { String name = entry.getKey(); Timer timer = entry.getValue(); if (skipMetric(name, timer)) { continue; } batch.addTimer(name, timer); } BatchResult result = batch.post(source, epoch); for (PostResult postResult : result.getFailedPosts()) { LOG.warn("Failure posting to Librato: " + postResult); } } private boolean skipMetric(String name, Counting counting) { return deleteIdleStats() && deltaTracker.peekDelta(name, counting.getCount()) == 0; } private boolean deleteIdleStats() { return deleteIdleStats; } /** * A builder for the LibratoReporter class that requires things that cannot be inferred and uses * sane default values for everything else. */ public static class Builder { private String username; private String token; private final String source; private Sanitizer sanitizer = Sanitizer.NO_OP; private long timeout = 5; private TimeUnit timeoutUnit = TimeUnit.SECONDS; private TimeUnit rateUnit = TimeUnit.SECONDS; private TimeUnit durationUnit = TimeUnit.MILLISECONDS; private String name = "librato-reporter"; private final MetricRegistry registry; private MetricFilter filter = MetricFilter.ALL; private Clock clock = Clock.defaultClock(); private MetricExpansionConfig expansionConfig = MetricExpansionConfig.ALL; private HttpPoster httpPoster; private String prefix; private String prefixDelimiter = "."; private Pattern sourceRegex; private boolean deleteIdleStats = true; private boolean omitComplexGauges; public Builder(MetricRegistry registry, String username, String token, String source) { this.registry = registry; this.username = username; this.token = token; this.source = source; } /** * Sets whether or not complex gauges (includes mean, min, max) should be sent to Librato. Only * applies to Timers and Histograms. * * @param omitComplexGauges if the complex gauges should be elided * @return itself */ public Builder setOmitComplexGauges(boolean omitComplexGauges) { this.omitComplexGauges = omitComplexGauges; return this; } /** * Sets whether or not idle timers, meters, and histograms will be send to Librato or not. * * @param deleteIdleStats true if idle metrics should be elided * @return itself */ @SuppressWarnings("UnusedDeclaration") public Builder setDeleteIdleStats(boolean deleteIdleStats) { this.deleteIdleStats = deleteIdleStats; return this; } /** * Sets the source regular expression to be applied against metric names to determine dynamic sources. * * @param sourceRegex the regular expression * @return itself */ @SuppressWarnings("unused") public Builder setSourceRegex(Pattern sourceRegex) { this.sourceRegex = sourceRegex; return this; } /** * Sets the timeout for POSTs to Librato * * @param timeout the timeout * @return itself */ @SuppressWarnings("unused") public Builder setTimeout(long timeout) { this.timeout = timeout; return this; } /** * Sets the timeout time unit for POSTs to Librato * * @param timeoutUnit the timeout unit * @return itself */ @SuppressWarnings("unused") public Builder setTimeoutUnit(TimeUnit timeoutUnit) { this.timeoutUnit = timeoutUnit; return this; } /** * Sets the delimiter which will separate the prefix from the metric name. Defaults * to "." * * @param prefixDelimiter the delimiter * @return itself */ @SuppressWarnings("unused") public Builder setPrefixDelimiter(String prefixDelimiter) { this.prefixDelimiter = prefixDelimiter; return this; } /** * Sets a prefix that will be prepended to all metric names * * @param prefix the prefix * @return itself */ @SuppressWarnings("unused") public Builder setPrefix(String prefix) { this.prefix = prefix; return this; } /** * Sets the {@link HttpPoster} which will send the payload to Librato * * @param poster the HttpPoster * @return itself */ @SuppressWarnings("unused") public Builder setHttpPoster(HttpPoster poster) { this.httpPoster = poster; return this; } /** * Sets the time unit to which rates will be converted by the reporter. The default * value is TimeUnit.SECONDS * * @param rateUnit the rate * @return itself */ @SuppressWarnings("unused") public Builder setRateUnit(TimeUnit rateUnit) { this.rateUnit = rateUnit; return this; } /** * Sets the time unit to which durations will be converted by the reporter. The default * value is TimeUnit.MILLISECONDS * * @param durationUnit the time unit * @return itself */ @SuppressWarnings("unused") public Builder setDurationUnit(TimeUnit durationUnit) { this.durationUnit = durationUnit; return this; } /** * set the HTTP timeout for a publishing attempt * * @param timeout duration to expect a response * @param timeoutUnit unit for duration * @return itself */ @SuppressWarnings("unused") public Builder setTimeout(long timeout, TimeUnit timeoutUnit) { this.timeout = timeout; this.timeoutUnit = timeoutUnit; return this; } /** * Specify a custom name for this reporter * * @param name the name to be used * @return itself */ @SuppressWarnings("unused") public Builder setName(String name) { this.name = name; return this; } /** * Use a custom sanitizer. All metric names are run through a sanitizer to ensure validity before being sent * along. Librato places some restrictions on the characters allowed in keys, so all keys are ultimately run * through APIUtil.lastPassSanitizer. Specifying an additional sanitizer (that runs before lastPassSanitizer) * allows the user to customize what they want done about invalid characters and excessively long metric names. * * @param sanitizer the custom sanitizer to use (defaults to a noop sanitizer). * @return itself */ @SuppressWarnings("unused") public Builder setSanitizer(Sanitizer sanitizer) { this.sanitizer = sanitizer; return this; } /** * Filter the metrics that this particular reporter publishes * * @param filter the {@link MetricFilter} * @return itself */ @SuppressWarnings("unused") public Builder setFilter(MetricFilter filter) { this.filter = filter; return this; } /** * use a custom clock * * @param clock to be used * @return itself */ @SuppressWarnings("unused") public Builder setClock(Clock clock) { this.clock = clock; return this; } /** * Enables control over how the reporter generates 'expanded' metrics from meters and histograms, * such as percentiles and rates. * * @param expansionConfig the configuration * @return itself * @see {@link ExpandedMetric} */ @SuppressWarnings("unused") public Builder setExpansionConfig(MetricExpansionConfig expansionConfig) { this.expansionConfig = expansionConfig; return this; } /** * Build the LibratoReporter as configured by this Builder * * @return a fully configured LibratoReporter */ public LibratoReporter build() { constructHttpPoster(); return new LibratoReporter( registry, name, filter, rateUnit, durationUnit, sanitizer, source, timeout, timeoutUnit, clock, expansionConfig, httpPoster, prefix, prefixDelimiter, sourceRegex, deleteIdleStats, omitComplexGauges); } /** * Construct the httpPoster with httpClientConfig if it has been set. */ private void constructHttpPoster() { if (this.httpPoster == null) { String url = "https://metrics-api.librato.com/v1/metrics"; this.httpPoster = new DefaultHttpPoster(url, username, token); } } } /** * convenience method for creating a Builder */ public static Builder builder(MetricRegistry metricRegistry, String username, String token, String source) { return new Builder(metricRegistry, username, token, source); } public static enum ExpandedMetric { // sampling MEDIAN("median"), PCT_75("75th"), PCT_95("95th"), PCT_98("98th"), PCT_99("99th"), PCT_999("999th"), // metered COUNT("count"), RATE_MEAN("meanRate"), RATE_1_MINUTE("1MinuteRate"), RATE_5_MINUTE("5MinuteRate"), RATE_15_MINUTE("15MinuteRate"); private final String displayName; public String buildMetricName(String metric) { return metric + "." + displayName; } private ExpandedMetric(String displayName) { this.displayName = displayName; } } /** * Configures how to report "expanded" metrics derived from meters and histograms (e.g. percentiles, * rates, etc). Default is to report everything. * * @see ExpandedMetric */ public static class MetricExpansionConfig { public static MetricExpansionConfig ALL = new MetricExpansionConfig(EnumSet.allOf(ExpandedMetric.class)); private final Set<ExpandedMetric> enabled; public MetricExpansionConfig(Set<ExpandedMetric> enabled) { this.enabled = EnumSet.copyOf(enabled); } public boolean isSet(ExpandedMetric metric) { return enabled.contains(metric); } } /** * @param builder a LibratoReporter.Builder * @param interval the interval at which the metrics are to be reporter * @param unit the timeunit for interval */ public static void enable(Builder builder, long interval, TimeUnit unit) { builder.build().start(interval, unit); } }
package com.metaframe.cooma; import com.metaframe.cooma.internal.utils.ConcurrentHashSet; import com.metaframe.cooma.internal.utils.Holder; import com.metaframe.cooma.internal.utils.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.InputStreamReader; import java.lang.reflect.*; import java.net.URL; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.regex.Pattern; public class ExtensionLoader<T> { private static final Logger logger = LoggerFactory.getLogger(ExtensionLoader.class); private static final String SERVICES_DIRECTORY = "META-INF/services/"; private static final Pattern NAME_SEPARATOR = Pattern.compile("\\s*,+\\s*"); private static final ConcurrentMap<Class<?>, ExtensionLoader<?>> EXTENSION_LOADERS = new ConcurrentHashMap<Class<?>, ExtensionLoader<?>>(); @SuppressWarnings("unchecked") public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) { if (type == null) throw new IllegalArgumentException("Extension type == null"); if(!withExtensionAnnotation(type)) { throw new IllegalArgumentException("type(" + type + ") is not a extension, because WITHOUT @Extension Annotation!"); } ExtensionLoader<T> loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type); if (loader == null) { EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader<T>(type)); loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type); } return loader; } public T getExtension(String name) { if (name == null || name.length() == 0) throw new IllegalArgumentException("Extension name == null"); Holder<T> holder = extInstances.get(name); if (holder == null) { extInstances.putIfAbsent(name, new Holder<T>()); holder = extInstances.get(name); } T instance = holder.get(); if (instance == null) { synchronized (holder) { // holder instance = holder.get(); if (instance == null) { instance = createExtension(name); holder.set(instance); } } } return instance; } /** * <code>null</code> * * @since 0.1.0 */ public T getDefaultExtension() { getExtensionClasses(); if(null == defaultExtension || defaultExtension.length() == 0) { return null; } return getExtension(defaultExtension); } public boolean hasExtension(String name) { if (name == null || name.length() == 0) throw new IllegalArgumentException("Extension name == null"); try { return getExtensionClass(name) != null; } catch (Throwable t) { return false; } } /** * <code>null</code> * * @since 0.1.0 */ public String getDefaultExtensionName() { getExtensionClasses(); return defaultExtension; } /** * @since 0.1.0 */ public Set<String> getSupportedExtensions() { Map<String, Class<?>> classes = getExtensionClasses(); return Collections.unmodifiableSet(new TreeSet<String>(classes.keySet())); } /** * @since 0.1.0 */ public String getExtensionName(T extensionInstance) { return getExtensionName(extensionInstance.getClass()); } /** * @since 0.1.0 */ public String getExtensionName(Class<?> extensionClass) { // FIXME return extClass2Name.get(extensionClass); } /** * Adaptive * ExtensionLoaderAdaptive * * @deprecated Adaptive * @since 0.1.0 */ @Deprecated public T getAdaptiveExtension() { if(createAdaptiveInstanceError == null) { try { return createAdaptiveInstance(); } catch (Throwable t) { createAdaptiveInstanceError = t; throw new IllegalStateException("Fail to create adaptive extension " + type + ", cause: " + t.getMessage(), t); } } else { throw new IllegalStateException("Fail to create adaptive extension " + type + ", cause: " + createAdaptiveInstanceError.getMessage(), createAdaptiveInstanceError); } } @Override public String toString() { return this.getClass().getName() + "<" + type.getName() + ">"; } // internal methods private final Class<T> type; private final String defaultExtension; private final ConcurrentMap<String, Holder<T>> extInstances = new ConcurrentHashMap<String, Holder<T>>(); private ExtensionLoader(Class<T> type) { this.type = type; String defaultExt = null; final Extension annotation = type.getAnnotation(Extension.class); if(annotation != null) { String value = annotation.value(); if(value != null && (value = value.trim()).length() > 0) { String[] names = NAME_SEPARATOR.split(value); if(names.length > 1) { throw new IllegalStateException("more than 1 default extension name on extension " + type.getName() + ": " + Arrays.toString(names)); } if(names.length == 1 && names[0].trim().length() > 0) { defaultExt = names[0].trim(); } } } defaultExtension = defaultExt; } @SuppressWarnings("unchecked") private T createExtension(String name) { Class<?> clazz = getExtensionClasses().get(name); if (clazz == null) { throw findExtensionClassLoadException(name); } try { T instance = injectExtension((T) clazz.newInstance()); Set<Class<?>> wrapperClasses = this.wrapperClasses; if (wrapperClasses != null && wrapperClasses.size() > 0) { for (Class<?> wrapperClass : wrapperClasses) { instance = injectExtension((T) wrapperClass.getConstructor(type).newInstance(instance)); } } return instance; } catch (Throwable t) { throw new IllegalStateException("Extension instance(name: " + name + ", class: " + type + ") could not be instantiated: " + t.getMessage(), t); } } private T injectExtension(T instance) { try { for (Method method : instance.getClass().getMethods()) { if (method.getName().startsWith("set") && method.getParameterTypes().length == 1 && Modifier.isPublic(method.getModifiers())) { Class<?> pt = method.getParameterTypes()[0]; if (pt.isInterface() && withExtensionAnnotation(pt) && getExtensionLoader(pt).getSupportedExtensions().size() > 0) { try { Object adaptive = getExtensionLoader(pt).getAdaptiveExtension(); method.invoke(instance, adaptive); } catch (Exception e) { logger.error("fail to inject via method " + method.getName() + " of interface " + type.getName() + ": " + e.getMessage(), e); } } } } } catch (Exception e) { logger.error(e.getMessage(), e); } return instance; } // get & create Adaptive Instance private final Holder<T> adaptiveInstanceHolder = new Holder<T>(); private volatile Throwable createAdaptiveInstanceError; private final Map<Method, Integer> method2ConfigArgIndex = new HashMap<Method, Integer>(); private final Map<Method, Method> method2ConfigGetter = new HashMap<Method, Method>(); /** * Thread-safe. */ private T createAdaptiveInstance() { T adaptiveInstance = adaptiveInstanceHolder.get(); if(null != adaptiveInstance) { return adaptiveInstance; } getExtensionClasses(); synchronized (adaptiveInstanceHolder) { adaptiveInstance = adaptiveInstanceHolder.get(); if(null != adaptiveInstance) { // double check return adaptiveInstance; } checkAndSetAdaptiveInfo0(); Object p = Proxy.newProxyInstance(ExtensionLoader.class.getClassLoader(), new Class[]{type}, new InvocationHandler() { // FIXME toString public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // if(method.getDeclaringClass().equals(Object.class)) { // return if(!method2ConfigArgIndex.containsKey(method)) { throw new UnsupportedOperationException("method " + method.getName() + " of interface " + type.getName() + " is not adaptive method!"); } int confArgIdx = method2ConfigArgIndex.get(method); Object confArg = args[confArgIdx]; Config config; if(method2ConfigGetter.containsKey(method)) { if(confArg == null) { throw new IllegalArgumentException(method.getParameterTypes()[confArgIdx].getName() + " argument == null"); } Method configGetter = method2ConfigGetter.get(method); config = (Config) configGetter.invoke(confArg); if(config == null) { throw new IllegalArgumentException(method.getParameterTypes()[confArgIdx].getName() + " argument " + configGetter.getName() + "() == null"); } } else { if(confArg == null) { throw new IllegalArgumentException("config == null"); } config = (Config) confArg; } String[] value = method.getAnnotation(Adaptive.class).value(); if(value.length == 0) { value = new String[]{StringUtils.toDotSpiteString(type.getSimpleName())}; } String extName = null; for(int i = 0; i < value.length; ++i) { if(!config.contains(value[i])) { if(i == value.length - 1) extName = defaultExtension; continue; } extName = config.get(value[i]); break; } if(extName == null) throw new IllegalStateException("Fail to get extension(" + type.getName() + ") name from config(" + config + ") use keys())"); return method.invoke(ExtensionLoader.this.getExtension(extName), args); } }); T adaptive = type.cast(p); adaptiveInstanceHolder.set(adaptive); return adaptiveInstanceHolder.get(); } } private void checkAndSetAdaptiveInfo0() { Method[] methods = type.getMethods(); boolean hasAdaptiveAnnotation = false; for(Method m : methods) { if(m.isAnnotationPresent(Adaptive.class)) { hasAdaptiveAnnotation = true; break; } } // AdaptiveAdaptive if(! hasAdaptiveAnnotation) throw new IllegalStateException("No adaptive method on extension " + type.getName() + ", refuse to create the adaptive class!"); // ConfigConfigConfig for(Method method : methods) { Adaptive annotation = method.getAnnotation(Adaptive.class); // AdaptiveConfig if(annotation == null) continue; // Configs Class<?>[] parameterTypes = method.getParameterTypes(); for(int i = 0; i < parameterTypes.length; ++i) { if(Config.class.isAssignableFrom(parameterTypes[i])) { method2ConfigArgIndex.put(method, i); break; } } if(method2ConfigArgIndex.containsKey(method)) continue; // Configs LBL_PARAMETER_TYPES: for (int i = 0; i < parameterTypes.length; ++i) { Method[] ms = parameterTypes[i].getMethods(); for (Method m : ms) { String name = m.getName(); if ((name.startsWith("get") || name.length() > 3) && Modifier.isPublic(m.getModifiers()) && !Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0 && Config.class.isAssignableFrom(m.getReturnType())) { method2ConfigArgIndex.put(method, i); method2ConfigGetter.put(method, m); break LBL_PARAMETER_TYPES; } } } if(!method2ConfigArgIndex.containsKey(method)) { throw new IllegalStateException("fail to create adaptive class for interface " + type.getName() + ": not found config parameter or config attribute in parameters of method " + method.getName()); } } } // get & load Extension Class // Holder<Map<ext-name, ext-class>> private final Holder<Map<String, Class<?>>> extClassesHolder = new Holder<Map<String,Class<?>>>(); private volatile Class<?> adaptiveClass = null; private Set<Class<?>> wrapperClasses; private final ConcurrentMap<Class<?>, String> extClass2Name = new ConcurrentHashMap<Class<?>, String>(); private Map<String, IllegalStateException> extClassLoadExceptions = new ConcurrentHashMap<String, IllegalStateException>(); private Class<?> getExtensionClass(String name) { if (name == null) throw new IllegalArgumentException("Extension name == null"); Class<?> clazz = getExtensionClasses().get(name); if (clazz == null) throw findExtensionClassLoadException(name); return clazz; } /** * Thread-safe */ private Map<String, Class<?>> getExtensionClasses() { Map<String, Class<?>> classes = extClassesHolder.get(); if (classes == null) { synchronized (extClassesHolder) { classes = extClassesHolder.get(); if (classes == null) { // double check classes = loadExtensionClasses0(); extClassesHolder.set(classes); } } } return classes; } private IllegalStateException findExtensionClassLoadException(String name) { String msg = "No such extension " + type.getName() + " by name " + name; for (Map.Entry<String, IllegalStateException> entry : extClassLoadExceptions.entrySet()) { if (entry.getKey().toLowerCase().contains(name.toLowerCase())) { IllegalStateException e = entry.getValue(); return new IllegalStateException(msg + ", cause: " + e.getMessage(), e); } } StringBuilder buf = new StringBuilder(msg); if(!extClassLoadExceptions.isEmpty()) { buf.append(", possible causes: "); int i = 1; for (Map.Entry<String, IllegalStateException> entry : extClassLoadExceptions.entrySet()) { buf.append("\r\n("); buf.append(i++); buf.append(") "); buf.append(entry.getKey()); buf.append(":\r\n"); buf.append(StringUtils.toString(entry.getValue())); } } return new IllegalStateException(buf.toString()); } private Map<String, Class<?>> loadExtensionClasses0() { Map<String, Class<?>> extName2Class = new HashMap<String, Class<?>>(); String fileName = null; try { ClassLoader classLoader = getClassLoader(); fileName = SERVICES_DIRECTORY + type.getName(); Enumeration<java.net.URL> urls; if (classLoader != null) { urls = classLoader.getResources(fileName); } else { urls = ClassLoader.getSystemResources(fileName); } if(urls == null) { // FIXME throw exception to notify no extension found? return extName2Class; } while (urls.hasMoreElements()) { java.net.URL url = urls.nextElement(); readExtension0(extName2Class, classLoader, url); } } catch (Throwable t) { logger.error("Exception when load extension class(interface: " + type + ", description file: " + fileName + ").", t); } return extName2Class; } private void readExtension0(Map<String, Class<?>> extName2Class, ClassLoader classLoader, URL url) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line; while ((line = reader.readLine()) != null) { // delete comments final int ci = line.indexOf(' if (ci >= 0) line = line.substring(0, ci); line = line.trim(); if (line.length() == 0) continue; try { String name = null; int i = line.indexOf('='); if (i > 0) { name = line.substring(0, i).trim(); line = line.substring(i + 1).trim(); } Class<?> clazz = Class.forName(line, true, classLoader); if (! type.isAssignableFrom(clazz)) { throw new IllegalStateException("Error when load extension class(interface: " + type + ", class line: " + clazz.getName() + "), class " + clazz.getName() + "is not subtype of interface."); } if (clazz.isAnnotationPresent(Adaptive.class)) { if(adaptiveClass == null) { adaptiveClass = clazz; } else if (! adaptiveClass.equals(clazz)) { throw new IllegalStateException("More than 1 adaptive class found: " + adaptiveClass.getClass().getName() + ", " + clazz.getClass().getName()); } } else { if(hasCopyConstructor(clazz)) { Set<Class<?>> wrappers = wrapperClasses; if (wrappers == null) { wrapperClasses = new ConcurrentHashSet<Class<?>>(); wrappers = wrapperClasses; } wrappers.add(clazz); } else { clazz.getConstructor(); // Extension if (name == null || name.length() == 0) { name = findAnnotationName(clazz); if(name == null || name.length() == 0) { throw new IllegalStateException( "No such extension name for the class " + clazz.getName() + " in the config " + url); } } String[] nameList = NAME_SEPARATOR.split(name); for (String n : nameList) { if (! extClass2Name.containsKey(clazz)) { extClass2Name.put(clazz, n); // FIXME } Class<?> c = extName2Class.get(n); if (c == null) { extName2Class.put(n, clazz); } else if (c != clazz) { throw new IllegalStateException("Duplicate extension " + type.getName() + " name " + n + " on " + c.getName() + " and " + clazz.getName()); } } } } } catch (Throwable t) { IllegalStateException e = new IllegalStateException("Failed to load extension class(interface: " + type + ", class line: " + line + ") in " + url + ", cause: " + t.getMessage(), t); extClassLoadExceptions.put(line, e); } } // end of while read lines } catch (Throwable t) { logger.error("Exception when load extension class(interface: " + type + ", class file: " + url + ") in " + url, t); } finally { if(reader != null) { try { reader.close(); } catch (Throwable t) { // ignore } } } } // small helper methods private boolean hasCopyConstructor(Class<?> clazz) { try { clazz.getConstructor(type); return true; } catch (NoSuchMethodException e) { // ignore } return false; } private String findAnnotationName(Class<?> clazz) { Extension extension = clazz.getAnnotation(Extension.class); return extension == null ? null : extension.value().trim(); } private static ClassLoader getClassLoader() { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if (classLoader != null) { return classLoader; } classLoader = ExtensionLoader.class.getClassLoader(); if(classLoader != null) { return classLoader; } return classLoader; } private static <T> boolean withExtensionAnnotation(Class<T> type) { return type.isAnnotationPresent(Extension.class); } }
package org.wildfly.clustering.web.infinispan.session; import org.infinispan.Cache; import org.infinispan.remoting.transport.Address; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.jboss.msc.service.ValueService; import org.jboss.msc.value.InjectedValue; import org.jboss.msc.value.Value; import org.wildfly.clustering.dispatcher.CommandDispatcherFactory; import org.wildfly.clustering.ee.infinispan.TransactionBatch; import org.wildfly.clustering.group.NodeFactory; import org.wildfly.clustering.infinispan.spi.affinity.KeyAffinityServiceFactory; import org.wildfly.clustering.infinispan.spi.service.CacheContainerServiceName; import org.wildfly.clustering.infinispan.spi.service.CacheBuilder; import org.wildfly.clustering.infinispan.spi.service.CacheServiceName; import org.wildfly.clustering.infinispan.spi.service.TemplateConfigurationBuilder; import org.wildfly.clustering.registry.Registry; import org.wildfly.clustering.service.AliasServiceBuilder; import org.wildfly.clustering.service.Builder; import org.wildfly.clustering.service.SubGroupServiceNameFactory; import org.wildfly.clustering.spi.CacheGroupServiceName; import org.wildfly.clustering.spi.GroupServiceName; import org.wildfly.clustering.web.session.SessionManagerFactoryConfiguration; import org.wildfly.clustering.web.session.SessionManagerFactory; public class InfinispanSessionManagerFactoryBuilder implements Builder<SessionManagerFactory<TransactionBatch>>, Value<SessionManagerFactory<TransactionBatch>>, InfinispanSessionManagerFactoryConfiguration { public static final String DEFAULT_CACHE_CONTAINER = "web"; private static ServiceName getCacheServiceName(String cacheName) { ServiceName baseServiceName = CacheContainerServiceName.CACHE_CONTAINER.getServiceName(DEFAULT_CACHE_CONTAINER).getParent(); ServiceName serviceName = ServiceName.parse((cacheName != null) ? cacheName : DEFAULT_CACHE_CONTAINER); if (!baseServiceName.isParentOf(serviceName)) { serviceName = baseServiceName.append(serviceName); } return (serviceName.length() < 4) ? serviceName.append(SubGroupServiceNameFactory.DEFAULT_SUB_GROUP) : serviceName; } private final SessionManagerFactoryConfiguration configuration; @SuppressWarnings("rawtypes") private final InjectedValue<Cache> cache = new InjectedValue<>(); private final InjectedValue<KeyAffinityServiceFactory> affinityFactory = new InjectedValue<>(); private final InjectedValue<CommandDispatcherFactory> dispatcherFactory = new InjectedValue<>(); @SuppressWarnings("rawtypes") private final InjectedValue<NodeFactory> nodeFactory = new InjectedValue<>(); public InfinispanSessionManagerFactoryBuilder(SessionManagerFactoryConfiguration configuration) { this.configuration = configuration; } @Override public ServiceName getServiceName() { return ServiceName.JBOSS.append("clustering", "web", this.configuration.getDeploymentName()); } @Override public ServiceBuilder<SessionManagerFactory<TransactionBatch>> build(ServiceTarget target) { ServiceName templateCacheServiceName = getCacheServiceName(this.configuration.getCacheName()); String templateCacheName = templateCacheServiceName.getSimpleName(); String containerName = templateCacheServiceName.getParent().getSimpleName(); String cacheName = this.configuration.getDeploymentName(); new TemplateConfigurationBuilder(containerName, cacheName, templateCacheName).build(target).install(); new CacheBuilder<>(containerName, cacheName).build(target) .addAliases(InfinispanRouteLocatorBuilder.getCacheServiceAlias(cacheName)) .install(); new AliasServiceBuilder<>(InfinispanRouteLocatorBuilder.getNodeFactoryServiceAlias(cacheName), CacheGroupServiceName.NODE_FACTORY.getServiceName(containerName, RouteCacheGroupBuilderProvider.CACHE_NAME), NodeFactory.class).build(target).install(); new AliasServiceBuilder<>(InfinispanRouteLocatorBuilder.getRegistryServiceAlias(cacheName), CacheGroupServiceName.REGISTRY.getServiceName(containerName, RouteCacheGroupBuilderProvider.CACHE_NAME), Registry.class).build(target).install(); return target.addService(this.getServiceName(), new ValueService<>(this)) .addDependency(CacheServiceName.CACHE.getServiceName(containerName, cacheName), Cache.class, this.cache) .addDependency(CacheContainerServiceName.AFFINITY.getServiceName(containerName), KeyAffinityServiceFactory.class, this.affinityFactory) .addDependency(GroupServiceName.COMMAND_DISPATCHER.getServiceName(containerName), CommandDispatcherFactory.class, this.dispatcherFactory) .addDependency(InfinispanRouteLocatorBuilder.getNodeFactoryServiceAlias(cacheName), NodeFactory.class, this.nodeFactory) .setInitialMode(ServiceController.Mode.ON_DEMAND) ; } @Override public SessionManagerFactory<TransactionBatch> getValue() { return new InfinispanSessionManagerFactory(this); } @Override public SessionManagerFactoryConfiguration getSessionManagerFactoryConfiguration() { return this.configuration; } @Override public <K, V> Cache<K, V> getCache() { return this.cache.getValue(); } @Override public KeyAffinityServiceFactory getKeyAffinityServiceFactory() { return this.affinityFactory.getValue(); } @Override public CommandDispatcherFactory getCommandDispatcherFactory() { return this.dispatcherFactory.getValue(); } @Override public NodeFactory<Address> getNodeFactory() { return this.nodeFactory.getValue(); } }
package com.muzima.view.login; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Typeface; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.internal.nineoldandroids.animation.ValueAnimator; import com.muzima.MuzimaApplication; import com.muzima.R; import com.muzima.api.context.Context; import com.muzima.domain.Credentials; import com.muzima.service.CredentialsPreferenceService; import com.muzima.service.MuzimaSyncService; import com.muzima.service.WizardFinishPreferenceService; import com.muzima.utils.StringUtils; import com.muzima.view.MainActivity; import com.muzima.view.cohort.CohortWizardActivity; import static com.muzima.utils.Constants.DataSyncServiceConstants.SyncStatusConstants; //This class shouldn't extend BaseActivity. Since it is independent of the application's context public class LoginActivity extends Activity { private static final String TAG = "LoginActivity"; public static final String isFirstLaunch = "isFirstLaunch"; public static final String sessionTimeOut = "SessionTimeOut"; private EditText serverUrlText; private EditText usernameText; private EditText passwordText; private Button loginButton; private CheckBox updatePassword; private TextView versionText; private BackgroundAuthenticationTask backgroundAuthenticationTask; private TextView authenticatingText; private ValueAnimator flipFromNoConnToLoginAnimator; private ValueAnimator flipFromLoginToNoConnAnimator; private ValueAnimator flipFromLoginToAuthAnimator; private ValueAnimator flipFromAuthToLoginAnimator; private ValueAnimator flipFromAuthToNoConnAnimator; private boolean honeycombOrGreater; private boolean isUpdatePasswordChecked; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((MuzimaApplication) getApplication()).cancelTimer(); setContentView(R.layout.activity_login); showSessionTimeOutPopUpIfNeeded(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { honeycombOrGreater = true; } initViews(); setupListeners(); initAnimators(); boolean isFirstLaunch = getIntent().getBooleanExtra(LoginActivity.isFirstLaunch, true); String serverURL = getServerURL(); if (!isFirstLaunch && !StringUtils.isEmpty(serverURL)) { removeServerUrlAsInput(); } useSavedServerUrl(serverURL); if(isFirstLaunch){ removeChangedPasswordRecentlyCheckbox(); } //Hack to get it to use default font space. passwordText.setTypeface(Typeface.DEFAULT); versionText.setText(getApplicationVersion()); } private void showSessionTimeOutPopUpIfNeeded() { if (getIntent().getBooleanExtra(LoginActivity.sessionTimeOut, false)) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder .setCancelable(true) .setIcon(getResources().getDrawable(R.drawable.ic_warning)) .setTitle(getResources().getString(R.string.session_timed_out_header)) .setMessage(getResources().getString(R.string.session_timed_out_msg)) .setPositiveButton("Ok", null).show(); } } private void removeServerUrlAsInput() { serverUrlText.setVisibility(View.GONE); findViewById(R.id.server_url_divider).setVisibility(View.GONE); } private void useSavedServerUrl(String serverUrl) { if (!StringUtils.isEmpty(serverUrl)) { serverUrlText.setText(serverUrl); } } private void removeChangedPasswordRecentlyCheckbox() { updatePassword.setVisibility(View.GONE); } private String getApplicationVersion() { String versionText = ""; String versionCode = ""; try { versionCode = String.valueOf(getPackageManager().getPackageInfo(getPackageName(), 0).versionName); versionText = String.format(getResources().getString(R.string.version), versionCode); } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Unable to read application version.", e); } return versionText; } private String getServerURL() { Credentials credentials; credentials = new Credentials(this); return credentials.getServerUrl(); } @Override public void onResume() { super.onResume(); setupStatusView(); } private void setupStatusView() { if (backgroundAuthenticationTask != null && backgroundAuthenticationTask.getStatus() == AsyncTask.Status.RUNNING) { loginButton.setVisibility(View.GONE); authenticatingText.setVisibility(View.VISIBLE); } else { loginButton.setVisibility(View.VISIBLE); authenticatingText.setVisibility(View.GONE); } } @Override protected void onDestroy() { super.onDestroy(); if (backgroundAuthenticationTask != null) { backgroundAuthenticationTask.cancel(true); } } @Override public void onBackPressed() { moveTaskToBack(true); } private void setupListeners() { loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (validInput()) { if (backgroundAuthenticationTask != null && backgroundAuthenticationTask.getStatus() == AsyncTask.Status.RUNNING) { Toast.makeText(getApplicationContext(), "Authentication in progress...", Toast.LENGTH_SHORT).show(); return; } String username = (usernameText.getText() == null) ? "" : usernameText.getText().toString().trim(); //not trimming passwords since passwords may contain space. String password = (passwordText.getText() == null) ? "" : passwordText.getText().toString(); backgroundAuthenticationTask = new BackgroundAuthenticationTask(); backgroundAuthenticationTask.execute( new Credentials(serverUrlText.getText().toString(), username, password) ); } else { int errorColor = getResources().getColor(R.color.error_text_color); if (StringUtils.isEmpty(serverUrlText.getText().toString())) { serverUrlText.setHint("Please Enter Server URL"); serverUrlText.setHintTextColor(errorColor); } if (StringUtils.isEmpty(usernameText.getText().toString())) { usernameText.setHint("Please Enter Username"); usernameText.setHintTextColor(errorColor); } if (StringUtils.isEmpty(passwordText.getText().toString())) { passwordText.setHint("Please Enter Password"); passwordText.setHintTextColor(errorColor); } } } }); } private boolean validInput() { return !(StringUtils.isEmpty(serverUrlText.getText().toString()) || StringUtils.isEmpty(usernameText.getText().toString()) || StringUtils.isEmpty(passwordText.getText().toString())); } private void initViews() { serverUrlText = (EditText) findViewById(R.id.serverUrl); usernameText = (EditText) findViewById(R.id.username); passwordText = (EditText) findViewById(R.id.password); updatePassword = (CheckBox) findViewById(R.id.update_password); loginButton = (Button) findViewById(R.id.login); authenticatingText = (TextView) findViewById(R.id.authenticatingText); versionText = (TextView) findViewById(R.id.version); } public void onUpdatePasswordCheckboxClicked(View view) { isUpdatePasswordChecked = ((CheckBox) view).isChecked(); } public void removeRemnantDataFromPreviousRunOfWizard() { if (!new WizardFinishPreferenceService(this).isWizardFinished()) { try { MuzimaApplication application = ((MuzimaApplication) getApplicationContext()); Context context = application.getMuzimaContext(); //Cohort Wizard activity application.getPatientController().deleteAllPatients(); application.getCohortController().deleteCohortMembers(application.getCohortController().getAllCohorts()); application.getCohortController().deleteAllCohorts(); context.getLastSyncTimeService().deleteAll(); //FormTemplateWizardActivity application.getConceptController().deleteAllConcepts(); application.getLocationController().deleteAllLocations(); application.getProviderController().deleteAllProviders(); application.getFormController().deleteAllForms(); application.getFormController().deleteAllFormTemplates(); //CustomConceptWizardActivity context.getObservationService().deleteAll(); context.getEncounterService().deleteAll(); } catch (Throwable e) { Log.e(TAG, "Unable to delete previous wizard run data. Error: " + e); } } } private class BackgroundAuthenticationTask extends AsyncTask<Credentials, Void, BackgroundAuthenticationTask.Result> { @Override protected void onPreExecute() { if (loginButton.getVisibility() == View.VISIBLE) { flipFromLoginToAuthAnimator.start(); } } @Override protected Result doInBackground(Credentials... params) { Credentials credentials = params[0]; MuzimaSyncService muzimaSyncService = ((MuzimaApplication) getApplication()).getMuzimaSyncService(); int authenticationStatus = muzimaSyncService.authenticate(credentials.getCredentialsArray(), isUpdatePasswordChecked); return new Result(credentials, authenticationStatus); } @Override protected void onPostExecute(Result result) { if (result.status == SyncStatusConstants.AUTHENTICATION_SUCCESS) { new CredentialsPreferenceService(getApplicationContext()).saveCredentials(result.credentials); ((MuzimaApplication) getApplication()).restartTimer(); startNextActivity(); } else { Toast.makeText(getApplicationContext(), getErrorText(result), Toast.LENGTH_SHORT).show(); if (authenticatingText.getVisibility() == View.VISIBLE || flipFromLoginToAuthAnimator.isRunning()) { flipFromLoginToAuthAnimator.cancel(); flipFromAuthToLoginAnimator.start(); } } } private String getErrorText(Result result) { switch (result.status) { case SyncStatusConstants.MALFORMED_URL_ERROR: return "Invalid Server URL."; case SyncStatusConstants.INVALID_CREDENTIALS_ERROR: return "Invalid Username, Password, Server combination."; case SyncStatusConstants.INVALID_CHARACTER_IN_USERNAME: return "Invalid Character in Username. These are not allowed: " + SyncStatusConstants.INVALID_CHARACTER_FOR_USERNAME; case SyncStatusConstants.CONNECTION_ERROR: return "Error while connecting to the server. Please connect to the internet and try again."; default: return "Authentication failed"; } } private void startNextActivity() { Intent intent; if (new WizardFinishPreferenceService(LoginActivity.this).isWizardFinished()) { intent = new Intent(getApplicationContext(), MainActivity.class); } else { removeRemnantDataFromPreviousRunOfWizard(); intent = new Intent(getApplicationContext(), CohortWizardActivity.class); } startActivity(intent); finish(); } protected class Result { Credentials credentials; int status; private Result(Credentials credentials, int status) { this.credentials = credentials; this.status = status; } } } private void initAnimators() { flipFromLoginToNoConnAnimator = ValueAnimator.ofFloat(0, 1); flipFromNoConnToLoginAnimator = ValueAnimator.ofFloat(0, 1); flipFromLoginToAuthAnimator = ValueAnimator.ofFloat(0, 1); flipFromAuthToLoginAnimator = ValueAnimator.ofFloat(0, 1); flipFromAuthToNoConnAnimator = ValueAnimator.ofFloat(0, 1); initFlipAnimation(flipFromLoginToAuthAnimator, loginButton, authenticatingText); initFlipAnimation(flipFromAuthToLoginAnimator, authenticatingText, loginButton); } public void initFlipAnimation(ValueAnimator valueAnimator, final View from, final View to) { valueAnimator.setInterpolator(new AccelerateDecelerateInterpolator()); valueAnimator.setDuration(300); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float animatedFraction = animation.getAnimatedFraction(); if (from.getVisibility() == View.VISIBLE) { if (animatedFraction > 0.5) { from.setVisibility(View.INVISIBLE); to.setVisibility(View.VISIBLE); } } else if (to.getVisibility() == View.VISIBLE) { if (honeycombOrGreater) { to.setRotationX(-180 * (1 - animatedFraction)); } } if (from.getVisibility() == View.VISIBLE) { if (honeycombOrGreater) { from.setRotationX(180 * animatedFraction); } } } }); } }
package org.bsc.maven.plugin.processor; import java.io.InputStream; import java.io.OutputStream; import java.io.Writer; import java.nio.charset.Charset; import java.util.Locale; import java.util.Set; import javax.annotation.processing.Processor; import javax.lang.model.SourceVersion; import javax.tools.Diagnostic; import javax.tools.DiagnosticListener; import javax.tools.JavaCompiler; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; import org.apache.maven.execution.MavenSession; import org.apache.maven.project.MavenProject; import org.apache.maven.toolchain.Toolchain; import org.codehaus.plexus.compiler.CompilerConfiguration; import org.codehaus.plexus.compiler.CompilerException; import org.codehaus.plexus.compiler.CompilerMessage; import org.codehaus.plexus.compiler.CompilerResult; import org.codehaus.plexus.compiler.manager.CompilerManager; import org.codehaus.plexus.util.Os; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.cli.CommandLineUtils; import org.codehaus.plexus.util.cli.Commandline; class PlexusJavaCompilerWithOutput { static final PlexusJavaCompilerWithOutput INSTANCE = new PlexusJavaCompilerWithOutput(); private PlexusJavaCompilerWithOutput() { } private String getJavacExecutable(CompilerConfiguration config ) throws java.io.IOException { if( !StringUtils.isEmpty(config.getExecutable())) { return config.getExecutable(); } final String javacCommand = "javac" + ( Os.isFamily( Os.FAMILY_WINDOWS ) ? ".exe" : "" ); String javaHome = System.getProperty( "java.home" ); java.io.File javacExe; if ( Os.isName( "AIX" ) ) { javacExe = new java.io.File( javaHome + java.io.File.separator + ".." + java.io.File.separator + "sh", javacCommand ); } else if ( Os.isName( "Mac OS X" ) ) { javacExe = new java.io.File( javaHome + java.io.File.separator + "bin", javacCommand ); } else { javacExe = new java.io.File( javaHome + java.io.File.separator + ".." + java.io.File.separator + "bin", javacCommand ); } // Try to find javacExe from JAVA_HOME environment variable if ( !javacExe.isFile() ) { java.util.Properties env = CommandLineUtils.getSystemEnvVars(); javaHome = env.getProperty( "JAVA_HOME" ); if ( StringUtils.isEmpty( javaHome ) ) { throw new java.io.IOException( "The environment variable JAVA_HOME is not correctly set." ); } if ( !new java.io.File( javaHome ).isDirectory() ) { throw new java.io.IOException( "The environment variable JAVA_HOME=" + javaHome + " doesn't exist or is not a valid directory." ); } javacExe = new java.io.File( env.getProperty( "JAVA_HOME" ) + java.io.File.separator + "bin", javacCommand ); } if ( !javacExe.isFile() ) { throw new java.io.IOException( "The javadoc executable '" + javacExe + "' doesn't exist or is not a file. Verify the JAVA_HOME environment variable." ); } return javacExe.getAbsolutePath(); } /** * * @param args * @return * @throws java.io.IOException */ private java.io.File createFileWithArguments( String[] args, String outputDirectory ) throws java.io.IOException { java.io.PrintWriter writer = null; try { final java.io.File tempFile; { tempFile = java.io.File.createTempFile( org.codehaus.plexus.compiler.javac.JavacCompiler.class.getName(), "arguments" ); tempFile.deleteOnExit(); } writer = new java.io.PrintWriter( new java.io.FileWriter( tempFile ) ); for ( String arg : args ) { String argValue = arg.replace( java.io.File.separatorChar, '/' ); writer.write( "\"" + argValue + "\"" ); writer.println(); } writer.flush(); return tempFile; } finally { if ( writer != null ) { writer.close(); } } } private CompilerResult compileOutOfProcess( CompilerConfiguration config, String executable, String[] args ) throws CompilerException { Commandline cli = new Commandline(); cli.setWorkingDirectory( config.getWorkingDirectory().getAbsolutePath() ); cli.setExecutable( executable ); try { final java.io.File argumentsFile = createFileWithArguments( args, config.getOutputLocation() ); cli.addArguments( new String[]{ "@" + argumentsFile.getCanonicalPath().replace( java.io.File.separatorChar, '/' ) } ); if ( !StringUtils.isEmpty( config.getMaxmem() ) ) { cli.addArguments( new String[]{ "-J-Xmx" + config.getMaxmem() } ); } if ( !StringUtils.isEmpty( config.getMeminitial() ) ) { cli.addArguments( new String[]{ "-J-Xms" + config.getMeminitial() } ); } for ( String key : config.getCustomCompilerArgumentsAsMap().keySet() ) { if ( StringUtils.isNotEmpty( key ) && key.startsWith( "-J" ) ) { cli.addArguments( new String[]{ key } ); } } } catch ( java.io.IOException e ) { throw new CompilerException( "Error creating file with javac arguments", e ); } final CommandLineUtils.StringStreamConsumer out = new CommandLineUtils.StringStreamConsumer(); int returnCode; final java.util.List<CompilerMessage> messages = java.util.Collections.emptyList(); try { // ==> DEBUG //out.consumeLine( cli.toString() ); returnCode = CommandLineUtils.executeCommandLine( cli, out, out ); } catch ( Exception e ) { throw new CompilerException( "Error while executing the external compiler.", e ); } boolean success = returnCode == 0; return new CompilerResult( success, messages ) { @Override public String toString() { return out.getOutput(); } }; } private String[] getSourceFiles( CompilerConfiguration config ) throws java.io.IOException { final java.util.Set<String> sourceFiles = new java.util.HashSet<String>(); for( java.io.File src : config.getSourceFiles() ) { sourceFiles.add( src.getCanonicalPath() ); } return sourceFiles.toArray( new String[sourceFiles.size()] ); } /** * * @param config * @return */ protected CompilerResult performCompile( CompilerConfiguration config ) throws CompilerException, java.io.IOException { final java.util.Set<String> sourceFiles = new java.util.HashSet<String>(); for( java.io.File src : config.getSourceFiles() ) { sourceFiles.add( src.getCanonicalPath() ); } final String[] compilerArguments = org.codehaus.plexus.compiler.javac.JavacCompiler.buildCompilerArguments(config, getSourceFiles(config) ); return compileOutOfProcess( config, getJavacExecutable(config), compilerArguments ); } } /** * * @author bsorrentino */ public class AnnotationProcessorCompiler implements JavaCompiler { private static final String COMPILER_TARGET = "maven.compiler.target"; private static final String COMPILER_SOURCE = "maven.compiler.source"; private static final String PROCESSOR_TARGET = "maven.processor.target"; private static final String PROCESSOR_SOURCE = "maven.processor.source"; private static final String DEFAULT_SOURCE_VERSION = "1.7"; private static final String DEFAULT_TARGET_VERSION = DEFAULT_SOURCE_VERSION ; final JavaCompiler systemJavaCompiler = ToolProvider.getSystemJavaCompiler(); final MavenProject project; final MavenSession session; final CompilerManager plexusCompiler; final Toolchain toolchain; public static JavaCompiler createOutProcess( Toolchain toolchain, CompilerManager plexusCompiler, MavenProject project, MavenSession session ) { return new AnnotationProcessorCompiler( toolchain, plexusCompiler, project, session); } public static JavaCompiler createInProcess() { return ToolProvider.getSystemJavaCompiler(); } static void printCommand( final org.codehaus.plexus.compiler.Compiler javac, final CompilerConfiguration javacConf, final java.io.PrintWriter out ) throws CompilerException { out.println(); out.println(); out.println( "javac \\"); for( String c : javac.createCommandLine(javacConf) ) out.printf( "%s \\\n", c); out.println(); out.println(); out.println(); } private AnnotationProcessorCompiler( Toolchain toolchain, CompilerManager plexusCompiler, MavenProject project, MavenSession session ) { this.project = project; this.session = session; this.plexusCompiler = plexusCompiler; this.toolchain = toolchain; } private boolean execute( final Iterable<String> options, final Iterable<? extends JavaFileObject> compilationUnits, final Writer w ) throws Exception { final java.io.PrintWriter out = ((w instanceof java.io.PrintWriter) ? ((java.io.PrintWriter)w) : new java.io.PrintWriter(w)); final CompilerConfiguration javacConf = new CompilerConfiguration(); final java.util.Iterator<String> ii = options.iterator(); while( ii.hasNext() ) { final String option = ii.next(); if( "-cp".equals(option)) { javacConf.addClasspathEntry(ii.next()); } else if( "-sourcepath".equals(option) ) { String [] sourceLocations = ii.next().split(java.util.regex.Pattern.quote(java.io.File.pathSeparator)); for( String path : sourceLocations ) { final java.io.File dir = new java.io.File( path ); if( dir.exists() ) javacConf.addSourceLocation(path); } //javacConf.addCompilerCustomArgument(option, ii.next()); } else if( "-proc:only".equals(option) ) { javacConf.setProc("only"); } else if( "-processor".equals(option) ) { final String processors[] = ii.next().split(","); javacConf.setAnnotationProcessors( processors ); } else if( "-d".equals(option) ) { javacConf.setOutputLocation(ii.next()); } else if( "-s".equals(option) ) { javacConf.setGeneratedSourcesDirectory( new java.io.File(ii.next())); } else if( "--release".equals(option) ) { javacConf.setReleaseVersion(ii.next()); } else /*if( option.startsWith("-A") ) */ { // view pull #70 // Just pass through any other arguments javacConf.addCompilerCustomArgument(option, ""); } } final java.util.Properties props = project.getProperties(); final String sourceVersion = props.getProperty(PROCESSOR_SOURCE,props.getProperty(COMPILER_SOURCE, DEFAULT_SOURCE_VERSION)); final String targetVersion = props.getProperty(PROCESSOR_TARGET,props.getProperty(COMPILER_TARGET, DEFAULT_TARGET_VERSION)); javacConf.setSourceVersion(sourceVersion ); javacConf.setTargetVersion(targetVersion); javacConf.setWorkingDirectory(project.getBasedir()); final java.util.Set<java.io.File> sourceFiles = new java.util.HashSet<java.io.File>(); for( JavaFileObject src : compilationUnits ) { sourceFiles.add( new java.io.File( src.toUri() ) ); } javacConf.setSourceFiles(sourceFiles); javacConf.setDebug(false); javacConf.setFork(true); javacConf.setVerbose(false); if( toolchain != null ) { final String executable = toolchain.findTool( "javac"); //out.print( "==> TOOLCHAIN EXECUTABLE: "); out.println( executable ); javacConf.setExecutable(executable); } CompilerResult result; // USING STANDARD PLEXUS /* final org.codehaus.plexus.systemJavaCompiler.Compiler javac = plexusCompiler.getCompiler("javac"); //printCommand(javac, javacConf, out ); result = javac.performCompile( javacConf ); for( CompilerMessage m : result.getCompilerMessages()) out.println( m.getMessage() ); */ // USING CUSTOM PLEXUS result = PlexusJavaCompilerWithOutput.INSTANCE.performCompile(javacConf); out.println( result.toString() ); out.flush(); return result.isSuccess(); } @Override public CompilationTask getTask( final Writer out, final JavaFileManager fileManager, final DiagnosticListener<? super JavaFileObject> diagnosticListener, final Iterable<String> options, final Iterable<String> classes, final Iterable<? extends JavaFileObject> compilationUnits) { return new CompilationTask() { @Override public void setProcessors(Iterable<? extends Processor> processors) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void setLocale(Locale locale) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void addModules(Iterable<String> moduleNames) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Boolean call() { try { return execute(options, compilationUnits, out); } catch (final Exception ex) { diagnosticListener.report( new Diagnostic<JavaFileObject>() { @Override public Diagnostic.Kind getKind() { return Diagnostic.Kind.ERROR; } @Override public String getMessage(Locale locale) { return ex.getLocalizedMessage(); } public String toString() { return ex.getLocalizedMessage(); } @Override public JavaFileObject getSource() { return null;} @Override public long getPosition() { return -1; } @Override public long getStartPosition() { return -1; } @Override public long getEndPosition() { return -1; } @Override public long getLineNumber() { return -1; } @Override public long getColumnNumber() { return -1; } @Override public String getCode() { return null; } }); return false; } } }; } @Override public StandardJavaFileManager getStandardFileManager(DiagnosticListener<? super JavaFileObject> diagnosticListener, Locale locale, Charset charset) { return systemJavaCompiler.getStandardFileManager(diagnosticListener, locale, charset); } @Override public int run(InputStream in, OutputStream out, OutputStream err, String... arguments) { throw new UnsupportedOperationException("Not supported yet."); } @Override public Set<SourceVersion> getSourceVersions() { return systemJavaCompiler.getSourceVersions(); } @Override public int isSupportedOption(String option) { return systemJavaCompiler.isSupportedOption(option); } }
package utility; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.net.URL; import java.security.CodeSource; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import junit.framework.TestCase; import org.eclipse.birt.core.archive.FileArchiveWriter; import org.eclipse.birt.core.archive.IDocArchiveWriter; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.core.framework.Platform; import org.eclipse.birt.core.framework.PlatformConfig; import org.eclipse.birt.report.engine.api.EngineConfig; import org.eclipse.birt.report.engine.api.EngineConstants; import org.eclipse.birt.report.engine.api.EngineException; import org.eclipse.birt.report.engine.api.HTMLRenderContext; import org.eclipse.birt.report.engine.api.HTMLRenderOption; import org.eclipse.birt.report.engine.api.IEngineTask; import org.eclipse.birt.report.engine.api.IRenderOption; import org.eclipse.birt.report.engine.api.IRenderTask; import org.eclipse.birt.report.engine.api.IReportDocument; import org.eclipse.birt.report.engine.api.IReportEngine; import org.eclipse.birt.report.engine.api.IReportEngineFactory; import org.eclipse.birt.report.engine.api.IReportRunnable; import org.eclipse.birt.report.engine.api.IRunAndRenderTask; import org.eclipse.birt.report.engine.api.IRunTask; import org.eclipse.birt.report.engine.api.RenderOptionBase; import org.eclipse.birt.report.engine.api.ReportRunner; /** * Base class for Engine test. */ public abstract class EngineCase extends TestCase { private String caseName; protected static final String BUNDLE_NAME = "utility.messages";//$NON-NLS-1$ protected static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle .getBundle( BUNDLE_NAME ); protected static final String PLUGIN_NAME = "utility"; //$NON-NLS-1$ protected static final String PLUGINLOC = "/utility/"; //$NON-NLS-1$ protected static final String PLUGIN_PATH = System.getProperty( "user.dir" ) //$NON-NLS-1$ + "/plugins/" + PLUGINLOC.substring( PLUGINLOC.indexOf( "/" ) + 1 ) //$NON-NLS-1$//$NON-NLS-2$ + "bin/"; //$NON-NLS-1$ protected static final String TEST_FOLDER = "src/"; //$NON-NLS-1$ protected static final String OUTPUT_FOLDER = "output"; //$NON-NLS-1$ protected static final String INPUT_FOLDER = "input"; //$NON-NLS-1$ protected static final String GOLDEN_FOLDER = "golden"; //$NON-NLS-1$ protected IReportEngine engine = null; protected IEngineTask engineTask = null; private static final String FORMAT_HTML = "html"; //$NON-NLS-1$ private static final String FORMAT_PDF = "pdf"; private static final String ENCODING_UTF8 = "UTF-8"; //$NON-NLS-1$ private String IMAGE_DIR = "image"; //$NON-NLS-1$ private boolean pagination = false; private Locale locale = Locale.ENGLISH; /* * @see TestCase#setUp() */ protected void setUp( ) throws Exception { super.setUp( ); // IPlatformContext context = new PlatformFileContext( ); // config.setEngineContext( context ); // this.engine = new ReportEngine( config ); EngineConfig config = new EngineConfig( ); this.engine = createReportEngine( config ); } /** * Create a report engine instance. * * @param config * @return * @throws BirtException */ public IReportEngine createReportEngine( EngineConfig config ) throws BirtException { setScriptingPath( ); if ( config == null ) { config = new EngineConfig( ); } Platform.startup( new PlatformConfig( ) ); // assume we has in the platform Object factory = Platform .createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY ); if ( factory instanceof IReportEngineFactory ) { return ( (IReportEngineFactory) factory ) .createReportEngine( config ); } return null; } /** * Constructor. */ public EngineCase( ) { super( null ); } /** * Constructor for DemoCase. * * @param name */ public EngineCase( String name ) { super( name ); } protected void setCase( String caseName ) { // set the case and emitter manager accroding to caseName. this.caseName = caseName; } protected void runCase( String args[] ) { Vector runArgs = new Vector( ); // invoke the report runner. String input = PLUGIN_PATH + System.getProperty( "file.separator" ) //$NON-NLS-1$ + RESOURCE_BUNDLE.getString( "CASE_INPUT" ); //$NON-NLS-1$ input += System.getProperty( "file.separator" ) + caseName //$NON-NLS-1$ + ".rptdesign"; //$NON-NLS-1$ System.out.println( "input is : " + input ); //$NON-NLS-1$ // run report runner. if ( args != null ) { for ( int i = 0; i < args.length; i++ ) { runArgs.add( args[i] ); } } runArgs.add( "-f" ); //$NON-NLS-1$ runArgs.add( "test" ); //$NON-NLS-1$ runArgs.add( input ); args = (String[]) runArgs.toArray( new String[runArgs.size( )] ); ReportRunner.main( args ); } /** * Make a copy of a given file to the target file. * * @param from * the file where to copy from * @param to * the target file to copy to. * @throws IOException */ protected final void copyFile( String from, String to ) throws IOException { BufferedInputStream bis = null; BufferedOutputStream bos = null; try { new File( to ).createNewFile( ); bis = new BufferedInputStream( new FileInputStream( from ) ); bos = new BufferedOutputStream( new FileOutputStream( to ) ); int nextByte = 0; while ( ( nextByte = bis.read( ) ) != -1 ) { bos.write( nextByte ); } } catch ( IOException e ) { throw e; } finally { try { if ( bis != null ) bis.close( ); if ( bos != null ) bos.close( ); } catch ( IOException e ) { // ignore } } } protected void copyResource( String src, String tgt, String folder ) { String className = getFullQualifiedClassName( ); tgt = this.tempFolder( ) + className + "/" + folder + "/" + tgt; className = className.replace( '.', '/' ); src = className + "/" + folder + "/" + src; System.out.println( "src: " + src ); System.out.println( "tgt: " + tgt ); File parent = new File( tgt ).getParentFile( ); if ( parent != null ) { parent.mkdirs( ); } InputStream in = getClass( ).getClassLoader( ) .getResourceAsStream( src ); assertTrue( in != null ); try { FileOutputStream fos = new FileOutputStream( tgt ); byte[] fileData = new byte[5120]; int readCount = -1; while ( ( readCount = in.read( fileData ) ) != -1 ) { fos.write( fileData, 0, readCount ); } fos.close( ); in.close( ); } catch ( Exception ex ) { ex.printStackTrace( ); fail( ); } } protected void copyResource_INPUT( String input_resource, String input ) { this.copyResource( input_resource, input, INPUT_FOLDER ); } protected void copyResource_GOLDEN( String input_resource, String golden ) { this.copyResource( input_resource, golden, GOLDEN_FOLDER ); } /** * Remove a given file or directory recursively. * * @param file */ public void removeFile( File file ) { if ( file.isDirectory( ) ) { File[] children = file.listFiles( ); for ( int i = 0; i < children.length; i++ ) { removeFile( children[i] ); } } if ( file.exists( ) ) { if ( !file.delete( ) ) { System.out.println( file.toString( ) + " can't be removed" ); //$NON-NLS-1$ } } } /** * Remove a given file or directory recursively. * * @param file */ public void removeFile( String file ) { removeFile( new File( file ) ); } public void removeResource( ) { String className = getFullQualifiedClassName( ); removeFile( className ); } /** * Locates the folder where the unit test java source file is saved. * * @return the path name where the test java source file locates. */ protected String getClassFolder( ) { String pathBase = null; ProtectionDomain domain = this.getClass( ).getProtectionDomain( ); if ( domain != null ) { CodeSource source = domain.getCodeSource( ); if ( source != null ) { URL url = source.getLocation( ); pathBase = url.getPath( ); if ( pathBase.endsWith( "bin/" ) ) //$NON-NLS-1$ pathBase = pathBase.substring( 0, pathBase.length( ) - 4 ); if ( pathBase.endsWith( "bin" ) ) //$NON-NLS-1$ pathBase = pathBase.substring( 0, pathBase.length( ) - 3 ); } } pathBase = pathBase + TEST_FOLDER; String className = this.getClass( ).getName( ); int lastDotIndex = className.lastIndexOf( "." ); //$NON-NLS-1$ className = className.substring( 0, lastDotIndex ); className = pathBase + className.replace( '.', '/' ); return className; } /** * Compares two text file. The comparison will ignore the line containing * "modificationDate". * * @param golden * the 1st file name to be compared. * @param output * the 2nd file name to be compared. * @return true if two text files are same line by line * @throws Exception * if any exception. */ protected boolean compareHTML( String golden, String output ) throws Exception { FileReader readerA = null; FileReader readerB = null; boolean same = true; StringBuffer errorText = new StringBuffer( ); try { String outputFile = genOutputFile( output ); String goldenFile = this.tempFolder( ) + getFullQualifiedClassName( ) + "/" + GOLDEN_FOLDER + "/" + golden; readerA = new FileReader( goldenFile ); readerB = new FileReader( outputFile ); same = compareTextFile( readerA, readerB, output ); } catch ( IOException e ) { errorText.append( e.toString( ) ); errorText.append( "\n" ); //$NON-NLS-1$ e.printStackTrace( ); } finally { try { readerA.close( ); readerB.close( ); } catch ( Exception e ) { readerA = null; readerB = null; errorText.append( e.toString( ) ); throw new Exception( errorText.toString( ) ); } } return same; } /** * Compares the string. The comparison will ignore the line containing * * @param output * the file name to be compared. * @param checkstring * the string to be compared. * @param checktimes * the times that the checkstring display. * @return true if the string display times is the same as checktimes * @throws Exception * if any exception. */ protected boolean compareHTML_STRING( String output, String checkstring, int checktimes ) { StringBuffer errorText = new StringBuffer( ); String outputFile = genOutputFile( output ); String line = null; int count = 0; boolean same = true; try { BufferedReader reader = new BufferedReader( new FileReader( new File( outputFile ) ) ); while ( ( line = reader.readLine( ) ) != null ) { if ( line.indexOf( checkstring ) > 0 ) { count++; } } same = compareString( checktimes, count ); } catch ( IOException e ) { errorText.append( e.toString( ) ); errorText.append( "\n" ); //$NON-NLS-1$ e.printStackTrace( ); } return same; } /** * Run and render the given design file into html file. If the input is * "a.xml", output html file will be named "a.html" under folder "output". * * @param input * @throws EngineException */ protected ArrayList runAndRender_HTML( String input, String output ) throws EngineException { this.pagination = false; return runAndRender( input, output, null, FORMAT_HTML ); //$NON-NLS-1$ } /** * Run and render the given design file into html file with pagination. If * the input is "a.xml", output html file will be named "a.html" under * folder "output". * * @param input * @throws EngineException */ protected ArrayList runAndRender_HTMLWithPagination( String input, String output ) throws EngineException { this.pagination = true; return runAndRender( input, output, null, FORMAT_HTML ); //$NON-NLS-1$ } /** * Run and render the given design file into pdf file. If the input is * "a.xml", output html file will be named "a.pdf" under folder "output". * * @param input * @throws EngineException */ protected void runAndRender_PDF( String input, String output ) throws EngineException { runAndRender( input, output, null, FORMAT_PDF ); //$NON-NLS-1$ } protected String getFullQualifiedClassName( ) { String className = this.getClass( ).getName( ); int lastDotIndex = className.lastIndexOf( "." ); //$NON-NLS-1$ className = className.substring( 0, lastDotIndex ); return className; } /** * RunAndRender a report with the given parameters. */ protected final ArrayList runAndRender( String input, String output, Map paramValues, String format ) throws EngineException { String outputFile = genOutputFile( output ); String inputFile = this.tempFolder( ) + getFullQualifiedClassName( )+ "/" + INPUT_FOLDER + "/" + input; IReportRunnable runnable = engine.openReportDesign( inputFile.replace( '\\', '/' ) ); IRunAndRenderTask task = engine.createRunAndRenderTask( runnable ); // set engine task engineTask = task; if ( paramValues != null ) { Iterator keys = paramValues.keySet( ).iterator( ); while ( keys.hasNext( ) ) { String key = (String) keys.next( ); task.setParameterValue( key, paramValues.get( key ) ); } } task.setLocale( locale ); IRenderOption options = null; if ( FORMAT_PDF.equals( format ) ) //$NON-NLS-1$ { options = new RenderOptionBase( ); options.setOutputFileName( outputFile ); } else { options = new HTMLRenderOption( ); options.setOutputFileName( outputFile ); ( (HTMLRenderOption) options ).setHtmlPagination( this.pagination ); HTMLRenderContext renderContext = new HTMLRenderContext( ); renderContext.setImageDirectory( IMAGE_DIR ); HashMap appContext = new HashMap( ); appContext.put( EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT, renderContext ); task.setAppContext( appContext ); } options.setOutputFormat( format ); options.getOutputSetting( ).put( HTMLRenderOption.URL_ENCODING, ENCODING_UTF8 ); task.setRenderOption( options ); task.run( ); ArrayList errors = (ArrayList) task.getErrors( ); task.close( ); return errors; } /** * Run a report, generate a self-contained report document. * * @throws EngineException */ protected final ArrayList run( String input, String output ) throws EngineException { String outputFile = genOutputFile( output ); input = getFullQualifiedClassName( ) + "/" + INPUT_FOLDER + "/" + input; IReportRunnable runnable = engine.openReportDesign( input ); IRunTask task = engine.createRunTask( runnable ); task.setAppContext( new HashMap( ) ); task.setLocale( locale ); IDocArchiveWriter archive = null; try { archive = new FileArchiveWriter( outputFile ); } catch ( IOException e ) { e.printStackTrace( ); } task.run( archive ); ArrayList errors = (ArrayList) task.getErrors( ); task.close( ); return errors; } /** * @param doc * input rpt docuement file * @param output * output file of the generation. * @param pageRange * The pages to render, use "All" to render all, use 1-N to * render a selected page. * @throws EngineException */ protected ArrayList render_HTML( String doc, String output, String pageRange ) throws EngineException { this.pagination = true; return render( FORMAT_HTML, doc, output, pageRange ); //$NON-NLS-1$ } /** * Render a report document into PDF file. * * @param doc * @param output * @param pageRange * @throws EngineException */ protected ArrayList render_PDF( String doc, String output, String pageRange ) throws EngineException { return render( FORMAT_PDF, doc, output, pageRange ); //$NON-NLS-1$ } private ArrayList render( String format, String doc, String output, String pageRange ) throws EngineException { String outputFile = genOutputFile( output ); doc = getFullQualifiedClassName( ) + "/" + INPUT_FOLDER + "/" + doc; String encoding = "UTF-8"; //$NON-NLS-1$ IReportDocument document = engine.openReportDocument( doc ); IRenderTask task = engine.createRenderTask( document ); task.setLocale( locale ); IRenderOption options = new HTMLRenderOption( ); options.setOutputFileName( outputFile ); options.setOutputFormat( format ); options.getOutputSetting( ).put( HTMLRenderOption.URL_ENCODING, encoding ); if ( !format.equalsIgnoreCase( FORMAT_PDF ) ) { ( (HTMLRenderOption) options ).setHtmlPagination( this.pagination ); } HTMLRenderContext renderContext = new HTMLRenderContext( ); renderContext.setImageDirectory( IMAGE_DIR ); HashMap appContext = new HashMap( ); appContext.put( EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT, renderContext ); appContext.put( EngineConstants.APPCONTEXT_CLASSLOADER_KEY, EngineCase.class.getClassLoader( ) ); task.setAppContext( appContext ); task.setRenderOption( options ); task.setPageRange( pageRange ); task.render( ); ArrayList errors = (ArrayList) task.getErrors( ); task.close( ); return errors; } /** * Run the input design, generate a report document, and then render the * report document into a html file, <code>pageRange</code> specified the * page(s) to render. * * @throws IOException * @throws EngineException */ protected final ArrayList runAndThenRender( String input, String output, String pageRange, String format ) throws Exception { String tempDoc = "temp_123aaabbbccc789.rptdocument"; //$NON-NLS-1$ ArrayList errors = run( input, tempDoc ); if ( errors.size( ) > 0 ) { return errors; } String from = genOutputFile( tempDoc ); try { copyFile( from, this.getFullQualifiedClassName( ) + "/" + INPUT_FOLDER + "/" + tempDoc ); if ( FORMAT_PDF.equals( format ) ) //$NON-NLS-1$ return render_PDF( tempDoc, output, pageRange ); else return render_HTML( tempDoc, output, pageRange ); } catch ( Exception e ) { throw e; } finally { // remove the temp file on exit. removeFile( tempDoc ); } } /** * Compares the two text files. * * @param golden * the reader for golden file * @param output * the reader for output file * @return true if two text files are same. * @throws Exception * if any exception */ protected boolean compareTextFile( Reader golden, Reader output, String fileName ) throws Exception { StringBuffer errorText = new StringBuffer( ); BufferedReader lineReaderA = null; BufferedReader lineReaderB = null; boolean same = true; int lineNo = 1; try { lineReaderA = new BufferedReader( golden ); lineReaderB = new BufferedReader( output ); String strA = lineReaderA.readLine( ).trim( ); String strB = lineReaderB.readLine( ).trim( ); while ( strA != null ) { // filter the random part of the page. String filterA = this.filterLine( strA ); String filterB = this.filterLine( strB ); same = filterA.trim( ).equals( filterB.trim( ) ); if ( !same ) { StringBuffer message = new StringBuffer( ); message.append( "line=" ); //$NON-NLS-1$ message.append( lineNo ); message.append( "(" ); //$NON-NLS-1$ message.append( fileName ); message.append( ")" ); //$NON-NLS-1$ message.append( " is different:\n" );//$NON-NLS-1$ message.append( " The line from golden file: " );//$NON-NLS-1$ message.append( strA ); message.append( "\n" );//$NON-NLS-1$ message.append( " The line from result file: " );//$NON-NLS-1$ message.append( strB ); message.append( "\n" );//$NON-NLS-1$ message.append( "Text after filtering: \n" ); //$NON-NLS-1$ message.append( " golden file: " ); //$NON-NLS-1$ message.append( filterA ); message.append( "\n" );//$NON-NLS-1$ message.append( " result file: " ); //$NON-NLS-1$ message.append( filterB ); throw new Exception( message.toString( ) ); } strA = lineReaderA.readLine( ); strB = lineReaderB.readLine( ); lineNo++; } same = ( strA == null ) && ( strB == null ); } finally { try { lineReaderA.close( ); lineReaderB.close( ); } catch ( Exception e ) { lineReaderA = null; lineReaderB = null; errorText.append( e.toString( ) ); throw new Exception( errorText.toString( ) ); } } return same; } /** * Compares the two times. * * @param checktimes * the times that the string display. * @param countstring * the golden times. * @return true if two times are same. * @throws Exception * if any exception */ private boolean compareString( int checktimes, int countstring ) { boolean same = true; StringBuffer errorText = new StringBuffer( ); try { if ( checktimes == countstring ) same = true; else same = false; } catch ( Exception e ) { errorText.append( e.toString( ) ); } return same; } /** * All kinds of filter-pattern pairs that will be filtered and replace * during comparasion. */ // Sample: id="AUTOGENBOOKMARK_6354527823361272054" private final static Pattern PATTERN_ID_AUTOBOOKMARK = Pattern .compile( "id[\\s]*=[\\s]*\"AUTOGENBOOKMARK_[\\d]+\"" ); //$NON-NLS-1$ // Sample: private final static Pattern PATTERN_NAME_AUTOBOOKMARK = Pattern .compile( "name[\\s]*=[\\s]*\"AUTOGENBOOKMARK_[\\d]+\"" ); //$NON-NLS-1$ // Sample: iid="/9(QuRs13:0)" private final static Pattern PATTERN_IID = Pattern .compile( "iid[\\s]*=[\\s]*\"/.*(.*)\"" ); //$NON-NLS-1$ // Sample: style="background-image:url(image\file44.jpg)" private final static Pattern PATTERN_BG_IMAGE = Pattern .compile( "background-image[\\s]*:url[(]image.*[)]" ); //$NON-NLS-1$ // Sample: .style_1 { background-image: url('image%5cfile24.jpg');} private final static Pattern PATTERN_BG_IMAGE2 = Pattern .compile( "background-image[\\s]*:[\\s]*url[(]'image.*'[)]" ); //$NON-NLS-1$ // Sample: src="image/design31" // src="image\file31.jpg" private final static Pattern PATTERN_IMAGE_SOURCE = Pattern .compile( "src=\"image.*\"" ); //$NON-NLS-1$ /** * Normalize some seeding values, lines that matches certain patterns will * be repalced by a replacement. */ private static Object[][] FILTER_PATTERNS = { {PATTERN_ID_AUTOBOOKMARK, "REPLACEMENT_ID_AUTOBOOKMARK"}, //$NON-NLS-1$ {PATTERN_NAME_AUTOBOOKMARK, "REPLACEMENT_NAME_AUTOBOOKMARK"}, //$NON-NLS-1$ {PATTERN_IID, "REPLACEMENT_IID"}, //$NON-NLS-1$ {PATTERN_BG_IMAGE, "REPLACEMENT_BG_IMAGE"}, //$NON-NLS-1$ {PATTERN_BG_IMAGE2, "REPLACEMENT_BG_IMAGE2"}, //$NON-NLS-1$ {PATTERN_IMAGE_SOURCE, "REPLACEMENT_IMAGE_SOURCE"} //$NON-NLS-1$ }; /** * Replace the given string with a replacement if it matches a certain * pattern. * * @param str * @return filtered string, the tokens that matches the patterns are * replaced with replacement. */ protected String filterLine( String str ) { String result = str; for ( int i = 0; i < FILTER_PATTERNS.length; i++ ) { Pattern pattern = (Pattern) FILTER_PATTERNS[i][0]; String replacement = (String) FILTER_PATTERNS[i][1]; Matcher matcher = pattern.matcher( result ); while ( matcher.find( ) ) { result = matcher.replaceFirst( replacement ); } // result = matcher.replaceAll( replacement ); } return result; } /** * Locates the folder where the unit test java source file is saved. * * @return the path where the test java source file locates. */ protected String getBaseFolder( ) { String className = getClass( ).getName( ); int lastDotIndex = className.lastIndexOf( "." ); //$NON-NLS-1$ className = className.substring( 0, lastDotIndex ); return PLUGIN_PATH + className.replace( '.', '/' ); } protected URL getResource( String name ) { return this.getClass( ).getResource( name ); } /** * Set scripts class folder */ protected void setScriptingPath( ) { System.setProperty( EngineConstants.WEBAPP_CLASSPATH_KEY, this .getClassFolder( ) + "/input/scripts" ); } /** * Set locale for run/render report * * @param loc * location used to run report */ protected void setLocale( Locale loc ) { this.locale = loc; } /** * Set image folder to save rendered temp image file * * @param imageDir * folder to save temp image. */ protected void setImageDir( String imageDir ) { IMAGE_DIR = imageDir; } protected void tearDown( ) throws Exception { this.engine.destroy( ); super.tearDown( ); } protected String genOutputFile( String output ) { String tempDir = System.getProperty( "java.io.tmpdir" ); //$NON-NLS-1$ if ( !tempDir.endsWith( File.separator ) ) tempDir += File.separator; String outputFile = tempDir + getFullQualifiedClassName( ) //$NON-NLS-1$ + "/" + OUTPUT_FOLDER + "/" + output; return outputFile; } private void copyFolder( File from, File to ) throws Exception { if ( !from.isDirectory( ) || !from.exists( ) ) { throw new Exception( "Input foler: " + from + " doesn't exist." ); //$NON-NLS-1$//$NON-NLS-2$ } File[] files = from.listFiles( new FilenameFilter( ) { public boolean accept( File dir, String name ) { return true; } } ); if ( !to.exists( ) ) to.mkdir( ); System.out.println( "size is " + files.length ); for ( int i = 0; i < files.length; i++ ) { // File file = files[i]; if ( files[i].isDirectory( ) ) { this.copyFolder( files[i], new File( to.getPath( ) + "/" + files[i].getName( ) ) ); } DataInputStream instr; DataOutputStream outstr; File outFile = new File( to.getPath( ) ); try { instr = new DataInputStream( new BufferedInputStream( new FileInputStream( files[i] ) ) ); outstr = new DataOutputStream( new BufferedOutputStream( new FileOutputStream( outFile + "\\" + files[i].getName( ) ) ) ); try { int data; while ( true ) { data = instr.readUnsignedByte( ); outstr.writeByte( data ); } } catch ( EOFException eof ) { outstr.close( ); instr.close( ); } } catch ( FileNotFoundException nfx ) { System.out.println( "Problem opening files:" + files[i] ); } catch ( IOException iox ) { System.out.println( "IO Problems" ); } } } public void copyFolder( String from, String to ) throws Exception { copyFolder( new File( from ), new File( to ) ); } public String tempFolder( ) { String tempDir = System.getProperty( "java.io.tmpdir" ); if ( !tempDir.endsWith( File.separator ) ) tempDir += File.separator; return tempDir; } }
package com.notnoop.apns.internal; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.Socket; import java.security.KeyStore; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManagerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Utilities { private static Logger logger = LoggerFactory.getLogger(Utilities.class); public static final String SANDBOX_GATEWAY_HOST = "gateway.sandbox.push.apple.com"; public static final int SANDBOX_GATEWAY_PORT = 2195; public static final String SANDBOX_FEEDBACK_HOST = "feedback.sandbox.push.apple.com"; public static final int SANDBOX_FEEDBACK_PORT = 2196; public static final String PRODUCTION_GATEWAY_HOST = "gateway.push.apple.com"; public static final int PRODUCTION_GATEWAY_PORT = 2195; public static final String PRODUCTION_FEEDBACK_HOST = "feedback.push.apple.com"; public static final int PRODUCTION_FEEDBACK_PORT = 2196; public static final int MAX_PAYLOAD_LENGTH = 256; public static SSLSocketFactory newSSLSocketFactory(InputStream cert, String password, String ksType, String ksAlgorithm) throws Exception { SSLContext context = newSSLContext(cert, password, ksType, ksAlgorithm); return context.getSocketFactory(); } public static SSLContext newSSLContext(InputStream cert, String password, String ksType, String ksAlgorithm) throws Exception { KeyStore ks = KeyStore.getInstance(ksType); ks.load(cert, password.toCharArray()); // Get a KeyManager and initialize it KeyManagerFactory kmf = KeyManagerFactory.getInstance(ksAlgorithm); kmf.init(ks, password.toCharArray()); // Get a TrustManagerFactory and init with KeyStore TrustManagerFactory tmf = TrustManagerFactory.getInstance(ksAlgorithm); tmf.init(ks); // Get the SSLContext to help create SSLSocketFactory SSLContext sslc = SSLContext.getInstance("TLS"); sslc.init(kmf.getKeyManagers(), null, null); return sslc; } private static final Pattern pattern = Pattern.compile("[ -]"); public static byte[] decodeHex(String deviceToken) { String hex = pattern.matcher(deviceToken).replaceAll(""); byte[] bts = new byte[hex.length() / 2]; for (int i = 0; i < bts.length; i++) { bts[i] = (byte) (charval(hex.charAt(2*i)) * 16 + charval(hex.charAt(2*i + 1))); } return bts; } private static int charval(char a) { if ('0' <= a && a <= '9') return (a - '0'); else if ('a' <= a && a <= 'f') return (a - 'a') + 10; else if ('A' <= a && a <= 'F') return (a - 'A') + 10; else throw new RuntimeException("Invalid hex character: " + a); } private static final char base[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; public static String encodeHex(byte[] bytes) { char[] chars = new char[bytes.length * 2]; for (int i = 0; i < bytes.length; ++i) { int b = ((int)bytes[i]) & 0xFF; chars[2 * i] = base[b >>> 4]; chars[2 * i + 1] = base[b & 0xF]; } return new String(chars); } public static byte[] toUTF8Bytes(String s) { try { return s.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } public static byte[] marshall(byte command, byte[] deviceToken, byte[] payload) { ByteArrayOutputStream boas = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(boas); try { dos.writeByte(command); dos.writeShort(deviceToken.length); dos.write(deviceToken); dos.writeShort(payload.length); dos.write(payload); return boas.toByteArray(); } catch (IOException e) { throw new AssertionError(); } } public static Map<byte[], Integer> parseFeedbackStreamRaw(InputStream in) { Map<byte[], Integer> result = new HashMap<byte[], Integer>(); DataInputStream data = new DataInputStream(in); while (true) { try { int time = data.readInt(); int dtLength = data.readUnsignedShort(); byte[] deviceToken = new byte[dtLength]; data.readFully(deviceToken); result.put(deviceToken, time); } catch (EOFException e) { break; } catch (IOException e) { throw new RuntimeException(e); } } return result; } public static Map<String, Date> parseFeedbackStream(InputStream in) { Map<String, Date> result = new HashMap<String, Date>(); Map<byte[], Integer> raw = parseFeedbackStreamRaw(in); for (Map.Entry<byte[], Integer> entry : raw.entrySet()) { byte[] dtArray = entry.getKey(); int time = entry.getValue(); // in seconds Date date = new Date(time * 1000L); // in ms String dtString = encodeHex(dtArray); result.put(dtString, date); } return result; } public static void close(Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (IOException e) { logger.debug("error while closing resource", e); } } public static void close(Socket closeable) { try { if (closeable != null) { closeable.close(); } } catch (IOException e) { logger.debug("error while closing socket", e); } } public static void sleep(int delay) { try { Thread.sleep(delay); } catch (InterruptedException e1) {} } public static byte[] copyOf(byte[] bytes) { byte[] copy = new byte[bytes.length]; System.arraycopy(bytes, 0, copy, 0, bytes.length); return copy; } public static byte[] copyOfRange(byte[] original, int from, int to) { int newLength = to - from; if (newLength < 0) throw new IllegalArgumentException(from + " > " + to); byte[] copy = new byte[newLength]; System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); return copy; } }
package org.eclipse.persistence.internal.oxm.record.namespaces; import java.util.HashSet; import java.util.Set; import javax.xml.stream.XMLStreamReader; import org.eclipse.persistence.oxm.XMLConstants; /** * An UnmarshalNamespaceResolver that delegates all work to a NamespaceContext. * This is useful when using XML input from sources such as StAX. */ public class UnmarshalNamespaceContext implements UnmarshalNamespaceResolver { private XMLStreamReader xmlStreamReader; private Set<String> prefixes; public UnmarshalNamespaceContext() { this.prefixes = new HashSet(); } public UnmarshalNamespaceContext(XMLStreamReader anXMLStreamReader) { this.xmlStreamReader = anXMLStreamReader; this.prefixes = new HashSet(); } public String getNamespaceURI(String prefix) { if(null == prefix) { prefix = XMLConstants.EMPTY_STRING; } try { return xmlStreamReader.getNamespaceURI(prefix); } catch(IllegalStateException e) { return null; } } public String getPrefix(String namespaceURI) { return xmlStreamReader.getNamespaceContext().getPrefix(namespaceURI); } /** * The underlying NamespaceContext is responsible for maintaining the * appropriate prefix/URI associations. */ public void push(String prefix, String namespaceURI) { prefixes.add(prefix); } /** * The underlying NamespaceContext is responsible for maintaining the * appropriate prefix/URI associations. */ public void pop(String prefix) { if(null!= getNamespaceURI(prefix)) { prefixes.remove(prefix); } } public Set<String> getPrefixes() { return prefixes; } public XMLStreamReader getXmlStreamReader() { return xmlStreamReader; } public void setXmlStreamReader(XMLStreamReader xmlStreamReader) { this.xmlStreamReader = xmlStreamReader; } }
package nl.idgis.publisher.service.geoserver.rest; public class LayerRef { private final String layerId; private final boolean group; public LayerRef(String layerId, boolean group) { this.layerId = layerId; this.group = group; } public String getLayerId() { return layerId; } public boolean isGroup() { return group; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (group ? 1231 : 1237); result = prime * result + ((layerId == null) ? 0 : layerId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; LayerRef other = (LayerRef) obj; if (group != other.group) return false; if (layerId == null) { if (other.layerId != null) return false; } else if (!layerId.equals(other.layerId)) return false; return true; } @Override public String toString() { return "LayerRef [layerId=" + layerId + ", group=" + group + "]"; } }
package com.pattern.singleton; /** * @date 2021-12-16 19:42 * @author krisjin */ public enum SingletonEnum { INSTANCE; private SingletonEnum() { } public SingletonEnum SingletonEnum() { return INSTANCE; } }
package com.jetbrains.python.inspections.quickfix; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.codeInsight.template.*; import com.intellij.codeInspection.LocalQuickFix; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; import com.intellij.psi.ResolveResult; import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.python.PyBundle; import com.jetbrains.python.codeInsight.controlflow.ScopeOwner; import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil; import com.jetbrains.python.psi.PyRecursiveElementVisitor; import com.jetbrains.python.psi.PyReferenceExpression; import com.jetbrains.python.psi.impl.references.PyReferenceImpl; import com.jetbrains.python.refactoring.PyRefactoringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; /** * User : ktisha * * Quick fix to rename unresolved references */ public class PyRenameUnresolvedRefQuickFix implements LocalQuickFix { @NotNull @Override public String getName() { return PyBundle.message("QFIX.rename.unresolved.reference"); } @Override @NotNull public String getFamilyName() { return PyBundle.message("QFIX.rename.unresolved.reference"); } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { final PsiElement element = descriptor.getPsiElement(); final PyReferenceExpression referenceExpression = PsiTreeUtil.getParentOfType(element, PyReferenceExpression.class); if (referenceExpression == null) return; ScopeOwner parentScope = ScopeUtil.getScopeOwner(referenceExpression); if (parentScope == null) return; List<PyReferenceExpression> refs = collectExpressionsToRename(referenceExpression, parentScope); LookupElement[] items = collectLookupItems(parentScope); final String name = referenceExpression.getReferencedName(); ReferenceNameExpression refExpr = new ReferenceNameExpression(items, name); TemplateBuilderImpl builder = (TemplateBuilderImpl)TemplateBuilderFactory.getInstance(). createTemplateBuilder(parentScope); for (PyReferenceExpression expr : refs) { if (!expr.equals(referenceExpression)) { builder.replaceElement(expr, name, name, false); } else { builder.replaceElement(expr, name, refExpr, true); } } Editor editor = getEditor(project, element.getContainingFile(), parentScope.getTextRange().getStartOffset()); if (editor != null) { Template template = builder.buildInlineTemplate(); TemplateManager.getInstance(project).startTemplate(editor, template); } } public static boolean isValidReference(final PsiReference reference) { if (!(reference instanceof PyReferenceImpl)) return false; ResolveResult[] results = ((PyReferenceImpl)reference).multiResolve(true); if(results.length == 0) return false; for (ResolveResult result : results) { if (!result.isValidResult()) return false; } return true; } private static List<PyReferenceExpression> collectExpressionsToRename(@NotNull final PyReferenceExpression expression, @NotNull final ScopeOwner parentScope) { final List<PyReferenceExpression> result = new ArrayList<PyReferenceExpression>(); PyRecursiveElementVisitor visitor = new PyRecursiveElementVisitor() { @Override public void visitPyReferenceExpression(PyReferenceExpression node) { if (node.textMatches(expression) && !isValidReference(node.getReference())) { result.add(node); } super.visitPyReferenceExpression(node); } }; parentScope.accept(visitor); return result; } @Nullable private static Editor getEditor(@NotNull final Project project, @NotNull final PsiFile file, int offset) { final VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile != null) { return FileEditorManager.getInstance(project).openTextEditor( new OpenFileDescriptor(project, virtualFile, offset), true ); } return null; } private static LookupElement[] collectLookupItems(@NotNull final ScopeOwner parentScope) { Set<LookupElement> items = new LinkedHashSet<LookupElement>(); final Collection<String> usedNames = PyRefactoringUtil.collectUsedNames(parentScope); for (String name : usedNames) { if (name != null) items.add(LookupElementBuilder.create(name)); } return items.toArray(new LookupElement[items.size()]); } private class ReferenceNameExpression extends Expression { class HammingComparator implements Comparator<LookupElement> { @Override public int compare(LookupElement lookupItem1, LookupElement lookupItem2) { String s1 = lookupItem1.getLookupString(); String s2 = lookupItem2.getLookupString(); int diff1 = 0; for (int i = 0; i < Math.min(s1.length(), myOldReferenceName.length()); i++) { if (s1.charAt(i) != myOldReferenceName.charAt(i)) diff1++; } int diff2 = 0; for (int i = 0; i < Math.min(s2.length(), myOldReferenceName.length()); i++) { if (s2.charAt(i) != myOldReferenceName.charAt(i)) diff2++; } return diff1 - diff2; } } ReferenceNameExpression(LookupElement[] items, String oldReferenceName) { myItems = items; myOldReferenceName = oldReferenceName; Arrays.sort(myItems, new HammingComparator()); } LookupElement[] myItems; private final String myOldReferenceName; @Override public Result calculateResult(ExpressionContext context) { if (myItems == null || myItems.length == 0) { return new TextResult(myOldReferenceName); } return new TextResult(myItems[0].getLookupString()); } @Override public Result calculateQuickResult(ExpressionContext context) { return null; } @Override public LookupElement[] calculateLookupItems(ExpressionContext context) { if (myItems == null || myItems.length == 1) return null; return myItems; } } }
package com.rhymestore.proc; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.TwitterStream; import twitter4j.TwitterStreamFactory; import com.rhymestore.config.Configuration; import com.rhymestore.twitter.TwitterScheduler; import com.rhymestore.twitter.stream.GetMentionsListener; /** * Main Twitter listener process. * * @author Ignasi Barrera */ public class TwitterListener { /** The logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(TwitterListener.class); /** The Twitter API call scheduler. */ private TwitterScheduler twitterScheduler; /** The Twitter API client. */ private Twitter twitter; /** The Twitter streaming API. */ private TwitterStream stream; /** * Start listening to tweets. */ public void start() throws IllegalStateException, TwitterException { twitter = new TwitterFactory().getInstance(); stream = new TwitterStreamFactory().getInstance(); LOGGER.info("Connected to Twitter as: {}", twitter.getScreenName()); LOGGER.info("Starting the Twitter API scheduler"); twitterScheduler = new TwitterScheduler(twitter); twitterScheduler.start(); // Start processing the command queue LOGGER.info("Starting the Twitter stream listener"); stream.addListener(new GetMentionsListener(twitter, twitterScheduler)); stream.user(); // Start reading to user stream } /** * Shutdown hook to close the connection to Twitter. */ private static class TwitterShutdown extends Thread { /** The listener to shutdown. */ private TwitterListener listener; public TwitterShutdown(final TwitterListener listener) { super(); this.listener = listener; } @Override public void run() { LOGGER.info("Shutting down the Twitter API scheduler"); listener.twitterScheduler.shutdown(); // Stop scheduler LOGGER.info("Disconnecting from the Twitter streaming API"); listener.stream.shutdown(); LOGGER.info("Disconnecting from Twitter"); listener.twitter.shutdown(); } } public static void main(final String[] args) throws Exception { Configuration.loadTwitterConfig(); // Start the Twitter listener TwitterListener listener = new TwitterListener(); listener.start(); // Register the shutdown hook to close the connection properly Runtime.getRuntime().addShutdownHook(new TwitterShutdown(listener)); } }
package com.routeme.service; import static java.util.stream.Collectors.toList; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.routeme.dto.UserDTO; import com.routeme.model.User; import com.routeme.repository.UserRepository; @Service public class UserServiceImpl implements UserService { private final UserRepository repository; @Autowired public UserServiceImpl(UserRepository repository) { this.repository = repository; } @Override public UserDTO create(UserDTO user) { User persistedUser = User.getFactory().name(user.getUsername()).email(user.getEmail()).password(user.getPassword()) .build(); persistedUser = repository.save(persistedUser); return convertToDTO(persistedUser); } @Override public UserDTO delete(String id) { User deletedUser = findUserById(id); repository.delete(deletedUser); return convertToDTO(deletedUser); } @Override public List<UserDTO> findAll() { List<User> userEntries = repository.findAll(); return convertToDTOs(userEntries); } private List<UserDTO> convertToDTOs(List<User> userModels) { return userModels.stream().map(this::convertToDTO).collect(toList()); } @Override public UserDTO findById(String id) { User foundUser = findUserById(id); return convertToDTO(foundUser); } @Override public UserDTO update(UserDTO userModel) { User updatedUser = findUserById(userModel.getId()); updatedUser.update(userModel.getUsername(), userModel.getEmail(), userModel.getPassword()); updatedUser = repository.save(updatedUser); return convertToDTO(updatedUser); } private User findUserById(String id) { Optional<User> result = repository.findOne(id); return result.get(); } private UserDTO convertToDTO(User model) { UserDTO dto = new UserDTO(); dto.setId(model.getId()); dto.setUsername(model.getName()); dto.setEmail(model.getEmail()); dto.setPassword(model.getPassword()); return dto; } }
package com.rultor.agents.github.qtn; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.Collections2; import com.google.common.collect.Iterables; import com.jcabi.aspects.Immutable; import com.jcabi.github.Comment; import com.jcabi.github.Contents; import com.jcabi.log.Logger; import com.jcabi.xml.XML; import com.jcabi.xml.XMLDocument; import com.rultor.agents.github.Answer; import com.rultor.agents.github.Question; import com.rultor.agents.github.Req; import java.io.IOException; import java.net.URI; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Locale; import java.util.ResourceBundle; import javax.json.Json; import lombok.EqualsAndHashCode; import lombok.ToString; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.CharEncoding; import org.apache.commons.lang3.StringUtils; import org.xembly.Directives; import org.xembly.Xembler; /** * Lock branch. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @since 1.53 */ @Immutable @ToString @EqualsAndHashCode public final class QnLock implements Question { /** * Message bundle. */ private static final String PATH = ".rultor.lock"; /** * Message bundle. */ private static final ResourceBundle PHRASES = ResourceBundle.getBundle("phrases"); @Override public Req understand(final Comment.Smart comment, final URI home) throws IOException { final XML args = new XMLDocument( new Xembler( new Directives().add("args").append( new QnParametrized(Question.EMPTY) .understand(comment, home) .dirs() ) ).xmlQuietly() ); final String branch; if (args.nodes("//arg[@name='branch']").isEmpty()) { branch = "master"; } else { branch = args.xpath("//arg[@name='branch']/text()").get(0); } final Collection<String> users = new LinkedHashSet<>(0); users.add(comment.author().login().toLowerCase(Locale.ENGLISH)); if (!args.nodes("//arg[@name='users']").isEmpty()) { users.addAll( Collections2.transform( Arrays.asList( args.xpath( "//arg[@name='users']/text()" ).get(0).split(",") ), new Function<String, String>() { @Override public String apply(final String input) { return StringUtils.stripStart( input.toLowerCase(Locale.ENGLISH), "@" ); } } ) ); } final Contents contents = comment.issue().repo().contents(); if (contents.exists(QnLock.PATH, branch)) { new Answer(comment).post( String.format( QnLock.PHRASES.getString("QnLock.already-exists"), branch ) ); } else { contents.create( Json.createObjectBuilder() .add("path", QnLock.PATH) .add( "message", String.format( "by request of @%s in comment.author().login(), comment.issue().number() ) ) .add( "content", Base64.encodeBase64String( Joiner.on("\n").join(users).getBytes( CharEncoding.UTF_8 ) ) ) .add("branch", branch) .build() ); new Answer(comment).post( String.format( QnLock.PHRASES.getString("QnLock.response"), branch, Joiner.on(", ").join( Iterables.transform( users, new Function<String, String>() { @Override public String apply(final String input) { return String.format("@%s", input); } } ) ) ) ); } Logger.info(this, "lock request in #%d", comment.issue().number()); return Req.DONE; } }
package com.syncleus.ferma.pipes; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import com.tinkerpop.pipes.Pipe; import com.tinkerpop.pipes.PipeFunction; import com.tinkerpop.pipes.sideeffect.SideEffectPipe; import com.tinkerpop.pipes.util.AbstractMetaPipe; import com.tinkerpop.pipes.util.FastNoSuchElementException; import com.tinkerpop.pipes.util.PipeHelper; public class DivertPipe<S, T> extends AbstractMetaPipe<S, S> { private final SideEffectPipe<S, T> pipeToCap; private final PipeFunction<T, ?> sideEffectFunction; public DivertPipe(final SideEffectPipe<S, T> pipeToCap, final PipeFunction<T, ?> sideEffectFunction) { this.pipeToCap = pipeToCap; this.sideEffectFunction = sideEffectFunction; } public void setStarts(final Iterator<S> starts) { this.pipeToCap.setStarts(starts); } protected S processNextStart() { if (this.pipeToCap instanceof SideEffectPipe.LazySideEffectPipe) { final S next = this.pipeToCap.next(); sideEffectFunction.compute(this.pipeToCap.getSideEffect()); return next; } else { try { return this.pipeToCap.next(); } catch (final NoSuchElementException e) { sideEffectFunction.compute(this.pipeToCap.getSideEffect()); throw FastNoSuchElementException.instance(); } } } public List getCurrentPath() { if (this.pathEnabled) { final List list = this.pipeToCap.getCurrentPath(); list.add(this.currentEnd); return list; } else { throw new RuntimeException(Pipe.NO_PATH_MESSAGE); } } public String toString() { return PipeHelper.makePipeString(this, this.pipeToCap); } public List<Pipe> getPipes() { return Arrays.asList((Pipe) this.pipeToCap); } }
package com.ubervu.river.github; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonStreamParser; import org.apache.commons.codec.digest.DigestUtils; import org.elasticsearch.action.bulk.BulkProcessor; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.Base64; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.index.query.FilterBuilders; import org.elasticsearch.index.query.FilteredQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.indices.IndexAlreadyExistsException; import org.elasticsearch.river.AbstractRiverComponent; import org.elasticsearch.river.River; import org.elasticsearch.river.RiverName; import org.elasticsearch.river.RiverSettings; import org.elasticsearch.search.sort.FieldSortBuilder; import org.elasticsearch.search.sort.SortBuilders; import org.elasticsearch.search.sort.SortOrder; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; public class GitHubRiver extends AbstractRiverComponent implements River { private final Client client; private final String index; private final String repository; private final String owner; private final int userRequestedInterval; private final String endpoint; private String password; private String username; private DataStream dataStream; private String eventETag = null; private int pollInterval = 60; @SuppressWarnings({"unchecked"}) @Inject public GitHubRiver(RiverName riverName, RiverSettings settings, Client client) { super(riverName, settings); this.client = client; if (!settings.settings().containsKey("github")) { throw new IllegalArgumentException("Need river settings - owner and repository."); } // get settings Map<String, Object> githubSettings = (Map<String, Object>) settings.settings().get("github"); owner = XContentMapValues.nodeStringValue(githubSettings.get("owner"), null); repository = XContentMapValues.nodeStringValue(githubSettings.get("repository"), null); index = String.format("%s&%s", owner, repository); userRequestedInterval = XContentMapValues.nodeIntegerValue(githubSettings.get("interval"), 60); // auth (optional) username = null; password = null; if (githubSettings.containsKey("authentication")) { Map<String, Object> auth = (Map<String, Object>) githubSettings.get("authentication"); username = XContentMapValues.nodeStringValue(auth.get("username"), null); password = XContentMapValues.nodeStringValue(auth.get("password"), null); } // endpoint (optional - default to github.com) endpoint = XContentMapValues.nodeStringValue(githubSettings.get("endpoint"), "https://api.github.com"); logger.info("Created GitHub river."); } @Override public void start() { // create the index explicitly so we can use the whitespace tokenizer // because there are usernames like "user-name" and we want those // to be treated as just one term try { Settings indexSettings = ImmutableSettings.settingsBuilder().put("analysis.analyzer.default.tokenizer", "whitespace").build(); client.admin().indices().prepareCreate(index).setSettings(indexSettings).execute().actionGet(); logger.info("Created index."); } catch (IndexAlreadyExistsException e) { logger.info("Index already created"); } catch (Exception e) { logger.error("Exception creating index.", e); } dataStream = new DataStream(); dataStream.start(); logger.info("Started GitHub river."); } @Override public void close() { dataStream.setRunning(false); dataStream.interrupt(); logger.info("Stopped GitHub river."); } private class DataStream extends Thread { private volatile boolean isRunning; @Inject public DataStream() { super("DataStream thread"); isRunning = true; } private boolean checkAndUpdateETag(HttpURLConnection conn) throws IOException { if (eventETag != null) { conn.setRequestProperty("If-None-Match", eventETag); } String xPollInterval = conn.getHeaderField("X-Poll-Interval"); if (xPollInterval != null) { logger.debug("Next GitHub specified minimum polling interval is {} s", xPollInterval); pollInterval = Integer.parseInt(xPollInterval); } if (conn.getResponseCode() == 304) { logger.debug("304 {}", conn.getResponseMessage()); return false; } String eTag = conn.getHeaderField("ETag"); if (eTag != null) { logger.debug("New eTag: {}", eTag); eventETag = eTag; } return true; } String previouslyIndexedEvent = null; private void indexResponse(HttpURLConnection conn, String type) { InputStream input; try { input = conn.getInputStream(); } catch (IOException e) { logger.info("Exception encountered (403 usually is rate limit exceeded): ", e); return; } JsonStreamParser jsp = new JsonStreamParser(new InputStreamReader(input)); JsonArray array = (JsonArray) jsp.next(); BulkProcessor bp = BulkProcessor.builder(client, new BulkProcessor.Listener() { @Override public void beforeBulk(long executionId, BulkRequest request) { } @Override public void afterBulk(long executionId, BulkRequest request, BulkResponse response) { } @Override public void afterBulk(long executionId, BulkRequest request, Throwable failure) { } }).build(); IndexRequest req = null; for (JsonElement e : array) { if (type.equals("event")) { req = indexEvent(e); if (req == null) { logger.debug("Found existing event, all remaining events should already have been indexed"); } else if (previouslyIndexedEvent != null) { logger.warn("New non-indexed event {}, even though the previous event {} has already been indexed?", req.id(), previouslyIndexedEvent); } } else if (type.equals("issue")) { req = indexOther(e, "IssueData", true); } else if (type.equals("pullreq")) { req = indexOther(e, "PullRequestData"); } else if (type.equals("milestone")) { req = indexOther(e, "MilestoneData"); } else if (type.equals("label")) { req = indexOther(e, "LabelData"); } else if (type.equals("collaborator")) { req = indexOther(e, "CollaboratorData"); } if (req != null) { bp.add(req); } } bp.close(); try { input.close(); } catch (IOException e) { logger.warn("Couldn't close connection?", e); } } private boolean isEventIndexed(String id) { return client.prepareGet(index, null, id).get().isExists(); } private IndexRequest indexEvent(JsonElement e) { JsonObject obj = e.getAsJsonObject(); String type = obj.get("type").getAsString(); String id = obj.get("id").getAsString(); if (isEventIndexed(id)) { logger.debug("Found id {} already in the index. No more IDs should be found from now on", id); previouslyIndexedEvent = id; return null; } logger.debug("Indexing event {}", id); IndexRequest req = new IndexRequest(index) .type(type) .id(id).create(false) // we want to overwrite old items .source(e.toString()); return req; } private IndexRequest indexOther(JsonElement e, String type, boolean overwrite) { JsonObject obj = e.getAsJsonObject(); // handle objects that don't have IDs (i.e. labels) // set the ID to the MD5 hash of the string representation String id; if (obj.has("id")) { id = obj.get("id").getAsString(); } else { id = DigestUtils.md5Hex(e.toString()); } IndexRequest req = new IndexRequest(index) .type(type) .id(id).create(!overwrite) .source(e.toString()); return req; } private IndexRequest indexOther(JsonElement e, String type) { return indexOther(e, type, false); } private HashMap<String, String> parseHeader(String header) { // inspired from https://github.com/uberVU/elasticboard/blob/4ccdfd8c8e772c1dda49a29a7487d14b8d820762/data_processor/github.py#L73 Pattern p = Pattern.compile("\\<([a-z/0-9:\\.\\?_&=]+page=([0-9]+))\\>;\\s*rel=\\\"([a-z]+)\\\".*"); Matcher m = p.matcher(header); if (!m.matches()) { return null; } HashMap<String, String> data = new HashMap<String, String>(); data.put("url", m.group(1)); data.put("page", m.group(2)); data.put("rel", m.group(3)); return data; } private boolean morePagesAvailable(URLConnection response) { String link = response.getHeaderField("link"); if (link == null || link.length() == 0) { return false; } HashMap<String, String> headerData = parseHeader(response.getHeaderField("link")); if (headerData == null) { return false; } String rel = headerData.get("rel"); return rel.equals("next"); } private String nextPageURL(URLConnection response) { HashMap<String, String> headerData = parseHeader(response.getHeaderField("link")); if (headerData == null) { return null; } return headerData.get("url"); } private void addAuthHeader(URLConnection connection) { if (username == null || password == null) { return; } String auth = String.format("%s:%s", username, password); String encoded = Base64.encodeBytes(auth.getBytes()); connection.setRequestProperty("Authorization", "Basic " + encoded); } private boolean getData(String fmt, String type) { return getData(fmt, type, null); } private boolean getData(String fmt, String type, String since) { try { URL url; if (since != null) { url = new URL(String.format(fmt, owner, repository, since)); } else { url = new URL(String.format(fmt, owner, repository)); } HttpURLConnection connection = (HttpURLConnection) url.openConnection(); addAuthHeader(connection); if (type.equals("event")) { boolean modified = checkAndUpdateETag(connection); if (!modified) { return false; } } previouslyIndexedEvent = null; logger.debug("Fetching data of type {}", type); indexResponse(connection, type); while (morePagesAvailable(connection)) { logger.debug("More pages available, fetching next page"); url = new URL(nextPageURL(connection)); connection = (HttpURLConnection) url.openConnection(); addAuthHeader(connection); indexResponse(connection, type); } } catch (Exception e) { logger.error("Exception in getData", e); } return true; } private void deleteByType(String type) { client.prepareDeleteByQuery(index) .setQuery(termQuery("_type", type)) .execute() .actionGet(); } /** * Gets the creation data of the single newest entry. * * @return ISO8601 formatted time of most recent entry, or null on empty or error. */ private String getMostRecentEntry() { long totalEntries = client.prepareCount(index).setQuery(matchAllQuery()).execute().actionGet().getCount(); if (totalEntries > 0) { FilteredQueryBuilder updatedAtQuery = QueryBuilders .filteredQuery(QueryBuilders.matchAllQuery(), FilterBuilders.existsFilter("created_at")); FieldSortBuilder updatedAtSort = SortBuilders.fieldSort("created_at").order(SortOrder.DESC); SearchResponse response = client.prepareSearch(index) .setQuery(updatedAtQuery) .addSort(updatedAtSort) .setSize(1) .execute() .actionGet(); String createdAt = (String) response.getHits().getAt(0).getSource().get("created_at"); logger.debug("Most recent event was created at {}", createdAt); return createdAt; } else { // getData will get all data on a null. logger.info("No existing entries, assuming first run"); return null; } } @Override public void run() { while (isRunning) { // Must be read before getting new events. String mostRecentEntry = getMostRecentEntry(); logger.debug("Checking for events"); if (getData(endpoint + "/repos/%s/%s/events?per_page=1000", "event")) { logger.debug("First run or new events found, fetching rest of the data"); if (mostRecentEntry != null) { getData(endpoint + "/repos/%s/%s/issues?state=all&per_page=1000&since=%s", "issue", mostRecentEntry); } else { getData(endpoint + "/repos/%s/%s/issues?state=all&per_page=1000", "issue"); } // delete pull req data - we are only storing open pull reqs // and when a pull request is closed we have no way of knowing; // this is why we have to delete them and reindex "fresh" ones deleteByType("PullRequestData"); getData(endpoint + "/repos/%s/%s/pulls", "pullreq"); // same for milestones deleteByType("MilestoneData"); getData(endpoint + "/repos/%s/%s/milestones?per_page=1000", "milestone"); // collaborators deleteByType("CollaboratorData"); getData(endpoint + "/repos/%s/%s/collaborators?per_page=1000", "collaborator"); // and for labels - they have IDs based on the MD5 of the contents, so // if a property changes, we get a "new" document deleteByType("LabelData"); getData(endpoint + "/repos/%s/%s/labels?per_page=1000", "label"); } else { logger.debug("No new events found"); } try { int waitTime = Math.max(pollInterval, userRequestedInterval) * 1000; logger.debug("Waiting {} ms before polling for new events", waitTime); Thread.sleep(waitTime); // needs milliseconds } catch (InterruptedException e) { logger.info("Wait interrupted, river was probably stopped"); } } } public void setRunning(boolean running) { isRunning = running; } } }
package com.vesperin.reflects; import com.vesperin.utils.Expect; import java.util.AbstractMap; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringJoiner; import java.util.function.BinaryOperator; import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.IntStream; import java.util.stream.Stream; /** * @author Huascar Sanchez */ public class JdkPredicates { private static final Pattern PACKAGES_PATTERN; private JdkPredicates() { } /** * Returns a {@code Pattern} instance that test if given {@code CharSequence} matches * one of existing public JDK packages, such as "java.util", "org.w3c.dom" and so on. * * @return a {@code Pattern} instance. */ public static Pattern jdkAll() { return PACKAGES_PATTERN; } /** * Wraps a call to {@link JdkPredicates#jdkAll()} as a {@link Predicate} object. * * @return a new predicate that checks if the package (in string form) * is in the Jdk. */ public static Predicate<Class<?>> inJdk(){ return JdkPredicates::isPublicDocumentedJdkClass; } /** * Test if the given {@code CharSequence} is public and belongs to one of public * documented JDK packages. * * @return {@code true} if the given {@code CharSequence} is public and belongs * to one of public documented JDK packages. */ public static boolean isPublicDocumentedJdkClass(Class<?> k) { if (ClassDefinition.isPublic(k)) { final String packageName = k.getPackage().getName(); return inJdk(packageName); } return false; } /** * Test if the given {@code CharSequence} is public and belongs to one of public * documented JDK packages. * * @param packageName package name * * @return {@code true} if the given {@code CharSequence} is public and belongs * to one of public documented JDK packages. */ public static boolean inJdk(String packageName){ return packageName != null && inPackage(packageName, jdkAll()); } /** * Test if the given {@code CharSequence} is in a package. * * @param packageName name of package. * @param pattern regex to match package names. * @return */ public static boolean inPackage(String packageName, Pattern pattern){ return Expect.nonNull(pattern).matcher(packageName).matches(); } static { final List<String> fullSE8API = Arrays.asList("java.applet", "java.awt", "java.awt.color", "java.awt.datatransfer", "java.awt.dnd", "java.awt.event", "java.awt.font", "java.awt.geom", "java.awt.im", "java.awt.im.spi", "java.awt.image", "java.awt.image.renderable", "java.awt.print", "java.beans", "java.beans.beancontext", "java.io", "java.lang", "java.lang.annotation", "java.lang.instrument", "java.lang.invoke", "java.lang.management", "java.lang.ref", "java.lang.reflect", "java.math", "java.net", "java.nio", "java.nio.channels", "java.nio.channels.spi", "java.nio.charset", "java.nio.charset.spi", "java.nio.file", "java.nio.file.attribute", "java.nio.file.spi", "java.rmi", "java.rmi.activation", "java.rmi.dgc", "java.rmi.registry", "java.rmi.server", "java.security", "java.security.acl", "java.security.cert", "java.security.interfaces", "java.security.spec", "java.sql", "java.text", "java.text.spi", "java.time", "java.time.chrono", "java.time.format", "java.time.temporal", "java.time.zone", "java.util", "java.util.concurrent", "java.util.concurrent.atomic", "java.util.concurrent.locks", "java.util.function", "java.util.jar", "java.util.logging", "java.util.prefs", "java.util.regex", "java.util.spi", "java.util.stream", "java.util.zip", "javax.accessibility", "javax.activation", "javax.activity", "javax.annotation", "javax.annotation.processing", "javax.crypto", "javax.crypto.interfaces", "javax.crypto.spec", "javax.imageio", "javax.imageio.event", "javax.imageio.metadata", "javax.imageio.plugins.bmp", "javax.imageio.plugins.jpeg", "javax.imageio.spi", "javax.imageio.stream", "javax.jws", "javax.jws.soap", "javax.lang.model", "javax.lang.model.element", "javax.lang.model.type", "javax.lang.model.util", "javax.management", "javax.management.loading", "javax.management.modelmbean", "javax.management.monitor", "javax.management.openmbean", "javax.management.relation", "javax.management.remote", "javax.management.remote.rmi", "javax.management.timer", "javax.naming", "javax.naming.directory", "javax.naming.event", "javax.naming.ldap", "javax.naming.spi", "javax.net", "javax.net.ssl", "javax.print", "javax.print.attribute", "javax.print.attribute.standard", "javax.print.event", "javax.rmi", "javax.rmi.CORBA", "javax.rmi.ssl", "javax.script", "javax.security.auth", "javax.security.auth.callback", "javax.security.auth.kerberos", "javax.security.auth.login", "javax.security.auth.spi", "javax.security.auth.x500", "javax.security.cert", "javax.security.sasl", "javax.sound.midi", "javax.sound.midi.spi", "javax.sound.sampled", "javax.sound.sampled.spi", "javax.sql", "javax.sql.rowset", "javax.sql.rowset.serial", "javax.sql.rowset.spi", "javax.swing", "javax.swing.border", "javax.swing.colorchooser", "javax.swing.event", "javax.swing.filechooser", "javax.swing.plaf", "javax.swing.plaf.basic", "javax.swing.plaf.metal", "javax.swing.plaf.multi", "javax.swing.plaf.nimbus", "javax.swing.plaf.synth", "javax.swing.table", "javax.swing.text", "javax.swing.text.html", "javax.swing.text.html.parser", "javax.swing.text.rtf", "javax.swing.tree", "javax.swing.undo", "javax.tools", "javax.transaction", "javax.transaction.xa", "javax.xml", "javax.xml.bind", "javax.xml.bind.annotation", "javax.xml.bind.annotation.adapters", "javax.xml.bind.attachment", "javax.xml.bind.helpers", "javax.xml.bind.util", "javax.xml.crypto", "javax.xml.crypto.dom", "javax.xml.crypto.dsig", "javax.xml.crypto.dsig.dom", "javax.xml.crypto.dsig.keyinfo", "javax.xml.crypto.dsig.spec", "javax.xml.datatype", "javax.xml.namespace", "javax.xml.parsers", "javax.xml.soap", "javax.xml.stream", "javax.xml.stream.events", "javax.xml.stream.util", "javax.xml.transform", "javax.xml.transform.dom", "javax.xml.transform.sax", "javax.xml.transform.stax", "javax.xml.transform.stream", "javax.xml.validation", "javax.xml.ws", "javax.xml.ws.handler", "javax.xml.ws.handler.soap", "javax.xml.ws.http", "javax.xml.ws.soap", "javax.xml.ws.spi", "javax.xml.ws.spi.http", "javax.xml.ws.wsaddressing", "javax.xml.xpath", "org.ietf.jgss", "org.omg.CORBA", "org.omg.CORBA_2_3", "org.omg.CORBA_2_3.portable", "org.omg.CORBA.DynAnyPackage", "org.omg.CORBA.ORBPackage", "org.omg.CORBA.portable", "org.omg.CORBA.TypeCodePackage", "org.omg.CosNaming", "org.omg.CosNaming.NamingContextExtPackage", "org.omg.CosNaming.NamingContextPackage", "org.omg.Dynamic", "org.omg.DynamicAny", "org.omg.DynamicAny.DynAnyFactoryPackage", "org.omg.DynamicAny.DynAnyPackage", "org.omg.IOP", "org.omg.IOP.CodecFactoryPackage", "org.omg.IOP.CodecPackage", "org.omg.Messaging", "org.omg.PortableInterceptor", "org.omg.PortableInterceptor.ORBInitInfoPackage", "org.omg.PortableServer", "org.omg.PortableServer.CurrentPackage", "org.omg.PortableServer.POAManagerPackage", "org.omg.PortableServer.POAPackage", "org.omg.PortableServer.portable", "org.omg.PortableServer.ServantLocatorPackage", "org.omg.SendingContext", "org.omg.stub.java.rmi", "org.w3c.dom", "org.w3c.dom.bootstrap", "org.w3c.dom.events", "org.w3c.dom.ls", "org.w3c.dom.views", "org.xml.sax", "org.xml.sax.ext", "org.xml.sax.helpers"); final Stream<String> pkgs = fullSE8API.stream(); final BinaryOperator<PackageNode> NO_COMBINER = (p1, p2) -> { throw new IllegalStateException(); }; final String ROOT_INDICATOR = "/"; final PackageNode root = pkgs.map(r -> { final String[] split = r.split("\\."); // The sentinel value is to indicate that the "middle" package is also one to be included in Pattern. // Example is "java.awt" which has sub package "java.awt.color" and etc. // On the other hand, middle packages like "java" and "org" is not to be included in Pattern. return Stream.concat(IntStream.range(0, split.length).mapToObj(depth -> PackageNode.of(split[depth], depth)), Stream.of(PackageNode.sentinel(split.length))); }).reduce(PackageNode.of(ROOT_INDICATOR, 0), (root_, stream) -> { stream.reduce(root_, (last, current) -> { if (last.containsKey(current)) { return last.get(current); } last.add(current); return current; }, NO_COMBINER); return root_; }, NO_COMBINER); PACKAGES_PATTERN = Pattern.compile(String.format("^%s$", root.toPatternGroup().replaceFirst("^" + ROOT_INDICATOR, ""))); } static class PackageNode extends AbstractMap<PackageNode, PackageNode> { private static final String PACKAGE_NAME_SENTINEL = "<>"; private final String name; private final Map<PackageNode, PackageNode> sub; private final int depth; private PackageNode(final String name, int depth) { this.name = name; this.depth = depth; this.sub = new HashMap<>(); } static PackageNode of(final String name, int depth) { return new PackageNode(name, depth); } static PackageNode sentinel(int depth) { return new PackageNode(PACKAGE_NAME_SENTINEL, depth); } public String getName() { return name; } @Override public PackageNode put(PackageNode key, PackageNode value) { return sub.put(key, value); } @Override public PackageNode get(Object key) { return sub.get(key); } public PackageNode add(PackageNode key) { return put(key, key); } @Override public Set<Entry<PackageNode, PackageNode>> entrySet() { return sub.entrySet(); } @Override public boolean containsKey(Object key) { return sub.containsKey(key); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof PackageNode)) { return false; } final PackageNode that = (PackageNode) o; return name.equals(that.name); } public String toPatternGroup() { final String dot = (depth != 0) ? "\\." : ""; final StringJoiner joiner = new StringJoiner("|", dot + name + "(?:", ")"); sub.keySet().stream() .sorted(Comparator.comparing(PackageNode::getName)) .forEach(p -> joiner.add(p.toPatternGroup())); return joiner.toString() .replace("\\." + PACKAGE_NAME_SENTINEL, "") .replace("(?:)", ""); } @Override public int hashCode() { return name.hashCode(); } @Override public String toString() { return name; } } }
package de.blackcraze.grb.commands; import static de.blackcraze.grb.util.CommandUtils.getResponseLocale; import static de.blackcraze.grb.util.CommandUtils.parseGroupName; import static de.blackcraze.grb.util.CommandUtils.parseStockName; import static de.blackcraze.grb.util.CommandUtils.parseStocks; import static de.blackcraze.grb.util.InjectorUtils.getMateDao; import static de.blackcraze.grb.util.InjectorUtils.getStockDao; import static de.blackcraze.grb.util.InjectorUtils.getStockTypeDao; import static de.blackcraze.grb.util.InjectorUtils.getStockTypeGroupDao; import static de.blackcraze.grb.util.PrintUtils.prettyPrint; import static de.blackcraze.grb.util.PrintUtils.prettyPrintMate; import static de.blackcraze.grb.util.PrintUtils.prettyPrintStockTypes; import static de.blackcraze.grb.util.PrintUtils.prettyPrintStocks; import static org.bytedeco.javacpp.Pointer.availablePhysicalBytes; import static org.bytedeco.javacpp.Pointer.formatBytes; import static org.bytedeco.javacpp.Pointer.maxBytes; import static org.bytedeco.javacpp.Pointer.maxPhysicalBytes; import static org.bytedeco.javacpp.Pointer.physicalBytes; import static org.bytedeco.javacpp.Pointer.totalBytes; import static org.bytedeco.javacpp.Pointer.totalPhysicalBytes; import java.lang.management.ManagementFactory; import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryUsage; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Scanner; import java.util.function.Predicate; import java.util.stream.Collectors; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import de.blackcraze.grb.core.BotConfig; import de.blackcraze.grb.core.Speaker; import de.blackcraze.grb.i18n.Resource; import de.blackcraze.grb.model.Device; import de.blackcraze.grb.model.PrintableTable; import de.blackcraze.grb.model.entity.Mate; import de.blackcraze.grb.model.entity.StockType; import de.blackcraze.grb.model.entity.StockTypeGroup; import de.blackcraze.grb.util.PrintUtils; import de.blackcraze.grb.util.wagu.Block; import net.dv8tion.jda.core.entities.ChannelType; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.entities.MessageChannel; public final class Commands { private Commands() { } public static void info(Scanner scanner, Message message) { Speaker.say(message.getChannel(), Resource.getString("INFO", getResponseLocale(message))); } public static void ping(Scanner scanner, Message message) { Speaker.say(message.getChannel(), Resource.getString("PONG", getResponseLocale(message))); } public static void credits(Scanner scanner, Message message) { Speaker.say(message.getChannel(), Resource.getString("CDS", getResponseLocale(message))); } public static void userConfig(Scanner scanner, Message message) { Mate mate = getMateDao().getOrCreateMate(message, getResponseLocale(message)); if (!scanner.hasNext()) { StringBuilder response = new StringBuilder(); response.append("language: "); response.append(mate.getLanguage()); response.append("\n"); response.append("device: "); response.append(mate.getDevice()); response.append(" ["); Device[] devices = Device.values(); for (int i = 0; i < devices.length; i++) { response.append(devices[i].name()); if (i + 1 < devices.length) { response.append(','); } } response.append("]\n"); Speaker.sayCode(message.getChannel(), response.toString()); return; } String config_action = scanner.next(); if ("set".equalsIgnoreCase(config_action)) { String field = scanner.next(); String value = scanner.next(); if (Objects.isNull(field) || Objects.isNull(value)) { message.addReaction(Speaker.Reaction.FAILURE).queue(); return; } try { if ("language".equalsIgnoreCase(field)) { new Locale(value); // may throw an exception mate.setLanguage(value); getMateDao().update(mate); message.addReaction(Speaker.Reaction.SUCCESS).queue(); } else if ("device".equalsIgnoreCase(field)) { Device dev = Device.valueOf(StringUtils.upperCase(value)); mate.setDevice(dev); getMateDao().update(mate); message.addReaction(Speaker.Reaction.SUCCESS).queue(); } else { throw new IllegalStateException(); } } catch (IllegalArgumentException e) { // when setting an unknown device message.addReaction(Speaker.Reaction.FAILURE).queue(); } catch (Exception e) { message.addReaction(Speaker.Reaction.FAILURE).queue(); e.printStackTrace(); } } } public static void config(Scanner scanner, Message message) { checkPublic(message); BotConfig.ServerConfig instance = BotConfig.getConfig(); if (!scanner.hasNext()) { StringBuilder response = new StringBuilder(); Field[] fields = BotConfig.ServerConfig.class.getDeclaredFields(); for (Field field : fields) { Object value; try { value = field.get(instance); } catch (IllegalAccessException e) { e.printStackTrace(); continue; } response.append(field.getName()); response.append(": "); response.append(value.toString()); response.append("\n"); } Speaker.sayCode(message.getChannel(), response.toString()); return; } String config_action = scanner.next(); if ("set".equalsIgnoreCase(config_action)) { String field = scanner.next(); String value = scanner.next(); if (Objects.isNull(field) || Objects.isNull(value)) { message.addReaction(Speaker.Reaction.FAILURE).queue(); return; } try { Field declaredField = BotConfig.ServerConfig.class.getDeclaredField(field.toUpperCase()); assert String.class.equals(declaredField.getType()); declaredField.set(instance, value); message.addReaction(Speaker.Reaction.SUCCESS).queue(); } catch (Exception e) { message.addReaction(Speaker.Reaction.FAILURE).queue(); e.printStackTrace(); } } } private static void checkPublic(Message message) { if (!ChannelType.TEXT.equals(message.getChannelType())) { message.addReaction(Speaker.Reaction.FAILURE).queue(); Speaker.say(message.getChannel(), Resource.getString("PUBLIC_COMMAND_ONLY", getResponseLocale(message))); throw new IllegalStateException("public command only"); // TODO MORE SOLID IMPLEMENTATION } } public static void shutdown(Scanner scanner, Message message) { checkPublic(message); System.exit(1); } public static void nativeStatus(Scanner scanner, Message message) { StringBuffer buffer = new StringBuffer(); buffer.append("JAVACPP:\n"); buffer.append("memory tracked by deallocators: " + formatBytes(totalBytes()) + "\n"); buffer.append("maximum memory allowed to be tracked: " + formatBytes(maxBytes()) + "\n"); try { buffer.append("physical memory installed according to the operating system, or 0 if unknown: " + formatBytes(totalPhysicalBytes()) + "\n"); buffer.append("maximum physical memory that should be used: " + formatBytes(maxPhysicalBytes()) + "\n"); buffer.append("physical memory that is free according to the operating system, or 0 if unknown: " + formatBytes(availablePhysicalBytes()) + "\n"); buffer.append("physical memory currently used by the whole process, or 0 if unknown: " + formatBytes(physicalBytes()) + "\n"); } catch (UnsatisfiedLinkError e) { buffer.append("no physical Data Available"); } Speaker.sayCode(message.getChannel(), buffer.toString()); } public static void status(Scanner scanner, Message message) { StringBuffer buffer = new StringBuffer(); buffer.append("My Memory:\n\n"); buffer.append("\n\n"); for (MemPool pool : getPools()) { MemoryUsage usage = pool.getUsage(); buffer.append(pool.getName()).append("\n"); buffer.append("\tINIT: ").append(FileUtils.byteCountToDisplaySize(usage.getInit())).append("\n"); buffer.append("\tUSED: ").append(FileUtils.byteCountToDisplaySize(usage.getUsed())).append("\n"); buffer.append("\tCOMMITED: ").append(FileUtils.byteCountToDisplaySize(usage.getCommitted())).append("\n"); buffer.append("\tMAX: ").append(FileUtils.byteCountToDisplaySize(usage.getMax())).append("\n"); } Speaker.sayCode(message.getChannel(), buffer.toString()); } static class MemPool { private final String name; private final MemoryUsage usage; public MemPool(String name, MemoryUsage usage) { this.name = name; this.usage = usage; } /** * @return The name. */ public String getName() { return name; } /** * @return The usage. */ public MemoryUsage getUsage() { return usage; } } private static List<MemPool> getPools() { List<MemoryPoolMXBean> poolMXBeans = ManagementFactory.getMemoryPoolMXBeans(); List<MemPool> result = new ArrayList<MemPool>(poolMXBeans.size() + 2); result.add(new MemPool("Heap", ManagementFactory.getMemoryMXBean().getHeapMemoryUsage())); result.add(new MemPool("Non-Heap", ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage())); for (MemoryPoolMXBean poolMXBean : poolMXBeans) { result.add(new MemPool(poolMXBean.getName(), poolMXBean.getUsage())); } return result; } public static void users(Scanner scanner, Message message) { List<Mate> mates = null; // Check if users has additional arguments if (scanner.hasNext()) { String action = scanner.next(); switch (action) { case "delete": checkPublic(message); String memberName = scanner.next(); mates = getMateDao().findByName(memberName); if (!mates.isEmpty()) { // Finally delete the member. for (Mate mate : mates) { getMateDao().delete(mate); } message.addReaction(Speaker.Reaction.SUCCESS).queue(); } else { // No Mate with given name. message.addReaction(Speaker.Reaction.FAILURE).queue(); } break; default: // Wrong argument! message.addReaction(Speaker.Reaction.FAILURE).queue(); break; } } else { // List Users List<List<String>> rows = getMateDao().listOrderByOldestStock(); Locale locale = getResponseLocale(message); PrintableTable table = new PrintableTable(Resource.getString("USERS_LIST_HEADER", locale), Collections.emptyList(), Arrays.asList(Resource.getString("USER", locale), Resource.getString("POPULATED", locale), Resource.getString("OLDEST_STOCK", locale)), rows, Arrays.asList(Block.DATA_MIDDLE_LEFT, Block.DATA_MIDDLE_RIGHT, Block.DATA_MIDDLE_RIGHT)); Speaker.sayCode(message.getChannel(), PrintUtils.prettyPrint(table)); } } public static void clear(Scanner scanner, Message message) { Optional<String> mateOrStockOptional = parseStockName(scanner); List<Mate> mates = null; String clearReaction = Speaker.Reaction.FAILURE; String mateOrStock = null; final Locale locale = getResponseLocale(message); Mate mate = getMateDao().getOrCreateMate(message, locale); if (!mateOrStockOptional.isPresent()) { // if no member was selected assume the user of the message. mates = Collections.singletonList(mate); } else { mateOrStock = mateOrStockOptional.get(); if ("all".equalsIgnoreCase(mateOrStock)) { checkPublic(message); // select guild members mates = getMateDao().findByNameLike("%"); } else { // select only given member with exact matching name. mates = getMateDao().findByName(mateOrStock); if (!mates.isEmpty()) { checkPublic(message); } } } // Delete the stocks from defined members. // otherwise try the parameter as an Item. if (!mates.isEmpty()) { for (Mate aMate : mates) { getStockDao().deleteAll(aMate); } clearReaction = Speaker.Reaction.SUCCESS; } else { String stockIdentifier = Resource.getItemKey(mateOrStock, locale); Optional<StockType> stockType = getStockTypeDao().findByKey(stockIdentifier); // Try to delete the given name from stocks of current user. getStockDao().delete(mate, stockType.get()); clearReaction = Speaker.Reaction.SUCCESS; } // Always response to a bot request. message.addReaction(clearReaction).queue(); } public static void update(Scanner scanner, Message message) { Locale responseLocale = getResponseLocale(message); Map<String, Long> stocks = parseStocks(scanner, responseLocale); internalUpdate(message, responseLocale, stocks); } static void internalUpdate(Message message, Locale responseLocale, Map<String, Long> stocks) { try { Mate mate = getMateDao().getOrCreateMate(message, getResponseLocale(message)); List<String> unknownStocks = getMateDao().updateStocks(mate, stocks); if (stocks.size() > 0) { if (!unknownStocks.isEmpty()) { Speaker.err(message, String.format(Resource.getString("DO_NOT_KNOW_ABOUT", responseLocale), unknownStocks.toString())); } if (unknownStocks.size() != stocks.size()) { message.addReaction(Speaker.Reaction.SUCCESS).queue(); } } else { Speaker.err(message, Resource.getString("RESOURCES_EMPTY", responseLocale)); } } catch (Exception e) { e.printStackTrace(); message.addReaction(Speaker.Reaction.FAILURE).queue(); return; } } public static void checkTypes(Scanner scanner, Message message) { Optional<String> stockNameOptional = parseStockName(scanner); Locale locale = getResponseLocale(message); List<StockType> stocks = stockNameOptional.isPresent() ? getStockTypeDao().findByNameLike(stockNameOptional.get(), locale) : getStockTypeDao().findAll(); Speaker.sayCode(message.getChannel(), prettyPrintStockTypes(stocks, locale)); } public static void group(Scanner scanner, Message message) { // create the user if it does not exist - prevent users to directly // message the bot that are not in the guild channel getMateDao().getOrCreateMate(message, getResponseLocale(message)); if (scanner.hasNext()) { String subCommand = scanner.next(); switch (subCommand) { case "create": checkPublic(message); groupCreate(scanner, message); break; case "delete": checkPublic(message); groupDelete(scanner, message); break; case "add": checkPublic(message); groupAdd(scanner, message); break; case "remove": checkPublic(message); groupRemove(scanner, message); break; case "list": groupList(scanner, message); break; default: Speaker.err(message, Resource.getString("GROUP_SUBCOMMAND_UNKNOWN", getResponseLocale(message))); break; } } else { groupList(scanner, message); } } private static void groupCreate(Scanner scanner, Message message) { List<String> groupNames = parseGroupName(scanner); List<String> inUse = new ArrayList<>(); for (String groupName : groupNames) { Optional<StockTypeGroup> groupOpt = getStockTypeGroupDao().findByName(groupName); if (groupOpt.isPresent()) { inUse.add(groupName); } else { StockTypeGroup group = new StockTypeGroup(); group.setName(groupName); getStockTypeGroupDao().save(group); message.addReaction(Speaker.Reaction.SUCCESS).queue(); } } if (groupNames.isEmpty()) { Speaker.err(message, Resource.getString("GROUP_CREATE_UNKNOWN", getResponseLocale(message))); } if (!inUse.isEmpty()) { String msg = String.format(Resource.getString("GROUP_CREATE_IN_USE", getResponseLocale(message)), inUse.toString()); Speaker.err(message, msg); } } private static void groupAdd(Scanner scanner, Message message) { Optional<StockTypeGroup> groupOpt = getTargetGroup(scanner, message, "ADD"); if (groupOpt.isPresent()) { List<StockType> stockTypes = getTargetStockTypes(scanner, message, "ADD"); StockTypeGroup group = groupOpt.get(); if (!stockTypes.isEmpty()) { List<StockType> types = group.getTypes(); if (types == null) { types = new ArrayList<>(); group.setTypes(types); } types.addAll(stockTypes); // removing doubles types = new ArrayList<>(new HashSet<>(types)); group.setTypes(types); getStockTypeGroupDao().update(group); message.addReaction(Speaker.Reaction.SUCCESS).queue(); } } } private static void groupRemove(Scanner scanner, Message message) { Optional<StockTypeGroup> groupOpt = getTargetGroup(scanner, message, "REMOVE"); if (groupOpt.isPresent()) { List<StockType> stockTypes = getTargetStockTypes(scanner, message, "REMOVE"); StockTypeGroup group = groupOpt.get(); if (!stockTypes.isEmpty()) { List<StockType> types = group.getTypes(); if (types == null) { group.setTypes(new ArrayList<>()); } group.getTypes().removeAll(stockTypes); getStockTypeGroupDao().update(group); message.addReaction(Speaker.Reaction.SUCCESS).queue(); } } } private static Optional<StockTypeGroup> getTargetGroup(Scanner scanner, Message message, String operation) { Locale locale = getResponseLocale(message); if (scanner.hasNext()) { String groupName = scanner.next(); Optional<StockTypeGroup> groupOpt = getStockTypeGroupDao().findByName(groupName); if (groupOpt.isPresent()) { return groupOpt; } else { Speaker.err(message, Resource.getString("GROUP_" + operation + "_UNKNOWN", locale)); } } else { Speaker.err(message, Resource.getString("GROUP_" + operation + "_UNKNOWN", locale)); } return Optional.empty(); } private static List<StockType> getTargetStockTypes(Scanner scanner, Message message, String operation) { Locale locale = getResponseLocale(message); List<StockType> stockTypes = new ArrayList<>(); List<String> unknownStockTypes = new ArrayList<>(); List<String> inputNames = new ArrayList<>(); while (scanner.hasNext()) { String next = scanner.next(); boolean groupStart = StringUtils.startsWithAny(next, "\"", "\'"); if (!groupStart) { inputNames.add(next); } else { StringBuilder buffer = new StringBuilder(next); boolean groupEnd = false; while (scanner.hasNext() && !groupEnd) { next = scanner.next(); groupEnd = StringUtils.endsWithAny(next, "\"", "\'"); buffer.append(" "); buffer.append(next); } buffer.deleteCharAt(0); buffer.deleteCharAt(buffer.length() - 1); inputNames.add(buffer.toString()); } } for (String inputName : inputNames) { try { String key = Resource.getItemKey(inputName, locale); Optional<StockType> stockOpt = getStockTypeDao().findByKey(key); if (!stockOpt.isPresent()) { unknownStockTypes.add(inputName); } else { stockTypes.add(stockOpt.get()); } } catch (Exception e) { unknownStockTypes.add(inputName); } } if (!unknownStockTypes.isEmpty()) { String msg = String.format(Resource.getString("GROUP_UNKNOWN_TYPE", locale), unknownStockTypes.toString()); Speaker.err(message, msg); } return stockTypes; } private static void groupDelete(Scanner scanner, Message message) { List<String> groupNames = parseGroupName(scanner); List<String> unknown = new ArrayList<>(); for (String groupName : groupNames) { Optional<StockTypeGroup> group = getStockTypeGroupDao().findByName(groupName); if (group.isPresent()) { getStockTypeGroupDao().delete(group.get()); message.addReaction(Speaker.Reaction.SUCCESS).queue(); } else { unknown.add(groupName); } } if (groupNames.isEmpty()) { Speaker.err(message, Resource.getString("GROUP_DELETE_UNKNOWN", getResponseLocale(message))); } if (!unknown.isEmpty()) { String msg = String.format(Resource.getString("GROUP_DELETE_UNKNOWN", getResponseLocale(message)), unknown.toString()); Speaker.err(message, msg); } } private static void groupList(Scanner scanner, Message message) { Locale locale = getResponseLocale(message); List<String> groupNames = parseGroupName(scanner); List<StockTypeGroup> groups = Collections.emptyList(); if (groupNames.isEmpty()) { groups = getStockTypeGroupDao().findAll(); } else { groups = getStockTypeGroupDao().findByNameLike(groupNames); } List<List<String>> rows = new ArrayList<>(); for (StockTypeGroup stockTypeGroup : groups) { List<StockType> types = stockTypeGroup.getTypes(); String amount = String.format("%,d", types != null ? types.size() : 0); rows.add(Arrays.asList(stockTypeGroup.getName(), amount)); if (types != null) { for (Iterator<StockType> it2 = types.iterator(); it2.hasNext();) { StockType stockType = it2.next(); String localisedStockName = Resource.getItem(stockType.getName(), locale); String tree = it2.hasNext() ? " " : " "; rows.add(Arrays.asList(tree + localisedStockName, " ")); } } } if (rows.isEmpty()) { rows.add(Arrays.asList(" ", " ")); } List<String> titles = Arrays.asList(Resource.getString("NAME", locale), Resource.getString("AMOUNT", locale)); String header = Resource.getString("GROUP_LIST_HEADER", locale); List<Integer> aligns = Arrays.asList(Block.DATA_MIDDLE_LEFT, Block.DATA_BOTTOM_RIGHT); List<String> footer = Collections.emptyList(); PrintableTable table = new PrintableTable(header, footer, titles, rows, aligns); Speaker.sayCode(message.getChannel(), PrintUtils.prettyPrint(table)); } public static void check(Scanner scanner, Message message) { Optional<String> nameOptional = parseStockName(scanner); MessageChannel channel = message.getChannel(); Locale locale = getResponseLocale(message); if (!nameOptional.isPresent()) { Mate mate = getMateDao().getOrCreateMate(message, getResponseLocale(message)); List<Mate> mates = Collections.singletonList(mate); Speaker.sayCode(channel, prettyPrintMate(mates, locale)); } else { List<Mate> mates = getMateDao().findByNameLike(nameOptional.get()); if (!mates.isEmpty()) { Speaker.sayCode(channel, prettyPrintMate(mates, locale)); return; } List<StockType> types = getStockTypeDao().findByNameLike(nameOptional.get(), locale); if (!types.isEmpty()) { Speaker.sayCode(channel, prettyPrintStocks(types, locale)); return; } Optional<StockTypeGroup> groupOpt = getStockTypeGroupDao().findByName(nameOptional.get()); if (groupOpt.isPresent()) { List<StockType> groupTypes = groupOpt.get().getTypes(); if (!groupTypes.isEmpty()) { Speaker.sayCode(channel, prettyPrintStocks(groupTypes, locale)); } else { String msg = String.format(Resource.getString("GROUP_EMPTY", locale), nameOptional.get()); Speaker.say(channel, msg); } } else { Speaker.say(channel, Resource.getString("RESOURCE_AND_USER_UNKNOWN", locale)); } } } public static void help(Scanner scanner, Message message) { Predicate<Method> filter = method -> Modifier.isPublic(method.getModifiers()); String response = Arrays.stream(Commands.class.getDeclaredMethods()).filter(filter).map(Method::getName) .collect(Collectors.joining("\n")); Speaker.sayCode(message.getChannel(), Resource.getString("COMMANDS", getResponseLocale(message)) + "\n" + response); } public static void total(Scanner scanner, Message message) { Optional<String> nameOptional = parseStockName(scanner); List<StockType> stockTypes; Locale locale = getResponseLocale(message); if (!nameOptional.isPresent()) { stockTypes = getStockTypeDao().findAll(); } else { stockTypes = getStockTypeDao().findByNameLike(nameOptional.get(), locale); if (stockTypes.isEmpty()) { Optional<StockTypeGroup> groupOpt = getStockTypeGroupDao().findByName(nameOptional.get()); if (groupOpt.isPresent()) { if (groupOpt.get().getTypes() == null || groupOpt.get().getTypes().isEmpty()) { String msg = String.format(Resource.getString("GROUP_EMPTY", locale), nameOptional.get()); Speaker.say(message.getChannel(), msg); return; } else { stockTypes = groupOpt.get().getTypes(); } } else { Speaker.say(message.getChannel(), Resource.getString("RESOURCE_UNKNOWN", locale)); return; } } } List<List<String>> rows = new ArrayList<>(); for (StockType stockType : stockTypes) { long total = getStockDao().getTotalAmount(stockType); if (total > 0) { String localisedStockName = Resource.getItem(stockType.getName(), locale); rows.add(Arrays.asList(localisedStockName, String.format("%,d", total))); } } if (!rows.isEmpty()) { PrintableTable total_guild_resources = new PrintableTable(Resource.getString("TOTAL_RESOURCES", locale), Collections.emptyList(), Arrays.asList(Resource.getString("RAW_MATERIAL", locale), Resource.getString("AMOUNT", locale)), rows, Arrays.asList(Block.DATA_MIDDLE_LEFT, Block.DATA_MIDDLE_RIGHT)); Speaker.sayCode(message.getChannel(), prettyPrint(total_guild_resources)); } else { Speaker.say(message.getChannel(), Resource.getString("RESOURCES_EMPTY", locale)); } } }